import {
  listCommonuser
} from "@/api/common.js"

var userdata = []
var userdatabefore = []

function getTreeUser() {

  listCommonuser({
    page_size: 999,
  }).
  then((res) => {
      console.log("123")
    // this.userdata = res.data ? res.data.reverse() : [];
    let data = res.data ? res.data.reverse() : [];
    userdatabefore = res.data ? res.data.reverse() : [];
    let contactData = contactUser(data)
    userdata = sortDepartment(contactData, 'department_id')
    console.log("this.userdata123", userdata)
    return {
      userdata:userdata,
      userdatabefore:userdatabefore
    }
  }).catch(error => {
    console.log(error)
  })
}
getTreeUser()
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'],
          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
  }
  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)
    })
  }

export default getTreeUser
