<!-- 菜单搜索表单 -->
<template>
  <a-space>
    <a-button type="dashed" @click="handleExport">备份</a-button>
    <a-button type="dashed" @click="openImport">恢复</a-button>
    <a-input-search
      allow-clear
      placeholder="请输入关键词搜索"
      style="width: 240px"
      v-model:value="where.keywords"
      @search="reload"
    />
    <a-button type="text" @click="reset">重置</a-button>
  </a-space>

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

<script lang="ts" setup>
import { ref } from 'vue';
import { message } from 'ant-design-vue';
import { utils, writeFile } from 'xlsx';
import { listMenus } from '@/api/system/menu';
import type { Menu, MenuParam } from '@/api/system/menu/model';
import useSearch from '@/utils/use-search';
import Import from "./Import.vue";
import {getTenantId} from "@/utils/domain";

// 定义包含关键词的参数类型
interface MenuSearchParam extends MenuParam {
  keywords?: string;
}

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

// 请求状态
const loading = ref(false);
const menuList = ref<Menu[]>([]);
// 是否显示导入弹窗
const showImport = ref(false);

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

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

// 新增
const add = () => {
  emit('add');
};

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

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

  loading.value = true;
  message.loading('正在准备导出数据...', 0);

  try {
    const array: (string | number)[][] = [
      [
        '菜单ID',
        '父级ID',
        '菜单名称',
        '路由地址',
        '组件路径',
        '权限标识',
        '菜单类型',
        '图标',
        '排序号',
        '是否隐藏'
      ]
    ];

    // 按搜索结果导出
    const list = await listMenus({
      title: where.keywords,
      path: where.keywords,
      authority: where.keywords
    });

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

    menuList.value = list as Menu[];

    list.forEach((d: Menu) => {
      array.push([
        `${d.menuId || ''}`,
        `${d.parentId || 0}`,
        `${d.title || ''}`,
        `${d.path || ''}`,
        `${d.component || ''}`,
        `${d.authority || ''}`,
        `${d.menuType !== undefined ? d.menuType : ''}`,
        `${d.icon || ''}`,
        `${d.sortNumber !== undefined ? d.sortNumber : ''}`,
        `${d.hide !== undefined ? d.hide : ''}`
      ]);
    });

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

    // 设置列宽
    sheet['!cols'] = [
      { wch: 10 }, // 菜单ID
      { wch: 10 }, // 父级ID
      { wch: 20 }, // 菜单名称
      { wch: 25 }, // 路由地址
      { wch: 25 }, // 组件路径
      { wch: 20 }, // 权限标识
      { wch: 10 }, // 菜单类型
      { wch: 15 }, // 图标
      { wch: 10 }, // 排序号
      { wch: 10 }, // 是否隐藏
      { wch: 20 }, // 创建时间
      { wch: 20 }  // 更新时间
    ];

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

    setTimeout(() => {
      writeFile(workbook, `${sheetName}.xlsx`);
      loading.value = false;
      message.destroy();
      message.success(`成功导出 ${list.length} 条记录`);
    }, 1000);

  } catch (error: any) {
    loading.value = false;
    message.destroy();
    message.error(error.message || '导出失败，请重试');
  }
};

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

/* 重置 */
const reset = () => {
  resetFields();
  reload();
};
</script>
