<script setup>
import {
  ref,
  onMounted,
  getCurrentInstance,
} from 'vue'
import { showFailToast } from 'vant';
const {
  proxy
} = getCurrentInstance()

/* 获取用户的部门信息 */
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]
}

// 定义需要保留的目标 deptCode 起始点
const targetDeptCodes = new Set([
  'D', 'D11', 'D1101', 'D110112',
  ...Array.from({ length: 10 }, (_, i) => `D110112${i + 6 < 10 ? '0' : ''}${i + 6}`),
  'D110113010501','D110113010502',
  ...Array.from({ length: 5 }, (_, i) => `D110113010${i + 4}`),
  'D110114',
  ...Array.from({ length: 11 }, (_, i) => `D110114${i + 3 < 10 ? '0' : ''}${i + 3}`),
])
for (let i = 6; 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}`;
    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 currentDeptInfo = ref('')
defineExpose({
  currentDeptInfo
})

const dataTree = 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('⚠️ 未找到匹配的部门')
    }
    renderAreaList.value = [...dataTree.value]
    findNodeWithBacktrack(renderAreaList.value[0],currentDeptCode.value)
    renderAreaList.value = selectedAreas.value[selectedAreas.value.length-1].children
    currentDeptInfo.value = selectedAreas.value[selectedAreas.value.length - 1].deptCode + '-' + selectedAreas.value[selectedAreas.value.length - 1].deptName
    emit('init',currentDeptInfo.value)
  })
}

/* 选出默认部门 */
function findNodeWithBacktrack(node, targetDeptCode) {
  selectedAreas.value.push(node);
  if (node.deptCode === targetDeptCode) {
    return true;
  }
  if (node.children && node.children.length > 0) {
    for (const child of node.children) {
      const found = findNodeWithBacktrack(child, targetDeptCode);
      if (found) {
        return true;
      }
    }
  }

  selectedAreas.value.pop();
  return false;
}

/* 点击任意部门时向其他组件传递信息 */
const emit = defineEmits(['update:selectedNode', 'close','init']);

const currentDeptCode = ref('')
onMounted(() => {
  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)
    }
  }
})

// 所有部门数据和已选择部门数据
const renderAreaList = ref([])
const selectedAreas = ref([])

// 点击切换当前组织
const toggleArea = (area, toggleClickIndex) => {
  renderAreaList.value =
    toggleClickIndex === 0
      ? [...dataTree.value][0].children
      : selectedAreas.value[toggleClickIndex].children
  selectedAreas.value = selectedAreas.value.slice(0, toggleClickIndex+1)
}

// 选中部门时处理
const selectDeptFun = (item) => {
  if (item.children.length > 0) {
    renderAreaList.value = item.children
  } else {
    selectedAreas.value = selectedAreas.value.filter(selected => selected.deptCode.length !== item.deptCode.length)
    const index = selectedAreas.value.findIndex(selected => item.id === selected.id)
    if (index !== -1) {
      selectedAreas.value.splice(index, 1)
    }
  }
  selectedAreas.value.push(item)
}

// 关闭组织树
const reset = () => {
  emit('close')
}

// 确定选择部门
const handleConfirm = () => {
  const nodeData = selectedAreas.value[selectedAreas.value.length - 1]
  emit('update:selectedNode', nodeData)
  reset()
}

</script>

<template>
  <!-- 部门树下拉选择组件 -->
  <div class="content-container">
    <!-- 操作按钮 -->
    <div class="action-buttons-container">
      <button class="action-button cancel-button" @click="reset">取消</button>
      <button class="action-button confirm-button" @click="handleConfirm">确定</button>
    </div>

    <!-- 已选择的部门数据 -->
    <div class="breadcrumb-container">
      <div class="breadcrumb-label">当前组织</div>
      <div class="breadcrumb">
            <span
              v-for="(selected, index) in selectedAreas"
              :key="selected.id"
              @click="toggleArea(selected, index)"
              class="breadcrumb-item"
              :class="{ active: index === selectedAreas.length - 1 }"
            >
              {{ selected.deptName }}
              <i v-if="index < selectedAreas.length - 1" class="breadcrumb-arrow"> > </i>
            </span>
      </div>
    </div>

    <!-- 当前可选择的部门数据 -->
    <div class="area-container">
      <div class="area-label">请选择组织</div>
      <div class="area-grid">
        <div
          v-for="item in renderAreaList"
          :key="item.id"
          @click="selectDeptFun(item)"
          class="area-item"
          :class="{ selected: selectedAreas.includes(item) }"
        >
          {{ item.deptName }}
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>

* {
  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 {
  padding: 20px;
}

/* 确定取消按钮 */
/* 操作按钮样式 */
.action-buttons-container {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-bottom: 25px;
  padding: 0 15px;
}

.action-button {
  flex: 1;
  max-width: 200px;
  padding: 13px 25px;
  border-radius: 30px;
  font-weight: 600;
  font-size: 16px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  border: none;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 8px;
}

.action-button i {
  font-size: 18px;
  font-weight: bold;
}

.cancel-button {
  background: #ffffff;
  color: #666;
  border: 1px solid #e0e0e0;
}

.cancel-button:hover {
  background: #f8f8f8;
  transform: translateY(-3px);
  box-shadow: 0 6px 15px rgba(0, 0, 0, 0.12);
}

.confirm-button {
  background: linear-gradient(to right, #4a90e2, #2c6ed5);
  color: white;
  box-shadow: 0 4px 15px rgba(44, 110, 213, 0.3);
}

.confirm-button:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 20px rgba(44, 110, 213, 0.4);
  background: linear-gradient(to right, #3d85e0, #2561c7);
}

/* 面包屑导航样式 */
.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;
}

</style>

