<template>
  <div class="page">
    <div class="ele-body">
      <a-card :bordered="false">
        <!-- 表格 -->
        <ele-pro-table
          ref="tableRef"
          row-key="orderId"
          :columns="columns"
          :datasource="datasource"
          v-model:selection="selection"
          :customRow="customRow"
          tool-class="ele-toolbar-form"
          :scroll="{ x: 1200 }"
          class="sys-org-table"
          :striped="true"
        >
          <template #toolbar>
            <search
              @search="reload"
              :selection="selection"
              @advanced="openAdvanced"
            />
          </template>
          <a-button class="ele-btn-icon" @click="handleExport">
            <template #icon>
              <DownloadOutlined />
            </template>
            <span>导出订单</span>
          </a-button>
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'restDay'">
              <strong v-if="record.restDay < 0" :style="{ color: 'red' }">{{
                record.restDay
              }}</strong>
              <span v-else-if="record.restDay >= 0">{{ record.restDay }}</span>
              <span> 天</span>
            </template>
            <template v-if="column.key === 'merchantName'">
              <div style="display: flex; flex-direction: column">
                <span>{{ record.merchantName }}</span>
                <span class="ele-text-placeholder">
                  {{ record.merchantCode }}
                </span>
              </div>
            </template>
            <template v-if="column.key === 'totalPayPrice'">
              <p>
                <span class="ele-text-warning price-edit">
                  ￥{{ record.totalPayPrice }}
                </span>
                <form-outlined
                  v-if="record.payStatus === 10"
                  @click="onEdit('totalPayPrice', record.totalPrice, record)"
              /></p>
              <p class="ele-text-placeholder"
                >(含运费：￥{{ record.expressPrice }})</p
              >
            </template>
            <template v-if="column.key === 'goods'">
              <template v-if="record.equipment">
                <p class="ele-text">{{ record.equipment.equipmentName }}</p>
                <p class="ele-text">{{ record.equipment.batteryModel }}</p>
                <p class="ele-text">{{ record.equipment.equipmentCode }}</p>
              </template>
            </template>
            <template v-if="column.key === 'payMethod'">
              <a-tag v-if="record.payMethod === '10'" color="orange"
                >余额支付</a-tag
              >
              <a-tag v-if="record.payMethod === '20'" color="green"
                >微信支付</a-tag
              >
              <a-tag v-if="record.payMethod === '30'" color="blue"
                >支付宝</a-tag
              >
              <a-tag v-if="record.payMethod === '40'" color="purple"
                >通联支付</a-tag
              >
            </template>
            <template v-if="column.key === 'deliveryType'">
              <span v-if="record.deliveryType === 10">快递配送</span>
              <span v-if="record.deliveryType === 20">门店自提</span>
            </template>
            <template v-if="column.key === 'payStatus'">
              <div class="ele-text-placeholder">
                <!--                付款状态：-->
                <a-tag
                  v-if="record.payStatus === 10"
                  @click="onAlipayQuery(record.orderId)"
                  >未付款</a-tag
                >
                <a-tag v-if="record.payStatus === 20" color="green"
                  >已付款</a-tag
                >
              </div>
              <div class="ele-text-placeholder">
                <!--                发货状态：-->
                <a-tag v-if="record.deliveryStatus === 10">未发货</a-tag>
                <a-tag v-else-if="record.deliveryStatus === 20" color="success"
                  >已发货</a-tag
                >
              </div>
              <div class="ele-text-placeholder">
                <!--                收货状态：-->
                <a-tag v-if="record.receiptStatus === 10">未收货</a-tag>
                <a-tag v-else-if="record.receiptStatus === 20" color="success"
                  >已收货</a-tag
                >
                <a-tag v-else-if="record.receiptStatus === 21" color="purple"
                  >退租中</a-tag
                >
                <a-tag v-else-if="record.receiptStatus === 30" color="error"
                  >已退租</a-tag
                >
              </div>
              <div class="ele-text-placeholder" v-if="record.orderSource != 10">
                <!--                分期状态：-->
                <a-tag v-if="record.fenqiStatus == 1" color="success"
                  >已完成</a-tag
                >
                <!-- <a-tag v-else-if="record.expirationDay < 0" color="error">逾期{{ record.expirationDay }}天</a-tag> -->
                <!-- <a-tag v-else-if="record.expirationDay >= 0" color="warning">剩余{{ record.expirationDay }}天</a-tag> -->
              </div>
            </template>
            <template v-if="column.key === 'comments'">
              <FormOutlined
                @click="onEditContent('comments', record.comments, record)"
              />
              <a-popover placement="topLeft">
                <template #content>
                  <div class="comments">{{ record.comments }}</div>
                </template>
                {{ record.comments }}
              </a-popover>
            </template>
            <template v-if="column.key === 'orderSourceData'">
              <a-image-preview-group v-if="record.orderSourceData">
                <a-image
                  :width="45"
                  v-for="(item, index) in JSON.parse(record.orderSourceData)"
                  :key="index"
                  :src="item"
                />
              </a-image-preview-group>
              <!--              <a-image-->
              <!--                v-if="record.orderSourceData"-->
              <!--                :src="JSON.parse(record.orderSourceData)"-->
              <!--                :width="45"-->
              <!--              />-->
            </template>
            <template v-if="column.key === 'status'">
              <a-tag v-if="record.status === '0'" color="green">正常</a-tag>
              <a-tag v-if="record.status === '1'" color="red">禁用</a-tag>
            </template>
            <template v-if="column.key === 'orderSource'">
              <a-tag v-if="Number(record.orderSource) === 10" color="success"
                >销售</a-tag
              >
              <a-tag v-if="Number(record.orderSource) === 20" color="red"
                >分期</a-tag
              >
              <a-tag v-if="Number(record.orderSource) === 30" color="orange"
                >以租代购</a-tag
              >
              <a-tag v-if="Number(record.orderSource) === 40" color="blue"
                >租赁</a-tag
              >
              <a-tag v-if="Number(record.orderSource) === 50" color="success"
                >续租</a-tag
              >
            </template>
            <template v-if="column.key === 'nickname'">
              <User :record="record" />
            </template>
            <template v-if="column.key === 'batteryModel'">
              {{ record.equipmentGoods.batteryModel }}
            </template>
            <template v-if="column.key === 'equipmentCode'">
              {{ record.equipment?.equipmentCode }}
            </template>
            <template v-if="column.key === 'createTime'">
              {{ record.createTime }}
            </template>
            <template v-if="column.key === 'action'">
              <a-space>
                <a-button class="ele-text-primary" @click="openInfo(record)"
                  >详情</a-button
                >
              </a-space>
              <view v-if="record.deliveryStatus == 40">
                <a-divider type="vertical" />
                <a-button class="ele-text-danger" @click="openChange(record)"
                  >换电</a-button
                >
                <view v-if="record.receiptStatus === 20">
                  <a-button
                    class="ele-text-danger"
                    @click="openOrderRefund(record)"
                    >退租</a-button
                  >
                </view>
              </view>
            </template>
          </template>
        </ele-pro-table>
      </a-card>
    </div>
    <battery-change
      v-model:visible="showChange"
      :data="current"
      @done="reload"
    />
    <order-refund
      v-model:visible="showOrderRefund"
      :data="current"
      @done="reload"
    />

    <!-- 编辑弹窗 -->
    <Delivery v-model:visible="deliveryEdit" :data="current" @done="reload" />
    <Markdown
      v-model:visible="showMarkdown"
      :data="data"
      :field="field"
      :orderId="orderId"
      :content="markdown"
      @done="reload"
    />
    <Field
      v-model:visible="showEdit"
      :data="data"
      :field="field"
      :orderId="orderId"
      :content="content"
      @done="reload"
    />
    <!-- 编辑弹窗 -->
    <!--    <order-edit v-model:visible="showEdit" :data="current" @done="reload" />-->
    <!-- 用户详情 -->
    <order-info v-model:visible="showInfo" :data="current" @done="reload" />
  </div>
