<template>
  <van-popup :close-on-click-overlay="false" v-model:show="deptCascadeVisible" position="bottom">
    <div class="content-container">
      <div class="action-buttons-container">
        <div style="color:#dc3545;" @click="close">取消</div>
        <div>部门选择</div>
        <div style="color: #007bff" @click="switchPeople">下一步</div>
      </div>
      <div class="cascade-container">
        <van-cascader
          v-model="cascadeValue"
          title="请选择组织"
          :options="options"
          :swipeable="true"
          :columns-num="3"
          @change="SelectedDeptChange"
          :field-names="{
            text: 'text',
            value: 'value',
            children: 'children'
          }"
        />
      </div>
    </div>
  </van-popup>
  <van-popup v-model:show="dialogVisible" position="bottom">

    <div class="action-buttons-container">
      <div style="color: #ffc107" @click="switchDept">返回</div>
    </div>

    <div class="content-container">
      <div class="search-container">
        <div class="search-label">人员查询</div>
        <div class="search-row">
          <van-field v-model="userName" class="search-field" placeholder="请输入姓名"></van-field>
          <div class="action-buttons">
            <van-button icon="Search" type="primary" @click="getAllTableData">查询</van-button>
          </div>
        </div>
      </div>

      <div class="table-container">
        <div class="table-label">人员选择</div>
        <div class="table">
          <div class="table-header">
            <div class="table-column">
              <div class="th" style="flex: 0 0 40px;"></div>
              <div class="th">工号</div>
              <div class="th">姓名</div>
              <div class="th">操作</div>
            </div>
          </div>
          <div class="table-body">
            <table-body>
              <div class="employee-list">
                <div
                  v-for="item in tableData"
                  :key="item.user.id"
                  class="employee-item"
                >
                  <div class="employee-row">
                    <div class="employee-id">{{ item.user.userCode }}</div>
                    <div class="employee-name">{{ item.user.userDesc }}</div>
                    <div class="employee-name">
                      <van-button style="margin: 10px"
                                  icon="Select"
                                  type="success"
                                  size="small"
                                  plain
                                  @click="handleSelect(item)"
                      >
                        选择
                      </van-button>
                    </div>
                  </div>
                </div>
              </div>
            </table-body>
          </div>
        </div>
      </div>
    </div>
  </van-popup>
</template>


<script setup>
import { ref, getCurrentInstance, defineProps, nextTick, onMounted } from 'vue';
import { showFailToast } from 'vant';

const {
  proxy
} = getCurrentInstance();

/* 组织树 */
const deptCascadeVisible = ref(false)
const switchPeople = () => {
  deptCascadeVisible.value = false
  dialogVisible.value = true
}

/* 人员列表 */
const dialogVisible = ref(false);
const switchDept = () => {
  dialogVisible.value = false
  deptCascadeVisible.value = true
}

/* 打开和关闭弹出框 */
const currentDeptCode = ref('');
const open = () => {
  if (roleCode.length !== 0) {
    if (roleCode.includes('SX01') || roleCode.includes('SX02') || roleCode.includes('SX03')) {
      if (superDeptCode === 'D11011301') {
        superDeptCode = 'D110113';
      }
      if (superDeptCode === 'D1101') {
        superDeptCode = 'D11';
      }
      currentDeptCode.value = superDeptCode;
      getSafeDataTree(superDeptCode);
    } else if (roleCode.includes('SX04') || roleCode.includes('SX05') || roleCode.includes('SX06')) {
      currentDeptCode.value = deptCode;
      getSafeDataTree(deptCode);
    }
  }
  nextTick(() => {
    deptCascadeVisible.value = true
  });
};
const close = () => {
  deptCascadeVisible.value = false
  dialogVisible.value = false;
};
defineExpose({
  open,
  close
});

/* 条件查询该部门下的所有人员信息 */
const currentPage = ref(1);
const pageSize = ref(10);
const userName = ref('');
const tableData = ref([]);

const currentDeptId = ref('');
/* 获取表格信息 */
const getTableData = async () => {
  var url = 'framework/SysUserDept/queryByDeptUserNamePage';
  var param = {
    page: currentPage.value,
    rows: pageSize.value,
    deptId: currentDeptId.value,
    userName: userName.value
  };
  await proxy.$axios.get(url, param).then(response => {
    if (response.data.code === 0) {
      tableData.value = response.data.data.records;
      pageSize.value = response.data.data.total;
    } else {
      showFailToast('操作失败！' + response.data.msg);
    }
  });
};

const getAllTableData = async () => {
  /* 获取所有数据 */
  await getTableData();
  await getTableData();
};

