<script setup>
import { computed, onMounted, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { InfoFilled } from '@element-plus/icons-vue'
import _ from 'lodash'
import request from '@/util/http'
import API from '@/util/http'
import { useAdminStore } from "@/store/index.js"
import { storeToRefs } from "pinia"
import { findMenuById, permissionMapping } from "@/utils/menuTreePermission.js"

import BackGroundSvg from '@/assets/SvgIcons/promptBackground.avg'


const adminStore = useAdminStore()
const { adminData, menuTree } = storeToRefs(adminStore)

// 表格数据
const tableData = ref([])
const total = ref(100)
const handleDialogClose = function () {
  closeUserAddVisible()
  console.log('hhh');
}
const propsAdduser = {
  multiple: true, // 多选
}
// 搜索admin
const admin = ref({
  account: '',
  market: '',
  postiton: ''
})
// 搜索对象
const getObj = ref({
  pageNum: 1,
  pageSize: 10
})
// 修改状态确认
const ackVisible = ref(false)
const currentStatusRow = ref(null)
const statusLoading = ref({})
const showStatusConfirm = (row, targetStatus) => {
  currentStatusRow.value = {
    ...row,// 当前行数据
    targetStatus// 目标状态
  }
  ackVisible.value = true
}
// 规则
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();
        }
      }
    }
  ]
};

