import {
  listCommonuser
} from "@/api/common.js"
let userData1 = []

// 获取 userdata
export function getChangeUser() {
  console.log("userData1", userData1)
  if (userData1.length > 0) {
    console.log("123")
    return
  } else {
    listCommonuser({
      page_size: 999,
    }).
    then((res) => {
      // userData1 = res.data ? res.data.reverse() : [];
      let data = res.data ? res.data.reverse() : [];
      let contactData = contactUser(data)
      userData1 = sortDepartment(contactData, 'department_id')
      console.log("userData1", userData1)
      return userData1
    }).catch(error => {
      console.log(error)
    })
  }
}


/**
 * @param {Object} arr
 * 处理小组返回
 */
export function contactGroup(arr) {
  let tempArr = [],
    newArr = []
  for (let i = 0; i < arr.length; i++) {
    if (tempArr.indexOf(arr[i].name) === -1) {
      if (arr[i].type === 1) {
        newArr.push({
          type: arr[i].type,
          name: arr[i]['name'],
          admin_details: arr[i].details,
          dep_details: []
        })
      } else {
        newArr.push({
          type: arr[i].type,
          name: arr[i]['name'],
          admin_details: [],
          dep_details: arr[i].details
        })
      }
      tempArr.push(arr[i].name);
    } else {
      for (let j = 0; j < newArr.length; j++) {
        if (newArr[j].name == arr[i].name) {
          if (arr[i].type === 1) {
            newArr[j].admin_details.push(...arr[i].details)
          } else {
            newArr[j].dep_details.push(
              ...arr[i].details
            )
          }
        }
      }
    }
  }
  return newArr
}
/*
* 人员按照部门重组
*/
export function contactUser(arr) {
  let tempArr = [],
    newArr = []
  for (let i = 0; i < arr.length; i++) {
    if (tempArr.indexOf(arr[i].department_id) === -1) {
      newArr.push({
        department_id: arr[i].department_id,
        name: arr[i]['department']['name'],
        manager_id: arr[i]['department']['manager_id'],
        leader_id: arr[i]['department']['leader_id'],
        children: [arr[i]]
      })
      tempArr.push(arr[i].department_id);
    } else {
      for (let j = 0; j < newArr.length; j++) {
        if (newArr[j].department_id == arr[i].department_id) {
          newArr[j].children.push(arr[i])
        }
      }
    }
  }
  return newArr
}
export function sortDepartment(arr, key) {
  return arr.sort(function(a, b) {
    var x = a[key]
    var y = b[key]
    return ((x < y) ? -1 : (x > y) ? 1 : 0)
  })
}
