<script setup lang="tsx">
import { nextTick, onMounted, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { NTag, useDialog } from 'naive-ui';
import type { InternalRowData } from 'naive-ui/es/data-table/src/interface';
import {
  // fetchAudit,
  fetchBreakDownload,
  fetchExportList,
  fetchExportOrderList,
  fetchGetDeliveryOrderList,
  fetchGetDeliveryStatusNum
} from '@/service/api/order-manage/normal-order';
// import { fetchGetLoginUserList } from '@/service/api/common';
// import { useAuth } from '@/hooks/business/auth';
// import { copyTextToClipboard } from '@/utils/zt';
// import { commonExport } from '@/utils/common';
import { useModal } from '@/components/zt/Modal/hooks/useModal';
import { useTable } from '@/components/zt/Table/hooks/useTable';
// import { type } from '../../../../packages/axios/src/index';
import { DJKOrderStatus, businessType, getSearchForm, orderStatus } from './normal-order';
const router = useRouter();
const route = useRoute();
const activeTab = ref('all');
const statusList = ref<{ label: string; value: string; num?: number }[]>([]);
// const ShipmentModal = useTemplateRef('Shipment');
const channelIdList = ref([]);
const orderNumber = route.query.orderNumber;
const options = [
  {
    label: '导出商品数据',
    key: 'goods'
  },
  {
    label: '导出订单数据',
    key: 'order'
  }
];
const columns: NaiveUI.TableColumn<Api.delivery.deliveryOrder>[] = [
  {
    key: 'orderNumber',
    title: '订单编号',
    align: 'center',
    width: 220
  },
  {
    key: 'consigneeAddress',
    title: '业务类型',
    align: 'center',
    width: 120,
    render: row => {
      return <NTag>{businessType[row.businessType as keyof typeof businessType] || row.businessType}</NTag>;
    }
  },
  {
    key: 'shopName',
    title: '门店名称',
    align: 'center',
    width: 120
  },
  {
    key: 'channelName',
    title: '所属企业',
    align: 'center',
    width: 120
  },
  {
    key: 'accessName',
    title: '渠道',
    align: 'center',
    width: 120
  },
  {
    key: 'info',
    title: '客户信息',
    align: 'center',
    width: 220,
    render: row => {
      return (
        <div>
          <div>
            {row.consigneeName}
            {row.consigneeMobile}
          </div>
          {row.dvyType == 2 ? <div>自提</div> : <div>{row.consigneeAddress}</div>}
        </div>
      );
    }
  },
  {
    key: 'orderMoney',
    title: '订单金额（元）',
    align: 'center',
    width: 120
  },
  {
    key: 'status',
    title: '业务状态',
    align: 'center',
    width: 120,
    render: row => {
      const statusKey = row.hbOrderStatus as keyof typeof orderStatus;
      let statusText;
      if (row.businessType == 'XNSP') {
        if (row.hbOrderStatus == 60 || row.hbOrderStatus == 50 || row.hbOrderStatus == 0) {
          statusText = '订单取消';
        } else {
          statusText = '订单完成';
        }
      } else if (row.businessType == 'DJK') {
        statusText = DJKOrderStatus[statusKey as keyof typeof DJKOrderStatus] || '未知状态';
      } else {
        statusText = orderStatus[statusKey] || '未知状态';
      }
      return <NTag>{statusText}</NTag>;
    }
  },
  {
    key: 'createTime',
    title: '下单时间',
    align: 'center',
    width: 180,
    render: row => {
      return <div>{row.createTime?.replace('T', '  ')}</div>;
    }
  }
];

const [registerTable, { refresh, getSeachForm, getTableData, setFieldsValue }] = useTable({
  searchFormConfig: {
    schemas: [...getSearchForm()]
  },
  tableConfig: {
    keyField: 'id',
    title: '',
    showAddButton: false,
    showTableHeaderAction: true,
    fieldMapToTime: [['createTime', ['startTime', 'endTime']]]
  }
});

const [registerLogTable, { refresh: refresh1, setTableLoading }] = useTable({
  tableConfig: {
    keyField: 'id',
    title: '',
    showAddButton: false,
    showTableHeaderAction: true,
    showSearch: false,
    minHeight: 400
  }
});

const exportColumns: NaiveUI.TableColumn<InternalRowData>[] = [
  {
    key: 'index',
    title: '序号',
    align: 'center',
    width: 100,
    render(_, rowIndex) {
      return rowIndex + 1;
    }
  },
  {
    key: 'taskName',
    title: '任务名称',
    align: 'center',
    minWidth: 100
  },
  {
    key: 'createTime',
    title: '时间',
    align: 'center'
  },
  {
    key: 'operatorAccount',
    title: '操作人',
    align: 'center',
    minWidth: 100
  },
  {
    key: 'status',
    title: '状态',
    align: 'center',
    minWidth: 100,
    render: row => {
      if (row.status == 0) {
        return (
          <div>
            请耐心等待，正在导出中...
            <n-button text type="info" onClick={() => handleBreak(row.id as string)}>
              中断
            </n-button>
          </div>
        );
      } else if (!row.fileUrl) {
        return <div>导出失败</div>;
      } else if (row.status == 1) {
        return (
          <div>
            完成 {row.fileSize}
            <n-button text type="info" onClick={() => handleDownload(row.fileUrl as string)}>
              下载
            </n-button>
          </div>
        );
      }
      // else if (row.exportStatus == 2) {
      //   return <div class={'text-gray-500'}>生成文件失败</div>;
      // } else if (row.exportStatus == 3) {
      //   return (
      //     <div>
      //       已下载&nbsp;
      //       <n-button text type="info" onClick={() => handleDownload(row.id as string)}>
      //         下载
      //       </n-button>
      //     </div>
      //   );
      // }

      return <div>进行中</div>;
    }
  }
];

async function handleDownload(fileUrl: string) {
  // setTableLoading(true);
  window.open(fileUrl);
  // await commonExport('/platform/exportTask/download', { fileId: id }, '正常订单列表.xlsx');
  refresh1();
}
async function handleBreak(id: string) {
  setTableLoading(true);
  await fetchBreakDownload(id);
  refresh1();
}

const [registerModalPrice, { openModal }] = useModal({
  title: '导出记录',
  width: 1200,
  height: 600,
  showFooter: false
});

const dialog = useDialog();

// async function handleDeivery(row: Api.delivery.deliveryOrder) {
//   if (!row.orderNumber) {
//     window.$message?.error('订单异常');
//     return;
//   }
//   ShipmentModal.value?.handleOpenOrder(row.orderNumber);
// }

function handleOrderDetail(row: Api.delivery.deliveryOrder) {
  if (!row.orderNumber) {
    window.$message?.error('订单异常');
  }
  router.push({
    path: '/order-manage/order-detail',
    query: {
      orderNumber: row.orderNumber
    }
  });
  // orderMoadl.value?.open(String(row.orderNumber));
}

function handleSaleOrder(row: Api.delivery.deliveryOrder) {
  if (!row.orderNumber) {
    window.$message?.error('订单异常');
  }
  router.push({
    path: '/order-manage/after-sales-order',
    query: {
      orderNumber: row.orderNumber
    }
  });
}

// async function handleAudit(row: any) {
//   window.$dialog?.info({
//     title: '提示',
//     content: `此操作将核销该订单，且无法撤销，确定要核销吗？`,
//     positiveText: '确定',
//     negativeText: '取消',
//     onPositiveClick: async () => {
//       const { error } = await fetchAudit({ orderNumber: row.orderNumber });
//       if (!error) {
//         refresh();
//       }
//     }
//   });
// }
async function getNums() {
  const form = getSeachForm();
  const params = {
    ...form,
    channelIdList: channelIdList.value,
    startTime: form?.createTime && form.createTime[0],
    endTime: form?.createTime && form.createTime[1],
    createTime: null
  };
  const { data: keyData } = await fetchGetDeliveryStatusNum(params);
  if (!keyData) return;
  const orderStatusList = [
    {
      label: '全部',
      value: 'all'
    },
    {
      label: '待支付',
      value: 'paddingPay'
    },
    {
      label: '进行中',
      value: 'ing'
    },
    {
      label: '已完成',
      value: 'completed'
    },
    {
      label: '已取消',
      value: 'cancel'
    }
  ];
  const updatedOrderStatusList = orderStatusList.map(item => {
    const key = item.value as keyof typeof keyData;
    if (Object.hasOwn(keyData, key)) {
      return {
        ...item,
        num: keyData[key]
      };
    }
    return item;
  });
  // console.log(updatedOrderStatusList, 'updatedOrderStatusList');
  statusList.value = updatedOrderStatusList;
}

getNums();

// async function handleCopy(row: Api.delivery.deliveryOrder, key: string) {
//   if (!row[key]) {
//     window.$message?.error('订单编号不存在');
//     return;
//   }
//   await copyTextToClipboard(row[key]);
// }

async function handleExport(exportType: any) {
  setTableLoading(true);
  try {
    // await commonExport(
    //   '/platform/order/export',
    //   { ...getFieldsValue(), orderStatus: activeTab.value },
    //   '正常订单列表.xlsx'
    // );
    await fetchExportOrderList({ exportType, ...getSeachForm(), orderStatus: activeTab.value });
    dialog.success({
      title: '提示',
      content: () => {
        return (
          <div>
            <p>导出操作进行中......</p>
            <p>是否进入导出记录</p>
          </div>
        );
      },
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: () => {
        openModal();
      },
      onNegativeClick: () => {}
    });
  } finally {
    setTableLoading(false);
  }
}

async function handleExportLog() {
  setTableLoading(true);
  try {
    openModal();
  } finally {
    setTableLoading(false);
  }
}
watch(
  () => [activeTab.value],
  () => {
    nextTick(() => {
      refresh();
    });
  }
);
onMounted(async () => {
  await setFieldsValue({ orderNumber });
  refresh();
});

function getData() {
  return getTableData() || [];
}

function handleSelect(key: string) {
  console.log(key);

  if (key === 'goods') {
    handleExport('PRODUCT');
  } else if (key === 'order') {
    handleExport('ORDER');
  }
}

function handleship(row: Api.delivery.deliveryOrder) {
  if (!row.orderNumber) {
    window.$message?.error('订单异常');
  }
  router.push({
    path: '/order-manage/order-detail',
    query: {
      orderNumber: row.orderNumber,
      type: 'ship'
    }
  });
}
</script>

<template>
  <LayoutTable>
    <ZTable
      :columns="columns"
      :api="fetchGetDeliveryOrderList"
      :immediate="false"
      :default-params="{ orderStatus: activeTab }"
      @register="registerTable"
      @search="getNums"
    >
      <template #op="{ row }">
        <div>
          <NButton size="small" type="primary" ghost @click="handleOrderDetail(row)">订单详情</NButton>
          <NButton
            v-if="row.backendOrderRefundButton"
            class="mt-10px"
            size="small"
            type="primary"
            ghost
            @click="handleSaleOrder(row)"
          >
            售后订单
          </NButton>

          <NButton
            v-if="row.dvyType === 10 && row.hbOrderStatus === 40 && !row.dvyNo"
            class="mt-10px"
            size="small"
            type="primary"
            ghost
            @click="handleship(row)"
          >
            发货
          </NButton>
          <NButton
            v-if="row.dvyType === 10 && (row.hbOrderStatus === 40 || row.hbOrderStatus === 70) && row.dvyNo"
            class="mt-10px"
            size="small"
            type="primary"
            ghost
            @click="handleship(row)"
          >
            修改发货信息
          </NButton>
        </div>
        <!--
 <NButton
          v-if="row.businessType === 'DJK' && row.isWriteOff == 1 && row.hbOrderStatus != 80"
          size="small"
          type="primary"
          ghost
          @click="handleAudit(row)"
        >
          核销
        </NButton>
-->
      </template>
      <template #header>
        <div class="flex items-center">
          <NScrollbar x-scrollable>
            <div class="flex items-center">
              <div class="max-w-800px">
                <NTabs v-model:value="activeTab" type="line" animated display-directive="show">
                  <NTab
                    v-for="item in statusList"
                    :key="item.value"
                    :name="item.value"
                    :tab="`${item.label}(${item.num})`"
                  ></NTab>
                </NTabs>
              </div>
            </div>
          </NScrollbar>
        </div>
      </template>
      <template #prefix="{ loading }">
        <div class="flex items-center">
          <NDropdown trigger="click" :options="options" @select="handleSelect">
            <NButton size="small" type="primary" ghost :loading="loading" :disabled="getData().length === 0">
              <template #icon>
                <SvgIcon icon="mingcute:file-export-line"></SvgIcon>
              </template>
              导出
            </NButton>
          </NDropdown>

          <NButton size="small" type="primary" class="ml10px" ghost :loading="loading" @click="handleExportLog">
            导出记录
          </NButton>
        </div>
      </template>
    </ZTable>
    <BasicModal @register="registerModalPrice" @after-leave="refresh">
      <LayoutTable>
        <ZTable
          :show-table-action="false"
          :columns="exportColumns"
          :api="fetchExportList"
          @register="registerLogTable"
        ></ZTable>
      </LayoutTable>
    </BasicModal>
  </LayoutTable>
</template>

<style scoped></style>
