import Vue from 'vue'
import { login, getInfo, logout, smsLogin } from '@/api/upms/login'
import { dictData } from '@/api/upms/dict'
import { configData } from '@/api/upms/config'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import DictCache from '@/utils/dict'
import { welcome } from '@/utils/util'

const user = {
  state: {
    token: '',
    name: '',
    welcome: '',
    avatar: '',
    rmbRate: 1,
    permissions: [],
    roles: [],
    info: {
      username: null,
      realName: null,
      isAuthentication: false

    }
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, { name, welcome }) => {
      state.name = name
      state.welcome = welcome
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_USER_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_USER_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
    },
    SET_INFO: (state, info) => {
      state.info = info
    },
    SET_RMB_RATE: (state, rmbRate) => {
      state.rmbRate = rmbRate
    }
  },

  actions: {
    // 登录
    Login ({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        const loginType = userInfo.loginType
        if (loginType === 1) {
          login(userInfo).then(response => {
            const result = response.data
            if (result) {
              const accessToken = result.access_token
              Vue.ls.set(ACCESS_TOKEN, accessToken, 7 * 24 * 60 * 60 * 1000)
              commit('SET_TOKEN', accessToken)
            }
            dictData().then(response => {
              const data = response.data
              Vue.ls.set(DictCache.BASE_DATA_CACHE, data)
            })
            resolve()
          }).catch(error => {
            reject(error)
          })
        } else if (loginType === 2) {
          smsLogin(userInfo).then(response => {
            const result = response.data
            if (result) {
              const accessToken = result.access_token
              Vue.ls.set(ACCESS_TOKEN, accessToken, 7 * 24 * 60 * 60 * 1000)
              commit('SET_TOKEN', accessToken)
            }
            dictData().then(response => {
              const data = response.data
              Vue.ls.set(DictCache.BASE_DATA_CACHE, data)
            })
            resolve()
          }).catch(error => {
            reject(error)
          })
        }
      })
    },
    setAvatar ({ commit }, avatar) {
      commit('SET_AVATAR', avatar)
    },
    setUserInfo ({ commit }, userInfo) {
      console.log(userInfo)
      commit('SET_INFO', userInfo)
    },
    // 获取用户信息
    GetInfo ({ commit }) {
      return new Promise((resolve, reject) => {
        getInfo().then(response => {
          const result = response.data

          // if (result && result.permissions && result.permissions.length > 0) {
          //   result.permissions.map(per => {
          //     if (per.actionEntitySet != null && per.actionEntitySet.length > 0) {
          //       const action = per.actionEntitySet.map(action => { return action.action })
          //       per.actionList = action
          //     }
          //   })
          if (result && result.permissions && result.permissions.length > 0) {
            const permissionList = []
            result.permissions.forEach(function (v) {
              permissionList.push(...v.split(','))
            })
            commit('SET_USER_PERMISSIONS', permissionList)
          } else {
            commit('SET_USER_PERMISSIONS', ['test:permissions'])
          }
          if (result && result.roles && result.roles.length > 0) {
            const roleList = []
            result.roles.forEach(function (v) {
              roleList.push(...v.split(','))
            })
            commit('SET_USER_ROLES', roleList)
            console.log(roleList)
          } else {
            commit('SET_USER_ROLES', ['test:role'])
          }
          commit('SET_INFO', result.userInfo)
          // } else {
          //   reject(new Error('getInfo: roles must be a non-null array !'))
          // }

          commit('SET_NAME', { name: result.userInfo.realName, welcome: welcome() })
          commit('SET_AVATAR', result.userInfo.avatar)

          configData().then(res => {
            const configMap = res.data['config:open:value']
            const rmbRate = parseFloat(configMap[DictCache.TYPE.MONEY_TYPE + DictCache.VALUE.MONEY_TYPE.RMB + '_' + DictCache.VALUE.MONEY_TYPE.MY])
            commit('SET_RMB_RATE', rmbRate)
          })

          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    Logout ({ commit, state }) {
      return new Promise((resolve) => {
        commit('SET_TOKEN', '')
        commit('SET_USER_ROLES', [])
        Vue.ls.remove(ACCESS_TOKEN)
        resolve()
        // logout(state.token).then(() => {
        //   resolve()
        // }).catch(() => {
        //   resolve()
        // }).finally(() => {
        //   commit('SET_TOKEN', '')
        //   commit('SET_USER_ROLES', [])
        //   Vue.ls.remove(ACCESS_TOKEN)
        // })
      })
    }

  }
}

export default user