const SelectedDeptChange = (selectInfo) => {
  currentDeptInfo.value = findNodeWithBacktrack(dataTree.value[0], selectInfo.value);
  currentDeptId.value = currentDeptInfo.value.id;
  getAllTableData();
};

/* 选中数据返回主页面 */
const emit = defineEmits(['receiveFromChild']);
const handleSelect = (item) => {
  emit('receiveFromChild', item);
  close();
};

// 转换部门数据为 cascade 格式
function convertToCascadeFormat(data) {
  if (!data || !Array.isArray(data)) return [];
  return data.map(item => ({
    text: item.deptName,
    value: item.deptCode,
    children: item.children && item.children.length > 0 ? convertToCascadeFormat(item.children) : []
  }));
}

// 叶子节点去掉children
const processTreeNodes  = (node) => {
  // 如果节点没有子节点，删除children属性并返回
  if (!node.children || node.children.length === 0) {
    if (node.children) delete node.children;
    return;
  }

  // 递归处理所有子节点
  node.children.forEach(child => processTreeNodes(child));

  // 检查当前节点是否应该保留children属性
  const hasChildrenWithChildren = node.children.some(child =>
    child.children && child.children.length > 0
  );

  // 如果所有子节点都没有子节点（都是叶子节点），删除它们的children属性
  if (!hasChildrenWithChildren) {
    node.children.forEach(child => {
      if (child.children) delete child.children;
    });
  }
}

const dataTree = ref([]);
const options = ref([]);
const cascadeValue = ref();
const currentDeptInfo = ref({});
const getSafeDataTree = async (deptCode) => {
  let url = 'sgsafe/SafeDepartment/queryDeptTreeWithLeafByDeptCode';
  let param = {
    deptCode: deptCode
  };
  await proxy.$axios.get(url, param).then(res => {
    dataTree.value = res.data.data;
    // 应用过滤逻辑
    const filteredData = filterDeptTree(dataTree.value);
    if (filteredData && filteredData.length > 0) {
      dataTree.value = filteredData;
    } else {
      console.warn('⚠️ 未找到匹配的部门');
    }

    options.value = convertToCascadeFormat(dataTree.value);

    options.value.forEach(child => {
      processTreeNodes(child)
    })

    /* 组件默认选择该部门 */
    cascadeValue.value = currentDeptCode.value;

    /* 默认返回当前部门所有信息 */
    currentDeptInfo.value = findNodeWithBacktrack(dataTree.value[0], currentDeptCode.value);
    currentDeptId.value = currentDeptInfo.value.id;
    getAllTableData();
  });
};

/* 根据deptCode查出部门信息 */
function findNodeWithBacktrack(node, targetDeptCode) {
  if (node.deptCode === targetDeptCode) {
    return node;
  }
  if (node.children && node.children.length > 0) {
    for (const child of node.children) {
      const found = findNodeWithBacktrack(child, targetDeptCode);
      if (found.deptCode) {
        return found;
      }
    }
  }
  return '';
}

/* 组织架构白名单 */
const targetDeptCodes = new Set([
  'D', 'D11',
  ...Array.from({ length: 14 }, (_, i) => `D1101${i + 1 < 10 ? '0' : ''}${i + 1}`)
]);
for (let i = 1; i <= 15; i++) {
  const baseCode = `D110112${i < 10 ? '0' : ''}${i}`;
  targetDeptCodes.add(baseCode);
  for (let j = 1; j <= 99; j++) {
    const childCode = `${baseCode}${j < 10 ? '0' : ''}${j}`;
    if (childCode !== 'D1101120604') {
      targetDeptCodes.add(childCode);
    }
  }
}
for (let i = 1; i <= 8; i++) {
  const baseCode = `D11011301${i < 10 ? '0' : ''}${i}`;
  targetDeptCodes.add(baseCode);
  for (let j = 1; j <= 99; j++) {
    const childCode = `${baseCode}${j < 10 ? '0' : ''}${j}`;
    targetDeptCodes.add(childCode);
  }
}
for (let i = 1; i <= 13; i++) {
  const baseCode = `D110114${i < 10 ? '0' : ''}${i}`;
  targetDeptCodes.add(baseCode);
  for (let j = 1; j <= 99; j++) {
    const childCode = `${baseCode}${j < 10 ? '0' : ''}${j}`;
    targetDeptCodes.add(childCode);
  }
}

function filterDeptTree(nodes) {
  if (!Array.isArray(nodes)) return null;
  const result = [];
  for (const node of nodes) {
    // 递归处理子节点
    const filteredChildren = filterDeptTree(node.children);
    // 判断当前节点是否应保留
    const shouldKeep = targetDeptCodes.has(node.deptCode);
    // 如果当前节点应该保留 或者 子节点中有保留的节点
    if (shouldKeep || (filteredChildren && filteredChildren.length > 0)) {
      result.push({
        ...node,
        children: filteredChildren || []
      });
    }
  }
  return result.length > 0 ? result : null;
}

