<script setup>
import { ref, onMounted, reactive, computed, watch, nextTick } from 'vue'
import ElementPlus from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import moment from 'moment'
import { InfoFilled, UserFilled } from '@element-plus/icons-vue'
import _ from 'lodash'
import request from '@/util/http'
import API from '@/util/http'
import { } from 'vue';
// 客户明细表格   什么表格？？？？？？？
const tableData = ref([])
const roleData = ref([])
const total = ref(100)
const roleTotal = ref(100)//角色分页
const checkTab = ref('admin')
// 搜索admin
const admin = ref({
  account: '',
  market: '',
  postiton: ''
})
// 角色搜索
const role = ref({
  name: ''
})
// 搜索对象
const getObj = ref({
  pageNum: 1,
  pageSize: 10
})
// 角色搜索对象
const getRoleObj = ref({
  pageNum: 1,
  pageSize: 10
})
// 新增用户权限弹窗
const userAddVisible = ref(false)
// 编辑用户权限弹窗
const userEditVisible = ref(false)
//选地区
const market = ref([])
// 选部门
const postiton = ref([])
// 新增用户对象
const userAddObj = ref({})
// 新增角色弹窗
const permissionAddVisible = ref(false)
// 新增用户权限对象，机器码要实现存储多个，addMachineIdInput方法实现
const addAdmin = ref({
  account: '',
  name: '',
  market: [],
  permission: '',
  postiton: '',
  machineIds: [''], // 动态添加的机器码输入框
  machineId: '',
  remark: ''
})
// 新增角色对象
const addRole = ref({
  roleName: '',
  parentId: null,
  checkedKeys: [],
  grade: '',
  market: ''
})
const addRoleMarket = ref([])
// 新增角色的权限列表
const permissionSelect = ref()
//这是获取用户信息的接口
const adminData = ref({})
const getAdminData = async function () {
  try {
    const result = await API({ url: '/admin/userinfo', data: {} })
    adminData.value = result
    // console.log('请求成功', result)
    console.log('管理员用户信息', adminData.value)
  } catch (error) {
    console.log('请求失败', error)
  }
}
const viewRole = ref([])
const getRolePermission = async function () {
  const result = await request({
    url: '/menu/tree',
    data: {
      "id": adminData.value.roleId
    }
  })
  viewRole.value = collectIds(result.data)
  console.log('result111', viewRole.value);
}
// 编辑用户权限对象
const permissionEditObj = ref({
  checkedKeys: [],
  machineIds: [''],
  machineId: '',
  password: '',
  postiton:''
})
const addMachineIdInput = function () {
  if (addAdmin.value.machineIds.length >= 2) {
    ElMessage.warning('设备数量已达上限')
    return
  }
  addAdmin.value.machineIds.push('')
}
const UseraddMachineIdInput = function () {
  if (permissionEditObj.value.machineIds.length >= 2) {
    ElMessage.warning('设备数量已达上限')
    return
  }
  permissionEditObj.value.machineIds.push('')
}

// 删除权限对象
const delObj = ref({})
// 删除角色对象
const delRoleObj = ref({})
const get = async function (val) {
  try {
    if (typeof val === 'number') {
      getObj.value.pageNum = val
    }
    console.log('搜索参数', getObj.value, admin.value)
    const result = await request({
      url: '/permission/getPermission',
      data: {
        ...getObj.value,
        permission: {
          ...admin.value
        }
      }
    })
    tableData.value = result.data.list
    console.log('tableData', tableData.value)
    total.value = result.data.total
  } catch (error) {
    console.log('请求失败', error)
  }
}
const getRoleList = async function (val) {
  try {
    if (typeof val === 'number') {
      getObj.value.pageNum = val
    }
    console.log('搜索参数', getObj.value, role.value)
    const result = await request({
      url: '/role/selectBy',
      data: {
        ...getRoleObj.value,
        roleVo: {
          roleName: role.value.name
        }
      }
    })
    roleData.value = result.data.list
    console.log('roleData', roleData.value)
    roleTotal.value = result.data.total
  } catch (error) {
    console.log('请求失败', error)
  }
}
// 试试D老师的方法
const formatPermissions = (tree) => {
  if (!tree || tree.length === 0) return '';

  return tree.map(menu => {
    const mainMenu = menu.menuName;
    const subMenus = menu.children?.map(child => child.menuName) || [];

    // 如果有子菜单，显示前2个子菜单名称
    if (subMenus.length > 0) {
      const maxSub = Math.min(2, subMenus.length);
      const subText = subMenus.slice(0, maxSub).join('、');
      const moreText = subMenus.length > maxSub ? '...' : '';
      return `${mainMenu}+${subText}${moreText}`;
    }

    // 没有子菜单时只显示主菜单
    return mainMenu;
  }).join('+');
};
const trimJwCode = () => {
  if (admin.value.account) {
    admin.value.account = admin.value.account.replace(/\s/g, '');
  }
}
const search = function () {
  trimJwCode();
  getObj.value.pageNum = 1
  get()
}
const searchRole = function () {
  trimJwCode();
  getObj.value.pageNum = 1
  getRoleList()
}
// 重置
const reset = function () {
  admin.value = {}
  role.value.name = ''

  get()
  getRoleList()
}
const RoleArea = ref([])
const getRoleArea = async function () {
  try {
    const result = await request({
      url: '/general/allRoleMarket',
      data: {}
    })
    RoleArea.value = result.data
  } catch (error) {
    console.log('请求失败', error)
  }
}
const getArea = async function () {
  try {
    const result = await request({
      url: '/general/adminMarkets',
      data: { account: adminData.value.account }
    })
    market.value = result.data
  } catch (error) {
    console.log('请求失败', error)
  }
}
// 获取部门
const getStore = async function () {
  try {
    const result = await request({
      url: '/permission/getposition',
      data: {}
    })
    postiton.value = result.data
  } catch (error) {
    console.log('请求失败', error)
  }
}

