<script setup lang="tsx">
import { nextTick, ref, watch } from 'vue';
import { useRouter } from 'vue-router';
import { NTag } from 'naive-ui';
import { fetchAudit, fetchGetOrderList, fetchGetStatusNum } from '@/service/api/djk-manage/normal-order';
// import { fetchGetLoginUserList } from '@/service/api/common';
// import { useAuth } from '@/hooks/business/auth';
// import { copyTextToClipboard } from '@/utils/zt';
import { useTable } from '@/components/zt/Table/hooks/useTable';
// import { type } from '../../../../packages/axios/src/index';
import { DJKOrderStatus, SearchForm } from './normal-order';
const router = useRouter();
const activeTab = ref('all');
const statusList = ref<{ label: string; value: string; num?: number }[]>([]);
// const ShipmentModal = useTemplateRef('Shipment');
const channelIdList = ref([]);
const loading = ref(false);
const columns: NaiveUI.TableColumn<Api.delivery.deliveryOrder>[] = [
  {
    key: 'shopName',
    title: '门店名称',
    align: 'center',
    width: 220
  },
  {
    key: 'orderNumber',
    title: '订单编号',
    align: 'center'
  },
  {
    key: 'consigneeMobile',
    title: '客户手机号',
    align: 'center'
  },
  {
    key: 'activityName',
    title: '活动名称',
    align: 'center'
  },
  {
    key: 'goodsName',
    title: '商品名称',
    align: 'center'
  },
  {
    key: 'actualTotal',
    title: '金额',
    align: 'center',
    render: row => {
      return <div>￥{row.actualTotal}</div>;
    }
  },
  {
    key: 'hbOrderStatus',
    title: '订单状态',
    align: 'center',
    width: 120,
    render: row => {
      const statusKey = row.hbOrderStatus as keyof typeof DJKOrderStatus;
      const statusText = DJKOrderStatus[statusKey as keyof typeof DJKOrderStatus] || '未知状态';
      return <NTag>{statusText}</NTag>;
    }
  }
];

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

// 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));
}

async function handleAudit(row: any) {
  window.$dialog?.info({
    title: '提示',
    content: `此操作将核销该订单，且无法撤销，确定要核销吗？`,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      if (loading.value) return;
      loading.value = true;
      const { error } = await fetchAudit({ orderNumber: row.orderNumber });
      loading.value = false;
      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 fetchGetStatusNum(params);
  if (!keyData) return;
  const orderStatusList = [
    {
      label: '全部',
      value: 'all'
    },
    {
      label: '待支付',
      value: 'paddingPay'
    },
    {
      label: '待使用',
      value: 'pendingUse'
    },
    {
      label: '已核销',
      value: 'verification'
    },
    {
      label: '已退款',
      value: 'refunded'
    },
    {
      label: '已过期',
      value: 'expire'
    },
    {
      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() {
//   setTableLoading(true);
//   try {
//     // await commonExport(
//     //   '/platform/order/export',
//     //   { ...getFieldsValue(), orderStatus: activeTab.value },
//     //   '正常订单列表.xlsx'
//     // );
//     await fetchExportOrderList({ ...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();
    });
  }
);
</script>

<template>
  <LayoutTable>
    <ZTable
      :columns="columns"
      :api="fetchGetOrderList"
      :default-params="{ orderStatus: activeTab }"
      @register="registerTable"
    >
      <template #op="{ row }">
        <NButton size="small" type="primary" ghost @click="handleOrderDetail(row)">订单详情</NButton>
        <NButton v-if="row.hbOrderStatus == 20" 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>
    </ZTable>
  </LayoutTable>
</template>

<style scoped></style>
