<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('rote信息：'+JSON.stringify(localStorage.getItem('role')))
  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]
}

// 白名单：组织树中需要保留数据
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;
}

// 转换部门数据为 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属性(避免请选择)
 * @param node options.value
 */
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
  }
  const res = await proxy.$axios.get(url, param)
  dataTree.value = res.data.data
  // console.log(dataTree.value);
  // 应用过滤逻辑
  const filteredData = filterDeptTree(dataTree.value)
  // console.log('filterTree',filteredData);
  if (filteredData && filteredData.length > 0) {
    dataTree.value = filteredData
  } else {
    console.warn('⚠️ 未找到匹配的部门')
  }

  // console.log('dataTree',dataTree.value);

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

  /* 组件默认选择该部门和标签选择部门 */
  if (treeBranchesList.value[0]) {
    cascadeValue.value = treeBranchesList.value[currentTabIndex.value]
  } else {
    cascadeValue.value = currentDeptCode.value
  }

  /* 缓存信息 */
  if (props.cachedDeptCode) {
    cascadeValue.value = props.cachedDeptCode
  }

  /* 默认返回当前部门 */
  currentDeptInfo.value = findNodeWithBacktrack(dataTree.value[0], currentDeptCode.value)
  emit('init', currentDeptInfo.value)

}

/* 选出目标部门 */
function findNodeWithBacktrack(node, targetDeptCode) {
  if (node.deptCode === targetDeptCode) {
    return node.deptCode + '-' + node.deptName
  }
  if (node.children && node.children.length > 0) {
    for (const child of node.children) {
      const found = findNodeWithBacktrack(child, targetDeptCode);
      if (found) {
        return found
      }
    }
  }
  return ''
}

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 emit = defineEmits(['update:selectedNode', 'close', 'init']);

/**
 * 缓存的deptCode
 */
const props = defineProps({
  cachedDeptCode: {
    type: String,
    default: () => ''
  }
})

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

// 确定选择部门
const handleConfirm = async () => {
  let selectedDeptInfo = findNodeWithBacktrack(dataTree.value[0], cascadeValue.value)
  let temp = selectedDeptInfo.split('-')
  var url = '/sgsafe/JuBaoHiddendanger/queryUserIdByPostWithDeptCode'
  var param = {
    deptCode: temp[0]
  }
  var res = await proxy.$axios.get(url, param)
  if (res.data.code === 0){
    selectedDeptInfo = selectedDeptInfo + '-' + res.data.data
  }else {
    showFailToast('操作失败')
  }
  emit('update:selectedNode', selectedDeptInfo)
  reset()
}

/**
 * 点击标签时回显组织
 */
const treeBranchesList = ref([])
const allTreeList = ref([])
const currentTabIndex = ref()
const onClickTab = async (tabIndex, title) => {
  treeBranchesList.value = []
  currentTabIndex.value = tabIndex
  getPathToTarget(allTreeList.value[0],cascadeValue.value)
  await getSafeDataTree(currentDeptCode.value)
}

/**
 * 根据cascadeValue获取所有直系节点
 */
const getPathToTarget = (root, targetValue) => {
  const dfs = (node, path) => {
    if (!node) return false;

    path.push(node.value);

    if (node.value === targetValue) {
      treeBranchesList.value.push(...path);
      return true;
    }

    for (const child of node.children) {
      if (dfs(child, path)) {
        return true;
      }
    }

    path.pop();
    return false;
  }
  dfs(root, []);
}

</script>

<template>
  <!-- 部门树下拉选择组件 -->
  <div class="content-container">
    <!-- 操作按钮 - 固定在顶部 -->
    <div class="action-buttons-container">
      <div @click="reset">取消</div>
      <div>部门选择</div>
      <div style="color: #007bff" @click="handleConfirm">确定</div>
    </div>

    <!-- 选择器内容区域 -->
    <div class="cascade-container">
      <van-cascader
        v-model="cascadeValue"
        title="请选择组织"
        :options="options"
        @click-tab="onClickTab"
        :swipeable="true"
        :columns-num="3" :field-names="{
          text: 'text',
          value: 'value',
          children: 'children'
        }" />
    </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 {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #f8fafd;
}

/* 选择器容器 */
.cascade-container {
  flex: 1;
  overflow: hidden;
  background: rgb(255, 255, 255);
}

/* 确保 van-cascade 占满剩余空间 */
.cascade-container :deep(.van-cascader) {
  height: 100%;
}

.cascade-container :deep(.van-cascader__content) {
  height: calc(100% - 44px);
  /* 减去标题栏高度 */
}

/* 为 van-cascader 选项添加分割线 */
.cascade-container :deep(.van-cascader__option) {
  border-bottom: 1px solid #e4e4e4;
}

.cascade-container :deep(.van-cascader__option:last-child) {
  border-bottom: none;
}

/* 操作按钮样式 - 固定在顶部 */
.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="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="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:active {
  transform: translateY(0);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}
</style>
