import { login, logout, getInfo, getPermission } from '@/api/user'
import { getToken, setToken, removeToken, setSessionStorage } from '@/utils/auth'
import { resetRouter, constantRoutes } from '@/router'
import { queryParent } from '@/utils'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    permission: []
  }
}

const state = getDefaultState()

const filterRoutes = (route, menus) => {
  route.forEach(item => {
    if (menus.includes(item.name)) {
      item.hidden = false
    } else {
      item.hidden = true
    }
    if (item.children && item.children?.length) {
      filterRoutes(item.children, menus)
    }
  })
}

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_USERINFO: (state, info) => {
    state.userInfo = info
  },
  SET_PERMISSION: (state, info) => {
    state.permission = info
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    commit('SET_TOKEN', userInfo.token)
    setToken(userInfo.token)
    const { loginName, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ loginName: loginName.trim(), password: password, resources: 0 }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo().then(response => {
        const { data } = response
        if (!data) {
          return reject('Verification failed, please Login again.')
        }

        const { loginName } = data

        commit('SET_NAME', loginName)
        commit('SET_USERINFO', data)
        // commit('SET_AVATAR', avatar)

        let showFlag = false
        if (data.admin) {
          showFlag = true
        } else {
          if (data.roles) {
            for (let i = 0; i < data.roles.length; i++) {
              if (data.roles[i].name === '业务经理') {
                showFlag = true
                break
              }
            }
          } else {
            showFlag = false
          }
        }
        sessionStorage.setItem('showFlag', showFlag)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      removeToken() // must remove  token  first
      resetRouter()
      commit('RESET_STATE')
      resolve()
      // logout(state.token).then(() => {
      // }).catch(error => {
      //   reject(error)
      // })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  },
  getPermissions({ commit, state }) {
    return new Promise((resolve, reject) => {
      getPermission().then(({ data }) => {
        if (!data) {
          return reject('Verification failed, please Login again.')
        }
        commit('SET_PERMISSION', data)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  generateRoutes({ dispatch }) {
    return new Promise((resolve, reject) => {
      dispatch('getPermissions').then(({ buttons, menus }) => {
        setSessionStorage('buttons', JSON.stringify(buttons))
        // setTimeout(() => {
        const list = ['Dashboard', 'DashboardIndex']
        menus.forEach(item => {
          list.push(...queryParent(constantRoutes, item, 'name', 'children', 'name'))
        })
        filterRoutes(constantRoutes, list)
        resolve(constantRoutes)
        // }, 1000)
      })
    })
  }
}

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