<template>
  <a-space>
    <a-button @click="add" type="primary">添加字段</a-button>
    <a-button type="dashed" :disabled="!hasRole('superAdmin')" @click="handleExport">备份</a-button>
    <a-button type="dashed" :disabled="!hasRole('superAdmin')"  @click="openImport">恢复</a-button>
    <a-input-search
      allow-clear
      placeholder="请输入关键词"
      style="width: 280px"
      v-model:value="where.keywords"
      @search="reload"
    />
  </a-space>
  <!-- 导入弹窗 -->
  <import v-model:visible="showImport" @done="reload"/>
</template>

<script lang="ts" setup>
import {ref} from 'vue';
import {CmsWebsiteField, CmsWebsiteFieldParam} from "@/api/cms/cmsWebsiteField/model";
import useSearch from "@/utils/use-search";
import {hasRole} from "@/utils/permission";
import {utils, writeFile} from 'xlsx';
import {message} from 'ant-design-vue';
import Import from "./Import.vue";
import {listCmsWebsiteField} from "@/api/cms/cmsWebsiteField";
import {getTenantId} from "@/utils/domain";


// 是否显示导入弹窗
const showImport = ref(false);
const loading = ref(false);
const xlsFileName = ref<string>();
const fields = ref<CmsWebsiteField[]>([]);

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

const add = () => {
  emit('add');
};

// 表单数据
const {where} = useSearch<CmsWebsiteFieldParam>({
  keywords: ''
});

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

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


// 导出
const handleExport = async () => {
  loading.value = true;
  const array: (string | number)[][] = [
    [
      '类型',
      '名称',
      '值',
      '加密',
      '备注'
    ]
  ];

  // 按搜索结果导出
  await listCmsWebsiteField(where)
    .then((list) => {
      fields.value = list;
      list?.forEach((d: CmsWebsiteField) => {
        array.push([
          `${d.type}`,
          `${d.name}`,
          `${d.value}`,
          `${d.encrypted ? '1' : '0'}`,
          `${d.comments}`
        ]);
      });
      const sheetName = `bak_config_${getTenantId()}`;
      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(() => {
    });

};
</script>
