import {
  getPortrait,
  getModuleMetrics,
  getGrowthPortrait,
  getOverview,
  getUserProfile,
  getCollaborationProfile,
  getDetailProfile,
  getSiteStatistics,
  getAttendanceStatistics,
  getDeptProfile,
  getSiteProfile
} from '@/api/eikonStatistics/eikonStatistics';
import { getUserInfoById, getDeptUserTree } from '@/api/system/user';
const eikonLevel = {
  namespaced: true,
  state: () => ({
    currentLevel: '',
    currentLevelId: '',
    oldLevel: '',
    oldLevelId: '',
    allData: {},
    systemData: {},
    attendanceData: {},
    itemData: {},
    portraitData: {},
    growthPortraitData: {},
    overviewData: {},
    profileData: {},
    collaborationData: {},
    detailData: {},
    stationSiteData: [],
    stationAttendanceData: [],
    // 新增角色状态
    isPersonal: false,
    isZhanZhang: false,
    isKeZhang: false,
    isBanZuZhang: false,
    isJingLi: false,
    // 新增部门树数据
    departmentTree: [],
    // 当前部门的完整路径
    currentDepartmentPath: '',
    // 当前levelId在组织中管理的人数
    currentLevelUserCount: 0
  }),
  mutations: {
    SET_CURRENT_LEVEL: (state, level) => {
      state.currentLevel = level
    },
    SET_CURRENT_LEVEL_ID: (state, levelId) => {
      state.currentLevelId = levelId
    },
    SET_OLD_LEVEL: (state, level) => {
      state.oldLevel = level
    },
    SET_OLD_LEVEL_ID: (state, levelId) => {
      state.oldLevelId = levelId
    },
    SET_ALL_DATA: (state, data) => {
      state.allData = data
    },
    SET_SYSTEM_DATA: (state, data) => {
      state.systemData = data
    },
    SET_ATTENDANCE_DATA: (state, data) => {
      state.attendanceData = data
    },
    SET_ITEM_DATA: (state, data) => {
      state.itemData = data
    },
    SET_PORTRAIT_DATA: (state, data) => {
      state.portraitData = data
    },
    SET_GROWTH_PORTRAIT_DATA: (state, data) => {
      state.growthPortraitData = data
    },
    // 新增角色状态mutations
    SET_ROLE_STATES: (state, { isPersonal, isZhanZhang, isKeZhang, isBanZuZhang, isJingLi }) => {
      state.isPersonal = isPersonal
      state.isZhanZhang = isZhanZhang
      state.isKeZhang = isKeZhang
      state.isBanZuZhang = isBanZuZhang
      state.isJingLi = isJingLi
    },
    SET_OVERVIEW_DATA: (state, data) => {
      state.overviewData = data
    },
    SET_PROFILE_DATA: (state, data) => {
      state.profileData = data
    },
    SET_COLLABORATION_DATA: (state, data) => {
      state.collaborationData = data
    },
    SET_DETAIL_DATA: (state, data) => {
      state.detailData = data
    },
    // 新增部门树相关mutations
    SET_DEPARTMENT_TREE: (state, treeData) => {
      state.departmentTree = treeData
    },
    SET_CURRENT_DEPARTMENT_PATH: (state, path) => {
      state.currentDepartmentPath = path
    },
    SET_CURRENT_LEVEL_USER_COUNT: (state, count) => {
      state.currentLevelUserCount = count
    },
    // 新增站点统计相关mutations
    SET_STATION_SITE_DATA: (state, data) => {
      state.stationSiteData = data
    },
    SET_STATION_ATTENDANCE_DATA: (state, data) => {
      state.stationAttendanceData = data
    }
  },
  actions: {
    // 加载数据
    async loadData({ commit, state, rootState, dispatch, getters }) {
      // 清空所有数据变量
      commit('SET_ALL_DATA', null)
      commit('SET_SYSTEM_DATA', null)
      commit('SET_ATTENDANCE_DATA', null)
      commit('SET_ITEM_DATA', null)
      commit('SET_PORTRAIT_DATA', null)
      commit('SET_GROWTH_PORTRAIT_DATA', null)
      commit('SET_OVERVIEW_DATA', null)
      commit('SET_PROFILE_DATA', null)
      commit('SET_COLLABORATION_DATA', null)
      commit('SET_DETAIL_DATA', null)
      commit('SET_STATION_SITE_DATA', null)
      commit('SET_STATION_ATTENDANCE_DATA', null)

      // let params = {
      //   userId: rootState.user.id || '',
      //   userTypeStr: state.currentLevel
      // }
      let portraitParams = {};
      let overviewParams = {};
      let detailParams = {};
      let growthParams = {};

      if (getters.isPersonal) {
        portraitParams = {
          checkedUserId: state.currentLevelId
        }
        overviewParams = {
          userId: state.currentLevelId
        }
        detailParams = {
          userId: state.currentLevelId
        }
        growthParams = {
          userId: state.currentLevelId
        }
      }
      if (getters.isBanZuZhang) {
        portraitParams = {
          checkedTeamId: state.currentLevelId
        }
        overviewParams = {
          deptId: state.currentLevelId
        }
        detailParams = {
          deptId: state.currentLevelId
        }
        growthParams = {
          teamId: state.currentLevelId
        }
      }
      if (getters.isKeZhang) {
        portraitParams = {
          checkedDepartmentId: state.currentLevelId
        }
        overviewParams = {
          deptId: state.currentLevelId
        }
        detailParams = {
          deptId: state.currentLevelId
        }
        growthParams = {
          departmentId: state.currentLevelId
        }
      }
      if (getters.isZhanZhang) {
        portraitParams = {
          checkedSiteId: state.currentLevelId
        }
        overviewParams = {
          siteId: state.currentLevelId
        }
        detailParams = {
          deptId: state.currentLevelId
        }
      }
      if (getters.isJingLi) {
        portraitParams = {
          checkedBrigadeId: state.currentLevelId
        }
        detailParams = {
          deptId: state.currentLevelId
        }
        growthParams = {
          brigadeId: state.currentLevelId
        }
        overviewParams = {
          deptId: state.currentLevelId
        }
      }

      try {
        //总体概览
        const overviewRes = await getOverview(detailParams)
        commit('SET_OVERVIEW_DATA', overviewRes.data)
        //资质能力
        const res = await getModuleMetrics({ ...detailParams, userTypeStr: state.currentLevel })
        let result = res.data && res.data.moduleResults;
        commit('SET_ALL_DATA', result)
        commit('SET_SYSTEM_DATA', result && result.system || {})
        commit('SET_ATTENDANCE_DATA', result && result.attendance || {})
        commit('SET_ITEM_DATA', result && result.item || {})
        //巡检
        const portraitRes = await getPortrait(portraitParams)
        commit('SET_PORTRAIT_DATA', portraitRes.data)
        //学习成长
        const growthPortraitRes = await getGrowthPortrait(growthParams)
        commit('SET_GROWTH_PORTRAIT_DATA', growthPortraitRes.data)
        //测试
        let profileRes = {}
        if (getters.isKeZhang || getters.isJingLi) {
          profileRes = await getDeptProfile(overviewParams)
        } else if (getters.isZhanZhang) {
          profileRes = await getSiteProfile(overviewParams)
        } else {
          profileRes = await getUserProfile(overviewParams)
        }
        commit('SET_PROFILE_DATA', profileRes.data)
        //协同配合
        let collaborationRes = {}
        if (getters.isPersonal) {
          collaborationRes = await getUserInfoById(state.currentLevelId)
        } else {
          collaborationRes = await getCollaborationProfile({ deptId: state.currentLevelId })
        }
        commit('SET_COLLABORATION_DATA', collaborationRes.data)
        //能力画像-明细
        if (!getters.isPersonal) {
          const detailRes = await getDetailProfile(detailParams)
          commit('SET_DETAIL_DATA', detailRes.data)
        }

        // 只有当state.currentLevel为station的时候请求这俩接口
        if (getters.isZhanZhang) {
          const siteStatisticsRes = await getSiteStatistics({ deptId: state.currentLevelId })
          const attendanceStatisticsRes = await getAttendanceStatistics({ deptId: state.currentLevelId })
          console.log(siteStatisticsRes, attendanceStatisticsRes)

          commit('SET_STATION_SITE_DATA', siteStatisticsRes.data)
          commit('SET_STATION_ATTENDANCE_DATA', attendanceStatisticsRes)
        }


      } catch (error) {
        console.error('加载数据失败:', error);
        throw error
      }
    },
    // 保存所有数据
    saveAllData({ commit }, data = {}) {
      commit('SET_ALL_DATA', data)
      commit('SET_SYSTEM_DATA', data.system || {})
      commit('SET_ATTENDANCE_DATA', data.attendance || {})
      commit('SET_ITEM_DATA', data.item || {})
    },
    // 切换级别
    async initLevel({ commit, dispatch }, { level = '', levelId = '' } = {}) {
      // 清空旧的级别信息
      commit('SET_OLD_LEVEL', '')
      commit('SET_OLD_LEVEL_ID', '')

      commit('SET_CURRENT_LEVEL', level)
      commit('SET_CURRENT_LEVEL_ID', levelId)

      // 根据当前级别更新角色状态
      const roleStates = {
        isPersonal: level === 'personal',
        isBanZuZhang: level === 'team',
        isKeZhang: level === 'department',
        isZhanZhang: level === 'station' || level === 'zhijianke',
        isJingLi: level === 'brigade'
      }
      commit('SET_ROLE_STATES', roleStates)

      // 确保部门树数据已加载，然后更新当前部门路径
      await dispatch('loadDepartmentTree')
      dispatch('updateCurrentDepartmentPath', { level, levelId })
    },
    // 切换级别
    async changeLevel({ commit, state, dispatch }, { level = '', levelId = '' } = {}) {
      // 保存旧的级别信息
      commit('SET_OLD_LEVEL', state.currentLevel)
      commit('SET_OLD_LEVEL_ID', state.currentLevelId)

      commit('SET_CURRENT_LEVEL', level)
      commit('SET_CURRENT_LEVEL_ID', levelId)

      // 根据当前级别更新角色状态
      const roleStates = {
        isPersonal: level === 'personal',
        isBanZuZhang: level === 'team',
        isKeZhang: level === 'department',
        isZhanZhang: level === 'station' || level === 'zhijianke',
        isJingLi: level === 'brigade'
      }
      commit('SET_ROLE_STATES', roleStates)

      // 确保部门树数据已加载，然后更新当前部门路径
      await dispatch('loadDepartmentTree')
      dispatch('updateCurrentDepartmentPath', { level, levelId })
    },
    // 重置级别状态
    resetLevel({ commit }) {
      commit('SET_CURRENT_LEVEL', '')
      commit('SET_CURRENT_LEVEL_ID', '')
      commit('SET_ROLE_STATES', {
        isPersonal: false,
        isZhanZhang: false,
        isKeZhang: false,
        isBanZuZhang: false,
        isJingLi: false
      })
    },
    // 更新角色状态
    updateRoleStates({ commit }, roleStates) {
      commit('SET_ROLE_STATES', roleStates)
    },
    // 获取部门树数据
    async loadDepartmentTree({ commit, rootState }) {
      try {
        const res = await getDeptUserTree({})
        commit('SET_DEPARTMENT_TREE', res.data)
        return res.data
      } catch (error) {
        console.error('获取部门树数据失败:', error)
        throw error
      }
    },
    // 根据ID获取部门完整路径
    getDepartmentPathById({ state }, nodeId) {

      if (!nodeId || !state.departmentTree.length) {
        return []
      }

      const findNodePath = (treeNodes, targetId, path = []) => {
        for (const treeNode of treeNodes) {
          // 如果找到目标节点，返回包含本级 label 的路径
          if (treeNode.id === targetId) {
            return [...path, treeNode.label]
          }

          // 如果有子节点，递归查找
          if (treeNode.children && treeNode.children.length > 0) {
            const newPath = [...path, treeNode.label]
            const result = findNodePath(treeNode.children, targetId, newPath)
            if (result) {
              return result
            }
          }
        }
        return null
      }

      const fullPath = findNodePath(state.departmentTree, nodeId)
      return fullPath || []
    },
    // 根据ID获取本级别的label
    getDepartmentLabelById({ state }, nodeId) {
      if (!nodeId || !state.departmentTree.length) {
        return ''
      }

      const findNode = (treeNodes, targetId) => {
        for (const treeNode of treeNodes) {
          // 如果找到目标节点，返回本级的label
          if (treeNode.id === targetId) {
            return treeNode.label
          }

          // 如果有子节点，递归查找
          if (treeNode.children && treeNode.children.length > 0) {
            const result = findNode(treeNode.children, targetId)
            if (result) {
              return result
            }
          }
        }
        return null
      }

      const label = findNode(state.departmentTree, nodeId)
      return label || ''
    },
    // 获取指定节点所有子级中nodeType为"user"的节点个数
    getUserCountByLevelId({ state }, levelId) {
      if (!levelId || !state.departmentTree || !state.departmentTree.length) {
        return 0
      }

      // 查找目标节点
      const findTargetNode = (treeNodes, targetId) => {
        for (const treeNode of treeNodes) {
          if (treeNode.id === targetId) {
            return treeNode
          }
          if (treeNode.children && treeNode.children.length > 0) {
            const result = findTargetNode(treeNode.children, targetId)
            if (result) {
              return result
            }
          }
        }
        return null
      }

      // 递归统计所有子级中nodeType为"user"的节点个数
      const countUserNodes = (node) => {
        let count = 0

        // 如果当前节点是用户节点，计数加1
        if (node.nodeType === 'user') {
          count++
        }

        // 递归统计所有子节点
        if (node.children && node.children.length > 0) {
          for (const child of node.children) {
            count += countUserNodes(child)
          }
        }

        return count
      }

      const targetNode = findTargetNode(state.departmentTree, levelId)
      if (!targetNode) {
        return 0
      }

      // 统计目标节点所有子级中的用户节点个数
      return countUserNodes(targetNode)
    },
    // 更新当前部门路径
    async updateCurrentDepartmentPath({ commit, dispatch, state, rootState }, { level, levelId }) {

      // 根据级别获取对应的部门路径
      const path = await dispatch('getDepartmentPathById', levelId)

      if (level === 'personal') {
        // 个人模式：去掉数组里的最后一个元素
        const personalPath = path.slice(0, -1)
        const pathString = personalPath.join(' / ')
        commit('SET_CURRENT_DEPARTMENT_PATH', pathString)
        // 个人模式下管理人数为1（自己）
        commit('SET_CURRENT_LEVEL_USER_COUNT', 1)
      } else {
        // 其他模式：使用完整路径
        const pathString = path.join(' / ')
        commit('SET_CURRENT_DEPARTMENT_PATH', pathString)
        // 获取当前levelId在组织中管理的人数
        const userCount = await dispatch('getUserCountByLevelId', levelId)
        commit('SET_CURRENT_LEVEL_USER_COUNT', userCount)
      }
    }
  },

  getters: {
    currentLevel: state => state.currentLevel,
    currentLevelId: state => state.currentLevelId,
    oldLevel: state => state.oldLevel,
    oldLevelId: state => state.oldLevelId,
    allData: state => state.allData,
    // 新增角色状态getters
    isPersonal: state => state.isPersonal,
    isZhanZhang: state => state.isZhanZhang,
    isKeZhang: state => state.isKeZhang,
    isBanZuZhang: state => state.isBanZuZhang,
    isJingLi: state => state.isJingLi
  }
}

export default eikonLevel