<!-- 搜索表单 -->
<template>
  <a-space :size="10" style="flex-wrap: wrap">
    <!--    <a-button type="primary" class="ele-btn-icon" @click="add">-->
    <!--      <template #icon>-->
    <!--        <PlusOutlined />-->
    <!--      </template>-->
    <!--      <span>添加</span>-->
    <!--    </a-button>-->
    <a-range-picker
      v-model:value="dateRange"
      @change="search"
      value-format="YYYY-MM-DD"
      class="ele-fluid"
    />
    <a-input-search
      allow-clear
      placeholder="请输入关键词"
      v-model:value="where.keywords"
      @pressEnter="search"
      @search="search"
      style="width: 380px"
    />
    <a-button @click="reset">重置</a-button>
  </a-space>
</template>

<script lang="ts" setup>
  import { PlusOutlined } from '@ant-design/icons-vue';
  import { watch, ref } from 'vue';
  import useSearch from '@/utils/use-search';
  import dayjs from 'dayjs';
  import { toDateString } from 'ele-admin-pro';
  import { utils, writeFile } from 'xlsx';
  import { message } from 'ant-design-vue';
  import {
    ThinkCardLog,
    ThinkCardLogParam
  } from '@/api/think/thinkCardLog/model';
  import { listThinkCardLog } from '@/api/think/thinkCardLog';

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

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

  // 请求状态
  const loading = ref(false);
  // 日期范围选择
  const dateRange = ref<[string, string]>(['', '']);
  const orders = ref<ThinkCardLog[] | any[]>();
  const xlsFileName = ref<string>();
  const payType = ref<string[]>([
    '',
    '微信支付',
    '支付宝支付',
    '现金支付',
    'POS机支付'
  ]);

  // 表单数据
  const { where, resetFields } = useSearch<ThinkCardLogParam>({
    code: undefined,
    timeStart: undefined,
    timeEnd: undefined,
    keywords: undefined
  });

  // 新增
  const add = () => {
    emit('add');
  };

  const search = () => {
    const [d1, d2] = dateRange.value ?? [];
    xlsFileName.value = `${d1}至${d2}`;
    where.timeStart = d1 ? dayjs(d1).valueOf() / 1000 : undefined;
    where.timeEnd = d2 ? dayjs(d2).valueOf() / 1000 : undefined;
    emit('search', {
      ...where
    });
  };

  /*  重置 */
  const reset = () => {
    resetFields();
    search();
  };

  // 导出
  const handleExport = async () => {
    loading.value = true;
    const array: (string | number)[][] = [
      [
        '卡号',
        '姓名',
        '手机号',
        '会员卡名称',
        '支付方式',
        '充值金额',
        '充值次数',
        '操作员',
        '第三方订单号',
        '充值时间'
      ]
    ];
    if (!where.timeStart) {
      message.error('请选择导出的开始日期、结束日期，每次最多导出5000条记录');
      return false;
    }
    await listThinkCardLog(where)
      .then((list) => {
        orders.value = list;
        orders.value?.forEach((d: ThinkCardLog) => {
          array.push([
            `${d.code}`,
            `${d.username}`,
            `${d.phone}`,
            `${d.cardName}`,
            `${payType.value[Number(d.payType)]}`,
            `${d.money}`,
            `${d.count}`,
            `${d.adminName || d.aid}`,
            `${d.wechatOrder}`,
            `${toDateString(d.createTime)}`
          ]);
        });
        const sheetName = `充值记录导出`;
        const workbook = {
          SheetNames: [sheetName],
          Sheets: {}
        };
        const sheet = utils.aoa_to_sheet(array);
        workbook.Sheets[sheetName] = sheet;
        // 设置列宽
        sheet['!cols'] = [
          { wch: 10 },
          { wch: 10 },
          { wch: 10 },
          { wch: 10 },
          { wch: 20 },
          { wch: 40 },
          { wch: 10 }
        ];
        message.loading('正在导出...');
        setTimeout(() => {
          writeFile(
            workbook,
            `${
              where.createTimeEnd ? xlsFileName.value + '_' : ''
            }${sheetName}.xlsx`
          );
          loading.value = false;
        }, 2000);
      })
      .catch((msg) => {
        message.error(msg);
        loading.value = false;
      })
      .finally(() => {});
  };

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