<template>
    <el-dialog :title="dialogTitle" :model-value="dialogVisible" @close="close" v-bind="dialogMiddle">
      <el-form :model="formContent" ref='formRuleRef' :rules='rules' >
        <el-form-item label="上级菜单" prop="pid" :label-width="100">
          <el-tree-select
            v-model="value"
            :data="data"
            check-strictly
            :render-after-expand="false"
            show-checkbox
            check-on-click-node
          
          />
        </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="icon" :label-width="100">
          <IconSelect
          :iconValue="formContent.icon"
          @update:iconValue="(value) => formContent.icon = value"
          placeholder="选择一个图标"
        />
        </el-form-item>
        <el-form-item label="路由地址" prop="path" :label-width="100">
          <el-input v-model="formContent.path" />
        </el-form-item>
        <el-form-item 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" />
        </el-form-item>
        <el-form-item label="类型" prop="type" :label-width="100">
          <el-select v-model="formContent.type" placeholder="请选择资源类型">
            <el-option
            v-for="item in dictStore.getDictData('resourceType')"
            :key="item.id"
            :label="item.name"
            :value="item.code"
          />
          </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, FormInstance, FormItemRule } from 'element-plus'
  import { useDictStore } from '@/stores/modules/dict'
  import { type Function } from '@/api/function/interface'
  import {addFunction,updateFunction,} from '@/api/function/index.ts'
  import IconSelect from '@/components/SelectIcon/index.vue'
  import { functionList } from '@/api/function/functionExample.ts'
  const value = ref()

const data = [
  {
    value: '1',
    label: 'Level one 1',
    children: [
      {
        value: '1-1',
        label: 'Level two 1-1',
        children: [
          {
            value: '1-1-1',
            label: 'Level three 1-1-1',
          },
        ],
      },
    ],
  },
  {
    value: '2',
    label: 'Level one 2',
    children: [
      {
        value: '2-1',
        label: 'Level two 2-1',
        children: [
          {
            value: '2-1-1',
            label: 'Level three 2-1-1',
          },
        ],
      },
      {
        value: '2-2',
        label: 'Level two 2-2',
        children: [
          {
            value: '2-2-1',
            label: 'Level three 2-2-1',
          },
        ],
      },
    ],
  },
  {
    value: '3',
    label: 'Level one 3',
    children: [
      {
        value: '3-1',
        label: 'Level two 3-1',
        children: [
          {
            value: '3-1-1',
            label: 'Level three 3-1-1',
          },
        ],
      },
      {
        value: '3-2',
        label: 'Level two 3-2',
        children: [
          {
            value: '3-2-1',
            label: 'Level three 3-2-1',
          },
        ],
      },
    ],
  },
]
  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:'菜单名称必填!'}],
          path :[{required:true,trigger:'blur',message:'菜单路径必填!'}],
          type :[{required:true,trigger:'change',message:'菜单类型必选!'}]
  })
 
  // 关闭弹窗
const close = () => {
    dialogVisible.value = false
    // 清空dialogForm中的值
    resetFormContent()
    // 重置表单
    dialogFormRef.value?.resetFields()
  }
  
  // 保存数据
  const save = () => {
    try {
        dialogFormRef.value?.validate(async (valid: boolean) => {
        if (valid) {
          if (formContent.value.id) {
                const result = await updateFunction(formContent.value);
                if(result.code != 'A0000'){
                  ElMessage.error({ message: result.message})
                }else{
                  ElMessage.success({ message: `${dialogTitle.value}成功！` })
                }
            } else {
                const result = await addFunction(formContent.value);
               if(result.code != 'A0000'){
                  ElMessage.error({ message: result.message})
                }else{
                  ElMessage.success({ message: `${dialogTitle.value}成功！` })
                }
          }
          close()
          // 刷新表格
          await props.refreshTable!()
        }
      })
    } catch (err) {
      console.error('验证过程中出现错误', err)
    }
  }
  
  // 打开弹窗，可能是新增，也可能是编辑
  const open = async (sign: string, data: Function.ResFunction) => {
    titleType.value = sign
    dialogVisible.value = true
    if (data.id) {
      formContent.value = { ...data }
    } else {
      resetFormContent()
    }
  }
  
  // 对外映射
  defineExpose({ open })
  const props = defineProps<{
    refreshTable: (() => Promise<void>) | undefined;
  }>()
  </script>
  