<!-- 搜索表单 -->
<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-button
      danger
      v-if="hasRole('superAdmin')"
      type="primary"
      class="ele-btn-icon"
      :disabled="selection?.length === 0"
      @click="removeBatch"
    >
      <template #icon>
        <DeleteOutlined />
      </template>
      <span>批量删除</span>
    </a-button>
    <DictSelect
      dict-code="Type"
      :width="200"
      :show-search="true"
      placeholder="项目类型"
      v-model:value="where.type"
      @done="chooseType"
    />
    <a-date-picker
      v-model:value="where.itemYear"
      value-format="YYYY"
      picker="year"
      @change="onYear"
    />
    <a-input-search
      allow-clear
      placeholder="请输入关键词"
      v-model:value="where.keywords"
      @pressEnter="search"
      @search="search"
    />
    <a-button @click="reset">重置</a-button>
    <div
      class="border-blue-400 text-blue-400 rounded border border-solid py-1 px-2 text-sm cursor-pointer"
      type="text"
      v-if="hasRole('superAdmin')"
      @click="handleExport"
      >导出xls</div
    >
    <div
      class="border-green-600 text-green-600 rounded border border-solid py-1 px-2 text-sm cursor-pointer"
      type="text"
      v-if="hasRole('superAdmin')"
      @click="openImport"
      >导入xls</div
    >
  </a-space>

  <!-- 导入弹窗 -->
  <Import v-model:visible="showImport" @done="search" />
</template>

<script lang="ts" setup>
  import { DeleteOutlined, PlusOutlined } from '@ant-design/icons-vue';
  import type { GradeParam } from '@/api/user/grade/model';
  import { watch, ref } from 'vue';
  import { hasRole } from '@/utils/permission';
  import dayjs from 'dayjs';
  import { message } from 'ant-design-vue';
  import { utils, writeFile } from 'xlsx';
  import { PwlProject, PwlProjectParam } from '@/api/pwl/pwlProject/model';
  import useSearch from '@/utils/use-search';
  import { listPwlProject } from '@/api/pwl/pwlProject';
  import Import from './Import.vue';
  import DictSelect from '@/components/DictSelect/index.vue';

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

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

  // 新增
  const add = () => {
    emit('add');
  };
  // 日期范围选择
  const dateRange = ref<[string, string]>(['', '']);
  const loading = ref(false);
  const projectList = ref<PwlProject[]>([]);
  const xlsFileName = ref<string>();
  // 是否显示用户导入弹窗
  const showImport = ref(false);
  // 表单数据
  const { where, resetFields } = useSearch<PwlProjectParam>({
    id: undefined,
    type: undefined,
    itemYear: undefined,
    keywords: undefined
  });

  /* 打开编辑弹窗 */
  const openImport = () => {
    showImport.value = true;
  };

  const chooseType = (e) => {
    console.log(e, 'yyyy');
    where.type = e.label;
    search();
  };

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

  const onYear = (date: any, dateString: string) => {
    where.itemYear = dateString;
    search();
  };

  /* 搜索 */
  const search = () => {
    const [d1, d2] = dateRange.value ?? [];
    emit('search', {
      ...where,
      createTimeStart: d1 ? d1 + ' 00:00:00' : '',
      createTimeEnd: d2 ? d2 + ' 23:59:59' : ''
    });
  };

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

  // 导出
  const handleExport = async () => {
    loading.value = true;
    const array: (string | number)[][] = [
      [
        '报告时间',
        '审计单位',
        '项目名称',
        '项目信息-开票单位/汇款人',
        '项目信息-所属年度',
        '项目信息-类型',
        '项目信息-审计意见',
        '年末资产总额(万元)',
        '合同金额',
        '实收金额',
        '到账信息-银行',
        '到账信息-日期',
        '到账信息-金额',
        '开票信息-日期',
        '开票信息-金额',
        '开票信息-发票类型',
        '报告份数',
        '底稿人员',
        '参与人员',
        '签字注会',
        '展业人员',
        '底稿情况'
      ]
    ];

    // 按搜索结果导出
    where.sceneType = 'Content';
    await listPwlProject(where)
      .then((list) => {
        projectList.value = list;
        list?.forEach((d: PwlProject) => {
          array.push([
            `${d.expirationTime || ''}`,
            `${d.name || ''}`,
            `${d.code || ''}`,
            `${d.itemName || ''}`,
            `${d.itemYear || ''}`,
            `${d.itemType || ''}`,
            `${d.itemOpinion || ''}`,
            `${d.totalAssets || ''}`,
            // `${d.comments || ''}`,
            `${d.contractPrice || ''}`,
            `${d.payPrice || ''}`,
            `${d.bankName || ''}`,
            `${d.bankPayTime || ''}`,
            `${d.bankPrice || ''}`,
            `${d.invoiceTime || ''}`,
            `${d.invoicePrice || ''}`,
            `${d.invoiceType || ''}`,
            `${d.reportNum || ''}`,
            `${d.draftUser ? JSON.parse(d.draftUser).join(',') : ''}`,
            `${d.users ? JSON.parse(d.users).join(',') : ''}`,
            `${d.signUser ? JSON.parse(d.signUser).join(',') : ''}`,
            `${d.saleUser ? JSON.parse(d.saleUser).join(',') : ''}`,
            `${d.files || ''}`
          ]);
        });
        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'] = [];
        message.loading('正在导出...');
        setTimeout(() => {
          writeFile(
            workbook,
            `${
              where.createTimeEnd ? xlsFileName.value + '_' : ''
            }${sheetName}.xlsx`
          );
          loading.value = false;
        }, 1000);
      })
      .catch((msg) => {
        message.error(msg);
        loading.value = false;
      })
      .finally(() => {});
  };

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