// 打开新增用户权限弹窗
const openUserAddVisible = function () {
  getRoles()
  userAddVisible.value = true
  addAdmin.value = {
    account: '',
    name: '',
    market: '',
    permission: '',
    postiton: '',
    machineId: '',
    machineIds: [''],
    remark: ''
  };

}
// 新增角色弹窗
const openPermissionAddVisible = function () {
  permissionAddVisible.value = true
  const addRole = ref({
    roleName: '',
    parentId: null,
    checkedKeys: [],
    grade: '',
    market: ''
  })
  getRoles()
  getLists()
}
// 关闭新增用户权限弹窗，并刷新表单
const closeUserAddVisible = function () {
  addAdmin.value = {
    account: '',
    name: '',
    market: '',
    permission: '',
    postiton: '',
    machineId: '',
    machineIds: [''],
    remark: ''
  };
  userAddVisible.value = false;
  // 清除表单验证状态
  Ref.value.resetFields();
}
const closePermissionAddVisible = function () {
  addRole.value = {
    roleName: '',
    parentId: null,
    checkedKeys: [],
    grade: '',
    market: ''
  }
  permissionAddVisible.value = false
  Ref.value.resetFields();
  getRoleList()
}
// 新增用户权限初始化
const userAddInit = function () {
  userAddObj.value = {}
  openUserAddVisible()
}
// 新增角色初始化
const permissionAddInit = function () {
  openPermissionAddVisible()
}
//新增用户
const permissionAdd = async function () {
  try {
    await new Promise((resolve, reject) => {
      Ref.value.validate((valid) => {
        if (valid) {
          resolve(); // 验证通过，继续执行后续代码
        } else {
          reject(new Error('请检查并完善表单信息')); // 验证失败，抛出错误
        }
      });
    });
    addAdmin.value.adminFlag = 1
    addAdmin.value.status1 = 1
    if (addAdmin.value.postiton == '管理员') {
      addAdmin.value.postiton == 1
    }
    const params = {
      "account": addAdmin.value.account,//OA号
      "adminName": addAdmin.value.name,//姓名
      "market": addAdmin.value.market,//地区
      "roleId": addAdmin.value.permission,//权限ID
      "postiton": addAdmin.value.postiton,//职位
      "machineId": addAdmin.value.machineIds[0],//机器码
      "remark": addAdmin.value.remark//备注
    }
    const result = await request({
      url: '/permission/addPermission',
      data: params
    })
    console.log(addAdmin.value)

    if (result.code == 200) {
      ElMessage.success('添加成功')
    } else {
      ElMessage.error(result.msg)
    }

    addAdmin.value = {}
    get()

    closeUserAddVisible()
  } catch (error) {
    console.log('新增用户权限失败', error)

    ElMessage.error('新增用户权限失败')
  }
}
const addUserRules = {
  account: [
    { required: true, message: '请输入OA号', trigger: 'blur' },
    { pattern: /^\d+$/, message: 'OA号必须为数字', trigger: 'blur' },
    { max: 20, message: '长度不能超过20位', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { max: 20, message: '长度不能超过20位', trigger: 'blur' }
  ],
  market: [
    { required: true, message: '请选择所属地区', trigger: 'change' }
  ],
  permission: [
    { required: true, message: '请选择角色名称', trigger: 'change' }
  ],
  postiton: [
    { required: true, message: '请输入职位', trigger: 'blur' },
    { max: 20, message: '长度不能超过20位', trigger: 'blur' }
  ],
  machineIds: [
    {
      required: true,
      message: '请至少输入一个机器码',
      trigger: 'change',
      validator: (rule, value, callback) => {
        // 检查是否有非空的机器码
        const hasValid = value.some(item => item.trim() !== '');
        if (!hasValid) {
          callback(new Error('请至少输入一个机器码'));
        } else {
          callback();
        }
      }
    }
  ]
};
// 表单验证ref
const Ref = ref(null)

// 权限类别
const permissionList = ref([])
const getRoles = async function () {
  try {
    const res = await API({ url: '/role/selectAll' })
    permissionList.value = res.data.map(item => ({
      label: item.roleName,
      value: item.id
    }))

    console.log('权限列表:', permissionList.value)
  } catch (error) {
    console.error('获取权限列表失败:', error)
  }
}

// 打开编辑用户权限弹窗
const openUserEditVisible = function () {
  userEditVisible.value = true
}
// 关闭编辑用户权限弹窗
const closeUserEditVisible = function () {
  userEditVisible.value = false
  data.value = []
}
// 编辑用户权限初始化
const permissionEditInit = async function (row) {
  getRoles()
  console.log('row', row)
  permissionEditObj.value = {}
  permissionEditObj.value.id = row.id
  permissionEditObj.value.account = row.account
  permissionEditObj.value.adminName = row.name
  permissionEditObj.value.remark = row.remark
  permissionEditObj.value.market = row.market
  permissionEditObj.value.password = ''
  // 将字符串形式的 market 转换为数组
  if (typeof row.market === 'string' && row.market) {
    permissionEditObj.value.market = row.market.split(',');
  } else {
    // 处理空值或非字符串情况
    permissionEditObj.value.market = [];
  }
  permissionEditObj.value.postiton = row.postiton || ''
  if(permissionEditObj.value.postiton ==' '){
    permissionEditObj.value.postiton = ''
  }
  permissionEditObj.value.roleId = row.roleId
  const result = await request({
    url: '/role/selectFather',
    data: {
      id: row.roleId
    }
  })
  console.log('初始查上级权限', result)
  permissionEditObj.value.parentId = result.data?.fatherId
  permissionEditObj.value.parentName = result.data?.fatherName
  console.log('get前', permissionEditObj.value.roleId);
  permissionEditObj.value.roleName = row.roleName
  if (permissionEditObj.value.roleId == 0) {
    permissionEditObj.value.roleId = ''
  }
  getUserLists(row.roleId)

  let machineIdsRef = await request({
    url: '/permission/getPermission',
    data: {
      "pageNum": 1,//页码数
      "pageSize": 1,//页条数
      "permission": {
        account: row.account,//OA号
      }
    }
  })

  if (machineIdsRef.data.list[0].machineIds == null || machineIdsRef.data.list[0].machineIds.length == 0) {
    permissionEditObj.value.machineIds = ['']
  } else {
    permissionEditObj.value.machineIds = machineIdsRef.data.list[0].machineIds
  }
  permissionEditObj.value.machineId = permissionEditObj.value.machineIds[0]
  //permissionEditObj.value.permission = row.permission

  console.log('编辑用户权限', permissionEditObj.value)
  console.log('11111111111111', permissionEditObj.value.machineId)
  openUserEditVisible()
}
const collectIds = (tree) => {
  let ids = [];
  tree.forEach((node) => {
    ids.push(node.id);
    if (node.children && node.children.length > 0) {
      ids = ids.concat(collectIds(node.children));
    }
  });
  return ids;
};
// 定义上级角色提示变量
const parentRoleTip = ref('');
//给data数据加上disabled属性，控制是否禁用
function processTreeData(data) {
  return data.map(item => ({
    ...item,
    disabled: item.id != null || item.menuName.includes("敏感权限"), //控制权限显示的条件
    children: item.children ? processTreeData(item.children) : []
  }));
}
//根据上级角色控制权限列表,选择角色调整上级角色
const getUserLists = async function (selectedRoleId) {
  try {
    console.log('permissionEditObj.value.roleId:', permissionEditObj.value.roleId)
    console.log('selectedRoleId', selectedRoleId);
    permissionEditObj.value.parentId = null;
    permissionEditObj.value.parentName = '';
    permissionEditObj.value.checkedKeys = [];
    parentRoleTip.value = '';
    const parentRes = await request({
      url: '/role/selectFather',
      data: { id: selectedRoleId }  // 用选中的角色ID请求
    });
    const parentId = parentRes.data.fatherId;
    const parentName = parentRes.data.parentName;

    permissionEditObj.value.parentId = parentId;
    permissionEditObj.value.parentName = parentName;
    if (parentId == null) {
      // 无上级角色：显示提示
      parentRoleTip.value = '该角色无上级角色';
    }

    let roleId = permissionEditObj.value.roleId
    if (permissionEditObj.value.parentId === null || permissionEditObj.value.parentId === undefined) {
      roleId = 2
    }
    const res = await API({
      url: '/menu/tree',
      data: { id: roleId }
    })
    data.value = processTreeData(res.data)
    permissionEditObj.value.checkedKeys = collectIds(res.data) || [];
    console.log('看看data', data.value)
    console.log('看checkedKeys', permissionEditObj.value.checkedKeys)
    console.log('parentID:', permissionEditObj.value.parentId, 'roleId:', roleId)
    console.log('permissionEditObj.value.roleId:', permissionEditObj.value.roleId)
  } catch (error) {
    console.log('请求失败', error)
  }
}
//编辑用户表单校验
const editAdminRules = {
  market: [
    { required: true, message: '请选择所属地区', trigger: 'change' }
  ],
  postiton: [
    { required: true, message: '请输入职位', trigger: ['blur', 'change'] },
    { max: 20, message: '长度不能超过20位', trigger: ['blur', 'change'] }
  ],
  machineIds: [
    {
      required: true,
      message: '请至少输入一个机器码',
      trigger: 'change',
      validator: (rule, value, callback) => {
        // 检查是否有非空的机器码
        const hasValid = value.some(item => item.trim() !== '');
        if (!hasValid) {
          callback(new Error('请至少输入一个机器码'));
        } else {
          callback();
        }
      }
    }
  ]
};
// 编辑用户权限提交
const permissionEdit = async function () {
  let { adminName: userName, roleName: oldRole, roleId: newRoleId } = permissionEditObj.value;
  if (oldRole == null) {
    oldRole = '暂未分配角色'
  }
  const newRole = permissionList.value.find(item => item.value === newRoleId)?.label || '未知角色';
  try {
    await new Promise((resolve, reject) => {
      Ref.value.validate((valid) => {
        if (valid) {
          resolve(); // 验证通过，继续执行后续代码
        } else {
          reject(new Error('请检查并完善表单信息')); // 验证失败，抛出错误
        }
      });
    });
    await ElMessageBox.confirm(
        `确认修改权限角色？<br>您正在将【${userName}】的权限角色从【${oldRole}】修改为【${newRole}】<br>变更后，该用户的可操作权限将同步更新为新角色配置，涉及数据访问、功能操作等权限变化，请谨慎确认。`,
        '警告',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: "warning",
          lockScroll: false,
          dangerouslyUseHTMLString: true //允许解析 HTML 标签
        }
    )
    const result = await request({
      url: '/permission/updateAdmin',
      data: {
        account: permissionEditObj.value.account,//OA号
        adminName: permissionEditObj.value.adminName,//姓名
        market: permissionEditObj.value.market,//地区
        postiton: permissionEditObj.value.postiton,//职位
        roleId: permissionEditObj.value.roleId,//角色id
        machineId: permissionEditObj.value.machineIds[0],//机器码
        machineIds: permissionEditObj.value.machineIds[1],//机器码
        password: permissionEditObj.value.password,//
        remark: permissionEditObj.value.remark//备注
      }
    });
    console.log('编辑最后提交数据', permissionEditObj.value);
    if (result.code == 200) {
      await ElMessageBox.alert(
          `用户${userName}的权限角色已更改为【${newRole}】`,
          '成功',
          {
            confirmButtonText: '确定',
            type: 'success' // 设置为 success 类型
          }
      );
      get();
      closeUserEditVisible();
    } else {
      ElMessage.error(result.msg)
    }

  } catch (error) {
    console.log('编辑用户权限失败', error)
    ElMessage.error('编辑用户权限失败')
  }
}


