<template>
    <el-dialog :title="dialogTitle" :model-value="dialogVisible" @close="close" v-bind="dialogMiddle">
      <el-form :model="formContent" ref='dialogFormRef' :rules='rules' class="form-two">
        <el-form-item label="上级菜单" prop="pid" :label-width="100">
          <el-tree-select
           v-model="displayPid"
            :data="functionList"
            check-strictly
            :render-after-expand="false"
            show-checkbox
            check-on-click-node
            node-key="id"
            :props="defaultProps"
          />
        </el-form-item>
        <el-form-item label="名称" prop="name" :label-width="100">
          <el-input v-model="formContent.name" />
        </el-form-item>
        <el-form-item label="编码" prop="code" :label-width="100">
          <el-input v-model="formContent.code" />
        </el-form-item>
        <el-form-item v-if="!formContent.type" label="图标" prop="icon" :label-width="100">
          <IconSelect
          v-model="formContent.icon"
          :iconValue="formContent.icon"
          @update:icon-value="iconValue => formContent.icon = iconValue"
          placeholder="选择一个图标"
        />
        </el-form-item>
        <el-form-item v-if="!formContent.type" label="路由地址" prop="path" :label-width="100">
          <el-input v-model="formContent.path" />
        </el-form-item>
        <el-form-item v-if="!formContent.type" label="组件地址" prop="component" :label-width="100">
          <el-input v-model="formContent.component" />
        </el-form-item>
        <el-form-item label="排序" prop="sort" :label-width="100">
          <el-input-number v-model="formContent.sort" :min='1' :max='999' />
        </el-form-item>
        <el-form-item label='类型'  prop='type' :label-width="100">
          <el-select v-model="formContent.type"  clearable placeholder="请选择资源类型">
            <el-option label="菜单" :value="0"></el-option>
            <el-option label="按钮" :value="1"></el-option>
            <!-- <el-option label="公共资源" :value="2"></el-option>
            <el-option label="服务间调用资源" :value="3"></el-option> -->
          </el-select>
        </el-form-item>                             
        <el-form-item label="描述" prop="remark" :label-width="100">
          <el-input v-model="formContent.remark" :rows="2" type="textarea"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="close()">取 消</el-button>
          <el-button type="primary" @click="save()">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </template>
  
  <script lang="ts" setup name="ResourceDialog">
  import { defineProps, defineEmits,watch,ref, type Ref, computed } from 'vue';
  import { dialogMiddle } from '@/utils/elementBind'
  import { ElMessage, type FormInstance, type FormItemRule } from 'element-plus'
  import { useDictStore } from '@/stores/modules/dict'
  import type { Function } from "@/api/user/interface/function"
  import {addFunction,updateFunction,getFunctionListNoButton} from '@/api/user/function/index'
  import IconSelect from '@/components/SelectIcon/index.vue'
  const value = ref()
  // 树形节点配置
  const defaultProps = {
    children: 'children',
    label: 'name',
    value: 'id'
  };
  const functionList = ref<Function.ResFunction[]>([])
  const dictStore = useDictStore()
 // 定义弹出组件元信息
 const dialogFormRef = ref()
 function useMetaInfo() {
    const dialogVisible = ref(false)
    const titleType = ref('add')
    const formContent = ref<Function.ResFunction>({
      id: '',//资源表Id
      pid:'',//节点（0为根节点）
      pids:'',//节点上层所有节点
      name: '',//名称
      code:'',//资源标识
      path:'',//路径
      component:'',
      icon:undefined as string | undefined, // 图标
      sort:100,//排序
      type:0,//资源类型0-菜单、1-按钮、2-公共资源、3-服务间调用资源
      remark: '',//权限资源描述
      state:1,//权限资源状态
    })
    return { dialogVisible, titleType, formContent }
  }

  const { dialogVisible, titleType, formContent } = useMetaInfo()
// 清空formContent
const resetFormContent = () => {
    formContent.value = {
      id: '',//资源表Id
      pid:'',//节点（0为根节点）
      pids:'',//节点上层所有节点
      name: '',//名称
      code:'',//资源标识
      path:'',//路径
      component:'',
      icon:undefined,//图标
      sort:100,//排序
      type:0,//资源类型0-菜单、1-按钮、2-公共资源、3-服务间调用资源
      remark:'',//权限资源描述
      state:1,//权限资源状态
    }
  }
  
  let dialogTitle = computed(() => {
    return titleType.value === 'add' ? '新增菜单' : '编辑菜单'
  })

  

  // 定义规则
  const formRuleRef = ref<FormInstance>()
  const rules : Ref<Record<string, Array<FormItemRule>>> = ref({
          name :[{required:true,trigger:'blur',message:'菜单名称必填!'}],
          code :[{required:true,trigger:'blur',message:'编码必填!'}]
  })

  watch(() => formContent.value.type, (newVal) => {
  if (newVal === 1) {
    // 选择按钮时，路由地址和组件地址无需校验
    rules.value.path = [];
    rules.value.component = [];
  } else {
    // 其他情况下，路由地址和组件地址需要校验
    rules.value.path = [{ required: true, trigger: 'blur', message: '路由地址必填!' }];
    rules.value.component = [{ required: true, trigger: 'blur', message: '组件地址必填!' }];
  }
});
 
  // 关闭弹窗
const close = () => {
    dialogVisible.value = false
    // 清空dialogForm中的值
    resetFormContent()
    // 重置表单
    dialogFormRef.value?.resetFields()
  }
  

// 计算属性，用于控制显示的 pid
const displayPid = computed({
  get: () => {
    return formContent.value.pid === '0' ? '' : formContent.value.pid;
  },
  set: (value) => {
    formContent.value.pid = value;
  }
});


  // 保存数据
  const save = () => {
    try {
        dialogFormRef.value?.validate(async (valid: boolean) => {

        if (formContent.value.pid === undefined || formContent.value.pid === null || formContent.value.pid === '') {
            formContent.value.pid = '0';
        }
        if (formContent.value.pids === undefined || formContent.value.pids === null || formContent.value.pids === '') {
            formContent.value.pids = '0';
        }
        if (valid) {
          if (formContent.value.id) {
              await updateFunction(formContent.value);
            } else {
              await addFunction(formContent.value);
          }
          ElMessage.success({ message: `${dialogTitle.value}成功！` })
          close()
          // 刷新表格
          await props.refreshTable!()
        
        }
      })
    } catch (err) {
      console.error('验证过程中出现错误', err)
    }
  }
  

  // 打开弹窗，可能是新增，也可能是编辑
  const open = async (sign: string, data: Function.ResFunction) => {
    // 重置表单
    dialogFormRef.value?.resetFields()
    const response = await getFunctionListNoButton()
    functionList.value = response.data as unknown as Function.ResFunction[]
    titleType.value = sign
    dialogVisible.value = true

    if (formContent.value.pid ==='0') {
        formContent.value.pid = '';
    }

    if (data.id) {
      formContent.value = { ...data }
    } else {
      resetFormContent()
    }
  }
  
  // 对外映射
  defineExpose({ open })
  const props = defineProps<{
    refreshTable: (() => Promise<void>) | undefined;
  }>()
  </script>
  