<!-- 搜索表单 -->
<template>
  <div class="search">
    <a-space class="flex items-center" :size="10" style="flex-wrap: wrap">
      <span class="text-gray-400">付款状态</span>
      <a-radio-group v-model:value="where.payStatus" @change="search">
        <a-radio-button :value="1">已付款</a-radio-button>
        <a-radio-button :value="2">未付款</a-radio-button>
      </a-radio-group>
      <span class="text-gray-400">订单状态</span>
      <a-radio-group v-model:value="where.orderStatus" @change="search">
        <a-radio-button :value="1">已完成</a-radio-button>
        <a-radio-button :value="2">未使用</a-radio-button>
        <a-radio-button :value="3">已取消</a-radio-button>
        <a-radio-button :value="4">退款中</a-radio-button>
        <a-radio-button :value="5">退款被拒</a-radio-button>
        <a-radio-button :value="6">退款成功</a-radio-button>
      </a-radio-group>
      <span class="text-gray-400">开票状态</span>
      <a-radio-group v-model:value="where.isInvoice" @change="search">
        <a-radio-button :value="1">已开票</a-radio-button>
        <a-radio-button :value="2">未开票</a-radio-button>
        <a-radio-button :value="3">不能开票</a-radio-button>
      </a-radio-group>
      <span class="text-gray-400">付款方式</span>
      <a-radio-group v-model:value="where.payType" @change="search">
        <a-radio-button :value="1">微信支付</a-radio-button>
        <a-radio-button :value="2">余额支付</a-radio-button>
        <a-radio-button :value="3">支付宝</a-radio-button>
        <a-radio-button :value="4">现金</a-radio-button>
        <a-radio-button :value="5">POS机</a-radio-button>
        <a-radio-button :value="6">VIP月卡</a-radio-button>
        <a-radio-button :value="7">VIP年卡</a-radio-button>
        <a-radio-button :value="8">VIP次卡</a-radio-button>
        <a-radio-button :value="9">IC月卡</a-radio-button>
        <a-radio-button :value="10">IC年卡</a-radio-button>
        <a-radio-button :value="11">IC次卡</a-radio-button>
        <a-radio-button :value="12">免费</a-radio-button>
        <a-radio-button :value="13">VIP充值卡</a-radio-button>
        <a-radio-button :value="14">IC充值卡</a-radio-button>
        <a-radio-button :value="15">积分支付</a-radio-button>
        <a-radio-button :value="16">VIP季卡</a-radio-button>
        <a-radio-button :value="17">IC季卡</a-radio-button>
      </a-radio-group>
    </a-space>
    <a-space :size="10" class="mt-5" style="flex-wrap: wrap">
      <ThinkSelectSite
        :placeholder="`选择场馆`"
        class="input-item"
        v-model:value="where.siteName"
        @done="chooseSiteId"
      />
      <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-button class="ele-btn-icon" :disabled="loading" @click="handleExport">
        <template #icon>
          <download-outlined />
        </template>
        <span>导出订单</span>
      </a-button>
    </a-space>
  </div>
</template>

<script lang="ts" setup>
  import useSearch from '@/utils/use-search';
  import { ref, watch } from 'vue';
  import { ThinkOrderInfoParam } from '@/api/think/thinkOrderInfo/model';
  import { utils, writeFile } from 'xlsx';
  import { message } from 'ant-design-vue';
  import { toDateString } from 'ele-admin-pro';
  import dayjs from 'dayjs';
  import { listThinkOrder } from '@/api/think/thinkOrder';
  import { ThinkOrder, ThinkOrderParam } from '@/api/think/thinkOrder/model';
  import { ThinkSite } from '@/api/think/thinkSite/model';

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

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

  // 表单数据
  const { where, resetFields } = useSearch<ThinkOrderParam>({
    sid: undefined,
    siteName: undefined,
    createTimeStart: undefined,
    createTimeEnd: undefined,
    timeStart: undefined,
    timeEnd: undefined,
    categoryId: undefined,
    keywords: undefined
  });
  // 请求状态
  const loading = ref(false);
  // 日期范围选择
  const dateRange = ref<[string, string]>(['', '']);
  const orders = ref<ThinkOrder[] | any[]>();
  const xlsFileName = ref<string>();

  /* 搜索 */
  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;
    // where.createTimeStart = d1 ? d1 + ' 00:00:00' : undefined;
    // where.createTimeEnd = d2 ? d2 + ' 00:00:00' : undefined;
    emit('search', {
      ...where
    });
  };

  const chooseSiteId = (data: ThinkSite) => {
    where.sid = data.id;
    where.siteName = data.name;
    search();
  };

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

  // 导出
  const handleExport = async () => {
    loading.value = true;
    const array: (string | number)[][] = [
      [
        '订单号',
        '订单编号',
        '姓名',
        '电话号码',
        '预定信息',
        '消费金额',
        '实付金额',
        '下单日期'
      ]
    ];
    if (!where.timeStart) {
      message.error('请选择导出的开始日期、结束日期，每次最多导出5000条记录');
      return false;
    }
    await listThinkOrder(where)
      .then((list) => {
        orders.value = list;
        orders.value?.forEach((d: ThinkOrder) => {
          array.push([
            `${d.id}`,
            `${d.orderNum}`,
            `${d.name}`,
            `${d.phone}`,
            `${d.siteName} ${d.dateTime} ${d.totalPrice}`,
            `${d.totalPrice}`,
            `${d.payPrice}`,
            `${toDateString(d.payTime)}`
          ]);
        });
        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>
