<template>
    <!-- 基础信息弹出框 -->
  <el-dialog :model-value="dialogVisible" :title="dialogTitle"  v-bind="dialogMiddle" @close="close" >
    <div>
        <el-form :model="formContent" ref='dialogFormRef'>
      <el-tree
        :data="functionList"
        :props="defaultProps"
        node-key="id"
        :expand-on-click-node="false"
        show-checkbox
        :default-checked-keys="checkedKeysRef"
        ref="treeRef"
      >
      </el-tree>

      </el-form>
      </div>
    <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>
  import{  ElMessage, ElTree, type FormInstance,type FormItemRule } from 'element-plus'
  import type { ProTableInstance } from '@/components/ProTable/interface'
  import { ref,computed, type Ref, nextTick  } from 'vue'
  import { Role } from '@/api/user/interface/role'
  import {dialogMiddle,dialogSmall} from '@/utils/elementBind'
  import { useDictStore } from '@/stores/modules/dict'
  import { type Function } from '@/api/user/function/interface'
  import {getRoleFunction,assignFunction} from '@/api/user/role/index'

  // 保存数据
  const treeRef = ref<InstanceType<typeof ElTree>>()
  const functionList = ref<Function.ResFunction[]>([])
  // 定义一个 ref 来存储已选中的 keys
  const checkedKeysRef = ref<string[]>([]);
  // 树形节点配置
  const defaultProps = {
    children: 'children',
    label: 'name',
  };

 // 定义弹出组件元信息
 const dialogFormRef = ref()
 const dialogTitle = ref('授权资源')
 const { dialogVisible,  formContent } = useMetaInfo()

 function useMetaInfo() {
    const dialogVisible = ref(false)
    
    const formContent = ref<Role.RoleBO>({
      id: '',    //角色类型ID
      name: '',   //角色类型名称
      code: '',  //角色代码
      type: 2, //角色类型
      remark:'',  //角色描述
      state:1,
    })
    return { dialogVisible, formContent }
  }
  
  

// 清空formContent
const resetFormContent = () => {
    formContent.value = {
      id: '',    //角色类型ID
      name: '',   //角色类型名称
      code: '',  //角色代码
      type: 2, //角色类型
      remark:'',  //角色描述
      state:1,
    }
  }
  

// 关闭弹窗
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) {
                 // 获取半选中的节点 ID
                const halfCheckedKeys = treeRef.value?.getHalfCheckedKeys() || [];
                // 获取全选中的节点 ID
                const checkedKeys = treeRef.value?.getCheckedKeys() || [];
                // 将两个数组合并
                const allCheckedKeys = [...halfCheckedKeys, ...checkedKeys];

                // 将 checkedKeys 转换为字符串数组
                const checkedKeysAsString: string[] = allCheckedKeys.map(key => String(key));
                // 假设 RoleFunctionId 是一个对象，且需要 id 属性
                const roleFunctionIdObject: Role.RoleFunctionId = {
                  id: checkedKeysAsString
                };
               
                const result = await assignFunction(formContent.value,roleFunctionIdObject);
                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: Role.RoleBO, AllFunction: Function.ResFunction[]) => {
  // 重置表单
  dialogFormRef.value?.resetFields()
  // 重置树状结构
  functionList.value = []
  checkedKeysRef.value = []
  const result = await getRoleFunction(data);
  if (result.code === 'A0000') {
    // 将 result.data 转换为 Function.ResFunction[] 类型
    const roleFunctions = result.data as Function.ResFunction[];
    // 获取 AllFunction 中所有层级的 id
    const allIds = getAllIds(AllFunction);
    // 匹配 roleFunctions 中的 id 并设置 checkedKeys
    const checkedKeys = allIds.filter(id => roleFunctions.some(roleFunc => roleFunc.id === id));
    // 过滤出叶子节点
    const leafCheckedKeys = filterLeafNodes(AllFunction, checkedKeys);

    // 设置 functionList 和 checkedKeys
    functionList.value = AllFunction;
    checkedKeysRef.value = leafCheckedKeys;
  
    // nextTick(() => {
    //   // 触发一次更新，确保表单中的数据被更新
    //   dialogFormRef.value?.validate();
    // });
  } else {
    ElMessage.error({ message: result.message });
  }

  dialogVisible.value = true;
  if (data.id) {
    formContent.value = { ...data };
  } else {
    resetFormContent();
  }
}
  
const filterLeafNodes = (functions: Function.ResFunction[], checkedKeys: string[]): string[] => {
  const leafNodes: string[] = [];
  const isLeafNode = (func: Function.ResFunction) => !func.children || func.children.length === 0;

  const traverse = (funcs: Function.ResFunction[]) => {
    for (const func of funcs) {
      if (isLeafNode(func)) {
        if (checkedKeys.includes(func.id)) {
          leafNodes.push(func.id);
        }
      } else {
        traverse(func.children);
      }
    }
  };

  traverse(functions);
  return leafNodes;
};
const getAllIds = (functions: Function.ResFunction[]): string[] => {
  const ids: string[] = [];

  const traverse = (func: Function.ResFunction) => {
    ids.push(func.id);
    if (func.children && func.children.length > 0) {
      func.children.forEach((child: any) => traverse(child));
    }
  };

  functions.forEach(func => traverse(func));

  return ids;
};

  // 对外映射
  defineExpose({ open })
  const props = defineProps<{
    refreshTable: (() => Promise<void>) | undefined;
  }>()
  
  </script>