/* 获取用户的部门信息 */
const jsonStringDept = localStorage.getItem('dept');
let deptInformation = ref([]);
try {
  deptInformation.value = jsonStringDept ? JSON.parse(jsonStringDept) : [];
} catch (error) {
  deptInformation.value = [];
}
let deptCode = deptInformation.value[0].deptCode;
let superDeptCode = deptCode.slice(0, -2);

/* 获取用户角色信息 */
const jsonStringRole = localStorage.getItem('role');
let roleInformation = ref([]);
try {
  roleInformation.value = jsonStringRole ? JSON.parse(jsonStringRole) : [];
} catch (error) {
  roleInformation.value = [];
}
// 查询当前角色中是否包含安全管理系统的角色
let roleCode = '';
let flag = ref(true);
let roleCodes = ref([]);
for (let item of roleInformation.value) {
  if (item.roleCode.includes('SX0')) {
    roleCodes.value.push(item.roleCode);
    flag.value = false;
  }
}
if (flag.value) {
  showFailToast('未配置角色，请联系管理员');
}
// 对用户拥有的安全角色进行排序，找出最高权限的角色
let temp = '';
for (let i = 0; i < roleCodes.value.length; i++) {
  for (let j = 0; j < roleCodes.value.length - 1 - i; j++) {
    if (parseInt(roleCodes.value[j].substring(3, 1)) > parseInt(roleCodes.value[j + 1].substring(3, 1))) {
      temp = roleCodes.value[j + 1];
      roleCodes.value[j + 1] = roleCodes.value[j];
      roleCodes.value[j] = temp;
    }
  }
}
if (!roleCodes.value[0]) {
  roleCode = '';
} else {
  roleCode = roleCodes.value[0];
}
for (let i = 0; i < roleCodes.value.length; i++) {
  for (let j = 0; j < roleCodes.value.length - 1 - i; j++) {
    if (parseInt(roleCodes.value[j].substring(3, 1)) > parseInt(roleCodes.value[j + 1].substring(3, 1))) {
      temp = roleCodes.value[j + 1];
      roleCodes.value[j + 1] = roleCodes.value[j];
      roleCodes.value[j] = temp;
    }
  }
}
if (!roleCodes.value[0]) {
  roleCode = '';
} else {
  roleCode = roleCodes.value[0];
}

</script>

<style scoped>

:deep(.van-checkbox__label) {
  flex: 1;
}

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
}

body {
  background: linear-gradient(135deg, #f5f7fa 0%, #e4edf9 100%);
  min-height: 100vh;
  padding: 20px;
  display: flex;
  justify-content: center;
  align-items: flex-start;
}

.content-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #f8fafd;
}

/* 面包屑导航样式 */
.breadcrumb-container {
  background: #f8fafd;
  border-radius: 12px;
  padding: 15px;
  margin-bottom: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);
}

.breadcrumb-label {
  font-size: 14px;
  color: #5a7eb5;
  font-weight: 500;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
}

.breadcrumb-label::before {
  content: "";
  display: inline-block;
  width: 4px;
  height: 16px;
  background: #4a90e2;
  border-radius: 2px;
  margin-right: 8px;
}

.breadcrumb {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  padding: 8px 12px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.breadcrumb-item {
  display: flex;
  align-items: center;
  padding: 6px 12px;
  background: #f0f7ff;
  border-radius: 6px;
  margin-right: 8px;
  margin-bottom: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  font-size: 14px;
  color: #2c6ed5;
  font-weight: 500;
  border: 1px solid #e0eeff;
}

.breadcrumb-item:hover {
  background: #e6f1ff;
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(44, 110, 213, 0.15);
}

.breadcrumb-item.active {
  background: #4a90e2;
  color: white;
}

.breadcrumb-arrow {
  margin: 0 8px;
  color: #a0b9e0;
  font-size: 14px;
}

/* 区域选择样式 */
.area-container {
  background: #f8fafd;
  border-radius: 12px;
  padding: 15px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);
}

.area-label {
  font-size: 14px;
  color: #5a7eb5;
  font-weight: 500;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
}

.area-label::before {
  content: "";
  display: inline-block;
  width: 4px;
  height: 16px;
  background: #4a90e2;
  border-radius: 2px;
  margin-right: 8px;
}