// 删除初始化
const del = function (row) {
  delObj.value = {}
  console.log(row, '删除初始化')
  delObj.value.account = row.account
  delObj.value.id = row.id
}
// 删除权限
const delConfirm = async function () {
  try {
    const result = await request({
      url: '/permission/deleteAdmin',
      data: delObj.value
    })
    console.log('看看删除对象', delObj.value)
    console.log('请求成功1', result)

    ElMessage.success('删除权限成功')
    delObj.value = {}
    get()
  } catch (error) {
    console.log('删除权限失败', error)
    ElMessage.error('删除权限失败')
  }
}
// // 删除角色初始化
// const delRole = function (row) {
//   delRoleObj.value = {}
//   console.log(row, '删除初始化')
//   delRoleObj.value.id = row.id
// }
// // 删除角色
// const delRoleConfirm = async function () {
//   try {
//     const result = await request({
//       url: '/role/delete',
//       data: delRoleObj.value
//     })
//     console.log('看看删除角色对象', delRoleObj.value)
//     console.log('请求成功2', result)
//     ElMessage.success('删除权限成功')
//     delRoleObj.value = {}
//     getRoleList()
//   } catch (error) {
//     console.log('删除权限失败', error)
//     ElMessage.error('删除权限失败')
//   }
// }
const handleAddRole = async function () {
  try {
    await new Promise((resolve, reject) => {
      Ref.value.validate((valid) => {
        if (valid) {
          resolve(); // 验证通过，继续执行后续代码
        } else {
          reject(new Error('请检查并完善表单信息')); // 验证失败，抛出错误
        }
      });
    });
    addRole.value.roleName = addRole.value.roleName.replace(/\s+/g, '');
    console.log('去除角色名空格：', addRole.value.roleName);

    // 确保提交时包含所有选中的权限ID（包括父节点）
    const finalCheckedKeys = addRole.value.checkedKeys || [];

    const res = await API({
      url: '/role/add',
      data: {
        "roleName": addRole.value.roleName,
        "menuIds": finalCheckedKeys,
        "priority": addRole.value.grade,
        "fatherId": addRole.value.parentId,
        "market": addRole.value.market
      }
    })
    if (res.code == 200) {
      ElMessage.success('角色' + addRole.value.roleName + '添加成功')
      console.log('成功了，看看addRole', addRole.value)
      console.log('提交的权限ID列表:', finalCheckedKeys);
      closePermissionAddVisible()
    } else {
      ElMessage.error(res.msg)
    }
  } catch (error) {
    console.log('请求失败', error)
    console.log('失败，看看addRole', addRole.value);
  }
}
// 禁用启用用户权限
const editStatus = async function (row) {
  try {
    console.log(row)

    permissionEditObj.value = {}
    permissionEditObj.value.id = row.id
    permissionEditObj.value.account = row.account
    permissionEditObj.value.adminStatus = row.adminStatus
    console.log('修改用户权限状态', permissionEditObj.value)

    const result = await request({
      url: '/permission/upadatePermission',
      data: permissionEditObj.value
    })
    console.log('请求成功2', result)
    ElMessage.success(
        permissionEditObj.value.adminStatus == 1 ? '启用成功' : '禁用成功'
    )
    permissionEditObj.value = {}
    get()
  } catch (error) {
    console.log('修改用户权限失败', error)
  }
}


