<!-- 搜索表单 -->
<template>
  <a-space :size="10" style="flex-wrap: wrap">
    <a-input-search
      allow-clear
      placeholder="客户名称|订单编号"
      style="width: 240px"
      v-model:value="where.keywords"
      @search="reload"
    />
    <a-button type="dashed" @click="handleExport">导出xls</a-button>
  </a-space>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import { utils, writeFile } from 'xlsx';
  import { message } from 'ant-design-vue';
  import { getTenantId } from '@/utils/domain';
  import useSearch from '@/utils/use-search';
  import type {
    ShopDealerOrder,
    ShopDealerOrderParam
  } from '@/api/shop/shopDealerOrder/model';
  import { pageShopDealerOrder } from '@/api/shop/shopDealerOrder';

  const props = withDefaults(
    defineProps<{
      // 选中的角色
      selection?: [];
    }>(),
    {}
  );

  const emit = defineEmits<{
    (e: 'search', where?: ShopDealerOrderParam): void;
  }>();

  const reload = () => {
    emit('search', where);
  };

  // 表单数据
  const { where } = useSearch<ShopDealerOrderParam>({
    keywords: '',
    userId: undefined,
    orderNo: undefined,
    isSettled: 1, // 与列表页一致：只展示/导出已结算订单
    page: 1,
    limit: 5000
  });

  const list = ref<ShopDealerOrder[]>([]);

  const toMoney = (val: unknown) => {
    const n = Number.parseFloat(String(val ?? '0'));
    return Number.isFinite(n) ? n.toFixed(2) : '0.00';
  };

  const toDateTime = (val: unknown) => {
    if (val === null || val === undefined || val === '') return '';
    if (typeof val === 'number') return new Date(val).toLocaleString();
    return String(val);
  };

  // 导出
  const handleExport = async () => {
    const array: (string | number)[][] = [
      [
        // 与 `src/views/shop/shopDealerOrder/index.vue` 表头保持一致
        '订单编号',
        '买家',
        '订单金额',
        '一级佣金(10%)',
        '二级佣金(5%)',
        '一级门店分红(2%/3%)',
        '二级门店分红(1%)',
        '结算状态',
        '创建时间'
      ]
    ];

    // 按搜索结果导出
    await pageShopDealerOrder(where)
      .then((data) => {
        list.value = data?.list || [];
        list.value?.forEach((d: ShopDealerOrder) => {
          const buyer =
            (d.title ? String(d.title) : '') +
            (d.nickname || d.userId
              ? `\n${d.nickname ?? '-'}(${d.userId ?? '-'})`
              : '');

          const firstDividendUserName = (d as any)?.firstDividendUserName ?? '-';
          const firstDividend = (d as any)?.firstDividend ?? 0;
          const secondDividendUserName =
            (d as any)?.secondDividendUserName ?? '-';
          const secondDividend = (d as any)?.secondDividend ?? 0;

          array.push([
            d.orderNo ?? '',
            buyer,
            toMoney(d.orderPrice),
            `${toMoney(d.firstMoney)}\n${d.firstNickname ?? '-'}`,
            `${toMoney(d.secondMoney)}\n${d.secondNickname ?? '-'}`,
            `${toMoney(firstDividend)}\n${firstDividendUserName}`,
            `${toMoney(secondDividend)}\n${secondDividendUserName}`,
            d.isSettled === 1 ? '已结算' : '未结算',
            `${d.createTime ?? ''}${
              d.settleTime ? `\n${toDateTime(d.settleTime)}` : ''
            }`
          ]);
        });
        const sheetName = `bak_shop_dealer_order_${getTenantId()}`;
        const workbook = {
          SheetNames: [sheetName],
          Sheets: {}
        };
        const sheet = utils.aoa_to_sheet(array);
        workbook.Sheets[sheetName] = sheet;
        // 设置列宽
        sheet['!cols'] = [
          { wch: 20 },
          { wch: 20 },
          { wch: 12 },
          { wch: 16 },
          { wch: 16 },
          { wch: 18 },
          { wch: 16 },
          { wch: 10 },
          { wch: 20 }
        ];
        message.loading('正在导出...', 0);
        setTimeout(() => {
          writeFile(workbook, `${sheetName}.xlsx`);
          message.destroy();
        }, 1000);
      })
      .catch((msg) => {
        message.destroy();
        message.error(msg);
      })
      .finally(() => {});
  };

  void props;
</script>
