<script setup lang="tsx">
import { reactive, ref, unref, useTemplateRef, watch } from 'vue';
import { NImage, NTag } from 'naive-ui';
import { fetchGetDeliveryOrderList, fetchGetDeliveryStatusNum } from '@/service/api/delivery/normal-orde';
import { useAppStore } from '@/store/modules/app';
import { defaultTransform, useNaivePaginatedTable } from '@/hooks/common/table';
import { copyTextToClipboard } from '@/utils/zt';
import { $t } from '@/locales';
import { useForm } from '@/components/zt/Form/hooks/useForm';
import { SearchForm, orderStatus, orderStatusEnum, refundStatus } from './normal-order';
import DeliveryModal from './component/delivery-modal.vue';
import NormalMoadl from './component/normal-modal.vue';
const appStore = useAppStore();
const checkedRowKeys = ref([]);
const activeTab = ref('all');
const statusList = ref<{ label: string; value: string; num?: number }[]>([]);
const orderMoadl = useTemplateRef('orderMoadl');
const ShipmentModal = useTemplateRef('Shipment');

const [registerSearchForm, { getFieldsValue }] = useForm({
  schemas: SearchForm,
  showAdvancedButton: false,
  labelWidth: 120,
  layout: 'horizontal',
  gridProps: {
    cols: '1 xl:4 s:1 l:3',
    itemResponsive: true
  },
  collapsedRows: 1
});
const searchForm = ref();
const searchParams = reactive({
  current: 1,
  size: 10
});
const { columns, data, loading, getData, mobilePagination } = useNaivePaginatedTable({
  api: () => fetchGetDeliveryOrderList({ ...searchParams, orderStatus: activeTab.value, ...unref(searchForm) }),
  transform: response => defaultTransform(response),
  paginationProps: {
    pageSizes: [10, 20, 50, 100, 150, 200]
  },
  onPaginationParamsChange: params => {
    searchParams.current = Number(params.page);
    searchParams.size = Number(params.pageSize);
  },
  columns: () => [
    {
      key: 'orderItems',
      title: '商品',
      align: 'left',
      width: 200,
      colSpan: (_rowData, _rowIndex) => 2,
      render: row => {
        return (
          <div>
            <div class={'mb3 flex items-center'}>
              <n-tag>
                <div class={'flex items-center'}>
                  订单编号：{row.orderNumber}
                  <div onClick={() => handleCopy(row)}>
                    <svgIcon icon={'bxs:copy'} class={'mx-3 cursor-pointer text-[#f97316]'}></svgIcon>
                  </div>
                  下单时间：
                  {row.createTime} 门店名称 {row.shopName}
                </div>
              </n-tag>
            </div>
            {row.orderItems?.map(item => {
              return (
                <div class={'mb-3 h-80px flex items-center'}>
                  <NImage src={item.pic} class="h-[80px] min-w-80px w-[80px]" lazy />
                  <div class={'ml12px flex-1'}>
                    <div class={'w-full flex items-center justify-between'}>
                      <div class={'w200px'}>
                        <n-ellipsis class={'w200px'}>
                          <span class={'w-full text-left text-15px font-semibold'}>{item.skuName}</span>
                        </n-ellipsis>
                      </div>
                      <div class={'w150px pl30px text-left'}>
                        <div class={'text-16px font-semibold'}>￥{item.price} </div>
                      </div>
                    </div>
                    <div class={'w-full flex items-center justify-between'}>
                      <div class={'w200px text-gray'}>规格： {item.spec}</div>
                      <div class={'w150px pl30px text-left text-gray'}>x{item.prodCount} </div>
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        );
      }
    },
    {
      key: 'deptName',
      title: '单价(元)/数量',
      align: 'center',
      width: 100
    },
    {
      key: 'actualTotal',
      title: '实付金额(元)',
      align: 'center',
      width: 120,
      render: row => {
        return (
          <div class={'mt7'}>
            <div class={'text-16px text-#ff0000 font-semibold'}>{row.actualTotal} 元</div>
            <div>共 {row.goodsTotalCount} 件</div>
          </div>
        );
      }
    },
    {
      key: 'payType',
      title: '支付方式',
      align: 'center',
      width: 120,
      render: row => {
        return (
          <NTag class={'mt7'} type="success">
            {row.payType == 0 || row.payType == 1 ? '微信' : '未支付'}
          </NTag>
        );
      }
    },
    {
      key: 'seq',
      title: '买家/收货人',
      align: 'center',
      width: 120,
      render: row => {
        return (
          <div class={'mt7'}>
            <div>{row.receiver}</div>
            <div>{row.userMobile}</div>
          </div>
        );
      }
    },
    {
      key: 'status',
      title: '订单状态',
      align: 'center',
      width: 320,
      render: row => {
        const statusKey = row.hbOrderStatus as keyof typeof orderStatus;
        const statusText = orderStatus[statusKey] || '未知状态';
        return <NTag class={'mt7'}>{statusText}</NTag>;
      }
    },
    {
      key: 'createTime',
      title: '售后状态',
      align: 'center',
      width: 160,
      render: row => {
        const statusKey = row.refundStatus as keyof typeof refundStatus;
        const statusText = refundStatus[statusKey] || '暂无售后';
        return <NTag class={'mt7'}>{statusText}</NTag>;
      }
    },
    {
      key: 'operate',
      title: $t('common.operate'),
      align: 'center',
      width: 130,
      fixed: 'right',
      render: row => {
        return (
          <div class={'mt7'}>
            <n-button size="small" type="primary" quaternary onClick={() => handleOpenMoadl(row)}>
              查看订单
            </n-button>
            {(row.hbOrderStatus == orderStatusEnum.WAIT_DELIVERY ||
              row.hbOrderStatus == orderStatusEnum.ORDER_DELIVERY ||
              row.hbOrderStatus == orderStatusEnum.ORDER_DELIVERY) && (
              <n-button size="small" type="primary" quaternary onClick={() => handleDeivery(row)}>
                {row.dvyFlowId ? '修改物流' : '发货'}
              </n-button>
            )}
          </div>
        );
      }
    }
  ]
});
async function handleDeivery(row: Api.delivery.deliveryOrder) {
  if (!row.orderNumber) {
    window.$message?.error('订单异常');
    return;
  }
  ShipmentModal.value?.handleOpenOrder(row.orderNumber);
}
function handleOpenMoadl(row: Api.delivery.deliveryOrder) {
  if (!row.orderNumber) {
    window.$message?.error('订单异常');
    return;
  }
  orderMoadl.value?.open(String(row.orderNumber));
}
async function getNums() {
  const { data: keyData } = await fetchGetDeliveryStatusNum();
  if (!keyData) return;
  const orderStatusList = [
    {
      label: '全部',
      value: 'all'
    },
    {
      label: '待支付',
      value: 'paddingPay'
    },
    {
      label: '待发货',
      value: 'paddingShipped'
    },
    {
      label: '待收货',
      value: 'paddingReceived'
    },
    {
      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();
watch(
  () => [activeTab.value],
  () => {
    searchParams.current = 1;
    getData();
  }
);
function handleSearch() {
  const form = getFieldsValue();
  if (form.createTime) {
    form.startTime = form.createTime[0];
    form.endTime = form.createTime[1];
    delete form.createTime;
  }
  searchForm.value = form;
  getData();
}
function handleReset() {
  searchForm.value = getFieldsValue();
  getData();
}
async function handleCopy(row: Api.delivery.deliveryOrder) {
  if (!row.orderNumber) {
    window.$message?.error('订单编号不存在');
    return;
  }
  await copyTextToClipboard(row.orderNumber);
}
function handleRefsh() {
  getData();
  getNums();
}
</script>

<template>
  <div class="flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <NCard :bordered="false" size="small">
      <NCollapse display-directive="show">
        <NCollapseItem title="搜索">
          <BasicForm @register-form="registerSearchForm" @submit="handleSearch" @reset="handleReset" />
        </NCollapseItem>
      </NCollapse>
    </NCard>
    <NCard title="订单列表" :bordered="false" size="small" class="card-wrapper sm:flex-1-hidden">
      <NTabs v-model:value="activeTab" type="line" animated class="mb-16px h-full" display-directive="show">
        <NTabPane v-for="item in statusList" :key="item.value" :name="item.value" :tab="`${item.label}(${item.num})`">
          <NDataTable
            v-model:checked-row-keys="checkedRowKeys"
            :columns="columns"
            :data="data"
            size="small"
            :flex-height="!appStore.isMobile"
            :scroll-x="1800"
            :loading="loading"
            :row-key="row => row.orderId"
            remote
            class="sm:h-full"
            :pagination="mobilePagination"
          />
        </NTabPane>
      </NTabs>
      <NormalMoadl ref="orderMoadl" @finish="handleRefsh"></NormalMoadl>
      <DeliveryModal ref="Shipment" @finish="handleRefsh"></DeliveryModal>
    </NCard>
  </div>
</template>

<style scoped>
:deep(.n-tabs-pane-wrapper) {
  height: 100%;
}
:deep(.n-tab-pane) {
  height: 100%;
}
</style>
