<template>
  <div class="p-4">
    <BasicTable @register="registerTable" :rowSelection="{ type: 'checkbox' }">
      <template #toolbar>
        <!-- <a-button type="primary" @click="exportExcel"> 导出</a-button> -->
      </template>
      <template #cover="{ record }">
        <TableImg :size="150" :simpleShow="true" :imgList="[record.cover]" />
      </template>
      <template #orderType="{ record }"> {{ renderOrderTypeLabel(record.orderType) }} </template>
      <template #orderStatus="{ record }">
        {{ renderOrderStatusLabel(record.orderStatus) }}
      </template>
      <template #shippingStatus="{ record }">
        {{ rendershippingStatusLabel(record.shippingStatus) }}
      </template>
      <template #payStatus="{ record }">
        {{ renderpayStatusLabel(record.payStatus) }}
      </template>
      <template #addTime="{ record }">
        <Time :value="record.addTime" mode="datetime" />
      </template>
      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              label: '发货',
              color: 'warning',
              disabled: record.shippingStatus == 1,
              onClick: sendPackage.bind(null, record),
            },
            {
              label: '详情',
              onClick: () => {
                go(
                  `/order/list/detail/${record.orderSn}?brandId=${record.brandId}&id=${record.id}`,
                );
              },
            },
            {
              label: '收货',
              color: 'warning',
              disabled: record.orderStatus !== 1,
              popConfirm: {
                title: '是否确认收货',
                confirm: handleConfirmReceive.bind(null, record),
              },
            },
            {
              label: '打印',
              color: 'error',
              onClick: printDetail.bind(null, record),
            },
          ]"
        />
      </template>
    </BasicTable>
    <ConfirmModal @register="registerConfirmModal" @reload="reload" />
    <PrintModal @register="registerPrintModal" @reload="reload" />
  </div>