// 新增用户权限弹窗
const userAddVisible = ref(false)
// 编辑用户权限弹窗
const userEditVisible = ref(false)
//选地区
const market = ref([])
// 选部门
const postiton = ref([])
// 新增用户对象
const userAddObj = ref({})
// 新增用户权限对象，机器码要实现存储多个，addMachineIdInput方法实现
const addAdmin = ref({
  account: '',
  name: '',
  market: [],
  permission: '',
  postiton: '',
  machineIds: [''], // 动态添加的机器码输入框
  machineId: '',
  remark: ''
})
// 编辑用户权限对象
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 getPermission = async function (val) {
  try {
    if (typeof val === 'number') {
      getObj.value.pageNum = val
    }
    console.log('搜索参数', getObj.value, admin.value)

    // if (admin.value.market === '总部' || admin.value.market === '研发部') {
    //   admin.value.market = '';
    // }
    if (admin.value.account) {
      // 纯数字
      const numberRegex = /^\d{1,20}$/;

      // 检查是否不是数字
      if (!numberRegex.test(admin.value.account)) {
        ElMessage.error('请检查OA号格式')
        // 上面提示过了
        return
      }
    }
    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 trimJwCode = () => {
  if (admin.value.account) {
    admin.value.account = admin.value.account.replace(/\s/g, '');
  }
}
const search = function () {
  trimJwCode();
  getObj.value.pageNum = 1
  getPermission()
}

// 重置
const reset = function () {
  admin.value = {}
  // 重置页码
  getObj.value.pageNum = 1
  getPermission()
}
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 marketsTree = ref([])
const getArea = async function () {
  try {
    // 发送POST请求
    const result = await API({

      url: '/market/selectMarket',
    });
    // 将响应结果存储到响应式数据中
    console.log('请求成功', result)

    // 递归转换树形结构为级联选择器需要的格式（跳过第一级节点）
    const transformTree = (nodes) => {
      // 直接处理第一级节点的子节点
      const allChildren = nodes.flatMap(node => node.children || []);

      return allChildren.map(child => {
        const grandchildren = child.children && child.children.length
          ? transformTree([child]) // 递归处理子节点
          : null;

        return {
          value: child.name,
          label: child.name,
          children: grandchildren
        };
      });
    };
    // 存储地区信息
    marketsTree.value = transformTree(result.data)
    console.log('转换后的地区树==============', marketsTree.value)
  } 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 () {
  userAddVisible.value = true

}
// 关闭新增用户权限弹窗，并刷新表单
const closeUserAddVisible = function () {
  userAddVisible.value = false;
  // 清除表单验证状态
  Ref.value.resetFields();
}
// 新增用户权限初始化
const userAddInit = function () {
  userAddObj.value = {}
  openUserAddVisible()
}

//新增用户
const permissionAdd = async function () {
  if (!canLook) {
    ElMessage.error('无此权限')
    return
  }
  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//备注
    }
    console.log('提交前addAdmin market', addAdmin.value.market)
    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 = {}
    getPermission()

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

    ElMessage.error('新增用户权限失败')
  }
}
// 表单验证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) {
  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 () {
  if (!canEdit) {
    ElMessage.error('无此权限')
    return
  }
  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 类型
        }
      );
      getPermission();
      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 () {
  if (!canDel) {
    ElMessage.error('无此权限')
    return
  }
  try {
    const result = await request({
      url: '/permission/deleteAdmin',
      data: delObj.value
    })
    console.log('看看删除对象', delObj.value)
    console.log('请求成功1', result)

    ElMessage.success('删除权限成功')
    delObj.value = {}
    getPermission()
  } catch (error) {
    console.log('删除权限失败', error)
    ElMessage.error('删除权限失败')
  }
}
// 禁用启用用户权限
const editStatus = async function (row) {
  if (!change) {
    ElMessage.error('无此权限')
    return
  }
  const { id, account, targetStatus, ...restRow } = currentStatusRow.value

  try {
    statusLoading.value[id] = true

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

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


const handlePageSizeChange = function (val) {
  getObj.value.pageSize = val
  getPermission()
}
const handleCurrentChange = function (val) {
  getObj.value.pageNum = val
  getPermission()
}


const data = ref([])

// todo 处理地区选择变化
/*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 selectedMarketPath = ref("")
// 这个不转id
const handleMarketChange = (value) => {
  if (value && value.length > 0) {
    admin.value.market = value[value.length - 1]
  } else {
    admin.value.market = ''
  }
}
// 修改地区选择处理函数
const handleMarketChangeAddUser = (value) => {
  if (Array.isArray(value) && value.length > 0) {
    // 提取所有选中项的最后一级
    const selectedMarkets = value
      .map(path => Array.isArray(path) && path.length > 0 ? path[path.length - 1] : null)
      .filter(Boolean);

    // 检查是否包含总部
    const hasHeadquarters = selectedMarkets.includes('总部');

    if (hasHeadquarters) {
      // 如果包含总部，只保留总部
      addAdmin.value.market = ['总部'];
    } else {
      // 不包含总部，保留所有选择
      addAdmin.value.market = selectedMarkets;
    }
  } else {
    // 未选择任何地区
    addAdmin.value.market = [];
  }
};

// 修改地区选择处理函数
const handleMarketChangeEditUser = (value) => {
  if (Array.isArray(value) && value.length > 0) {
    // 提取所有选中项的最后一级
    const selectedMarkets = value
      .map(path => Array.isArray(path) && path.length > 0 ? path[path.length - 1] : null)
      .filter(Boolean);

    // 检查是否包含总部
    const hasHeadquarters = selectedMarkets.includes('总部');

    if (hasHeadquarters) {
      // 如果包含总部，只保留总部
      permissionEditObj.value.market = ['总部'];
    } else {
      // 不包含总部，保留所有选择
      permissionEditObj.value.market = selectedMarkets;
    }
  } else {
    // 未选择任何地区
    permissionEditObj.value.market = [];
  }
};

const addUserProps = {
  multiple: true,
}
/*// 计算属性：控制级联选择器的选项禁用状态
const addUserProps = computed(() => {
  // 判断是否已选择总部
  const hasHeadquarters = addAdmin.value.market.includes('总部');

  return {
    multiple: true, // 保留多选功能
    // 选项禁用逻辑：如果已选择总部，则禁用非总部的选项
    disabled: (data) => {
      return hasHeadquarters && data.label !== '总部';

    }
  };
});*/

const editUserProps = {
  multiple: true,
}
/*// 计算属性：控制级联选择器的选项禁用状态
const editUserProps = computed(() => {
  // 判断是否已选择总部
  const hasHeadquarters = permissionEditObj.value.market.includes('总部');

  return {
    multiple: true, // 保留多选功能
    // 选项禁用逻辑：如果已选择总部，则禁用非总部的选项
    disabled: (data) => {
      return hasHeadquarters && data.label !== '总部';

    }
  };
});*/

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 resetConfirmVisible = ref(false)
// 当前选中的行数据
const currentRow = ref(null)
// 重置密码
const resetPassword = function (row) {
  // 显示确认弹窗
  currentRow.value = row
  resetConfirmVisible.value = true
}

// 确认重置密码
const confirmResetPassword = async function () {
  if (!canEdit) {
    ElMessage.error('无此权限')
    return
  }
  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] === '总部' || adminData.value.markets[0] === '研发部') {

    console.log('符合条件，可以操作', adminData.value.markets.includes(currentRow.value.market) || adminData.value.markets[0] === '总部' || 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; // 关闭弹窗
        await getPermission()

      } 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 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 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;
};


const throttledPermissionEdit = _.throttle(permissionEdit, 5000, {
  trailing: false
})
// 使用 _.throttle 并设置 trailing 为 false 实现严格节流，只执行一次
const throttledPermissionAdd = _.throttle(permissionAdd, 5000, {
  trailing: false
})
const canLook = findMenuById(menuTree.value, permissionMapping.display_user_management)// 我真是服啦，查询也做嘛
const canAdd = findMenuById(menuTree.value, permissionMapping.add_user_information)
const canEdit = findMenuById(menuTree.value, permissionMapping.edit_user_information)
const canReset = findMenuById(menuTree.value, permissionMapping.reset_user_password)
const canDel = findMenuById(menuTree.value, permissionMapping.delete_user_information)
const change = findMenuById(menuTree.value, permissionMapping.enable_disable_user)
// 挂载
onMounted(async function () {
  await getPermission()
  await getArea()
  await getStore()
  await getRoles()
  await getRoleArea()
  console.log('看看权限', canAdd, canEdit, canReset, canDel, change)
})
</script>

<template>
  <div>
    <el-card class="card1" style="margin-bottom: 1vh;">
      <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-cascader v-model="admin.market" :options="marketsTree" placeholder="请选择所属地区" clearable style="width:180px"
            @change="handleMarketChange" />

        </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="primary" @click="search()" v-if="canLook">查询</el-button>
          <el-button type="success" @click="reset()">重置</el-button>
        </div>
      </div>
    </el-card>
    <el-card class="card2">
      <!-- 展示表单 -->
      <div class="add-item">
        <el-button style="color: #048efb; border: 1px solid #048efb" :disabled="!canAdd" v-if="canAdd"
          @click="userAddInit()">新增用户
        </el-button>
      </div>

      <div>
        <el-table :data="tableData" style="width: 82vw;height:63.3vh" 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 :disabled="!canReset" @click="resetPassword(scope.row)" v-if="canReset">
                重置密码
              </el-button>
              <el-button type="primary" text @click="permissionEditInit(scope.row)" v-if="canEdit"
                :disabled="!canEdit || 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)" v-if="canDel"
                    :disabled="!canDel || 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 :model-value="scope.row.adminStatus" :active-value="1" :inactive-value="0" size="large"
                v-if="change"
                :disabled="!change || scope.row.account === adminData.account || statusLoading[scope.row.id]"
                @change="(targetStatus) => showStatusConfirm(scope.row, targetStatus)" style="
                    --el-switch-on-color: #13ce66;
                    --el-switch-off-color: #ff4949;
                  " active-text="启用" inactive-text="禁用" inline-prompt />
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination" style="margin-top: 1vh;">
          <el-pagination background :current-page="getObj.pageNum" :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>
      </div>
    </el-card>
  </div>

  <!-- 新增用户权限 -->
  <el-dialog v-model="userAddVisible" title="新增用户权限" width="800px" :close-on-click-modal="false"
    @close="handleDialogClose">
    <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-cascader v-model="addAdmin.market" :options="marketsTree" placeholder="请选择所属地区" clearable collapse-tags
            collapse-tags-tooltip style="width:220px" @change="handleMarketChangeAddUser" :max-collapse-tags="2"
            :props="addUserProps" />
        </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">
              <el-input v-model="addAdmin.machineIds[index]" placeholder="请输入机器码"
                style="width: 220px; 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-cascader v-model="permissionEditObj.market" :options="marketsTree" placeholder="请选择所属地区" clearable
          collapse-tags collapse-tags-tooltip style="width:220px" @change="handleMarketChangeEditUser"
          :max-collapse-tags="2" :props="editUserProps" />
      </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">
            <el-input v-model="permissionEditObj.machineIds[index]" placeholder=""
              style="width: 220px; 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="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="ackVisible" width="700px" :close-on-click-modal="false" :style="{
    backgroundImage: `url(${BackGroundSvg})`,
    backgroundSize: 'cover',
    backgroundPosition: 'center',
    height: '400px'
  }"
    @close="() => { if (currentStatusRow) currentStatusRow.adminStatus = currentStatusRow.adminStatus === 1 ? 0 : 1 }">
    <div class="status-confirm-content">
      将要{{ currentStatusRow?.adminStatus === 1 ? '禁用' : '启用' }}该用户
      <br>
    </div>
    <template #footer>
      <div style="display: flex; justify-content: center;  gap: 10px;">
        <el-button round size="large" @click="() => {
          currentStatusRow.adminStatus = currentStatusRow.adminStatus === 1 ? 0 : 1
          ackVisible = false
        }">
          取消
        </el-button>
        <el-button round size="large" type="primary" @click="() => {
          editStatus(currentStatusRow)
          ackVisible = false
        }">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">

// 新增用户按钮
.add-item {
  margin-bottom: 1vh;
}

// 搜索的卡片样式
.card1 {
  background: #F3FAFE;
}

// 表单的卡片样式
.card2 {
  background: #E7F4FD;
}


// 表头背景等
:deep(.el-table__header-wrapper),
:deep(.el-table__body-wrapper),
:deep(.el-table__cell),
/* 表格 */
:deep(.el-table__body td) {
  background-color: #F3FAFE !important;
}

/* 表头 */
:deep(.el-table__header th) {
  background-color: #F3FAFE !important;
}

/* 鼠标悬停 */
:deep(.el-table__row:hover > .el-table__cell) {
  background-color: #E5EBFE !important;
}

.pagination {
  display: flex;
}


.head-card {
  display: flex;
}

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

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

.status-confirm-content {
  text-align: center;
  margin-top: 160px;
  margin-bottom: 30px;
  font-size: 48px;
}
</style>