const handlePageSizeChange = function (val) {
  getObj.value.pageSize = val
  get()
}
const handleCurrentChange = function (val) {
  getObj.value.pageNum = val
  get()
}
const handleRolePageSizeChange = (val) => {
  getRoleObj.value.pageSize = val
  getRoleList() // 调用角色管理的查询
}

// 角色管理分页 - 当前页变化
const handleRoleCurrentChange = (val) => {
  getRoleObj.value.pageNum = val
  getRoleList() // 调用角色管理的查询
}

const data = ref([])
const getLists = async function () {
  try {
    console.log('addRole.value.roleId', addRole.value.roleId);

    let roleId = addRole.value.parentId
    if (addRole.value.parentId === null || addRole.value.parentId === undefined) {
      roleId = 2
    }
    const res = await API({
      url: '/menu/tree',
      data: { id: roleId }
    })
    data.value = res.data
    data.value = data.value.filter(item => item.id !== 9);
    console.log('看看data', data.value)
    console.log('parentID:', addRole.value.parentId, 'roleId:', roleId)

    if (addRole.value.parentId && addRole.value.parentId != 2) {
      const result = await API({
        url: '/general/roleMarket',
        data: { id: addRole.value.parentId }
      })
      if (result.code == 200) {
        if (typeof result.data === 'string' && result.data) {
          addRoleMarket.value = result.data.split(',');
          addRole.value.market = ''
        } else if (Array.isArray(result.data)) {
          addRoleMarket.value = result.data
          addRole.value.market = ''
        }
        else {
          addRoleMarket.value = [];
          addRole.value.market = ''
        }
      } else {
        ElMessage.error('该上级角色无所属地区')
        console.log('该上级角色无所属地区');

      }
      console.log('addRoleMarket.value', addRoleMarket.value);
    } else {
      addRoleMarket.value = RoleArea.value
      console.log('elseRoleArea', RoleArea);

    }

  } catch (error) {
    console.log('请求失败', error)
  }
}
const handleMarketChange = (values) => {
  console.log('values的类型:', typeof values);
  console.log('values的值:', values);
  //判断是否选择了总部
  const hasHeadquarters = values.includes('总部');

  if (hasHeadquarters) {
    // 如果选择了总部，只保留总部
    addAdmin.value.market = ['总部'];
  }
  console.log('看看现在的地区', addAdmin.value.market);

};
const includeHq = computed(() => {
  const i = addAdmin.value.market.includes('总部')
  return (item) => i && item != '总部'
})
const EditincludeHq = computed(() => {
  const i = permissionEditObj.value.market.includes('总部')
  return (item) => i && item != '总部'
})
const EdithandleMarketChange = (values) => {
  //判断是否选择了总部
  const hasHeadquarters = values.includes('总部');
  if (hasHeadquarters) {
    // 如果选择了总部，只保留总部
    permissionEditObj.value.market = ['总部'];
  }
  console.log('看看现在的地区', permissionEditObj.value.market);

};
const treeRef = ref(null)
// 处理编辑角色权限时的勾选事件
const handleEditRolePermissionCheck = (checkedNodes, checkedInfo) => {
  const { checkedKeys, checkedNodes: allCheckedNodes } = checkedInfo;

  // 判断是否有选中的节点
  if (allCheckedNodes.length === 0) {
    permissionEditRoleObj.value.checkedKeys = [];
    return;
  }

  // 由于设置了 check-strictly="false"，Element Plus 会自动处理父子节点联动
  // 我们只需要使用 checkedKeys，它已经包含了所有必要的节点ID
  permissionEditRoleObj.value.checkedKeys = checkedKeys;

  console.log('编辑角色选中的权限ID:', checkedKeys);
  console.log('选中的节点数量:', allCheckedNodes.length);
};






const handleCheckChange = async (checkedNodes, checkedInfo) => {
  const { checkedKeys, checkedNodes: allCheckedNodes } = checkedInfo;

  // 判断是否有选中的节点
  if (allCheckedNodes.length === 0) {
    addRole.value.checkedKeys = [];
    return;
  }

  // 创建一个Set存储所有需要选中的ID（包括父级）
  const allKeys = new Set(checkedKeys);

  // 遍历所有选中的节点，为每个节点添加其父级
  allCheckedNodes.forEach(node => {
    // 为每个选中的节点单独查找父级
    selectParentNodes(data.value, node.id, allKeys);
  });

  // 将Set转换为数组并更新
  addRole.value.checkedKeys = Array.from(allKeys);
  console.log('新增角色包含所有父级的选中项:', addRole.value.checkedKeys);
};

const selectParentNodes = (treeData, nodeId, checkedKeys) => {
  if (!Array.isArray(treeData)) return false;

  for (const item of treeData) {
    // 先检查子节点
    if (item.children && item.children.length > 0) {
      const foundInChildren = selectParentNodes(item.children, nodeId, checkedKeys);
      if (foundInChildren) {
        // 找到子节点后添加当前节点（父节点）
        checkedKeys.add(item.id);
        return true;
      }
    }

    // 检查当前节点是否为目标节点
    if (item.id === nodeId) {
      return true;
    }
  }

  return false;
};
//点击角色权限菜单树点击展示逻辑
const menuTreeVisible = ref(false);
const currentRoleMenuTree = ref([]);
const currentRoleName = ref('');
const Rolecheckedkeys = ref([])
const showMenuTree = (treeData, roleName) => {
  currentRoleMenuTree.value = processTreeData(treeData) || [];
  console.log('currentRoleMenuTree.value', currentRoleMenuTree.value);
  Rolecheckedkeys.value = collectIds(treeData)
  console.log('Rolecheckedkeys', Rolecheckedkeys.value);

  currentRoleName.value = roleName || '权限详情';
  menuTreeVisible.value = true;
};