</template>
<script lang="ts">
  import { defineComponent } from 'vue';
  import {
    BasicTable,
    useTable,
    BasicColumn,
    FormProps,
    TableAction,
    TableImg,
  } from '/@/components/Table';
  import { useMessage } from '/@/hooks/web/useMessage';

  import {
    ListApi,
    BrandListApi,
    GetOrderInfoApi,
    exportExcelApi,
    confirmOrder,
  } from '/@/api/order/list';
  import { useI18n } from '/@/hooks/web/useI18n';
  // import { useCopyToClipboard } from '/@/hooks/web/useCopyToClipboard';
  import { useGo } from '/@/hooks/web/usePage';
  import { Time } from '/@/components/Time';

  import { useModal } from '/@/components/Modal';
  import ConfirmModal from './confirmModal.vue';
  import PrintModal from './printModal.vue';
  import {
    downloadByUrl,
    // downloadByData,
    // downloadByBase64,
    // downloadByOnlineUrl,
  } from '/@/utils/file/download';

  export default defineComponent({
    components: {
      BasicTable,
      TableAction,
      TableImg,
      Time,
      ConfirmModal,
      PrintModal,
    },
    setup() {
      const { createMessage } = useMessage();
      const go = useGo();
      const { t } = useI18n();
      const columns: BasicColumn[] = [
        {
          title: 'ID',
          dataIndex: 'id',
          fixed: 'left',
          width: 60,
        },
        {
          title: '订单号',
          dataIndex: 'orderSn',
          ellipsis: false,
          width: 180,
        },
        {
          title: '会员昵称',
          dataIndex: 'nickName',
          width: 80,
        },
        {
          title: 'VR场景',
          dataIndex: 'brandName',
          width: 80,
        },
        {
          title: '订单类型',
          dataIndex: 'orderType',
          slots: { customRender: 'orderType' },
          sorter: true,
          width: 80,
        },
        {
          title: '订单状态',
          dataIndex: 'orderStatus',
          sorter: true,
          slots: { customRender: 'orderStatus' },
          width: 80,
        },
        {
          title: '发货状态',
          dataIndex: 'shippingStatus',
          sorter: true,
          slots: { customRender: 'shippingStatus' },
          width: 80,
        },
        {
          title: '付款状态',
          dataIndex: 'payStatus',
          slots: { customRender: 'payStatus' },
          width: 60,
        },
        {
          title: '快递公司',
          dataIndex: 'shipingName',
          width: 60,
        },
        {
          title: '快递单号',
          dataIndex: 'shippingNo',
          width: 80,
        },
        {
          title: '实际支付金额',
          dataIndex: 'actualPrice',
          width: 80,
        },
        {
          title: '下单时间',
          dataIndex: 'addTime',
          width: 120,
          slots: { customRender: 'addTime' },
        },
        {
          title: '操作',
          dataIndex: '',
          slots: { customRender: 'action' },
          fixed: 'right',
          align: 'center',
          width: 250,
        },
      ];

      const searchForm: Partial<FormProps> = {
        labelWidth: 100,
        schemas: [
          {
            field: 'orderSn',
            label: '订单号',
            component: 'Input',
            componentProps: {
              maxLength: 100,
            },
            colProps: {
              xl: 5,
              xxl: 5,
            },
          },
          {
            field: 'orderStatus',
            label: '订单状态',
            component: 'Select',
            colProps: {
              xl: 5,
              xxl: 5,
            },
            componentProps: {
              options: [
                {
                  label: '全部订单',
                  value: '',
                  key: '1',
                },
                {
                  label: '待付款',
                  value: '0',
                  key: '2',
                },
                {
                  label: '订单已取消',
                  value: '101',
                  key: '3',
                },
                {
                  label: '订单已付款',
                  value: '201',
                  key: '4',
                },
                {
                  label: '订单已发货',
                  value: '1',
                  key: '5',
                },
                {
                  label: '订单已收货',
                  value: '2',
                  key: '6',
                },
                {
                  label: '完成',
                  value: '501',
                  key: '7',
                },
              ],
            },
          },
          {
            field: 'brandId',
            label: 'VR场景',
            component: 'ApiSelect',
            componentProps: {
              api: BrandListApi,
              // resultField: 'list',
              numberToString: true,
              labelField: 'name',
              valueField: 'id',
              immediate: true,
              params: {
                page: 1,
                limit: 1000,
              },
            },
            colProps: {
              xl: 5,
              xxl: 5,
            },
          },
        ],
      };

      const getCheckboxProps = (record: Recordable) => {
        console.log('record', record);
        return { disabled: record.type == 2 };
      };
      const [registerConfirmModal, { openModal: openConfirmModal }] = useModal();

      const [registerPrintModal, { openModal: openPrintModal }] = useModal();

      const [registerTable, { getSelectRows, reload }] = useTable({
        title: '订单列表',
        api: ListApi,
        columns: columns,
        useSearchForm: true,
        formConfig: searchForm,
        clickToRowSelect: false,
        showTableSetting: true,
        tableSetting: { fullScreen: true },
        showIndexColumn: false,
        rowKey: 'id',
        pagination: { pageSize: 20 },
        ellipsis: false,
        fetchSetting: {
          pageField: 'page',
          sizeField: 'limit',
          listField: 'list',
          totalField: 'totalCount',
        },
        bordered: true,
        sortFn: (sortInfo) => {
          let order = sortInfo.order && sortInfo.order.replace('end', '');
          return { ...sortInfo, sidx: sortInfo.field, order: order };
        },
      });

      function renderOrderTypeLabel(type: number): string {
        switch (type) {
          case 0:
            return '立即购买';
          case 1:
            return '延后购买';
          default:
            return '立即购买';
        }
      }
      function renderOrderStatusLabel(type: number): string {
        switch (type) {
          case 0:
            return '待付款';
          case 101:
            return '已取消';
          case 102:
            return '已删除';
          case 201:
            return '已付款';
          case 300:
            return '已发货';
          case 301:
            return '已收货';
          case 401:
            return '退款';
          case 402:
            return '退款退货';
          case 501:
            return '完成';
          default:
            return '';
        }
      }
      function rendershippingStatusLabel(type: number): string {
        switch (type) {
          case 0:
            return '未发货';
          case 1:
            return '已发货';
          default:
            return '';
        }
      }
      function renderpayStatusLabel(type: number): string {
        switch (type) {
          case 0:
            return '未付款';
          case 1:
            return '已付款';
          default:
            return '已付款';
        }
      }
      // function onSelectChange(selectedRowKeys: (string | number)[]) {
      //   console.log(selectedRowKeys);
      //   // checkedKeys.value = selectedRowKeys;
      // }
      function sendPackage(record: Recordable) {
        openConfirmModal(true, record);
      }
      async function handleConfirmReceive(record: Recordable) {
        const { id, brandId } = record;
        let res = await confirmOrder({
          id,
          brandId,
        });
        if (res) {
          reload();
          createMessage.success('操作成功');
        }
      }
      async function printDetail(record: Recordable) {
        const orderInfo = await GetOrderInfoApi({
          id: record.id,
          brandId: record.brandId,
        });
        console.log('orderInfo', orderInfo);
        openPrintModal(true, orderInfo);
      }
      async function exportExcel() {
        const rows = getSelectRows();
        if (rows.length === 0) {
          createMessage.info(t('modal.atLeastOne'));
          return;
        }

        const data = rows.reduce((pre, current) => pre.concat(current['orderSn']), []).join(',');
        console.log('data', data);
        const res = await exportExcelApi({
          orderSnList: data,
        });
        if (res.url) {
          downloadByUrl({
            url: res.url,
            target: '_self',
          });
        }
      }

      return {
        registerTable,
        createMessage,
        t,
        go,
        renderOrderTypeLabel,
        renderOrderStatusLabel,
        rendershippingStatusLabel,
        renderpayStatusLabel,
        sendPackage,
        // onSelectChange,
        handleConfirmReceive,
        registerConfirmModal,
        reload,
        printDetail,
        registerPrintModal,
        exportExcel,
        getCheckboxProps,
      };
    },
  });
</script>
