<template>
  <basicModal
    @register="modalRegister"
    ref="modalRef"
    class="basicModal basicFormModal"
    @on-ok="handleSubmit"
    @on-close="handleClose"
  >
    <template #default>
      <n-form ref="formRef" :model="formData" label-placement="left" label-width="90px">
        <n-form-item label="菜单类型" path="type" required>
          <n-radio-group v-model:value="formData.type">
            <n-radio :value="0">菜单</n-radio>
            <n-radio :value="1">按钮</n-radio>
          </n-radio-group>
        </n-form-item>
        <n-form-item
          label="父级菜单"
          path="parentId"
          :rule="{ type: 'number', required: true, message: '请选择父级菜单', trigger: 'change' }"
        >
          <n-tree-select
            class="flex-1"
            v-model:value="formData.parentId"
            :options="menuOptions"
            label-field="name"
            key-field="id"
            default-expand-all
            placeholder="请选择父级菜单"
          />
        </n-form-item>
        <n-form-item
          label="菜单名称"
          path="name"
          :rule="{ required: true, message: '请输入菜单名称', trigger: 'blur' }"
        >
          <n-input v-model:value="formData.name" placeholder="请输入菜单名称" clearable />
        </n-form-item>
        <n-form-item v-if="formData.type == 0" label="菜单图标" path="icon2">
          <icon-picker v-model:icon="formData.icon2">
            <template #iconSelect>
              <n-input v-model:value="formData.icon2" placeholder="请选择菜单图标">
                <template #prefix>
                  <component :is="iconComponent(formData.icon2)" />
                </template>
              </n-input>
            </template>
          </icon-picker>
        </n-form-item>
        <n-form-item label="打开方式" path="target" v-if="formData.type == 0">
          <div>
            <n-radio-group v-model:value="formData.target">
              <n-radio :value="0">组件</n-radio>
              <n-radio :value="1">内链</n-radio>
              <n-radio :value="2">外链</n-radio>
            </n-radio-group>
            <div class="form-tips"> 选择外链，则新窗口打开页面 </div>
          </div>
        </n-form-item>
        <n-form-item
          v-if="formData.type == 0 && (formData.target == 0 || formData.target == 1)"
          label="路由路径"
          path="path"
          :rule="{ required: true, message: '请输入路由路径', trigger: 'blur' }"
        >
          <div class="flex-1">
            <n-input v-model:value="formData.path" placeholder="请输入路由路径" clearable />
            <div class="form-tips"> 访问的路由地址 </div>
          </div>
        </n-form-item>
        <n-form-item v-if="formData.type == 0" label="组件路径" path="component">
          <div class="flex-1">
            <n-auto-complete
              style="width: 100%"
              v-model:value="formData.component"
              :options="dataSource"
              @update:value="filterOption"
              placeholder="请输入组件路径"
            />
            <div class="form-tips">
              访问的组件路径，如：`permission/admin/index`，默认在`views`目录下，如外网地址需内链访问则以`http(s)://`开头
            </div>
          </div>
        </n-form-item>
        <n-form-item v-if="formData.target == 0" label="权限字符" path="permission">
          <div class="flex-1">
            <n-input v-model:value="formData.permission" placeholder="请输入权限字符" clearable />
            <div class="form-tips">
              将作为server端API验权使用，如`system:admin:list`，请谨慎修改
            </div>
          </div>
        </n-form-item>
        <n-form-item v-if="formData.type == 0" label="是否显示" path="hide" required>
          <div>
            <n-radio-group v-model:value="formData.hide">
              <n-radio :value="0">显示</n-radio>
              <n-radio :value="1">隐藏</n-radio>
            </n-radio-group>
            <div class="form-tips"> 选择隐藏则路由将不会出现在侧边栏，但仍然可以访问 </div>
          </div>
        </n-form-item>
        <n-form-item v-if="formData.type == 0" label="菜单状态" path="status" required>
          <div>
            <n-radio-group v-model:value="formData.status">
              <n-radio :value="0">正常</n-radio>
              <n-radio :value="1">停用</n-radio>
            </n-radio-group>
            <div class="form-tips"> 选择停用则路由将不会出现在侧边栏，也不能被访问 </div>
          </div>
        </n-form-item>
        <n-form-item label="菜单排序" path="sort">
          <div>
            <n-input-number v-model:value="formData.sort" :max="9999" />
            <div class="form-tips">数值越小越排前</div>
          </div>
        </n-form-item>
      </n-form>
    </template>
  </basicModal>
