<template>
  <div class="permission-management-page custom-page">
    <div class="page-content">
      <div class="header-section">
        <el-button type="primary" @click="handleAddRole">
          新增角色
        </el-button>
      </div>

      <div class="table-section">
        <div class="table-toolbar">
          <el-button icon="el-icon-refresh" size="small" @click="handleRefresh">
            刷新
          </el-button>
        </div>
        <el-table :data="tableData" border style="width: 100%">
          <el-table-column type="index" label="序号" width="90" align="center" />
          <el-table-column prop="roleName" label="角色名称" align="center" min-width="150" />
          <el-table-column prop="roleCode" label="角色代码" align="center" min-width="150" />
          <el-table-column prop="roleDescription" label="角色描述" align="center" min-width="150" />
          <el-table-column prop="creationDate" label="创建时间" align="center" width="180">
            <template slot-scope="{ row }">
              {{ formatDate(row.creationDate) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="280" align="center" fixed="right">
            <template slot-scope="scope">
              <a
                v-if="scope.row.roleName !== '超级管理员'"
                href="javascript:void(0)"
                class="el-link el-link--primary"
                @click.stop="handlePermissionConfig(scope.row)"
              >
                权限配置
              </a>
              <span class="link-separator"></span>
              <a
                href="javascript:void(0)"
                class="el-link el-link--primary"
                @click.stop="handlePersonConfig(scope.row)"
              >
                人员配置
              </a>
              <span class="link-separator"></span>
              <a
                v-if="scope.row.roleName !== '超级管理员'"
                href="javascript:void(0)"
                class="el-link el-link--primary"
                @click.stop="handleEdit(scope.row)"
              >
                编辑
              </a>
              <span class="link-separator"></span>
              <a
                v-if="scope.row.roleName !== '超级管理员'"
                href="javascript:void(0)"
                class="el-link el-link--primary"
                @click.stop="handleDelete(scope.row, scope.$index)"
              >
                删除
              </a>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination-section">
          <el-pagination
            :current-page="pagination.currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pagination.pageSize"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      title="权限配置"
      :visible.sync="dialogVisible"
      width="800px"
      :close-on-click-modal="false"
      :modal="false"
      class="permission-config-dialog"
      @close="handleDialogClose"
    >
      <div class="permission-config-content">
        <div class="permission-tree-wrapper">
          <el-tree
            ref="permissionTree"
            :key="'permission-tree-' + dialogVisible"
            :data="[]"
            node-key="id"
            :props="{ children: 'children', label: 'label', isLeaf: 'isLeaf' }"
            :filter-node-method="filterTreeNode"
            :default-expand-all="false"
            :lazy="true"
            :load="loadNode"
            class="permission-tree"
          >
            <span slot-scope="{ node, data }" class="custom-tree-node">
              <span class="node-label">
                {{ node.label }}
                <!-- <span v-if="data.type === 'menu'" class="type-tag menu-tag">菜单</span>
                <span v-if="data.type === 'subsystem'" class="type-tag subsystem-tag">子系统</span>
                <span v-if="data.type === 'parameter'" class="type-tag parameter-tag">参数类型</span> -->
              </span>
              <span v-if="data.type === 'subsystem' || data.type === 'parameter'" class="permission-checkboxes">
                <el-checkbox
                  v-model="data.permissions.view"
                  size="small"
                  @change="data.type === 'subsystem' ? handleSubsystemPermissionChange(data, 'view') : handlePermissionChange(data, 'view')"
                >
                  查看
                </el-checkbox>
                <el-checkbox
                  v-model="data.permissions.edit"
                  size="small"
                  @change="data.type === 'subsystem' ? handleSubsystemPermissionChange(data, 'edit') : handlePermissionChange(data, 'edit')"
                >
                  编辑
                </el-checkbox>
              </span>
            </span>
          </el-tree>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleDialogClose">
          取消
        </el-button>
        <el-button type="primary" :loading="submitting" @click="handleSubmit">
          确定
        </el-button>
      </div>
    </el-dialog>

    <!-- 人员配置对话框 -->
    <el-dialog
      title="人员配置"
      :visible.sync="personConfigDialogVisible"
      width="500px"
      :close-on-click-modal="false"
      :modal="false"
      class="person-config-dialog"
      @close="handlePersonConfigDialogClose"
    >
      <el-form
        ref="personConfigForm"
        :model="personConfigFormData"
        :rules="personConfigFormRules"
        label-width="100px"
      >
        <el-form-item label="配置类型:" prop="configType">
          <el-radio-group
            v-model="personConfigFormData.configType"
            @change="handleConfigTypeChange"
          >
            <el-radio label="person">
              配置人员
            </el-radio>
            <el-radio label="department">
              配置部门
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 配置部门模式 -->
        <template v-if="personConfigFormData.configType === 'department'">
          <el-form-item label="责任部门:" prop="department">
            <el-cascader
              ref="departmentCascader"
              v-model="personConfigFormData.department"
              :options="departmentList"
              :props="{
                multiple: true,
                checkStrictly: true,
                value: 'id',
                label: 'name',
                children: 'children',
                emitPath: true
              }"
              filterable
              placeholder="请选择责任部门（可多选）"
              clearable
              style="width: 100%"
              @change="handlePersonDepartmentChange"
            />
          </el-form-item>
        </template>
        <!-- 配置人员模式 -->
        <template v-else>
          <!-- <el-form-item label="责任部门:" prop="department">
            <el-cascader
              ref="departmentCascader"
              v-model="personConfigFormData.department"
              :options="departmentList"
              :props="departmentCascaderProps"
              filterable
              placeholder="请选择责任部门"
              clearable
              style="width: 100%"
              @change="handlePersonDepartmentChange"
            />
          </el-form-item> -->
          <el-form-item label="人员:" prop="person">
            <el-select
              v-model="personConfigFormData.person"
              multiple
              filterable
              remote
              reserve-keyword
              placeholder="请输入人员姓名进行搜索"
              style="width: 100%"
              clearable
              :remote-method="queryPersonByDepartment"
              :loading="personSearchLoading"
              class="person-select"
            >
              <el-option
                v-for="person in personOptions"
                :key="person.userNumber"
                :value="person.userId"
                :label="person.username"
              >
                <span class="username-text">{{ person.username }}</span>
                <span class="user-id-text">{{ person.userNumber }}</span>
              </el-option>
            </el-select>
          </el-form-item>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handlePersonConfigDialogClose">
          取消
        </el-button>
        <el-button
          type="primary"
          :loading="personConfigSubmitting"
          @click="handlePersonConfigSubmit"
        >
          确定
        </el-button>
      </div>
    </el-dialog>

    <!-- 新增/编辑角色对话框 -->
    <el-dialog
      :title="addRoleMode === 'add' ? '新增角色' : '编辑角色'"
      :visible.sync="addRoleDialogVisible"
      width="500px"
      :close-on-click-modal="false"
      :modal="false"
      class="add-role-dialog"
      @close="handleAddRoleDialogClose"
    >
      <el-form
        ref="addRoleForm"
        :model="addRoleFormData"
        :rules="addRoleFormRules"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input
            v-model="addRoleFormData.roleName"
            placeholder="请输入角色名称"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="角色代码" prop="roleCode">
          <el-input
            v-model="addRoleFormData.roleCode"
            placeholder="请输入角色代码"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDescription">
          <el-input
            v-model="addRoleFormData.roleDescription"
            type="textarea"
            :rows="4"
            placeholder="请输入角色描述"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleAddRoleDialogClose">
          取消
        </el-button>
        <el-button type="primary" :loading="addRoleSubmitting" @click="handleAddRoleSubmit">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import api from '@/api'
import { getUserId } from '@/utils'
import dayjs from 'dayjs'
export default {
  name: 'PermissionManagement',
  data() {
    return {
      tableData: [],
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      dialogVisible: false,
      dialogMode: 'add', // 'add' 或 'edit'
      submitting: false,
      formData: {
        roleName: '',
        rowId: '',
        permissions: [] // 权限数据 [{ menuId, menuName, subsystem, parameter, view, edit }]
      },
      formRules: {
        roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
        permissions: [
          {
            required: true,
            message: '请至少分配一个权限',
            trigger: 'change',
            validator: this.validatePermissions
          }
        ]
      },
      // 新增/编辑角色相关
      addRoleDialogVisible: false,
      addRoleSubmitting: false,
      addRoleMode: 'add', // 'add' 或 'edit'
      addRoleFormData: {
        roleName: '',
        roleDescription: '',
        roleId: '' // 编辑时使用
      },
      addRoleFormRules: {
        roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
        roleDescription: [{ required: true, message: '请输入角色描述', trigger: 'blur' }]
      },
      // 菜单树数据
      menuTreeData: [],
      // 子系统列表（数组格式）- 保留用于兼容
      subsystemList: [],
      // 子系统到partsName的映射（从GET_PARAM_LIST获取）
      subsystemPartsMap: {}, // { "子系统名": ["partsName1", "partsName2", ...] }
      treeFilterText: '',
      // 节点映射，用于快速查找
      nodeMap: {},
      // 待应用的权限数据（用于懒加载模式下延迟应用权限）
      pendingPermissions: [],
      // 固定的父级菜单列表
      menuList: ['模板管理', '玉柴发动机数据', '竞品发动机数据'],
      // 人员配置相关
      personConfigDialogVisible: false,
      personConfigSubmitting: false,
      personConfigFormData: {
        configType: 'person', // 配置类型：'person' 配置人员，'department' 配置部门
        department: '', // 级联选择器绑定的部门ID（配置人员时为单个，配置部门时为数组）
        person: [], // 人员数组（用于提交，包含 {userId, username} 对象）
        selectDeptId: '', // 选中的部门ID（用于搜索人员，配置人员模式使用）
        selectDeptName: '', // 选中的部门名称（用于提交）
        selectDeptIds: [], // 选中的部门ID数组（配置部门模式使用）
        roleId: '', // 角色ID（用于提交）
        roleName: '' // 角色名称（用于显示）
      },
      personOptions: [], // 人员选项列表
      personSearchLoading: false, // 人员搜索loading状态
      personConfigFormRules: {
        department: [
          {
            validator: (rule, value, callback) => {
              if (this.personConfigFormData.configType === 'department') {
                if (!value || (Array.isArray(value) && value.length === 0)) {
                  callback(new Error('请选择责任部门'))
                } else {
                  callback()
                }
              } else {
                callback()
              }
            },
            trigger: 'change'
          }
        ],
        person: [
          {
            validator: (rule, value, callback) => {
              if (this.personConfigFormData.configType === 'person') {
                if (!value || (Array.isArray(value) && value.length === 0)) {
                  callback(new Error('请选择人员'))
                } else {
                  callback()
                }
              } else {
                callback()
              }
            },
            trigger: 'change'
          }
        ]
      },
      departmentList: [],
      departmentCascaderProps: {
        value: 'id',
        label: 'name',
        children: 'children',
        checkStrictly: true, // 允许选择任意一级（单选）
        emitPath: false, // 只返回最后一级的值（单选时只返回选中的id）
        multiple: false // 明确指定为单选
      },
      personSearchTimer: null, // 防抖定时器
      currentPersonRequest: null // 当前请求引用
    }
  },
  computed: {
    dialogTitle() {
      return this.dialogMode === 'add' ? '新增' : '修改'
    },
    // 获取所有参数节点，用于表格显示（只有参数类型，没有第四级）
    // 在懒加载模式下，从 nodeMap 中收集所有已加载的参数节点
    allParameterNodes() {
      const nodes = []
      // 遍历 nodeMap，收集所有参数类型的节点
      Object.keys(this.nodeMap).forEach((nodeId) => {
        const node = this.nodeMap[nodeId]
        if (node && node.type === 'parameter') {
          // 确保权限对象存在
          if (!node.permissions) {
            this.$set(node, 'permissions', { view: false, edit: false })
          }
          nodes.push({
            id: node.id,
            menuName: node.menuName || '',
            subsystem: node.subsystem || '',
            parameter: node.parameter || node.label || '',
            partsName: node.partsName || node.label || '',
            parameterId: node.parameterId || '', // 保存参数ID
            permissions: node.permissions // 直接引用，保持响应式
          })
        }
      })
      return nodes
    }
  },
  watch: {
    treeFilterText(val) {
      this.$refs.permissionTree && this.$refs.permissionTree.filter(val)
    }
  },
  mounted() {
    this.loadPermissionData()
    this.loadParamList()
    this.loadDepartmentList()
    this.getUserSelfRole()
  },
  beforeDestroy() {
    // 清理定时器和请求
    if (this.personSearchTimer) {
      clearTimeout(this.personSearchTimer)
      this.personSearchTimer = null
    }
    this.currentPersonRequest = null
  },
  methods: {
    getUserSelfRole() {
      const request = {
        ...api.GET_USER_SELF_ROLE,
        params: {
          userOrDepID: getUserId()
        },
        disableSuccessMsg: true
      }
      this.$request(request)
        .asyncThen((resp) => {
          console.log('获取用户自身角色:', resp)
        })
        .asyncErrorCatch((err) => {
          console.error('获取用户自身角色失败:', err)
        })
    },
    // 验证权限
    validatePermissions(rule, value, callback) {
      const hasPermission = this.allParameterNodes.some((node) => {
        return node.permissions.view || node.permissions.edit
      })
      if (!hasPermission) {
        callback(new Error('请至少分配一个权限'))
      } else {
        callback()
      }
    },
    // 加载参数列表（获取所有子系统和partsName）
    loadParamList() {
      const request = {
        ...api.GET_PARAM_LIST,
        disableSuccessMsg: true
      }
      this.$request(request)
        .asyncThen((resp) => {
          if (resp && resp.data) {
            // 处理返回的数据，格式：{ "子系统名": ["partsName1", "partsName2", ...] }
            let paramData = {}
            if (typeof resp.data === 'object' && resp.data !== null) {
              // 如果直接是对象格式
              if (resp.data.result && typeof resp.data.result === 'object') {
                paramData = resp.data.result
              } else if (resp.data.data && typeof resp.data.data === 'object') {
                paramData = resp.data.data
              } else {
                paramData = resp.data
              }
            }

            // 处理数据：对每个子系统的partsName数组去重
            const processedMap = {}
            Object.keys(paramData).forEach((subsystemName) => {
              const partsArray = paramData[subsystemName]
              if (Array.isArray(partsArray)) {
                // 去重：使用Set去重，不过滤"/"，只过滤空值
                const uniqueParts = [...new Set(partsArray)].filter(
                  (part) => part !== null && part !== undefined && part !== ''
                )
                processedMap[subsystemName] = uniqueParts
              } else {
                processedMap[subsystemName] = []
              }
            })

            // 存储子系统到partsName的映射
            this.subsystemPartsMap = processedMap
            // 同时提取子系统列表（用于兼容）
            this.subsystemList = Object.keys(processedMap)

            console.log('加载参数列表成功，子系统数量:', this.subsystemList.length)
            console.log('子系统到partsName映射:', this.subsystemPartsMap)
          } else {
            this.subsystemPartsMap = {}
            this.subsystemList = []
          }
          this.buildMenuTree()
        })
        .asyncErrorCatch((err) => {
          console.error('加载参数列表失败:', err)
          this.subsystemPartsMap = {}
          this.subsystemList = []
          this.buildMenuTree()
        })
    },
    // 构建菜单树（菜单 -> 子系统）
    // 参数类型在展开子系统节点时动态加载
    buildMenuTree() {
      // 重置节点映射
      this.nodeMap = {}

      // 构建菜单树结构
      // 结构：菜单（固定6个） -> 子系统（从接口获取） -> 参数类型（展开时动态加载）
      const treeData = []

      // 遍历固定的菜单列表，即使子系统列表为空，也要构建菜单节点
      this.menuList.forEach((menuName, menuIdx) => {
        const menuId = `menu-${menuIdx}`
        const menuNode = {
          id: menuId,
          label: menuName,
          type: 'menu',
          children: null, // 初始为 null，懒加载时加载
          isLeaf: false // 明确标记为非叶子节点，让 el-tree 显示展开按钮
        }

        // 保存菜单节点映射
        this.nodeMap[menuId] = menuNode
        treeData.push(menuNode)
      })

      this.menuTreeData = treeData
    },
    // 树节点过滤
    filterTreeNode(value, data) {
      if (!value) return true
      return data.label && data.label.indexOf(value) !== -1
    },
    // 懒加载节点数据
    loadNode(node, resolve) {
      // 根节点（level === 0），返回第一级菜单数据
      if (node.level === 0) {
        // 如果菜单树数据为空，先构建它
        if (!this.menuTreeData || this.menuTreeData.length === 0) {
          this.buildMenuTree()
        }
        resolve(this.menuTreeData || [])
        return
      }
      // 如果节点是菜单类型，加载其子系统（第二级）
      if (node.data.type === 'menu') {
        this.loadMenuSubsystemsForLazy(node.data, resolve)
        return
      }
      // 如果节点是子系统类型，加载其参数类型（第三级）
      if (node.data.type === 'subsystem') {
        this.loadSubsystemParametersForLazy(node.data, resolve)
        return
      }
      // 其他节点（参数类型）都是叶子节点，不需要加载
      resolve([])
    },
    // 懒加载方式加载菜单下的子系统
    loadMenuSubsystemsForLazy(menuNode, resolve) {
      // 从subsystemPartsMap中获取子系统列表
      const subsystemNames = Object.keys(this.subsystemPartsMap || {})

      if (subsystemNames.length === 0) {
        resolve([])
        return
      }

      // 构建子系统节点（第二级），并预加载其partsName子节点
      const subsystemNodes = []
      subsystemNames.forEach((subsystemName, subIdx) => {
        if (!subsystemName) {
          return
        }

        const subsystemId = `${menuNode.id}-subsystem-${subIdx}`

        // 获取该子系统下的partsName列表（已去重）
        const partsNames = this.subsystemPartsMap[subsystemName] || []

        // 构建第三级节点（partsName节点）
        const partsNodes = []
        const seenParts = new Set() // 用于去重（虽然接口返回已去重，但这里再加一层保险）
        partsNames.forEach((partsName, partsIdx) => {
          // 不过滤 `/`，只过滤空值和重复值
          if (!partsName || seenParts.has(partsName)) {
            return
          }
          seenParts.add(partsName)

          const paramTypeId = `${subsystemId}-param-${partsIdx}`
          const paramTypeNode = {
            id: paramTypeId,
            label: partsName,
            type: 'parameter',
            menuName: menuNode.label,
            subsystem: subsystemName,
            parameter: partsName,
            parameterName: partsName, // 保存参数名称，用于权限匹配
            partsName: partsName,
            parameterId: '', // partsName没有对应的parameterId
            permissions: {
              view: false,
              edit: false
            },
            isLeaf: true, // 参数类型是叶子节点，没有第四级
            children: null // 没有子节点
          }

          partsNodes.push(paramTypeNode)
          // 保存节点映射
          this.nodeMap[paramTypeId] = paramTypeNode

          // 如果有待应用的权限数据，立即应用
          this.applyPendingPermissionsToNode(paramTypeNode)
        })

        const subsystemNode = {
          id: subsystemId,
          label: subsystemName,
          type: 'subsystem',
          menuName: menuNode.label,
          subsystem: subsystemName,
          children: partsNodes, // 直接设置子节点，不再懒加载
          isLeaf: partsNodes.length === 0, // 如果没有partsName，标记为叶子节点
          permissions: {
            view: false,
            edit: false
          }
        }

        subsystemNodes.push(subsystemNode)
        // 保存节点映射
        this.nodeMap[subsystemId] = subsystemNode
      })

      // 使用 $nextTick 确保节点渲染后，权限状态能正确显示
      this.$nextTick(() => {
        // 再次应用权限，确保视图更新
        subsystemNodes.forEach((subsystemNode) => {
          if (subsystemNode.children && Array.isArray(subsystemNode.children)) {
            subsystemNode.children.forEach((node) => {
              this.applyPendingPermissionsToNode(node)
            })
          }
        })
      })

      // 通过 resolve 回调返回子节点数据
      resolve(subsystemNodes)
    },
    // 懒加载方式加载子系统下的参数类型（已改为在loadMenuSubsystemsForLazy中预加载，此方法不再使用）
    loadSubsystemParametersForLazy(subsystemNode, resolve) {
      // 从预加载的数据中获取partsName列表
      if (!subsystemNode.subsystem) {
        console.warn('子系统节点缺少子系统名称')
        resolve([])
        return
      }

      // 从subsystemPartsMap中获取该子系统下的partsName列表
      const partsNames = this.subsystemPartsMap[subsystemNode.subsystem] || []

      // 构建参数类型节点（第三级，没有子节点）
      const parameterNodes = []
      const seenTypes = new Set() // 用于去重（虽然接口返回已去重，但这里再加一层保险）
      partsNames.forEach((partsName, paramIdx) => {
        // 不过滤 `/`，只过滤空值和重复值
        if (!partsName || seenTypes.has(partsName)) {
          return
        }
        seenTypes.add(partsName)

        const paramTypeId = `${subsystemNode.id}-param-${paramIdx}`
        const paramTypeNode = {
          id: paramTypeId,
          label: partsName,
          type: 'parameter',
          menuName: subsystemNode.menuName,
          subsystem: subsystemNode.subsystem,
          parameter: partsName,
          parameterName: partsName, // 保存参数名称，用于权限匹配
          partsName: partsName,
          parameterId: '', // partsName没有对应的parameterId
          permissions: {
            view: false,
            edit: false
          },
          isLeaf: true, // 参数类型是叶子节点，没有第四级
          children: null // 没有子节点
        }

        parameterNodes.push(paramTypeNode)
        // 保存节点映射
        this.nodeMap[paramTypeId] = paramTypeNode

        // 如果有待应用的权限数据，立即应用
        this.applyPendingPermissionsToNode(paramTypeNode)
      })

      // 通过 resolve 回调返回子节点数据
      resolve(parameterNodes)

      // 使用 $nextTick 确保节点渲染后，权限状态能正确显示
      this.$nextTick(() => {
        // 再次应用权限，确保视图更新
        parameterNodes.forEach((node) => {
          this.applyPendingPermissionsToNode(node)
        })
      })
    },
    // 权限变更处理（参数节点）
    handlePermissionChange(data, permissionType) {
      // 同步更新节点映射中的权限
      if (data.id && this.nodeMap[data.id]) {
        // 使用 $set 确保响应式更新
        this.$set(
          this.nodeMap[data.id].permissions,
          permissionType,
          data.permissions[permissionType]
        )
      }
      // 更新父节点（子系统）的权限状态
      this.updateSubsystemPermissionFromChildren(data)
      // 触发验证
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.validateField('permissions')
        }
      })
    },
    // 子系统权限变更处理（全选/取消全选子节点）
    handleSubsystemPermissionChange(data, permissionType) {
      // 同步更新节点映射中的权限
      if (data.id && this.nodeMap[data.id]) {
        // 使用 $set 确保响应式更新
        this.$set(
          this.nodeMap[data.id].permissions,
          permissionType,
          data.permissions[permissionType]
        )
      }
      // 获取该子系统下的所有子节点（参数节点）
      const children = data.children || []
      const isChecked = data.permissions[permissionType]
      // 全选/取消全选所有子节点
      children.forEach((childNode) => {
        if (childNode.id && this.nodeMap[childNode.id]) {
          // 更新子节点的权限
          this.$set(this.nodeMap[childNode.id].permissions, permissionType, isChecked)
          // 同时更新子节点本身的权限（确保视图更新）
          if (childNode.permissions) {
            this.$set(childNode, 'permissions', {
              ...childNode.permissions,
              [permissionType]: isChecked
            })
          }
        }
      })
      // 触发验证
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.validateField('permissions')
        }
      })
    },
    // 根据子节点权限更新子系统权限状态
    updateSubsystemPermissionFromChildren(parameterNode) {
      if (!parameterNode || !parameterNode.subsystem) {
        return
      }
      // 查找该参数节点所属的子系统节点
      const subsystemNode = Object.values(this.nodeMap).find(
        (node) =>
          node.type === 'subsystem' &&
          node.subsystem === parameterNode.subsystem &&
          node.menuName === parameterNode.menuName
      )
      if (!subsystemNode || !subsystemNode.children || subsystemNode.children.length === 0) {
        return
      }
      // 检查所有子节点的权限状态
      const allChildren = subsystemNode.children
      const allViewChecked = allChildren.every((child) => {
        const childNode = this.nodeMap[child.id]
        return childNode && childNode.permissions && childNode.permissions.view === true
      })
      const allEditChecked = allChildren.every((child) => {
        const childNode = this.nodeMap[child.id]
        return childNode && childNode.permissions && childNode.permissions.edit === true
      })
      // 更新子系统节点的权限状态
      if (subsystemNode.permissions) {
        this.$set(subsystemNode.permissions, 'view', allViewChecked)
        this.$set(subsystemNode.permissions, 'edit', allEditChecked)
      }
    },
    // 加载权限数据
    loadPermissionData() {
      const request = {
        ...api.GET_ROLE_PERMISSION,
        disableSuccessMsg: true
      }
      this.$request(request)
        .asyncThen((resp) => {
          if (resp && resp.data) {
            this.tableData = resp.data
            this.pagination.total = resp.data.length || 0
          } else {
            this.tableData = []
            this.pagination.total = 0
          }
        })
        .asyncErrorCatch((err) => {
          console.error('加载权限数据失败:', err)
          this.tableData = []
          this.pagination.total = 0
        })
    },
    // 新增角色
    handleAddRole() {
      this.addRoleMode = 'add'
      this.addRoleDialogVisible = true
      this.addRoleFormData = {
        roleName: '',
        roleDescription: '',
        roleId: ''
      }
      this.$nextTick(() => {
        if (this.$refs.addRoleForm) {
          this.$refs.addRoleForm.clearValidate()
        }
      })
    },
    // 新增/编辑角色提交
    handleAddRoleSubmit() {
      this.$refs.addRoleForm.validate((valid) => {
        if (valid) {
          this.addRoleSubmitting = true
          const isEdit = this.addRoleMode === 'edit'
          const config = isEdit ? api.EDIT_PERMISSION_DATA_ROLE : api.ADD_ROLE_PERMISSION
          const request = {
            ...config,
            url: isEdit ? config.url + getUserId() : config.url,
            params: isEdit
              ? {
                id: this.addRoleFormData.roleId,
                roleName: this.addRoleFormData.roleName,
                roleCode: this.addRoleFormData.roleCode,
                roleDescription: this.addRoleFormData.roleDescription
              }
              : {
                roleName: this.addRoleFormData.roleName,
                roleCode: this.addRoleFormData.roleCode,
                roleDescription: this.addRoleFormData.roleDescription
              }
          }
          this.$request(request)
            .asyncThen((resp) => {
              this.handleAddRoleDialogClose()
              this.loadPermissionData()
            })
            .asyncErrorCatch((err) => {
              console.error(isEdit ? '编辑角色失败' : '新增角色失败', err)
              this.$message.error(err.message || (isEdit ? '编辑角色失败' : '新增角色失败'))
            })
            .finally(() => {
              this.addRoleSubmitting = false
            })
        }
      })
    },
    // 关闭新增/编辑角色弹窗
    handleAddRoleDialogClose() {
      this.addRoleDialogVisible = false
      this.addRoleMode = 'add'
      this.addRoleFormData = {
        roleName: '',
        roleDescription: '',
        roleId: ''
      }
      if (this.$refs.addRoleForm) {
        this.$refs.addRoleForm.clearValidate()
      }
    },
    // 权限配置
    handlePermissionConfig(row) {
      this.dialogMode = 'edit'
      const roleId = row.rowId || row.id || ''
      this.formData = {
        roleName: row.roleName || '',
        rowId: roleId,
        permissions: []
      }
      // 重置所有权限复选框
      this.resetAllPermissions()
      // 确保菜单树已构建（如果还没有构建）
      if (!this.menuTreeData || this.menuTreeData.length === 0) {
        this.buildMenuTree()
      }
      // 打开弹窗（key 属性会强制重新渲染树组件）
      this.dialogVisible = true
      // 加载权限详情
      this.loadRolePermissionDetail(roleId)
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.clearValidate()
        }
      })
    },
    // 加载角色权限详情
    loadRolePermissionDetail(roleId) {
      if (!roleId) {
        return
      }
      const request = {
        ...api.GET_ROLE_CONTROL_LIST,
        params: {
          roleID: roleId
        },
        disableSuccessMsg: true
      }
      this.$request(request)
        .asyncThen((resp) => {
          // 处理返回的权限数据，格式应该是数组：[{ roleId, menuName, parameterId, parameterPer, userId }]
          let permissions = []
          if (resp && resp.data) {
            if (Array.isArray(resp.data)) {
              permissions = resp.data
            } else if (resp.data.result && Array.isArray(resp.data.result)) {
              permissions = resp.data.result
            } else if (resp.data.data && Array.isArray(resp.data.data)) {
              permissions = resp.data.data
            }
          }
          console.log('加载到的权限数据:', permissions)
          // 设置权限数据
          if (permissions.length > 0) {
            this.setPermissionsFromData(permissions)
          } else {
            // 如果没有权限数据，清空待应用的权限
            this.pendingPermissions = []
          }
        })
        .asyncErrorCatch((err) => {
          console.error('加载权限详情失败:', err)
          // 不显示错误提示，因为可能是新角色没有权限数据
        })
    },
    // 人员配置
    handlePersonConfig(row) {
      this.personConfigFormData = {
        configType: 'person',
        department: '',
        person: [], // userId 数组
        selectDeptId: '',
        selectDeptName: '',
        selectDeptIds: [],
        roleId: row.rowId || row.id || '',
        roleName: row.roleName || ''
      }
      const request = {
        ...api.CHECK_ROLE_USER_DEPT,
        params: {
          roleId: row.rowId || row.id || ''
        },
        disableSuccessMsg: true
      }
      this.$request(request)
        .asyncThen((resp) => {
          if (resp && resp.data) {
            // 解析返回数据，格式：{ "部门": [], "人员": ["李亚松-yc90117847"] }
            const respData = resp.data
            const personArray = respData['人员'] || respData.person || []
            // 解析人员数组，格式：["userName-userId"]
            const userIds = []
            const personOptionsMap = new Map()
            personArray.forEach((personStr) => {
              if (typeof personStr === 'string' && personStr.includes('-')) {
                const parts = personStr.split('-')
                if (parts.length >= 2) {
                  const userName = parts[0]
                  const userId = parts.slice(1).join('-') // 处理 userId 中可能包含 - 的情况
                  userIds.push(userId)
                  // 构建选项对象
                  personOptionsMap.set(userId, {
                    userId: userId,
                    username: userName,
                    userNumber: userId // userNumber 使用 userId
                  })
                }
              }
            })
            // 设置已选择的人员ID数组
            this.personConfigFormData.person = userIds
            // 设置选项（用于显示已选择的人员）
            this.personOptions = Array.from(personOptionsMap.values())
          }
        })
        .asyncErrorCatch((err) => {
          console.error('加载人员列表失败:', err)
        })
      this.personConfigDialogVisible = true
      this.$nextTick(() => {
        if (this.$refs.personConfigForm) {
          this.$refs.personConfigForm.clearValidate()
        }
      })
    },
    // 配置类型切换
    handleConfigTypeChange(value) {
      // 切换配置类型时，清空相关数据
      if (value === 'department') {
        // 切换到配置部门模式
        this.personConfigFormData.department = []
        this.personConfigFormData.selectDeptIds = []
        this.personConfigFormData.person = []
        this.personOptions = []
      } else {
        // 切换到配置人员模式
        this.personConfigFormData.department = ''
        this.personConfigFormData.selectDeptId = ''
        this.personConfigFormData.selectDeptName = ''
        this.personConfigFormData.selectDeptIds = []
      }
      // 清除表单验证
      this.$nextTick(() => {
        if (this.$refs.personConfigForm) {
          this.$refs.personConfigForm.clearValidate()
        }
      })
    },
    // 加载部门列表
    loadDepartmentList() {
      const request = {
        ...api.GET_SUB_DEPT,
        disableSuccessMsg: true
      }
      this.$request(request)
        .asyncThen((resp) => {
          // 处理返回的数据，确保格式为 { id, name, children }
          let result = []
          if (resp && resp.data) {
            result = resp.data.result || resp.data.data || resp.data || []
          }
          // 格式化数据为级联选择器需要的格式
          this.departmentList = this.formatDepartmentTreeData(result)
        })
        .asyncErrorCatch((err) => {
          console.error('加载部门列表失败:', err)
          this.departmentList = []
        })
    },
    // 格式化部门树数据为级联选择器格式
    formatDepartmentTreeData(data) {
      if (!Array.isArray(data)) {
        return []
      }

      // 递归格式化数据，确保每个节点都有 id 和 name 字段
      const formatNode = (node) => {
        const formatted = {
          id: node.id,
          name: node.name || node.label || node.deptName || ''
        }

        // 如果有子节点，递归格式化
        if (node.children && Array.isArray(node.children) && node.children.length > 0) {
          formatted.children = node.children.map((child) => formatNode(child))
        }

        return formatted
      }
      return data.map((node) => formatNode(node))
    },
    // 处理部门选择变化
    handlePersonDepartmentChange(value) {
      if (this.personConfigFormData.configType === 'department') {
        // 配置部门模式：value 是数组，每个元素是级联路径数组（多选）
        // 例如：[[id1, id2], [id3, id4]] 表示选中了两个部门
        if (value && Array.isArray(value) && value.length > 0) {
          // 提取所有选中部门的最后一级ID，存入数组
          this.personConfigFormData.selectDeptIds = value
            .map((path) => {
              // path 是级联路径数组，取最后一级作为部门ID
              if (Array.isArray(path) && path.length > 0) {
                return path[path.length - 1]
              }
              // 如果 path 不是数组，可能是直接的ID
              return path
            })
            .filter((id) => id) // 过滤掉空值
        } else {
          this.personConfigFormData.selectDeptIds = []
        }
        console.log('配置部门模式 - 选中的部门值:', value)
        console.log('配置部门模式 - 选中的部门ID数组:', this.personConfigFormData.selectDeptIds)
        // 触发表单验证
        this.$nextTick(() => {
          if (this.$refs.personConfigForm) {
            this.$refs.personConfigForm.validateField('department')
          }
        })
      } else {
        // 配置人员模式：value 是单个级联路径数组（单选）
        if (value && Array.isArray(value) && value.length > 0) {
          // 获取最后一级的id
          this.personConfigFormData.selectDeptId = value[value.length - 1]
          // 查找部门路径名称
          this.personConfigFormData.selectDeptName = this.getDepartmentPathName(
            this.personConfigFormData.selectDeptId
          )
          // 清空人员选择
          this.personConfigFormData.person = []
          this.personOptions = []
        } else {
          // 清空时重置
          this.personConfigFormData.selectDeptId = ''
          this.personConfigFormData.selectDeptName = ''
          this.personConfigFormData.person = []
          this.personOptions = []
        }
      }
    },
    // 远程搜索人员（用于 el-select，按照 modelDetail.vue 的方式）
    queryPersonByDepartment(queryString) {
      if (!queryString || queryString.trim() === '') {
        // 空查询时，只保留已选择的人员在选项中
        // personConfigFormData.person 现在是 userId 数组
        if (this.personConfigFormData.person && this.personConfigFormData.person.length > 0) {
          // 从现有 options 中查找已选择的人员信息
          const selectedOptions = this.personOptions.filter(
            (opt) => opt.userId && this.personConfigFormData.person.includes(opt.userId)
          )
          // 检查是否有已选择的人员不在 options 中
          const missingIds = this.personConfigFormData.person.filter(
            (id) => !selectedOptions.some((opt) => opt.userId === id)
          )
          if (missingIds.length > 0) {
            // 如果有缺失的人员信息，尝试通过搜索获取（搜索空字符串可能返回所有用户或最近使用的用户）
            // 这里先保留已找到的，缺失的会在用户下次搜索时自动补充
            this.personOptions = selectedOptions
          } else {
            this.personOptions = selectedOptions
          }
        } else {
          this.personOptions = []
        }
        return
      }

      // 清除之前的定时器
      if (this.personSearchTimer) {
        clearTimeout(this.personSearchTimer)
      }

      // 使用防抖，延迟300ms执行
      this.personSearchTimer = setTimeout(() => {
        const trimmedQuery = queryString.trim()
        if (!trimmedQuery) {
          this.personOptions = []
          return
        }

        this.personSearchLoading = true
        const request = {
          ...api.GET_ALLUSERS,
          params: {
            name: trimmedQuery
          },
          disableSuccessMsg: true
        }

        // 保存当前请求引用
        this.currentPersonRequest = this.$request(request)
        this.currentPersonRequest
          .asyncThen((resp) => {
            // 处理返回的数据
            const respData = resp && resp.data
            let result = []
            if (Array.isArray(respData)) {
              result = respData
            } else if (respData && Array.isArray(respData.result)) {
              result = respData.result
            } else if (respData && respData.data && Array.isArray(respData.data)) {
              result = respData.data
            }

            // 转换为选项格式：{userId: user.userId, username: user.username, userNumber: user.userNumber}
            const users = result
              .map((user) => ({
                userId: user.userId || user.id,
                username: user.username || user.name,
                userNumber: user.userNumber || user.userId || user.id
              }))
              .filter((user) => user.userId && user.userNumber) // 过滤掉没有 userId 或 userNumber 的数据

            // personConfigFormData.person 现在是 userId 数组
            const existingIds = new Set(this.personConfigFormData.person || [])
            // 过滤掉已选择的人员
            const filteredUsers = users.filter((user) => !existingIds.has(user.userId))
            // 合并：已选择的人员信息（从现有 options 中获取）+ 新的搜索结果
            const selectedOptions = (this.personOptions || []).filter(
              (opt) => opt.userId && this.personConfigFormData.person && this.personConfigFormData.person.includes(opt.userId)
            )
            // 去重：使用 Map 确保每个 userId 只出现一次
            const optionsMap = new Map()
            // 先添加已选择的选项
            selectedOptions.forEach((opt) => {
              if (opt.userId) {
                optionsMap.set(opt.userId, opt)
              }
            })
            // 再添加新的搜索结果
            filteredUsers.forEach((user) => {
              if (user.userId && !optionsMap.has(user.userId)) {
                optionsMap.set(user.userId, user)
              }
            })
            this.personOptions = Array.from(optionsMap.values())
            this.personSearchLoading = false
            this.currentPersonRequest = null
          })
          .asyncErrorCatch((err) => {
            console.error('搜索人员失败:', err)
            // 搜索失败时，保留已选择的人员信息
            if (this.personConfigFormData.person && this.personConfigFormData.person.length > 0) {
              const selectedOptions = this.personOptions.filter(
                (opt) => opt.userId && this.personConfigFormData.person.includes(opt.userId)
              )
              this.personOptions = selectedOptions
            } else {
              this.personOptions = []
            }
            this.personSearchLoading = false
            this.currentPersonRequest = null
          })
      }, 300)
    },
    // 根据部门id获取部门路径名称（用-连接）
    getDepartmentPathName(deptId) {
      if (!deptId || !this.departmentList || this.departmentList.length === 0) {
        return ''
      }

      // 递归查找部门节点及其路径
      const findNodePath = (nodes, targetId, path = []) => {
        for (const node of nodes) {
          const currentPath = [...path, node.name]

          if (node.id === targetId) {
            return currentPath
          }

          if (node.children && node.children.length > 0) {
            const found = findNodePath(node.children, targetId, currentPath)
            if (found) {
              return found
            }
          }
        }
        return null
      }

      const path = findNodePath(this.departmentList, deptId)
      return path ? path.join('-') : ''
    },
    // 人员配置提交
    handlePersonConfigSubmit() {
      this.$refs.personConfigForm.validate((valid) => {
        if (valid) {
          this.personConfigSubmitting = true

          let userOrDeptId = []
          let isDept = 0

          if (this.personConfigFormData.configType === 'department') {
            // 配置部门模式：传部门ID数组
            isDept = 1
            // 优先使用 selectDeptIds，如果没有则从 department 中提取
            if (
              this.personConfigFormData.selectDeptIds &&
              this.personConfigFormData.selectDeptIds.length > 0
            ) {
              userOrDeptId = this.personConfigFormData.selectDeptIds
            } else if (
              this.personConfigFormData.department &&
              Array.isArray(this.personConfigFormData.department) &&
              this.personConfigFormData.department.length > 0
            ) {
              // 如果 selectDeptIds 为空，从 department 中提取
              userOrDeptId = this.personConfigFormData.department
                .map((path) => {
                  if (Array.isArray(path) && path.length > 0) {
                    return path[path.length - 1]
                  }
                  return path
                })
                .filter((id) => id)
            } else {
              userOrDeptId = []
            }
            if (userOrDeptId.length === 0) {
              this.$message.warning('请至少选择一个部门')
              this.personConfigSubmitting = false
              return
            }
          } else {
            // 配置人员模式：传人员ID数组（person 已经是 userId 数组）
            isDept = 0
            userOrDeptId = (this.personConfigFormData.person || []).filter((id) => id)
            if (userOrDeptId.length === 0) {
              this.$message.warning('请至少选择一个人员')
              this.personConfigSubmitting = false
              return
            }
          }

          console.log('人员配置数据:', {
            roleId: this.personConfigFormData.roleId,
            roleName: this.personConfigFormData.roleName,
            configType: this.personConfigFormData.configType,
            isDept: isDept,
            userOrDeptIds: userOrDeptId
          })

          const request = {
            ...api.GET_ROLE_PERMISSION_BING,
            params: {
              roleId: this.personConfigFormData.roleId,
              userOrDeptIds: userOrDeptId,
              isDept: isDept
            },
            disableSuccessMsg: true
          }

          this.$request(request)
            .asyncThen((resp) => {
              this.handlePersonConfigDialogClose()
              this.loadPermissionData()
              this.$message({
                type: 'success',
                message: '配置成功'
              })
            })
            .asyncErrorCatch((err) => {
              console.error('配置失败:', err)
              this.$message({
                type: 'error',
                message: '配置失败'
              })
            })
            .finally(() => {
              this.personConfigSubmitting = false
            })
        }
      })
    },
    // 关闭人员配置弹窗
    handlePersonConfigDialogClose() {
      this.personConfigDialogVisible = false
      this.personConfigFormData = {
        configType: 'person',
        department: '',
        person: [],
        selectDeptId: '',
        selectDeptName: '',
        selectDeptIds: [],
        roleId: '',
        roleName: ''
      }
      this.personOptions = []
      // 清除定时器和请求
      if (this.personSearchTimer) {
        clearTimeout(this.personSearchTimer)
        this.personSearchTimer = null
      }
      this.currentPersonRequest = null
      if (this.$refs.personConfigForm) {
        this.$refs.personConfigForm.clearValidate()
      }
    },
    // 编辑角色（编辑角色名称和描述）
    handleEdit(row) {
      this.addRoleMode = 'edit'
      this.addRoleDialogVisible = true
      this.addRoleFormData = {
        roleName: row.roleName || '',
        roleDescription: row.roleDescription || '',
        roleId: row.rowId || row.id || ''
      }
      this.$nextTick(() => {
        if (this.$refs.addRoleForm) {
          this.$refs.addRoleForm.clearValidate()
        }
      })
    },
    // 重置所有权限
    resetAllPermissions() {
      Object.keys(this.nodeMap).forEach((key) => {
        const node = this.nodeMap[key]
        if (node && node.permissions) {
          node.permissions.view = false
          node.permissions.edit = false
        }
      })
    },
    // 从 menuPath 中提取第一级菜单名
    // menuPath 格式: "数据录入/模板管理" -> 提取 "模板管理"
    extractMenuNameFromPath(menuPath) {
      if (!menuPath) return ''
      // 按 "/" 分割，取最后一部分作为菜单名
      const parts = menuPath.split('/')
      return parts.length > 0 ? parts[parts.length - 1].trim() : menuPath.trim()
    },
    // 从数据设置权限
    setPermissionsFromData(permissions) {
      // permissions 格式是数组，每个元素包含：
      // { id, subsystem, partsName, parameterPer }
      // parameterPer 是字符串："查看" 或 "编辑"
      const permArray = Array.isArray(permissions) ? permissions : []

      // 先重置所有权限
      this.resetAllPermissions()

      // 保存权限数据，用于懒加载模式下延迟应用
      this.pendingPermissions = permArray

      // 处理权限数据：按 subsystem 和 partsName 分组，合并同一节点的查看和编辑权限
      const permissionMap = new Map() // key: `${subsystem}-${partsName}`, value: { view: boolean, edit: boolean }
      permArray.forEach((perm) => {
        const subsystem = perm.subsystem || ''
        const partsName = perm.partsName || ''
        const key = `${subsystem}-${partsName}`

        if (!permissionMap.has(key)) {
          permissionMap.set(key, {
            subsystem: subsystem,
            partsName: partsName,
            view: false,
            edit: false
          })
        }

        const permData = permissionMap.get(key)
        if (perm.parameterPer === '查看') {
          permData.view = true
        } else if (perm.parameterPer === '编辑') {
          permData.edit = true
        }
      })

      // 根据 subsystem 和 partsName 匹配节点并设置权限（只设置已加载的节点）
      permissionMap.forEach((permData, key) => {
        Object.keys(this.nodeMap).forEach((nodeId) => {
          const node = this.nodeMap[nodeId]
          if (node && node.type === 'parameter') {
            // 匹配子系统
            const subsystemMatch =
              permData.subsystem && node.subsystem && permData.subsystem === node.subsystem
            // 匹配零部件名称（partsName）
            const partsNameMatch =
              permData.partsName &&
              (node.partsName || node.parameterName || node.label) &&
              permData.partsName === (node.partsName || node.parameterName || node.label)

            if (subsystemMatch && partsNameMatch) {
              // 使用 $set 确保响应式更新，直接替换整个权限对象
              const newPermissions = {
                view: permData.view || false,
                edit: permData.edit || false
              }
              this.$set(node, 'permissions', newPermissions)
              console.log(
                '设置已加载节点权限:',
                node.id,
                node.label,
                {
                  subsystem: node.subsystem,
                  partsName: node.partsName || node.parameterName || node.label
                },
                newPermissions
              )
            }
          }
        })
      })

      // 设置完所有参数节点权限后，更新子系统节点的权限状态
      this.$nextTick(() => {
        Object.keys(this.nodeMap).forEach((nodeId) => {
          const node = this.nodeMap[nodeId]
          if (node && node.type === 'subsystem' && node.children && node.children.length > 0) {
            // 检查所有子节点的权限状态
            const allChildren = node.children
            const allViewChecked = allChildren.every((child) => {
              const childNode = this.nodeMap[child.id]
              return childNode && childNode.permissions && childNode.permissions.view === true
            })
            const allEditChecked = allChildren.every((child) => {
              const childNode = this.nodeMap[child.id]
              return childNode && childNode.permissions && childNode.permissions.edit === true
            })
            // 更新子系统节点的权限状态
            if (node.permissions) {
              this.$set(node.permissions, 'view', allViewChecked)
              this.$set(node.permissions, 'edit', allEditChecked)
            }
          }
        })
      })

      console.log(
        '权限数据已保存，待应用权限数量:',
        this.pendingPermissions.length,
        '处理后的权限映射:',
        Array.from(permissionMap.entries())
      )
    },
    // 将待应用的权限应用到新加载的节点
    applyPendingPermissionsToNode(node) {
      if (
        !node ||
        node.type !== 'parameter' ||
        !this.pendingPermissions ||
        this.pendingPermissions.length === 0
      ) {
        return
      }

      // 查找匹配的权限数据：根据 subsystem 和 partsName 匹配
      const matchingPerms = this.pendingPermissions.filter((perm) => {
        // 匹配子系统
        const subsystemMatch = perm.subsystem && node.subsystem && perm.subsystem === node.subsystem
        // 匹配零部件名称（partsName）
        const partsNameMatch =
          perm.partsName &&
          (node.partsName || node.parameterName || node.label) &&
          perm.partsName === (node.partsName || node.parameterName || node.label)

        return subsystemMatch && partsNameMatch
      })

      if (matchingPerms.length > 0) {
        // 确保权限对象存在
        if (!node.permissions) {
          this.$set(node, 'permissions', { view: false, edit: false })
        }

        // 应用权限：parameterPer 是字符串 "查看" 或 "编辑"
        let hasView = false
        let hasEdit = false
        matchingPerms.forEach((perm) => {
          if (perm.parameterPer === '查看') {
            hasView = true
          } else if (perm.parameterPer === '编辑') {
            hasEdit = true
          }
        })

        // 使用 $set 确保响应式更新，直接替换整个权限对象
        const newPermissions = {
          view: hasView,
          edit: hasEdit
        }
        // 更新 nodeMap 中的节点
        if (this.nodeMap[node.id]) {
          this.$set(this.nodeMap[node.id], 'permissions', newPermissions)
        }
        // 同时更新节点本身的权限
        this.$set(node, 'permissions', newPermissions)

        console.log(
          '应用权限到节点:',
          node.id,
          node.label,
          {
            menuName: node.menuName,
            subsystem: node.subsystem,
            parameterName: node.parameterName || node.label
          },
          newPermissions,
          '匹配的权限:',
          matchingPerms
        )

        // 应用权限后，更新父节点（子系统）的权限状态
        this.$nextTick(() => {
          this.updateSubsystemPermissionFromChildren(node)
        })
      }
    },
    // 收集选中的权限
    collectPermissions() {
      const permissions = []
      const roleId = this.formData.rowId || ''
      const userId = getUserId()

      // 直接从 nodeMap 中收集所有参数节点，确保包含所有已加载的节点
      Object.keys(this.nodeMap).forEach((nodeId) => {
        const node = this.nodeMap[nodeId]
        if (node && node.type === 'parameter') {
          // 确保权限对象存在
          const nodePermissions = node.permissions || { view: false, edit: false }
          // 获取子系统名称和partsName
          const subsystem = node.subsystem || ''
          const partsName = node.partsName || node.parameterName || node.label || ''

          // 如果选中了查看权限，添加一条记录（parameterPer = 1）
          if (nodePermissions.view) {
            permissions.push({
              roleId: roleId,
              subsystem: subsystem,
              partsName: partsName,
              parameterPer: 1, // 1是查看
              userId: userId
            })
          }
          // 如果选中了编辑权限，添加一条记录（parameterPer = 2）
          if (nodePermissions.edit) {
            permissions.push({
              roleId: roleId,
              subsystem: subsystem,
              partsName: partsName,
              parameterPer: 2, // 2是编辑
              userId: userId
            })
          }
        }
      })
      console.log(
        '收集到的权限:',
        permissions,
        'nodeMap中的参数节点数量:',
        Object.keys(this.nodeMap).filter(
          (id) => this.nodeMap[id] && this.nodeMap[id].type === 'parameter'
        ).length
      )
      return permissions
    },
    // 关闭对话框
    handleDialogClose() {
      this.dialogVisible = false
      this.formData = {
        roleName: '',
        rowId: '',
        permissions: []
      }
      this.treeFilterText = ''
      this.resetAllPermissions()
      this.pendingPermissions = [] // 清空待应用的权限数据
      if (this.$refs.form) {
        this.$refs.form.clearValidate()
      }
    },
    // 提交权限配置
    handleSubmit() {
      // 收集权限数据
      const permissions = this.collectPermissions()
      if (permissions.length === 0) {
        this.$message.warning('请至少分配一个权限')
        return
      }

      this.submitting = true
      console.log(permissions, 'permissions')

      // 修改权限配置，直接传递权限数组
      const request = {
        ...api.EDIT_ROLE_CONTROL_LIST,
        params: permissions, // 直接传递数组
        disableSuccessMsg: true
      }
      this.$request(request)
        .asyncThen((resp) => {
          this.handleDialogClose()
          this.loadPermissionData()
        })
        .asyncErrorCatch((err) => {
          console.error('权限配置失败:', err)
          this.$message.error(err.message || '权限配置失败')
        })
        .finally(() => {
          this.submitting = false
        })
    },
    // 删除
    handleDelete(row, index) {
      this.$confirm('确定要删除该记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const request = {
            ...api.DELETE_ROLE_PERMISSION,
            params: {
              roleID: row.roleId || row.id || row.rowId,
              userID: getUserId()
            },
            disableSuccessMsg: true
          }
          this.$request(request)
            .asyncThen((resp) => {
              this.loadPermissionData()
            })
            .asyncErrorCatch((err) => {
              console.error('删除失败:', err)
              this.$message.error(err.message || '删除失败')
            })
        })
        .catch(() => {
          // 取消删除
        })
    },
    // 处理每页条数变化
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.pagination.currentPage = 1
      this.loadPermissionData()
    },
    // 处理当前页变化
    handleCurrentChange(val) {
      this.pagination.currentPage = val
      this.loadPermissionData()
    },
    // 处理刷新
    handleRefresh() {
      this.pagination.currentPage = 1
      this.loadPermissionData()
    },
    formatDate(date) {
      return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
    }
  }
}
</script>

