import { defineStore } from 'pinia'
import { useDialogueStore } from '@/store'
import lodash from 'lodash'

import { ref } from 'vue'
import { createGlobalState, useStorage } from '@vueuse/core'
import { uniStorage } from '@/utils/uniStorage.js'
import {
  departmentV2TreeMy,
  departmentV2AllPosition,
  groupCreateDept,
  departmentV2TreeAll,
  departmentV2TreeAll2,
  userHasPermission,
  userV2List,
  userV2List2,
  v2TreePositionByDepartment,
} from '@/api/deps/index.js'
import { useAuth } from '@/store/auth'
const { userInfo } = useAuth()
export const useGroupTypeStore = createGlobalState(() => {
  const groupName = ref('')
  const groupActiveIndex = ref(-1) // 当前激活的分组索引
  const depTreeMyList = ref([])
  const postTreeList = ref([])
  const departmentAllPositions = ref([]) //部门下所有岗位
  const crumbs = ref([])
  const crumbsIndex = ref(0)
  const depCheckedKeys = ref([]) // 部门选择模式下，选中的部门keys
  const groupAdmins = ref([]) // 选中的管理员
  const memberDepCheckedKeys = ref([]) // 人员选择模式下，选中的部门keys
  const membersCheckedKeys = ref([]) // 选中的人员keys
  const allChooseMembers = ref([])

  const getDepsTreeMy = async () => {
    const res = await departmentV2TreeAll()
    if (res.status === 0) {
      depTreeMyList.value = res.data.nodes
    }
  }
  // userInfo?.value?.ID
  const getDepsTreeMy2 = async (chooseMode) => {
    let params = { nowUserId: 0 }
    if (chooseMode === 1) {
      const isHasRes = await userHasPermission({
        erpUserId: userInfo?.value?.ID,
        ruleUrl: [
          'auth_chat_app_create_all_dept',
          'auth_chat_app_create_limit_dept',
        ],
      })
      if (isHasRes.code === 200) {
        if (isHasRes.data.auth_chat_app_create_all_dept) {
          params = {
            nowUserId: 0,
          }
        } else {
          if (isHasRes.data.auth_chat_app_create_limit_dept) {
            params = {
              nowUserId: userInfo?.value?.ID,
            }
          } else {
            params = {
              nowUserId: 0,
            }
          }
        }
      }
    }
    const res = await departmentV2TreeAll2(params)
    if (res.status === 0) {
      depTreeMyList.value = res.data.nodes
    }
  }

  //获取指定部门下的所有岗位
  const getPositionByDepartment = async (params) => {
    const res = await v2TreePositionByDepartment(params)
    if (res.status === 0) {
      departmentAllPositions.value = res.data.data
    }
  }

  const getPositionsTree = async () => {
    const res = await departmentV2AllPosition()
    if (res.status === 0) {
      postTreeList.value = res.data.nodes
    }
  }

  const getDepMembers = async (param) => {
    const res = await userV2List2(param)
    return res
  }

  const resetGroupInfo = () => {
    groupName.value = ''
    groupActiveIndex.value = -1
    depTreeMyList.value = []
    postTreeList.value = []
    crumbs.value = []
    crumbsIndex.value = 0
    depCheckedKeys.value = []
    groupAdmins.value = []
    memberDepCheckedKeys.value = []
    membersCheckedKeys.value = []
    allChooseMembers.value = []
  }

  const createDepGroup = async (param) => {
    const res = await groupCreateDept({
      name: groupName.value,
      deptInfos: depCheckedKeys.value.map((v) => {
        return {
          dept_id: v.ID,
          dept_name: v.name,
        }
      }),
      positionInfos: groupAdmins.value.map((v) => {
        return {
          dept_id: v.dept_id,
          dept_name: v.dept_name,
          position_id: v.position_id,
          position_name: v.position_name,
        }
      }),
    })
    return res
  }

  //通过部门Id和岗位Id得到部门和岗位的对应关系
  const getDepartmentPositionsById = (departmentId, positionId) => {
    return buildDepMap(postTreeList.value).get(`${departmentId}-${positionId}`)
  }

  //建立部门和岗位对应map
  const buildDepMap = (departments) => {
    const index = new Map()
    function traverse(deps) {
      for (let dep of deps) {
        if (dep.positions && dep.positions.length > 0) {
          dep.positions.forEach((position) => {
            index.set(
              `${dep.ID}-${position.ID}`,
              dep.name + '-' + position.name,
            )
          })
        }
        if (dep.sons && dep.sons.length > 0) {
          traverse(dep.sons)
        }
      }
    }
    traverse(departments)
    return index
  }

  return {
    groupName,
    groupActiveIndex,
    depTreeMyList,
    postTreeList,
    departmentAllPositions,
    getDepsTreeMy,
    getDepsTreeMy2,
    getPositionByDepartment,
    getPositionsTree,
    crumbs,
    crumbsIndex,
    depCheckedKeys,
    groupAdmins,
    resetGroupInfo,
    createDepGroup,
    getDepMembers,
    membersCheckedKeys,
    memberDepCheckedKeys,
    allChooseMembers,
    getDepartmentPositionsById,
  }
})