</template>
<script lang="ts" setup>
  import { menuAdd, menuUpdate, getMenuList, getMenuDetail } from '@/api/system/menu';
  import { onMounted, reactive, ref } from 'vue';
  import { getModulesKey } from '@/router';
  import { arrayToTree, treeToArray, buildTree } from '@/utils/auth';
  import IconPicker from '@/components/icon/picker.vue';
  import * as VueIcon from '@vicons/antd';
  import { useMessage, useDialog } from 'naive-ui';
  import { useModal } from '@/components/Modal';
  import { renderIcon } from '@/utils';

  /**
   * 定义接收的参数
   */
  const props = defineProps({
    menuId: {
      type: Number,
      required: true,
      default: 0,
    },
    pid: {
      type: Number,
      default: 0,
    },
  });

  /**
   * 定义参数变量
   */
  const [modalRegister, { openModal, setSubLoading }] = useModal({
    title: props.menuId ? '编辑菜单' : '添加菜单',
    subBtuText: '确定',
    width: 600,
  });
  const message = useMessage();
  const emit = defineEmits(['success', 'update:visible']);
  const formRef = ref();
  const dataSource = ref([]);

  const componentsOptions = ref(getModulesKey());

  /**
   * 定义表单参数
   */
  const formData = reactive({
    id: '',
    //父级id
    parentId: 0,
    //类型
    type: 0,
    //图标
    icon2: '',
    //名称
    name: '',
    //排序号
    sort: 0,
    // 路由路径
    path: '',
    //权限链接
    permission: '',
    //前端组件
    component: '',
    //是否显示 0=显示， 1=不显示
    hide: 0,
    //是否外链 0=不是， 1=是
    target: 0,
    status: 0,
  });

  const menuOptions = ref<any[]>([]);

  /**
   * 定义Icon组件
   * @param icon 图标
   */
  const iconComponent = (icon) => {
    const IconComponent = renderIcon(VueIcon[icon]);
    return IconComponent;
  };

  const filterOption = (input: string) => {
    const results = input
      ? componentsOptions.value.filter((item) => item.toLowerCase().includes(input.toLowerCase()))
      : componentsOptions.value;
    dataSource.value = results.map((item) => ({ label: item, value: item }));
  };

  /**
   * 获取菜单列表
   */
  const getMenu = async () => {
    const data: any = await getMenuList();
    const menu: any = { id: 0, name: '顶级', children: [] };
    const lists = buildTree(data.filter((item) => item.type == 0));
    menu.children = lists;
    menuOptions.value.push(menu);
  };

  /**
   * 执行提交表单
   */
  const handleSubmit = async () => {
    formRef.value
      .validate()
      .then(async () => {
        props.menuId ? await menuUpdate(formData) : await menuAdd(formData);
        message.success('操作成功');
        setSubLoading(false);
        emit('update:visible', false);
        emit('success');
      })
      .catch((error) => {
        setSubLoading(false);
      });
  };

  /**
   * 设置表单数据
   * @param data 参数
   */
  const setFormData = (data: Record<any, any>) => {
    for (const key in formData) {
      if (data[key] != null && data[key] != undefined) {
        formData[key] = data[key];
      }
    }
  };

  /**
   *获取菜单详情
   */
  const getDetail = async () => {
    const data = await getMenuDetail(props.menuId);
    setFormData(data);
  };

  /**
   * 关闭窗体
   */
  const handleClose = () => {
    emit('update:visible', false);
  };

  /**
   * 钩子函数
   */
  onMounted(async () => {
    componentsOptions.value.map((item) => {
      dataSource.value.push({ label: item, value: item });
    });
    getMenu();
    if (props.menuId) {
      getDetail();
    } else {
      formData.parentId = props.pid;
    }
  });

  /**
   * 定义函数
   */
  defineExpose({
    openModal,
  });
</script>
