<template>
  <div class="system-add-menu-container">
    <el-dialog title="新增菜单" v-model="state.isShowDialog" width="769px" draggable>
      <el-form :model="state.ruleForm" ref="ruleFormRef" label-width="90px" label-poistion="left">
        <el-row :gutter="35">
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label="上级菜单" prop="parentId"
              :rules="[{ required: false, message: '请选择上级菜单', trigger: 'change' }]">
              <el-cascader :options="state.menuData" filterable
                :props="{ checkStrictly: true, value: 'id', label: 'title', emitPath: false }" placeholder="请选择上级菜单"
                clearable class="w100" v-model="state.ruleForm.parentId">
                <template #default="{ node, data }">
                  <span>{{ data.title }}</span>
                  <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
                </template>
              </el-cascader>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="菜单名称" prop="pageName"
              :rules="[{ required: true, message: '请输入菜单名称', trigger: 'blur' }]">
              <el-input v-model="state.ruleForm.pageName" placeholder="请输入菜单名称" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="路由名称" prop="ruleName"
              :rules="[{ required: state.ruleForm.isKeepAlive, message: '请输入路由名称', trigger: 'blur' }]">
              <el-input v-model="state.ruleForm.ruleName" placeholder="路由中的 name 值" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="路由路径" prop="path" :rules="[{ required: true, message: '请输入路由路径', trigger: 'blur' }]">
              <el-input v-model="state.ruleForm.path" placeholder="路由中的 path 值" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="菜单图标" prop="icon" :rules="[{ required: false, message: '请输入菜单名称', trigger: 'blur' }]">
              <IconSelector placeholder="请输入菜单图标" v-model="state.ruleForm.icon" type="all" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="组件路径" prop="component"
              :rules="[{ required: true, message: '请输入组件路径', trigger: 'blur' }]">
              <el-input v-model="state.ruleForm.component" placeholder="组件路径" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="链接地址" prop="link"
              :rules="[{ required: state.ruleForm.isLink, message: '请输入外链/内嵌时链接地址', trigger: 'blur' }]">
              <el-input v-model="state.ruleForm.link" placeholder="外链/内嵌时链接地址（http:xxx.com）" clearable
                :disabled="!state.ruleForm.isLink">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="权限编码" prop="permissionCode"
              :rules="[{ required: true, message: '请输入权限编码', trigger: 'blur' }]">
              <el-input v-model="state.ruleForm.permissionCode" placeholder="权限编码" clearable>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="菜单排序">
              <el-input-number v-model="state.ruleForm.displayOrder" controls-position="right" placeholder="请输入排序"
                class="w100" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="快捷入口">
              <el-switch v-model="state.ruleForm.isFast" inline-prompt active-text="是" inactive-text="否" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-if="state.ruleForm.isFast">
            <el-form-item label="入口图片" prop="title" :rules="[{ required: false, message: '请选择入口图片', trigger: 'blur' }]">
              <template #label>
                <p class="flex-center-align">入口图片
                  <el-tooltip content="首页快捷入口图标" placement="top-start" trigger="click">
                    <SvgIcon name="ele-QuestionFilled" class="cursor-help"></SvgIcon>
                  </el-tooltip>
                </p>
              </template>
              <el-select v-model="state.ruleForm.fastIcon" placeholder="请选择入口图片" class="w100" clearable>
                <el-option v-for="item in state.imgList" :key="item.value" :label="item.label" :value="item.value">
                  <div class="item-Img">
                    <span>{{ item.label }}</span>
                    <img v-lazy="getImageUrl(item.label)" alt="" />
                  </div>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="是否隐藏">
              <el-switch v-model="state.ruleForm.isHide" inline-prompt active-text="是" inactive-text="否" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="是否缓存">
              <el-switch v-model="state.ruleForm.isKeepAlive" inline-prompt active-text="是" inactive-text="否" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="是否固定">
              <el-switch v-model="state.ruleForm.isAffix" inline-prompt active-text="是" inactive-text="否" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="是否外链">
              <el-switch v-model="state.ruleForm.isLink" :disabled="state.ruleForm.isLink && state.ruleForm.isIframe"
                inline-prompt active-text="是" inactive-text="否" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item label="是否内嵌">
              <el-switch v-model="state.ruleForm.isIframe" @change="onSelectIframeChange" inline-prompt active-text="是"
                inactive-text="否" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="onCancel" class="default-button">取 消</el-button>
          <el-button type="primary" @click="onSubmit(ruleFormRef)" v-waves="'light'" :loading="state.loading">确 定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="systemAddMenu">