<style lang="scss" scoped>
.permission-management-page {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 20px;
  background: #fff;

  .page-content {
    display: flex;
    flex-direction: column;
    gap: 16px;
  }

  .header-section {
    display: flex;
    align-items: center;
    gap: 12px;
  }

  .table-section {
    width: 100%;

    .table-toolbar {
      display: flex;
      justify-content: flex-end;
      margin-bottom: 12px;
    }
  }

  .pagination-section {
    margin-top: 16px;
    display: flex;
    justify-content: flex-end;
  }

  .link-separator {
    margin: 0 8px;
    color: #dcdfe6;
  }
}

// 人员选择下拉框样式（参考 modelDetail.vue）
::v-deep .person-select {
  .el-select-dropdown__item {
    display: flex !important;
    justify-content: space-between !important;
    padding-right: 20px !important;
  }
}

.username-text {
  color: #303133 !important;
  display: inline-block;
  text-align: right !important;
}

.user-id-text {
  color: #909399 !important;
  display: inline-block;
  margin-left: 20px;
  margin-right: 30px;
  text-align: right !important;
}

// 权限配置弹窗样式
::v-deep .permission-config-dialog {
  .el-dialog__body {
    padding: 20px;
  }

  .permission-config-content {
    display: flex;
    flex-direction: column;
    height: 500px;
  }

  .permission-tree-wrapper {
    flex: 1;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    padding: 10px;
    overflow: hidden;
    display: flex;
    flex-direction: column;

    .tree-search-input {
      margin-bottom: 10px;
    }

    .permission-tree {
      flex: 1;
      overflow-y: auto;

      .custom-tree-node {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 14px;
        padding-right: 8px;
        width: 100%;

        .node-label {
          flex: 1;
          display: flex;
          align-items: center;
          gap: 8px;

          .type-tag {
            font-size: 12px;
            padding: 2px 6px;
            border-radius: 2px;
            color: #fff;
            white-space: nowrap;

            &.menu-tag {
              background-color: #909399;
            }

            &.subsystem-tag {
              background-color: #409eff;
            }

            &.parameter-tag {
              background-color: #67c23a;
            }
          }
        }

        .permission-checkboxes {
          display: flex;
          align-items: center;
          gap: 16px;
          margin-left: 12px;
          flex-shrink: 0;

          ::v-deep .el-checkbox {
            margin-right: 0;

            .el-checkbox__label {
              font-size: 12px;
              padding-left: 4px;
            }
          }
        }
      }
    }
  }
}

::v-deep .el-popper {
  width: auto !important;
}

.page-content {
  width: calc(100% - 80px) !important;
}
</style>
