<!-- 搜索表单 -->
<template>
  <a-space :size="10" style="flex-wrap: wrap">
    <a-button type="primary" class="ele-btn-icon" @click="emit('add')">
      <template #icon>
        <plus-outlined />
      </template>
      <span>新建</span>
    </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-button type="dashed" @click="openUrl('/website/model')"
      >模型管理
    </a-button>
    <a-divider type="vertical" />
    <a-radio-group v-model:value="position" @change="reload">
      <a-radio-button :value="1">顶部</a-radio-button>
      <a-radio-button :value="2">底部</a-radio-button>
      <a-radio-button :value="0">不限</a-radio-button>
    </a-radio-group>
    <a-divider type="vertical" />
    <a-select
      v-model:value="where.model"
      style="width: 150px"
      placeholder="选择模型"
      @change="reload"
    >
      <a-select-option value="">全部</a-select-option>
      <a-select-option :value="1">文章</a-select-option>
      <a-select-option :value="2">单页</a-select-option>
      <a-select-option :value="3">链接</a-select-option>
      <a-select-option :value="4">帮助</a-select-option>
      <a-select-option :value="5">关于</a-select-option>
    </a-select>
    <!-- 搜索表单 -->
    <a-input-search
      allow-clear
      v-model:value="searchText"
      placeholder="请输入搜索关键词"
      @search="reload"
      @pressEnter="reload"
    />
  </a-space>
  <!-- 导入弹窗 -->
  <import v-model:visible="showImport" @done="reload" />
</template>

<script lang="ts" setup>
  import { PlusOutlined } from '@ant-design/icons-vue';
  import type { GradeParam } from '@/api/user/grade/model';
  import { watch, ref } from 'vue';
  import { openUrl } from '@/utils/common';
  import { hasRole } from '@/utils/permission';
  import { utils, writeFile } from 'xlsx';
  import { message } from 'ant-design-vue';
  import { listCmsNavigation } from '@/api/cms/cmsNavigation';
  import { getTenantId } from '@/utils/domain';
  import Import from './Import.vue';

  // 是否显示导入弹窗
  const showImport = ref(false);
  const searchText = ref('');
  // 导出请求状态
  const loading = ref(false);

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

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

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

  // 表单数据
  const where = ref({
    keywords: '',
    model: '',
    position: 0
  });

  const position = ref(0);

  const reload = () => {
    // 更新搜索关键词
    where.value.keywords = searchText.value;
    emit('search', where.value);
  };

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

  // 导出
  const handleExport = async () => {
    if (loading.value) {
      return;
    }

    loading.value = true;
    const array: (string | number)[][] = [
      [
        '上级id',
        '菜单名称',
        '模型',
        '标识',
        '菜单路由地址',
        '菜单组件地址',
        '打开位置',
        '菜单图标',
        'banner图片',
        '图标颜色',
        '是否隐藏',
        '可见类型',
        '访问密码',
        '位置',
        '仅在顶部显示',
        '仅在底部显示',
        '菜单侧栏选中的path',
        '其它路由元信息',
        'css样式',
        '是否推荐',
        '排序',
        '备注',
        '状态'
      ]
    ];

    // 按搜索结果导出
    message.loading('正在准备导出数据...', 0);

    try {
      const list = await listCmsNavigation(where.value);

      if (!list || list.length === 0) {
        message.destroy();
        message.warning('没有数据可以导出');
        loading.value = false;
        return;
      }

      list.forEach((d) => {
        array.push([
          `${d.parentId || ''}`,
          `${d.title || ''}`,
          `${d.model || ''}`,
          `${d.code || ''}`,
          `${d.path || ''}`,
          `${d.component || ''}`,
          `${d.target || ''}`,
          `${d.icon || ''}`,
          `${d.banner || ''}`,
          `${d.color || ''}`,
          `${d.hide || 0}`,
          `${d.permission || 0}`,
          `${d.password || ''}`,
          `${d.position || 0}`,
          `${d.top || 0}`,
          `${d.bottom || 0}`,
          `${d.active || ''}`,
          `${d.meta || ''}`,
          `${d.style || ''}`,
          `${d.recommend ? 1 : 0}`,
          `${d.sortNumber || 0}`,
          `${d.comments || ''}`,
          `${d.status || 0}`
        ]);
      });

      const sheetName = `bak_navigation_${getTenantId()}`;
      const workbook = {
        SheetNames: [sheetName],
        Sheets: {}
      };
      const sheet = utils.aoa_to_sheet(array);
      workbook.Sheets[sheetName] = sheet;

      // 设置列宽
      sheet['!cols'] = [
        { wch: 10 }, // 上级id
        { wch: 20 }, // 菜单名称
        { wch: 10 }, // 模型
        { wch: 20 }, // 标识
        { wch: 30 }, // 菜单路由地址
        { wch: 30 }, // 菜单组件地址
        { wch: 10 }, // 打开位置
        { wch: 18 }, // 菜单图标
        { wch: 24 }, // banner图片
        { wch: 12 }, // 图标颜色
        { wch: 10 }, // 是否隐藏
        { wch: 10 }, // 可见类型
        { wch: 16 }, // 访问密码
        { wch: 10 }, // 位置
        { wch: 12 }, // 仅在顶部显示
        { wch: 12 }, // 仅在底部显示
        { wch: 26 }, // 菜单侧栏选中的path
        { wch: 20 }, // 其它路由元信息
        { wch: 20 }, // css样式
        { wch: 10 }, // 是否推荐
        { wch: 10 }, // 排序
        { wch: 20 }, // 备注
        { wch: 10 } // 状态
      ];

      message.destroy();
      message.loading('正在生成Excel文件...', 0);

      setTimeout(() => {
        writeFile(workbook, `${sheetName}.xlsx`);
        loading.value = false;
        message.destroy();
        message.success(`成功导出 ${list.length} 条记录`);
      }, 1000);
    } catch (e: any) {
      loading.value = false;
      message.destroy();
      message.error(e.message || '导出失败，请重试');
    }
  };
</script>
