import {
  login,
  logout,
  getInfo,
  getMenueList
} from '@/apiV2/user'
import {
  getToken,
  setToken,
  removeToken
} from '@/utils/auth'
import router, {
  resetRouter
} from '@/router'
import Layout from '@/layout'
const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: [],
  topnav: '',
  toplist: [],
  operations: []
}
/**
 * 添加动态(菜单)路由
 * @param {*} roles 菜单列表
 * @param {*} routes 递归创建的动态(菜单)路由
 */
function addDynamicMenuRoutes(roles = [], routes = []) {
  const accessedRoutes = filterAsyncRouter(roles)
  accessedRoutes.push({
    path: '*',
    redirect: '/',
    hidden: true
  })
  return accessedRoutes
}
// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap, fid) {
  return asyncRouterMap.filter(route => {
    if (route.path) {
      // Layout组件特殊处理
      if (route.component == 'Layout') { // 有子菜单的情况下
        route.component = Layout
      } else { // 子菜单
        if (fid) {
          route.meta.parentId = fid
          delete route.parentId
        }
        route.name = route.name || route.meta.title
        route.component = loadView(route.path)
      }
      if (route.children != null && route.children && route.children.length) {
        route.children = filterAsyncRouter(route.children, route.parentId)
      }
      return true
    }
  })
}
export const loadView = (view) => { // 路由懒加载
  return (resolve) => require([`@/views${view}`], resolve)
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_TOPLIST: (state, toplist) => {
    state.toplist = toplist
  },
  SET_TOPNAV: (state, topnav) => {
    state.topnav = topnav
  },
  SET_OPERATION: (state, operations) => {
    state.operations = operations
  }
}

const actions = {
  // user login
  login({
    commit
  }, userInfo) {
    const {
      username,
      password,
      verifyCode,
    } = userInfo
    return new Promise((resolve, reject) => {
      login({
        username: username.trim(),
        password: password,
        verifyCode: verifyCode,

      }).then(response => {
        resolve(response)
        // localStorage.setItem('manager-fs_aInfo', JSON.stringify(response.data.userId))
        commit('SET_TOKEN', response.data.token)
        setToken(response.data.token)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({
    commit,
    state
  }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const data = response
        localStorage.setItem('manager-userLogin', JSON.stringify(data.data))
        // localStorage.setItem('manager-companyId', JSON.stringify(response.data.enterprise.id))
        if (!data) {
          reject('Verification failed, please Login again.')
        }
        const { menus,roleNames } = data.data

        // roles must be a non-empty array
        /* if (!roles || roles.length <= 0) {
          reject('getInfo: roles must be a non-null array!')
        } */

        /* commit('SET_ROLES', roles)
        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        commit('SET_INTRODUCTION', introduction) */
        commit('SET_ROLES', 'admin')
        commit('SET_OPERATION', menus)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({
    commit,
    state,
    dispatch
  }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        removeToken()
        resetRouter()
        // localStorage.removeItem('manager-fs_aInfo')
        localStorage.removeItem('parkInfo')
        localStorage.removeItem('manager-companyId')
        // reset visited views and cached views
        // to fixed https://github.com/Pa'manager-fs_aInfo'lement-admin/issues/2485
        dispatch('tagsView/delAllViews', null, {
          root: true
        })
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({
    commit
  }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },
  // remove token
  changeTopNav({
    commit,
    dispatch
  }, val) {
    return new Promise(async resolve => {
      commit('SET_TOPNAV', val)
      resolve()
    })
  },

  // dynamically modify permissions
  changeRoles({
    commit,
    dispatch
  }, role) {
    return new Promise(async resolve => {
      const token = role + '-token'

      commit('SET_TOKEN', token)
      setToken(token)

      const {
        roleNames
      } = await dispatch('getInfo')
      resetRouter()
      // generate accessible routes map based on roles
      const accessRoutes = await dispatch('permission/generateRoutes', roleNames, {
        root: true
      })

      // dynamically add accessible routes
      router.addRoutes(accessRoutes)

      // reset visited views and cached views
      dispatch('tagsView/delAllViews', null, {
        root: true
      })

      resolve()
    })
  },

  // 获取菜单
  getMenue({
    commit
  }) {
    return new Promise(resolve => {
      getMenueList().then(res => {
        commit('SET_TOPNAV', res.data.level1s[0].id)
        // commit('SET_TOPNAV', res.data.level1s[res.data.level1s.length - 1].id)
        var info = []
        var newlevel1s = res.data.level1s.map(item => {
          info = res.data.level2s.filter(item2 => {
            return item.id == item2.parentId
          })[0]
          return {
            id: item.id,
            name: item.name,
            path: info != undefined ? info.children[0].path : '/'
          }
        }
        )
        commit('SET_TOPLIST', newlevel1s)
        var menue = addDynamicMenuRoutes(res.data.level2s)
        // 返回菜单列表
        var rtnArr = []
        rtnArr[0] = res.data.level2s // 后台菜单结构数据
        rtnArr[1] = menue // 拼接以后的菜单路由表
        resolve(rtnArr)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