</template>

<script lang="ts" setup>
  import { createVNode, ref } from 'vue';
  import { message, Modal } from 'ant-design-vue';
  import {
    // PlusOutlined,
    // DeleteOutlined,
    FormOutlined,
    ExclamationCircleOutlined,
    DownloadOutlined
  } from '@ant-design/icons-vue';
  import type { EleProTable } from 'ele-admin-pro';
  import type {
    DatasourceFunction,
    ColumnItem
  } from 'ele-admin-pro/es/ele-pro-table/types';
  import { toDateString } from 'ele-admin-pro';
  import Search from './components/search.vue';
  import Delivery from './components/delivery.vue';
  import Markdown from './components/markdown.vue';
  import Field from './components/field.vue';
  import OrderInfo from './components/order-info.vue';
  import BatteryChange from './components/battery-change.vue';
  import OrderRefund from './components/order-refund.vue';
  import { pageOrder, removeOrder, removeBatchOrder } from '@/api/order';
  import { alipayQuery } from '@/api/system/payment';
  import type { Order, OrderParam } from '@/api/order/model';
  import { getDictionaryOptions } from '@/utils/common';
  import { Equipment } from '@/api/apps/equipment/model';
  import { utils, writeFile } from 'xlsx';

  // 当前用户信息
  // const userStore = useUserStore();
  // const loginUser = computed(() => userStore.info ?? {});
  // const orderType = localStorage.getItem('orderType');
  defineProps<{
    activeKey?: boolean;
    data?: any;
  }>();

  // 表格实例
  const tableRef = ref<InstanceType<typeof EleProTable> | null>(null);

  /* 获取字典数据 */
  const orderSource = getDictionaryOptions('equipmentCategory');

  // 表格列配置
  const columns = ref<ColumnItem[]>([
    {
      key: 'index',
      width: 48,
      align: 'center',
      fixed: 'left',
      hideInSetting: true,
      hideInTable: true,
      customRender: ({ index }) => index + (tableRef.value?.tableIndex ?? 0)
    },
    {
      title: '操作',
      key: 'action',
      width: 100,
      align: 'center',
      fixed: 'left',
      hideInSetting: true
    },
    {
      title: '订单号',
      dataIndex: 'orderNo',
      key: 'orderNo',
      sorter: true
    },
    /* {
      title: '商品编号',
      dataIndex: 'goodsId',
      key: 'goodsId'
    }, */
    {
      title: '电池型号',
      dataIndex: 'batteryModel',
      key: 'batteryModel'
    },
    {
      title: '电池编号',
      dataIndex: 'equipmentCode',
      key: 'equipmentCode'
    },
    {
      title: '所属商户',
      dataIndex: 'merchantName',
      key: 'merchantName',
      sorter: true
    },
    {
      title: '下单方式',
      key: 'orderSource',
      dataIndex: 'orderSource',
      filters: orderSource,
      filterMultiple: false
    },
    {
      title: '到期时间',
      dataIndex: 'expirationTime',
      key: 'expirationTime',
      sorter: true
    },
    {
      title: '剩余天数',
      dataIndex: 'restDay',
      key: 'restDay',
      align: 'center',
      sorter: false
    },
    {
      title: '买家',
      dataIndex: 'nickname',
      key: 'nickname',
      align: 'center'
    },
    {
      title: '订单金额(元)',
      dataIndex: 'totalPayPrice',
      key: 'totalPayPrice',
      ellipsis: true
    },
    {
      title: '支付方式',
      key: 'payMethod',
      dataIndex: 'payMethod',
      filters: [
        {
          text: '余额支付',
          value: 10
        },
        {
          text: '微信支付',
          value: 20
        },
        {
          text: '支付宝',
          value: 30
        },
        {
          text: '通联支付',
          value: 40
        }
      ],
      filterMultiple: false
    },
    {
      title: '备注',
      dataIndex: 'comments',
      key: 'comments',
      ellipsis: true
    },
    // {
    //   title: '订单附件',
    //   dataIndex: 'orderSourceData',
    //   key: 'orderSourceData'
    // },
    {
      title: '推荐人手机号',
      key: 'dealerPhone',
      dataIndex: 'dealerPhone',
      ellipsis: true
    },
    {
      title: '实名用户',
      key: 'realName',
      dataIndex: 'realName',
      ellipsis: true
    },
    {
      title: '配送方式',
      key: 'deliveryType',
      dataIndex: 'deliveryType',
      hideInTable: true,
      filters: [
        {
          text: '快递配送',
          value: 10
        },
        {
          text: '门店自提',
          value: 20
        }
      ],
      filterMultiple: false
    },

    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      sorter: true,
      customRender: ({ text }) => toDateString(text)
    },
    {
      title: '交易状态',
      key: 'payStatus',
      dataIndex: 'payStatus',
      fixed: 'right',
      align: 'center',
      filters: [
        {
          text: '未付款',
          value: 10
        },
        {
          text: '已付款',
          value: 20
        }
      ],
      filterMultiple: false
    }
  ]);

  // 表格选中数据
  const selection = ref<Order[]>([]);
  // 当前编辑数据
  const current = ref<Order | null>(null);
  // 是否显示资产详情
  const showInfo = ref(false);
  // 是否显示编辑弹窗
  const showEdit = ref(false);
  // 是否显示换电弹窗
  const showChange = ref(false);
  const showOrderRefund = ref(false);
  const markdown = ref('请输入备注内容');
  const content = ref('请输入要修改的内容');
  const showMarkdown = ref(false);
  const deliveryEdit = ref(false);
  const field = ref('comments');
  const orderId = ref(undefined);
  // 是否显示高级搜索
  const showAdvancedSearch = ref(false);

  // 表格数据源
  const datasource: DatasourceFunction = ({
    page,
    limit,
    where,
    orders,
    filters
  }) => {
    // 搜索条件
    if (filters.payMethod) {
      where.payMethod = filters.payMethod;
    }
    if (filters.deliveryType) {
      where.deliveryType = filters.deliveryType;
    }
    if (filters.payStatus) {
      where.payStatus = filters.payStatus;
    }
    if (filters.orderSource) {
      where.orderSource = filters.orderSource;
    }
    where.tenantId = localStorage.getItem('tenantId');
    where.isRenew = 0;
    where.isFreeze = 1;
    return pageOrder({
      ...where,
      ...orders,
      page,
      limit
    });
  };
  // 导出
  const handleExport = () => {
    if (!selection.value?.length) {
      message.error('请至少选择一条数据');
      return;
    }
    const array: (string | number)[][] = [
      [
        '订单号',
        '下单日期',
        '电池型号',
        '电池编号',
        '所属商户',
        '到期时间',
        '剩余天数',
        '买家',
        '客户实名',
        '订单金额',
        '交易状态'
      ]
    ];

    selection.value?.forEach((d: Order) => {
      var username = d.phone ? d.phone : d.nickname;

      var equipmentCode = d.equipment ? d.equipment.equipmentCode : '';

      var orderStatus = '';
      if (d.payStatus == 10) {
        orderStatus = '待付款';
      } else {
        if (d.receiptStatus == 10) {
          orderStatus = '待收货';
        }
        if (d.receiptStatus == 20) {
          orderStatus = '已收货';
        }
        if (d.receiptStatus == 21) {
          orderStatus = '退租中';
        }
        if (d.receiptStatus == 30) {
          orderStatus = '已退租';
        }
      }

      array.push([
        `${d.orderNo}`,
        `${d.createTime}`,
        `${d.equipmentGoods.batteryModel}`,
        `${equipmentCode}`,
        `${d.merchantName}`,
        `${d.expirationTime}`,
        `${d.restDay}`,
        `${username}`,
        `${d.realName}`,
        `${d.totalPayPrice}`,

        `${orderStatus}`
      ]);
    });
    const sheetName = '设备列表';
    const workbook = {
      SheetNames: [sheetName],
      Sheets: {}
    };
    const sheet = utils.aoa_to_sheet(array);
    workbook.Sheets[sheetName] = sheet;
    // 设置列宽
    sheet['!cols'] = [
      { wch: 10 },
      { wch: 10 },
      { wch: 10 },
      { wch: 10 },
      { wch: 20 },
      { wch: 40 },
      { wch: 10 }
    ];
    writeFile(workbook, '导出订单管理表.xlsx');
  };

  /* 搜索 */
  const reload = (where?: OrderParam) => {
    selection.value = [];
    tableRef?.value?.reload({ where: where });
  };

  const onEdit = (name, text, item) => {
    orderId.value = item.orderId;
    field.value = name;
    content.value = text;
    showEdit.value = true;
  };

  const onEditContent = (name, text, item) => {
    orderId.value = item.orderId;
    field.value = name;
    markdown.value = text;
    showMarkdown.value = true;
  };

  const openDelivery = (row?: Order) => {
    current.value = row ?? null;
    deliveryEdit.value = true;
  };

  /* 打开编辑弹窗 */
  const openEdit = (row?: Order) => {
    current.value = row ?? null;
    showEdit.value = true;
  };

  /* 打开用户详情弹窗 */
  const openInfo = (row?: Order) => {
    current.value = row ?? null;
    showInfo.value = true;
  };

  /* 打开换电弹窗 */
  const openChange = (row?: Order) => {
    current.value = row ?? null;
    showChange.value = true;
  };

  /* 退租 */
  const openOrderRefund = (row?: Order) => {
    current.value = row ?? null;
    showOrderRefund.value = true;
  };

  /* 打开高级搜索 */
  const openAdvanced = () => {
    showAdvancedSearch.value = !showAdvancedSearch.value;
  };

  /* 支付宝统一收单交易查询 */
  const onAlipayQuery = (orderNo) => {
    alipayQuery(orderNo).then((res) => {
      console.log(res);
    });
  };

  /* 删除单个 */
  const remove = (row: Order) => {
    const hide = message.loading('请求中..', 0);
    removeOrder(row.orderId)
      .then((msg) => {
        hide();
        message.success(msg);
        reload();
      })
      .catch((e) => {
        hide();
        message.error(e.message);
      });
  };

  /* 批量删除 */
  const removeBatch = () => {
    console.log(selection.value);
    if (!selection.value.length) {
      message.error('请至少选择一条数据');
      return;
    }
    Modal.confirm({
      title: '提示',
      content: '确定要删除选中的记录吗?',
      icon: createVNode(ExclamationCircleOutlined),
      maskClosable: true,
      onOk: () => {
        const hide = message.loading('请求中..', 0);
        removeBatchOrder(selection.value.map((d) => d.orderId))
          .then((msg) => {
            hide();
            message.success(msg);
            reload();
          })
          .catch((e) => {
            hide();
            message.error(e.message);
          });
      }
    });
  };

  /* 自定义行属性 */
  const customRow = (record: Order) => {
    return {
      // 行点击事件
      onClick: () => {
        // console.log(record);
      },
      // 行双击事件
      onDblclick: () => {
        openInfo(record);
      }
    };
  };
</script>

<script lang="ts">
  export default {
    name: 'ShopOrderIndex'
  };
</script>

<style lang="less" scoped>
  p {
    line-height: 0.8;
  }
  .sys-org-table :deep(.ant-table-body) {
    overflow: auto !important;
    overflow: overlay !important;
  }

  .sys-org-table :deep(.ant-table-pagination.ant-pagination) {
    padding: 0 4px;
    margin-bottom: 0;
  }
  .price-edit {
    padding-right: 5px;
  }
  .comments {
    max-width: 200px;
  }
</style>