.area-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 12px;
  padding: 10px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.area-item {
  padding: 12px 10px;
  text-align: center;
  border-radius: 8px;
  background: #f5f9ff;
  cursor: pointer;
  transition: all 0.2s ease;
  font-size: 14px;
  color: #3a6ab7;
  font-weight: 500;
  border: 1px solid #e6f0ff;
  position: relative;
}

.area-item:hover {
  background: #e6f1ff;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(44, 110, 213, 0.15);
}

.area-item.selected {
  background: #4a90e2;
  color: white;
  border-color: #4a90e2;
}

.area-item.selected::after {
  content: "✓";
  position: absolute;
  right: 8px;
  top: 50%;
  transform: translateY(-50%);
  font-weight: bold;
}

/* 搜索区域样式 */
.search-container {
  background: #f8fafd;
  border-radius: 12px;
  padding: 15px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);
}

.search-label {
  font-size: 14px;
  color: #5a7eb5;
  font-weight: 500;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
}

.search-label::before {
  content: "";
  display: inline-block;
  width: 4px;
  height: 16px;
  background: #4a90e2;
  border-radius: 2px;
  margin-right: 8px;
}

.search-row {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px;
  padding: 10px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.search-field {
  flex: 1;
  min-width: 250px;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

/* 表格区域样式 */
.table-container {
  background: #f8fafd;
  border-radius: 12px;
  padding: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);
}

.table-label {
  font-size: 14px;
  color: #5a7eb5;
  font-weight: 500;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
}

.table-label::before {
  content: "";
  display: inline-block;
  width: 4px;
  height: 16px;
  background: #4a90e2;
  border-radius: 2px;
  margin-right: 8px;
}

.table {
  width: 100%;
  border-collapse: separate;
  border-spacing: 0;
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.table-header {
  background: linear-gradient(120deg, #f0f7ff, #e6f1ff);
}

.table-column {
  display: flex;
  width: 100%;
  border-bottom: 1px solid #e0eeff;
}

.th {
  padding: 16px 15px;
  font-weight: 600;
  color: #3a6ab7;
  flex: 1;
}

.table-body .table-column {
  transition: background-color 0.2s;
  border-bottom: 1px solid #f0f7ff;
}

.table-body .tr:last-child {
  border-bottom: none;
}

.table-body .tr:hover {
  background-color: #f8fbff;
}

/* 自定义行样式 */
.employee-row {
  display: flex;
  width: 100%;
}

.employee-id, .employee-name {
  flex: 1;
  padding: 0 15px;
  display: flex;
  align-items: center;
}

.employee-row {
  transition: all 0.3s ease;
}

.td {
  color: #4a5568;
  display: flex;
  align-items: center;
}

.van-checkbox {
  width: 100%;
  padding: 12px 15px;
}

.van-checkbox__label {
  width: 100%;
}

.selected-count {
  text-align: right;
  margin-top: 15px;
  font-size: 14px;
  color: #4a90e2;
  font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .app-container {
    margin: 10px;
    border-radius: 12px;
  }

  .search-row {
    flex-direction: column;
    align-items: stretch;
  }

  .action-buttons {
    width: 100%;
  }

  .van-button {
    flex: 1;
  }

  .tr {
    flex-direction: column;
    padding: 12px 0;
    border-bottom: 1px solid #eee;
  }

  .th, .td {
    padding: 8px 15px;
  }

  .th {
    font-size: 13px;
  }
}

/* 操作按钮样式 - 固定在顶部 */
.action-buttons-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background: white;
  border-bottom: 1px solid #e8e8e8;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  z-index: 10;
}

.button-text {
  width: 130rpx;
  padding: 8px 16px;
  border: none;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.button-text[type="primary"] {
  background: linear-gradient(135deg, #4fc3f7, #29b6f6);
  color: white;
}

.button-text[type="primary"]:hover {
  background: linear-gradient(135deg, #29b6f6, #0288d1);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(79, 195, 247, 0.3);
}

.button-text[type="warning"] {
  background: linear-gradient(135deg, #ff6b6b, #ee5a52);
  color: white;
}

.button-text[type="warning"]:hover {
  background: linear-gradient(135deg, #ff5252, #d32f2f);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(255, 107, 107, 0.3);
}

.button-text[type="danger"] {
  background: linear-gradient(135deg, #ff6b6b, #ee5a52);
  color: white;
}

.button-text[type="danger"]:hover {
  background: linear-gradient(135deg, #ff5252, #d32f2f);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(255, 107, 107, 0.3);
}

.button-text[type="success"] {
  background: linear-gradient(135deg, #ff6b6b, #ee5a52);
  color: white;
}

.button-text[type="success"]:hover {
  background: linear-gradient(135deg, #ff5252, #d32f2f);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(255, 107, 107, 0.3);
}

.button-text:active {
  transform: translateY(0);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

</style>
