<!-- 搜索表单 -->
<template>
  <a-space :size="10" style="flex-wrap: wrap">
    <a-tree-select
      allow-clear
      :tree-data="articles"
      tree-default-expand-all
      style="width: 280px"
      :listHeight="700"
      placeholder="按活动筛选"
      :value="where.formId || undefined"
      :dropdown-style="{ overflow: 'auto' }"
      @update:value="(value?: number) => (where.formId = value)"
      @change="onCategoryId"
    />
    <a-input-search
      allow-clear
      placeholder="请输入关键词"
      style="width: 280px"
      v-model:value="where.keywords"
      @search="reload"
    />
    <a-button type="text" @click="handleExport">导出</a-button>
  </a-space>
</template>

<script lang="ts" setup>
  import { ref, watch } from 'vue';
  import { utils, writeFile } from 'xlsx';
  import dayjs from 'dayjs';
  import { message } from 'ant-design-vue';
  import {AppBszxBm, AppBszxBmParam} from "@/api/app/appBszxBm/model";
  import useSearch from "@/utils/use-search";
  import {listAppBszxBm} from "@/api/app/appBszxBm";
  import {listCmsArticle} from "@/api/cms/cmsArticle";
  import {CmsArticle} from "@/api/cms/cmsArticle/model";

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

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

  // 表单数据
  const { where } = useSearch<AppBszxBmParam>({
    id: undefined,
    keywords: '',
    formId: undefined,
    userId: undefined
  });

  const articles = ref<CmsArticle[]>([]);

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

  // 变量
  const loading = ref(false);
  const bmList = ref<AppBszxBm[]>([])
  const xlsFileName = ref<string>();

  // 导出
  const handleExport = async () => {
    loading.value = true;
    const array: (string | number)[][] = [
      [
        '用户ID',
        '姓名',
        '性别',
        '手机号码',
        '班级',
        '年级',
        '居住地址',
        '工作单位',
        '职务',
        '是否能到场',
        '邀请函',
        '报名时间'
      ]
    ];

    // 按搜索结果导出
    where.sceneType = 'Content';
    await listAppBszxBm(where)
      .then((list) => {
        bmList.value = list;
        list?.forEach((d: AppBszxBm) => {
          array.push([
            `${d.userId}`,
            `${d.name}`,
            `${d.sex}`,
            `${d.phone}`,
            `${d.className}`,
            `${d.gradeName}`,
            `${d.address}`,
            `${d.workUnit}`,
            `${d.position}`,
            `${d.present}`,
            `${d.certificate}`,
            `${d.createTime}`
          ]);
        });
        const sheetName = `导出报名列表${dayjs(new Date()).format('YYYYMMDD')}`;
        const workbook = {
          SheetNames: [sheetName],
          Sheets: {}
        };
        const sheet = utils.aoa_to_sheet(array);
        workbook.Sheets[sheetName] = sheet;
        // 设置列宽
        sheet['!cols'] = [
          { wch: 10 },
          { wch: 40 },
          { wch: 20 },
          { wch: 20 },
          { wch: 60 },
          { wch: 15 },
          { wch: 10 },
          { wch: 10 },
          { wch: 20 },
          { wch: 10 },
          { wch: 20 }
        ];
        message.loading('正在导出...');
        setTimeout(() => {
          writeFile(
            workbook,
            `${
              where.createTimeEnd ? xlsFileName.value + '_' : ''
            }${sheetName}.xlsx`
          );
          loading.value = false;
        }, 1000);
      })
      .catch((msg) => {
        message.error(msg);
        loading.value = false;
      })
      .finally(() => {});

  };

  const query = () => {
    listCmsArticle({
      model: 'bm'
    }).then((res) => {
      articles.value = res.map(d => {
        d.value = d.articleId;
        d.label = d.title;
        return d;
      });
    })
  }

  // 按分类查询
  const onCategoryId = (id: number) => {
    where.formId = id;
    emit('search', where);
  };

  query();

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