// import { getAuth } from '@/api/login'
import { appRouter, loginRouter } from '../router/routes'
const state = {
  permissionList: null,
  addRoutes: [],
  authorIds: []
}
const getters = {
  getAuthIds() {
    return state.authorIds
  }
}
// 更改state
const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.permissionList = [loginRouter].concat(routes)
  },
  SET_AUTHORID: (state, idList) => {
    state.authorIds = idList
  },
  ClEAR_LIST: state => {
    state.permissionList = null
  }
}

const actions = {
  FETCH_PERMISSION({ commit }) {
    let allRoutes = clone(appRouter)
    return new Promise((resolve, reject) => {
          commit('SET_ROUTES', allRoutes)
          resolve(allRoutes)
    })
  },
  FETCH_AUTHORID({ commit }) {
    // getAuth().then(res => {
    //   let authorIds = res.data
    //   commit('SET_AUTHORID', authorIds)
    // })
  }
}
function clone(obj) {
  var copy
  // Handle the 3 simple types, and null or undefined
  if (null == obj || 'object' != typeof obj) return obj
  // Handle Date
  if (obj instanceof Date) {
    copy = new Date()
    copy.setTime(obj.getTime())
    return copy
  }
  // Handle Array
  if (obj instanceof Array) {
    copy = []
    for (var i = 0, len = obj.length; i < len; i++) {
      copy[i] = clone(obj[i])
    }
    return copy
  }
  // Handle Object
  if (obj instanceof Object) {
    copy = {}
    for (var attr in obj) {
      // eslint-disable-next-line no-prototype-builtins
      if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr])
    }
    return copy
  }

  throw new Error("Unable to copy obj! Its type isn't supported.")
}
// 根据接口返回权限id，查找节点
function getNodeById(json, id, path) {
  if (!path) {
    path = []
  }
  for (let i = 0; i < json.length; i++) {
    let temPath = path.concat()
    temPath.push(json[i])
    if (id === json[i].id) {
      temPath.forEach(list => {
        list['isTrget'] = true
      })
      return temPath
    } else {
      if (json[i].children && json[i].children.length > 0) {
        getNodeById(json[i].children, id, temPath)
      }
      if (json[i].button && json[i].button.length > 0) {
        getNodeById(json[i].button, id, temPath)
      }
    }
  }
}
// 过滤根据接口返回权限id查找的节点
function getFilterNode(json) {
  for (let i = json.length - 1; i >= 0; i--) {
    let item = json[i]
    if (!item.isTrget) {
      json.splice(i, 1)
    } else {
      if (item.children && item.children.length > 0) {
        getFilterNode(item.children)
      }
      if (item.button && item.button.length > 0) {
        getFilterNode(item.button)
      }
    }
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