// 重置密码弹窗状态
const resetConfirmVisible = ref(false)
// 当前选中的行数据
const currentRow = ref(null)
// 重置密码
const resetPassword = function (row) {
  // 显示确认弹窗
  currentRow.value = row
  resetConfirmVisible.value = true
}

// 确认重置密码
const confirmResetPassword = async function () {
  console.log('adminData', adminData.value)
  // 处理markets数据
  if (typeof adminData.value.markets === 'string' && adminData.value.markets) {
    adminData.value.markets = adminData.value.markets.split(',');
  } else if (Array.isArray(adminData.value.markets)) {
    // 不处理
  }
  else {
    adminData.value.markets = [];
  }

  console.log('重置密码markets2', adminData.value.markets)


  // 权限检查
  if (adminData.value.markets.includes(currentRow.value.market) || adminData.value.markets[0] === '总部') {

    console.log('符合条件，可以操作', adminData.value.markets.includes(currentRow.value.market) || adminData.value.markets[0] === '总部');
    const params = {
      account: currentRow.value.account,
    }
    console.log(params);

    // 发送请求
    try {
      const result = await request({
        url: '/admin/reset',
        method: 'post',
        data: params // 直接传递params对象
      });

      if (result.code === 200) { // 使用严格相等运算符
        ElMessage.success('重置密码成功');
        resetConfirmVisible.value = false; // 关闭弹窗
      } else {
        ElMessage.error(result.message || '重置密码失败');
      }
    } catch (error) {
      ElMessage.error('重置密码失败');
      console.error('请求错误:', error);
    }
  } else {
    // console.log("为什么不能重置",adminData.value.markets)
    ElMessage.error('您没有修改' + currentRow.value.market + '地区的用户密码的权限');
    resetConfirmVisible.value = false; // 关闭弹窗
  }
}

// 取消重置密码
const cancelResetPassword = function () {
  resetConfirmVisible.value = false
}

// 编辑角色对象
const permissionEditRoleObj = ref({
  id: null,
  roleName: '',
  market: '',
  parentId: null,
  parentName: '',
  checkedKeys: [],
  grade: '',
});

// 编辑角色弹窗
const permissionEditRoleVisible = ref(false);

const collectIds2 = (tree) => {
  let ids = [];
  tree.forEach((node) => {
    // 如果当前节点没有 children 或 children 为空，说明是叶子节点
    if (!node.children || node.children.length === 0) {
      ids.push(node.id);
    } else {
      // 如果有 children，递归收集子节点的叶子节点
      ids = ids.concat(collectIds2(node.children));
    }
  });
  return ids;
};


// 编辑角色初始化
const permissionEditRoleInit = async function (row) {
  console.log('row', row);
  console.log('row.tree', row.tree);
  permissionEditRoleObj.value = {};
  permissionEditRoleObj.value.id = row.id;
  permissionEditRoleObj.value.roleName = row.roleName;
  permissionEditRoleObj.value.market = row.market;
  permissionEditRoleObj.value.parentId = row.fatherId;
  permissionEditRoleObj.value.parentName = row.fatherName;
  permissionEditRoleObj.value.grade = row.priority;

  try {
    let roleId = permissionEditRoleObj.value.parentId;
    // 如果没有上级角色，设置为管理员的id
    if (permissionEditRoleObj.value.parentId === null || permissionEditRoleObj.value.parentId === undefined) {
      roleId = 2;
    }
    // 调用 /tree 接口，使用上级角色 ID 获取权限列表
    const res = await API({
      url: '/menu/tree',
      data: { id: roleId }
    });
    data.value = res.data;
    data.value = data.value.filter(item => item.id !== 9);

    // 收集当前行权限树的叶子节点id（只收集实际选中的叶子节点）
    if (row.tree && row.tree.length > 0) {
      const leafIds = collectIds2(row.tree);
      permissionEditRoleObj.value.checkedKeys = leafIds;
      console.log('编辑角色初始化时的权限列表', permissionEditRoleObj.value.checkedKeys);
    } else {
      permissionEditRoleObj.value.checkedKeys = [];
    }
  } catch (error) {
    console.log('根据上级角色获取权限列表失败', error);
    data.value = [];
    permissionEditRoleObj.value.checkedKeys = [];
  }
  console.log('编辑角色', permissionEditRoleObj.value);
  permissionEditRoleVisible.value = true;

  // 等待DOM更新后手动设置树的选中状态
  await nextTick();
  if (treeRef.value && permissionEditRoleObj.value.checkedKeys.length > 0) {
    treeRef.value.setCheckedKeys(permissionEditRoleObj.value.checkedKeys);
    console.log('手动设置树的选中状态:', permissionEditRoleObj.value.checkedKeys);
  }
};

// 编辑角色提交
const permissionEditRole = async function () {
  try {
    await new Promise((resolve, reject) => {
      Ref.value.validate((valid) => {
        if (valid) {
          resolve();
        } else {
          reject(new Error('请检查并完善表单信息'));
        }
      });
    });

    // 确保提交时包含所有选中的权限ID（包括父节点）
    let finalCheckedKeys = permissionEditRoleObj.value.checkedKeys || [];

    // 为所有选中的节点添加其父节点ID
    const allKeys = new Set(finalCheckedKeys);
    finalCheckedKeys.forEach(nodeId => {
      selectParentNodesForSubmit(data.value, nodeId, allKeys);
    });

    finalCheckedKeys = Array.from(allKeys);

    const res = await API({
      url: '/menu/update',
      data: {
        "id": permissionEditRoleObj.value.id,
        "roleName": permissionEditRoleObj.value.roleName,
        "menuIds": finalCheckedKeys,
        "priority": permissionEditRoleObj.value.grade,
        "fatherId": permissionEditRoleObj.value.parentId,
        "market": permissionEditRoleObj.value.market
      }
    });
    if (res.code === 200) {
      console.log('编辑角色成功', permissionEditRoleObj.value);
      console.log('提交的权限ID列表:', finalCheckedKeys);
      permissionEditRoleVisible.value = false;
      getRoleList();
      ElMessage.success('编辑角色成功');
    } else if (res.code === 0) {
      console.log('角色名重复', permissionEditRoleObj.value);
      ElMessage.error('角色名重复');
    } else {
      console.log('编辑角色失败', res);
      ElMessage.error('编辑角色失败');
    }
  } catch (error) {
    console.log('编辑角色失败', error);
    console.log('失败，看看permissionEditRoleObj', permissionEditRoleObj.value);
  }
};

