<!-- 搜索表单 -->
<template>
  <a-space :size="10" style="flex-wrap: wrap">
    <a-input-search
      allow-clear
      placeholder="用户ID|订单编号"
      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, watch } from 'vue';
  import { utils, writeFile } from 'xlsx';
  import { message } from 'ant-design-vue';
  import { pageShopDealerCapital } from '@/api/shop/shopDealerCapital';
  import {
    ShopDealerCapital,
    ShopDealerCapitalParam
  } from '@/api/shop/shopDealerCapital/model';
  import { getTenantId } from '@/utils/domain';
  import useSearch from '@/utils/use-search';

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

  const emit = defineEmits<{
    (e: 'search', where?: ShopDealerCapitalParam): void;
    (e: 'add'): void;
    (e: 'remove'): void;
    (e: 'batchMove'): void;
  }>();

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

  // 表单数据
  const { where } = useSearch<ShopDealerCapitalParam>({
    keywords: '',
    userId: undefined,
    toUserId: undefined,
    limit: 5000
  });

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

  // 导出
  const handleExport = async () => {
    const array: (string | number)[][] = [
      [
        '订单号',
        '用户',
        '收益类型',
        '金额',
        '描述',
        '创建时间',
        '租户ID'
      ]
    ];

    // 按搜索结果导出
    await pageShopDealerCapital(where)
      .then((data) => {
        list.value = data?.list || [];
        list.value?.forEach((d: ShopDealerCapital) => {
          array.push([
            `${d.orderNo}`,
            `${d.nickName}(${d.userId})`,
            `${d.flowType == 10 ? '佣金收入' : ''}`,
            `${d.money}`,
            `${d.comments}`,
            `${d.createTime}`,
            `${d.tenantId}`
          ]);
        });
        const sheetName = `bak_shop_dealer_capital_${getTenantId()}`;
        const workbook = {
          SheetNames: [sheetName],
          Sheets: {}
        };
        const sheet = utils.aoa_to_sheet(array);
        workbook.Sheets[sheetName] = sheet;
        // 设置列宽
        sheet['!cols'] = [
          { wch: 10 },
          { wch: 20 },
          { wch: 20 },
          { wch: 15 },
          { wch: 10 },
          { wch: 10 },
          { wch: 20 }
        ];
        message.loading('正在导出...');
        setTimeout(() => {
          writeFile(workbook, `${sheetName}.xlsx`);
        }, 1000);
      })
      .catch((msg) => {
        message.error(msg);
      })
      .finally(() => {});
  };

  watch(
    () => props.selection,
    () => {}
  );
</script>
