<template>
  <div class="flex items-center gap-20">
    <!-- 搜索表单 -->
    <a-form
      :model="where"
      layout="inline"
      class="search-form"
      @finish="handleSearch"
    >
      <a-form-item>
        <a-space>
          <a-button
            danger
            class="ele-btn-icon"
            v-if="selection.length > 0"
            :disabled="selection?.length === 0"
            @click="removeBatch"
          >
            <template #icon>
              <DeleteOutlined />
            </template>
            <span>批量删除</span>
          </a-button>
        </a-space>
      </a-form-item>

      <a-form-item>
        <a-space>
          <a-input-search
            allow-clear
            placeholder="请输入用户ID"
            style="width: 240px"
            v-model:value="where.keywords"
            @search="handleSearch"
          />
          <a-button type="dashed" @click="handleExport">导出xls</a-button>
          <a-button @click="resetSearch"> 重置 </a-button>
        </a-space>
      </a-form-item>
    </a-form>
  </div>

  <!-- 导入弹窗 -->
  <Import v-model:visible="showImport" @done="emit('importDone')" />
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import { DeleteOutlined } from '@ant-design/icons-vue';
  import { message } from 'ant-design-vue';
  import { utils, writeFile } from 'xlsx';
  import Import from './Import.vue';
  import useSearch from '@/utils/use-search';
  import { getTenantId } from '@/utils/domain';
  import { pageShopDealerWithdraw } from '@/api/shop/shopDealerWithdraw';
  import type {
    ShopDealerWithdraw,
    ShopDealerWithdrawParam
  } from '@/api/shop/shopDealerWithdraw/model';

  withDefaults(
    defineProps<{
      // 选中的数据
      selection?: any[];
    }>(),
    {
      selection: () => []
    }
  );

  const emit = defineEmits<{
    (e: 'search', where?: ShopDealerWithdrawParam): void;
    (e: 'batchSettle'): void;
    (e: 'export'): void;
    (e: 'importDone'): void;
    (e: 'remove'): void;
  }>();

  // 是否显示导入弹窗
  const showImport = ref(false);

  // 搜索表单
  const { where, resetFields } = useSearch<ShopDealerWithdrawParam>({
    keywords: '',
    page: 1,
    limit: 5000
  });

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

  // 搜索
  const handleSearch = () => {
    const searchParams = { ...where };
    // 清除空值
    Object.keys(searchParams).forEach((key) => {
      if (searchParams[key] === '' || searchParams[key] === undefined) {
        delete searchParams[key];
      }
    });
    emit('search', searchParams);
  };

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

  const toApplyStatus = (val: unknown) => {
    const n = Number(val);
    if (n === 10) return '待审核';
    if (n === 20) return '审核通过';
    if (n === 30) return '驳回/取消';
    if (n === 40) return '已打款';
    return '';
  };

  const toPayType = (val: unknown) => {
    const n = Number(val);
    if (n === 10) return '微信/商家转账';
    if (n === 20) return '支付宝';
    if (n === 30) return '银行卡';
    return '';
  };

  // 导出
  const handleExport = async () => {
    const array: (string | number)[][] = [
      [
        '订单号',
        '用户',
        '手机号',
        '提现金额',
        '打款方式',
        '申请状态',
        '审核/打款时间',
        '创建时间',
        '备注',
        '租户ID'
      ]
    ];

    const params = { ...where };
    // 清除空值，避免把空字符串传给后端
    Object.keys(params).forEach((key) => {
      if (params[key] === '' || params[key] === undefined) {
        delete params[key];
      }
    });
    params.page = 1;
    params.limit = 5000;

    await pageShopDealerWithdraw(params)
      .then((data) => {
        list.value = data?.list || [];
        list.value.forEach((d: ShopDealerWithdraw) => {
          array.push([
            d.id ?? '',
            `${d.realName || d.nickname || '-'}(${d.userId ?? '-'})`,
            d.phone ?? '',
            toMoney(d.money),
            toPayType(d.payType),
            toApplyStatus(d.applyStatus),
            d.auditTime ?? '',
            d.createTime ?? '',
            d.comments ?? '',
            d.tenantId ?? ''
          ]);
        });

        const sheetName = `bak_shop_dealer_withdraw_${getTenantId()}`;
        const workbook = { SheetNames: [sheetName], Sheets: {} as any };
        const sheet = utils.aoa_to_sheet(array);
        workbook.Sheets[sheetName] = sheet;
        sheet['!cols'] = [
          { wch: 10 },
          { wch: 20 },
          { wch: 14 },
          { wch: 12 },
          { wch: 14 },
          { wch: 12 },
          { wch: 20 },
          { wch: 20 },
          { wch: 24 },
          { wch: 10 }
        ];

        message.loading('正在导出...', 0);
        setTimeout(() => {
          writeFile(workbook, `${sheetName}.xlsx`);
          message.destroy();
        }, 1000);
      })
      .catch((e: any) => {
        message.destroy();
        message.error(e?.message ?? String(e));
      });
  };

  // 重置搜索
  const resetSearch = () => {
    resetFields();
    emit('search', {});
  };

  // 批量删除
  const removeBatch = () => {
    emit('remove');
  };
</script>