// 为提交时查找父节点的辅助函数
const selectParentNodesForSubmit = (treeData, nodeId, checkedKeys) => {
  if (!Array.isArray(treeData)) return false;

  for (const item of treeData) {
    // 先检查子节点
    if (item.children && item.children.length > 0) {
      const foundInChildren = selectParentNodesForSubmit(item.children, nodeId, checkedKeys);
      if (foundInChildren) {
        // 找到子节点后添加当前节点（父节点）
        checkedKeys.add(item.id);
        return true;
      }
    }

    // 检查当前节点是否为目标节点
    if (item.id === nodeId) {
      return true;
    }
  }

  return false;
};




// // 挂载 怎么有俩挂载，注掉一个
// onMounted(async function () {
//   await get()
//   await getArea()
//   await getStore()
//   await getRoleList()
//   await getAdminData()
// })

const Rolerules = reactive({
  roleName: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 20, message: '角色名称长度应在2-20个字符之间', trigger: 'blur' }
  ],
  market: [
    { required: true, message: '请选择所属地区', trigger: 'change' }
  ],
  grade: [
    { required: true, message: '请输入优先级', trigger: 'blur' },
    { pattern: /^[1-9]\d{0,2}$/, message: '优先级应为1-999的数字', trigger: 'blur' }
  ],
  checkedKeys: [
    {
      required: true,
      message: '请选择权限列表',
      trigger: 'change', // 选框变化或提交时触发，可根据实际调整
      validator: (rule, value, callback) => {
        if (value && value.length > 0) {
          callback(); // 有选中项，校验通过
        } else {
          callback(new Error('请选择权限列表')); // 未选中，抛出错误提示
        }
      }
    }
  ]
});

const throttledPermissionEdit = _.throttle(permissionEdit, 5000, {
  trailing: false
})
const throttledHandleAddRole = _.throttle(handleAddRole, 5000, {
  trailing: false
})
// 使用 _.throttle 并设置 trailing 为 false 实现严格节流，只执行一次
const throttledPermissionAdd = _.throttle(permissionAdd, 5000, {
  trailing: false
})

// 挂载
onMounted(async function () {
  await getAdminData()
  await get()
  await getArea()
  await getStore()
  await getRoleList()
  await getRolePermission()
  await getRoleArea()
})


</script>

