import Vue from 'vue'
import { getToken, setToken, getStorageDict, setStorageDict, getStorageUser, setStorageUser } from '@/utils/auth'

const getDefaultState = () => {
  return {
    token: getToken(),
    sysDomain: getStorageUser().domain,
    sysUser: getStorageUser(),
    dictData: getStorageDict(),
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SYS_DOMAIN: (state, data) => {
    state.sysDomain = data
  },
  SYS_USER: (state, data) => {
    state.sysUser = data
  },
  DICT_DATA: (state, data) => {
    state.dictData = data
  }
}

const actions = {
  // user login
  login({ commit, dispatch }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      Vue.$api.base.admLogin({ username: username.trim(), password: password }).then(res => {
        if (res.token) {
          setToken(res.token)
          commit('SET_TOKEN', res.token)
          commit('SYS_USER', res.data)
          setStorageUser(res.data)
          commit('SYS_DOMAIN', res.data.domain)
          dispatch('getDict')
          resolve()
        } else {
          console.log('未找到token')
        }
      }).catch(error => {
        reject(error)
      })
    })
  },
  getDict({ commit }) {
    return new Promise((resolve, reject) => {
      Vue.$api.base.admdicttree().then(res => {
        const cObj = res || {}
        let newDict = {}
        for (let k in cObj) {
          const cArr = cObj[k].map(item => {
            return {
              ...item,
              key: item.dict_label,
              val: item.dict_value
            }
          })
          newDict[k] = cArr
        }
        setStorageDict(newDict)
        Vue.$dictData = Vue.prototype.$dictData = newDict
        commit('DICT_DATA', newDict)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
}

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

