import { ref } from 'vue'
import { selectDeptTreeListToComponent, selectPostToComponent, selectAllUserToComponent, queryCompanyList } from '../../api/system/user'

const DeptTreeList:any = ref([])
const PostList:any = ref([])
const AllUserList:any = ref([])
const companyList:any = ref([])

const findLabel = (arr: any[], target: string, labelName: string, idName: string) => {
  let res = ''
  function find(arr: any[], target: string, labelName: string, idName: string) {
    for (let i = 0; i < arr.length; i += 1) {
      if (arr[i][idName] === target) {
        res = arr[i][labelName]
        return
      }
      if (arr[i].children && arr[i].children.length) {
        find(arr[i].children, target, labelName, idName)
      }
    }
  }
  find(arr, target, labelName, idName)
  return res
}

export function getDeptName(id: string) {
  const name = findLabel(DeptTreeList.value, id, 'label', 'id')
  return name
}

export function getPostName(id: string) {
  const name = findLabel(PostList.value, id, 'postName', 'postId')
  return name
}

export function getAllUserName(id: string) {
  const name = findLabel(AllUserList.value, id, 'nickName', 'userId')
  return name
}

export function getDeptList() {
  return DeptTreeList
}

export function getPostList() {
  return PostList
}

export const getCompanyList = () => {
  return companyList
}

export function refreshDeptTreeList() {
  selectDeptTreeListToComponent({}).then(res => {
    DeptTreeList.value = res
  })
}

export function refreshPostList() {
  selectPostToComponent({ deptId: '' }).then((res:any) => {
    PostList.value = res.data
  })
}

export function refreshAllUserList() {
  selectAllUserToComponent({}).then((res:any) => {
    AllUserList.value = res.data
  })
}

export function refreshCompanyList() {
  queryCompanyList({}).then((res:any) => {
    companyList.value = res.data
  })
}
export function getCompanyName(code: string) {
  const name = findLabel(companyList.value, code, 'companyName', 'companyCode')
  console.log('name',name)
  return name
}