import { defineAsyncComponent, reactive, ref } from 'vue';
import { ElMessage } from 'element-plus';
import { getImageUrl } from "/@/utils/tools";
import { setBackEndControlRefreshRoutes } from "/@/router/backEnd";
import { FormInstance } from "element-plus";
import { addMenu, getMenuList } from "/@/api/system/menu";

// 引入组件
const IconSelector = defineAsyncComponent(() => import('/@/components/iconSelector/index.vue'));

// 定义子组件向父组件传值/事件
const emit = defineEmits(['updateList']);

// 定义变量内容
const ruleFormRef = ref<FormInstance>()
const state = reactive({
  isShowDialog: false,
  // 参数请参考 `/src/router/route.ts` 中的 `dynamicRoutes` 路由菜单格式
  ruleForm: {
    parentId: '', // 上级菜单Id
    ruleName: '', // 路由名称
    component: '', // 组件路径
    isLink: false, // 是否外链
    displayOrder: 0, // 菜单排序
    path: '', // 路由路径
    pageName: '', // 菜单名称
    icon: '', // 菜单图标
    isHide: false, // 是否隐藏
    isKeepAlive: true, // 是否缓存
    isAffix: false, // 是否固定
    link: '', // 外链/内嵌时链接地址（http:xxx.com），开启外链条件，`1、isLink: 链接地址不为空`
    isIframe: false, // 是否内嵌，开启条件，`1、isIframe:true 2、isLink：链接地址不为空`
    permissionCode: "", //权限编码
    isFast: false, //是否是快捷入口
    fastIcon: "", //入口图片
  },
  menuData: [], // 上级菜单数据
  loading: false,
  imgList: [
    {
      label: 'home/sllb.png',
      value: 'home/sllb.png'
    }, {
      label: 'home/gdhf.png',
      value: 'home/gdhf.png'
    }, {
      label: 'home/qbgd.png',
      value: 'home/qbgd.png'
    }, {
      label: 'home/ywcx.png',
      value: 'home/ywcx.png'
    }, {
      label: 'home/zbgl.png',
      value: 'home/zbgl.png'
    },
  ]
});
// 获取全部菜单
const getMenuData = (routes: any) => {
  const arr: any = [];
  routes.map((val: any) => {
    val['title'] = val.pageName;
    arr.push({ ...val });
    if (val.children) getMenuData(val.children);
  });
  return arr;
};
// 打开弹窗
const openDialog = () => {
  getMenuList().then((res: any) => {
    ruleFormRef.value?.resetFields();
    ruleFormRef.value?.resetFields();
    state.isShowDialog = true;
    state.menuData = getMenuData(res.result);
  })
};
// 关闭弹窗
const closeDialog = () => {
  state.isShowDialog = false;
};
// 是否内嵌下拉改变
const onSelectIframeChange = () => {
  state.ruleForm.isLink = state.ruleForm.isIframe;
};
// 取消
const onCancel = () => {
  closeDialog();
};
// 新增
const onSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      addMenu(state.ruleForm).then(() => {
        emit("updateList");
        closeDialog(); // 关闭弹窗
        ElMessage.success('新增成功');
        setBackEndControlRefreshRoutes();
      })
    } else {
      console.log('error submit!', fields)
    }
  })
};
// 暴露变量
defineExpose({
  openDialog,
  closeDialog
});
</script>