<template>
  <div style="margin-bottom:20px">
    <el-button-group>
      <el-button :type="checkTab === 'admin' ? 'primary' : 'default'" @click="checkTab = 'admin'">
        用户管理
      </el-button>
      <el-button v-if="viewRole.includes(30)" :type="checkTab === 'role' ? 'primary' : 'default'"
                 @click="checkTab = 'role'">
        角色管理
      </el-button>
    </el-button-group>
  </div>
  <div v-show="checkTab === 'admin'">
    <!-- 用户搜索和展示 -->
    <el-row>
      <el-col>
        <el-card style="margin-bottom: 20px">
          <div class="head-card">
            <div class="head-card-element">
              <el-text class="mx-1" size="large">OA号：</el-text>
              <el-input v-model="admin.account" style="width: 240px" placeholder="请输入OA号" clearable />
            </div>
            <div class="head-card-element" style="margin-left: 50px">
              <el-text class="mx-1" size="large">所属地区：</el-text>
              <el-select v-model="admin.market" placeholder="请选择所属地区" style="width: 240px" clearable>
                <el-option v-for="item in market" :key="item" :label="item" :value="item" />
              </el-select>
            </div>
            <div class="head-card-element" style="margin-left: 50px">
              <el-text class="mx-1" size="large">职位名称：</el-text>
              <el-select v-model="admin.postiton" placeholder="请选择职位名称" style="width: 240px" clearable>
                <el-option v-for="item in postiton" :key="item" :label="item" :value="item" />
              </el-select>
            </div>

            <div class="head-card-btn">
              <el-button type="success" @click="reset()">重置</el-button>
              <el-button type="primary" @click="search()">查询</el-button>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row>
      <el-col>
        <el-card>
          <!-- 展示表单 -->
          <div class="add-item">
            <el-button style="color: #048efb; border: 1px solid #048efb" @click="userAddInit()">新增用户</el-button>
          </div>

          <div>
            <el-table :data="tableData" style="width: 100%" show-overflow-tooltip>
              <el-table-column type="index" label="序号" width="100px" fixed="left">
                <template #default="scope">
                  <span>{{
                      scope.$index + 1 + (getObj.pageNum - 1) * getObj.pageSize
                    }}</span>
                </template>
              </el-table-column>

              <el-table-column prop="account" label="OA号" />
              <el-table-column prop="name" label="姓名" />
              <el-table-column prop="market" label="所属地区" />
              <el-table-column prop="postiton" label="职位" />
              <el-table-column prop="roleName" label="部门权限">
              </el-table-column>
              <el-table-column prop="remark" label="备注" />
              <el-table-column prop="operation" label="操作" width="280px">
                <template #default="scope">
                  <el-button type="warning" text @click="resetPassword(scope.row)">
                    重置密码
                  </el-button>
                  <el-button type="primary" text @click="permissionEditInit(scope.row)"
                             :disabled="scope.row.adminStatus === 0 || scope.row.account === adminData.account">
                    修改权限
                  </el-button>
                  <el-popconfirm title="确定将此用户删除吗？" @confirm="delConfirm">
                    <template #reference>
                      <el-button type="danger" text @click="del(scope.row)"
                                 :disabled="scope.row.adminStatus === 0 || scope.row.account === adminData.account">
                        删除
                      </el-button>
                    </template>
                    <template #actions="{ confirm, cancel }">
                      <el-button size="small" @click="cancel">取消</el-button>
                      <el-button type="primary" size="small" @click="confirm">
                        确定
                      </el-button>
                    </template>
                  </el-popconfirm>
                </template>
              </el-table-column>
              <el-table-column prop="adminStatus" label="状态">
                <template #default="scope">
                  <el-switch v-model="scope.row.adminStatus" :active-value="1" :inactive-value="0" size="large"
                             :disabled="scope.row.account === adminData.account" @change="editStatus(scope.row)" style="
                    --el-switch-on-color: #13ce66;
                    --el-switch-off-color: #ff4949;
                  " active-text="启用" inactive-text="禁用" inline-prompt />
                </template>
              </el-table-column>
            </el-table>
          </div>

          <!-- 分页 -->
          <div class="pagination" style="margin-top: 20px">
            <el-pagination background :page-size="getObj.pageSize" :page-sizes="[5, 10, 20, 50, 100]"
                           layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handlePageSizeChange"
                           @current-change="handleCurrentChange"></el-pagination>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
  <div v-show="checkTab === 'role'">
    <!-- 角色搜索 -->
    <el-card style="margin-bottom: 20px">
      <div class="head-card">
        <el-text class="mx-1" size="large">角色名称：</el-text>
        <el-input v-model="role.name" style="width: 240px" placeholder="请输入角色名称" clearable />
        <div class="head-card-btn">
          <el-button type="success" @click="reset()">重置</el-button>
          <el-button type="primary" @click="searchRole()">查询</el-button>
        </div>
      </div>
    </el-card>
    <!-- 展示表单 -->
    <el-card>

      <div class="add-item">
        <el-button style="color: #048efb; border: 1px solid #048efb" @click="permissionAddInit()">新增角色</el-button>
      </div>
      <div>
        <el-table :data="roleData" style="width: 100%" show-overflow-tooltip>
          <el-table-column type="index" label="序号" width="100px" fixed="left">
            <template #default="scope">
              <span>{{
                  scope.$index + 1 + (getRoleObj.pageNum - 1) * getRoleObj.pageSize
                }}</span>
            </template>
          </el-table-column>

          <el-table-column prop="roleName" label="角色名称" />
          <el-table-column prop="fatherName" label="上级角色" />
          <el-table-column prop="priority" label="优先级" />
          <el-table-column label="权限范围" show-overflow-tooltip>
            <template #default="scope">
              <div class="permission-cell" @click="showMenuTree(scope.row.tree, scope.row.roleName)">
                {{ formatPermissions(scope.row.tree) }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="operation" label="操作" width="200px">
            <template #default="scope">
              <el-button type="warning" text @click="permissionEditRoleInit(scope.row)" :disabled="scope.row.id === 2">
                编辑
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination" style="margin-top: 20px">
        <el-pagination background :page-size="getObj.pageSize" :page-sizes="[5, 10, 20, 50, 100]"
                       layout="total, sizes, prev, pager, next, jumper" :total="roleTotal" @size-change="handleRolePageSizeChange"
                       @current-change="handleRoleCurrentChange"></el-pagination>
      </div>
    </el-card>
  </div>
  <!-- 角色菜单树展示 -->
  <el-dialog v-model="menuTreeVisible" :title='`权限详情：${currentRoleName}`' width="600px">
    <el-tree :data="currentRoleMenuTree" node-key="id" :props="{ label: 'menuName', children: 'children' }"
             show-checkbox check-strictly :expand-on-click-node="false"
             :default-expanded-keys="currentRoleMenuTree.map(item => item.id)" :default-checked-keys="Rolecheckedkeys" />
    <template #footer>
      <el-button @click="menuTreeVisible = false" type="primary">关闭</el-button>
    </template>
  </el-dialog>
  <!-- 新增用户权限 -->
  <el-dialog v-model="userAddVisible" title="新增用户权限" width="800px" :close-on-click-modal="false">
    <template #footer>
      <!-- 居中显示 -->

      <el-form ref="Ref" :rules="addUserRules" :model="addAdmin" label-width="auto"
               style="max-width: 600px; align-items: center">
        <el-form-item prop="account" label="OA号:" required clearable>
          <el-input v-model="addAdmin.account" placeholder="请输入OA号" style="width: 220px" />
        </el-form-item>

        <el-form-item prop="name" label="用户名:" required clearable>
          <el-input v-model="addAdmin.name" placeholder="请输入用户名" style="width: 220px" />
        </el-form-item>

        <el-form-item prop="market" label="所属地区:" required clearable>
          <el-select multiple v-model="addAdmin.market" placeholder="请选择所属地区" style="width: 220px" clearable
                     @change="handleMarketChange">
            <el-option v-for="item in market" :key="item" :label="item" :value="item" :disabled="includeHq(item)" />
          </el-select>
        </el-form-item>
        <el-form-item prop="permission" label="角色名称:" required>
          <el-select v-model="addAdmin.permission" placeholder="请选择角色名称" style="width: 220px" clearable>
            <el-option v-for="item in permissionList" :key="item.value" :label="item.label"
                       :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="postiton" label="职位:" required>
          <el-input v-model="addAdmin.postiton" placeholder="请输入职位" style="width: 220px" clearable />
        </el-form-item>
        <el-form-item prop="machineIds" label="机器码:" required>
          <div style="display: flex; align-items: center; flex-wrap: wrap; gap: 10px;">
            <!-- 动态添加的机器码输入框 -->
            <div v-for="(item, index) in addAdmin.machineIds" :key="index" style="margin-left: 10px;">
              <el-input v-model="addAdmin.machineIds[index]" placeholder="请输入机器码"
                        style="width: 180px; margin-right: 10px;" />
            </div>
            <el-button type="primary" @click="addMachineIdInput">添加</el-button>
          </div>
        </el-form-item>
        <el-form-item prop="remark" label="备注">
          <el-input v-model="addAdmin.remark" style="width: 300px" :rows="2" maxlength="100" show-word-limit
                    type="textarea" />
        </el-form-item>
      </el-form>

      <div>
        <el-button @click="closeUserAddVisible()">取消</el-button>
        <el-button type="primary" @click="throttledPermissionAdd()">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 这是编辑用户权限弹窗 -->
  <el-dialog v-model="userEditVisible" title="编辑用户权限" width="800px" :close-on-click-modal="false">
    <el-form ref="Ref" :rules="editAdminRules" :model="permissionEditObj" label-width="auto"
             style="max-width: 600px; align-items: center">
      <el-form-item prop="account" label="用户账号:" clearable>
        <el-input v-model="permissionEditObj.account" placeholder="请输入OA号" style="width: 220px" disabled />
      </el-form-item>
      <el-form-item prop="name" label="用户名称:">
        <el-input v-model="permissionEditObj.adminName" placeholder="请输入用户名" style="width: 220px" disabled />
      </el-form-item>
      <el-form-item prop="market" label="所属地区:" clearable>
        <el-select multiple v-model="permissionEditObj.market" placeholder="请选择所属地区" style="width: 220px" clearable
                   @change="EdithandleMarketChange">
          <el-option v-for="item in market" :key="item" :label="item" :value="item" :disabled="EditincludeHq(item)" />
        </el-select>
      </el-form-item>
      <el-form-item prop="postiton" label="职位:">
        <el-input v-model="permissionEditObj.postiton" placeholder="请输入职位" style="width: 220px" clearable />
      </el-form-item>
      <el-form-item prop="roleName" label="角色名称:">
        <el-select v-model="permissionEditObj.roleId" placeholder="请选择角色" style="width: 220px" @change="getUserLists">
          <el-option v-for="item in permissionList" :key="item.value" :label="item.label"
                     :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="parentName" label="上级角色:">
        <el-select v-model="permissionEditObj.parentId" placeholder="无上级角色" :disabled="!!parentRoleTip"
                   style="width: 220px">
          <el-option v-if="parentRoleTip" :key="0" :label="parentRoleTip" :value="null" disabled />
          <el-option v-else v-for="item in permissionList" :key="item.value" :label="item.label" disabled
                     :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="permissionSelect" label="权限列表:">
        <el-tree v-if="data.length > 0" :data="data" :disabled="true" show-checkbox node-key="id"
                 :props="{ label: 'menuName', children: 'children' }" :default-checked-keys="permissionEditObj.checkedKeys">
        </el-tree>
        <div v-else style="display: flex; align-items: center; gap: 8px;">
          <span style="color: #999;">暂无数据</span>
        </div>
      </el-form-item>
      <el-form-item prop="machineIds" label="机器码:">
        <div style="display: flex; align-items: center; flex-wrap: wrap; gap: 10px;">
          <!-- 动态添加的机器码输入框 -->
          <div v-for="(item, index) in permissionEditObj.machineIds" :key="index" style="margin-left: 10px;">
            <el-input v-model="permissionEditObj.machineIds[index]" placeholder=""
                      style="width: 180px; margin-right: 10px;" />
          </div>
          <el-button type="primary" @click="UseraddMachineIdInput">添加</el-button>
        </div>
      </el-form-item>
    </el-form>
    <div>
    </div>
    <template #footer>
      <div>
        <el-button @click="closeUserEditVisible()">取消</el-button>
        <el-button type="primary" @click="throttledPermissionEdit">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 新增角色 -->
  <el-dialog v-model="permissionAddVisible" title="新增角色" width="800px" :close-on-click-modal="false">
    <template #footer>
      <el-form ref="Ref" :rules="Rolerules" :model="addRole" label-width="auto"
               style="max-width: 600px; align-items: center">
        <el-form-item prop="roleName" label="角色名称:" required>
          <el-input v-model="addRole.roleName" placeholder="请输入用户名" style="width: 220px" />
        </el-form-item>
        <el-form-item prop="parentName" label="上级角色:">
          <el-select v-model="addRole.parentId" placeholder="请选择上级角色" style="width: 220px" @change="getLists" clearable>
            <el-option v-for="item in permissionList" :key="item.value" :label="item.label"
                       :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="market" label="所属地区:" required>
          <el-select v-model="addRole.market" placeholder="请选择所属地区" style="width: 240px" clearable>
            <el-option v-for="item in addRoleMarket" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item prop="checkedKeys" label="权限列表:" required>
          <el-tree v-if="data.length > 0" :data="data" show-checkbox node-key="id"
                   :props="{ label: 'menuName', children: 'children' }" :checked-keys="addRole.checkedKeys"
                   :check-strictly="false"
                   @check="handleCheckChange">
            <template #default="{ node, data }">
              <span>{{ node.label }}</span>
            </template>
          </el-tree>
          <div v-else style="display: flex; align-items: center; gap: 8px;">
            <span style="color: #999;">暂无数据</span>
          </div>
        </el-form-item>
        <el-form-item prop="grade" label="优先级:" required>
          <el-input v-model="addRole.grade" placeholder="数字1~999" style="width: 220px" />
        </el-form-item>
      </el-form>

      <div>
        <el-button @click="closePermissionAddVisible()">取消</el-button>
        <el-button type="primary" @click="throttledHandleAddRole">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 重置密码确认弹窗 -->
  <el-dialog v-model="resetConfirmVisible" width="500px" :close-on-click-modal="false"
             :before-close="cancelResetPassword">
    <el-row>
      <el-col :span="4" style="margin-top: 20px">
        <el-icon class="dialog-icon" color="#10AEFF" size="50">
          <InfoFilled />
        </el-icon>
      </el-col>
      <el-col :span="20">
        <h3>提示</h3>
        <p class="dialog-title">确认重置该账号密码？</p>
        <p class="dialog-desc">重置后密码为: 123456，请通知用户及时修改</p>
      </el-col>
    </el-row>
    <template #footer>
      <div style="display: flex; justify-content: center; gap: 30px">
        <el-button @click="cancelResetPassword">取消</el-button>
        <el-button type="primary" @click="confirmResetPassword">确定</el-button>
      </div>
    </template>
  </el-dialog>


  <!-- 編輯角色彈窗 -->
  <el-dialog v-model="permissionEditRoleVisible" title="编辑角色" width="800px" :close-on-click-modal="false">
    <template #footer>
      <el-form ref="Ref" :rules="Rolerules" :model="permissionEditRoleObj" label-width="auto"
               style="max-width: 600px; align-items: center">
        <el-form-item prop="roleName" label="角色名称:" required>
          <el-input v-model="permissionEditRoleObj.roleName" placeholder="请输入角色名称" style="width: 220px" />
        </el-form-item>
        <el-form-item prop="parentName" label="上级角色:">
          <el-input v-model="permissionEditRoleObj.parentName" placeholder="无上级角色" disabled style="width: 220px">
            <el-option v-for="item in permissionList" :key="item.value" :label="item.label"
                       :value="item.value"></el-option>
          </el-input>
        </el-form-item>
        <el-form-item prop="market" label="地区" required>
          <el-input v-model="permissionEditRoleObj.market" placeholder="请输入所属地区" style="width: 220px" disabled />
        </el-form-item>
        <el-form-item prop="checkedKeys" label="权限列表:" required>
          <el-tree v-if="data.length > 0" :data="data" show-checkbox node-key="id" ref="treeRef"
                   :props="{ label: 'menuName', children: 'children' }"
                   :default-checked-keys="permissionEditRoleObj.checkedKeys"
                   :check-strictly="false"
                   @check="handleEditRolePermissionCheck">
            <template #default="{ node, data }">
              <span>{{ node.label }}</span>
            </template>
          </el-tree>
          <div v-else style="display: flex; align-items: center; gap: 8px;">
            <span style="color: #999;">暂无数据</span>
          </div>
        </el-form-item>
        <!-- <el-form-item prop="grade" label="优先级:" required>
          <el-input v-model="permissionEditRoleObj.grade" placeholder="数字1~999" style="width: 220px" />
        </el-form-item> -->
      </el-form>

      <div>
        <el-button @click="permissionEditRoleVisible = false">取消</el-button>
        <el-button type="primary" @click="permissionEditRole">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.pagination {
  display: flex;
}

.status {
  display: flex;
}

.head-card {
  display: flex;
}

.head-card-element {
  margin-right: 20px;
}

.head-card-btn {
  margin-left: auto;
}

/* 新增样式让弹窗内容居中 */
.el-dialog__body {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.el-dialog__footer {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.permission-cell {
  cursor: pointer;
  color: #409eff;
  /* 蓝色文字，提示可点击 */
}
</style>