import Vue from 'vue'
import { login, getInfo, logout, getUserToken,getUserTokenOne } from '@/api/login'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { welcome } from '@/utils/util'
import { Message } from 'element-ui'

const user = {
  state: {
    token: '',
    name: '',
    welcome: '',
    avatar: '',
    roles: [],
    info: {},
    userToken: ''
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_USER_TOKEN: (state, userToken) => {
      state.userToken = userToken
    },
    SET_NAME: (state, { name, welcome }) => {
      state.name = name
      state.welcome = welcome
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_INFO: (state, info) => {
      state.info = info
    }
  },

  actions: {
    // 登录
    Login ({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo).then(response => {
          const result = response.data
          Vue.ls.set(ACCESS_TOKEN, result.token, 7 * 24 * 60 * 60 * 1000)
          commit('SET_TOKEN', result.token)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo ({ commit }) {
      return new Promise((resolve, reject) => {
        getInfo().then(response => {
          const result = response.result

          if (result.role && result.role.permissions.length > 0) {
            const role = result.role
            role.permissions = result.role.permissions
            role.permissions.map(per => {
              if (per.actionEntitySet != null && per.actionEntitySet.length > 0) {
                const action = per.actionEntitySet.map(action => { return action.action })
                per.actionList = action
              }
            })
            role.permissionList = role.permissions.map(permission => { return permission.permissionId })
            commit('SET_ROLES', result.role)
            commit('SET_INFO', result)
          } else {
            reject(new Error('getInfo: roles must be a non-null array !'))
          }

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

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

    // 登出
    Logout ({ commit, state }) {
      return new Promise((resolve) => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        Vue.ls.remove(ACCESS_TOKEN)

        logout(state.token).then(() => {
          resolve()
        }).catch(() => {
          resolve()
        })
      })
    },

    // 获取用户token
    GetUserToken({commit, state }) {
      return new Promise((resolve) => {
        let userIdLocal = document.cookie.split('user=')[1]?(document.cookie.split('user=')[1].split(';')[0]):(localStorage.getItem('user')?JSON.parse(localStorage.getItem('user')):'')
        let temp = sessionStorage.getItem('userIdLocal')?sessionStorage.getItem('userIdLocal'):''
        let userTokenTwoTemp = ''
        /*
        * 根据用户是否更换角色，是否已有流程设计器token选择是否请求
        * */
        if ( temp != userIdLocal || !sessionStorage.getItem('userTokenTwo')){
          // 清空已有token
          commit('SET_USER_TOKEN','')
          sessionStorage.setItem("userToken", '')
          sessionStorage.setItem("userTokenTwo", '')
          sessionStorage.setItem("userIdLocal", userIdLocal)
            // 请求第一阶段
          let temp = {mid:userIdLocal}
          let _formData = new FormData()
          for (var i in temp) {
            _formData.append(i, temp[i])
          }
            getUserTokenOne(_formData).then(res =>{
              if (res.code===200 && res.data && res.data != '') {
                let temp = 'Bearer ' + res.data
                commit('SET_USER_TOKEN',temp)
                sessionStorage.setItem("userToken", temp)
                // 请求第二阶段
                getUserToken().then(res => {
                  if (res.code===200 && res.data && res.data != '') {
                    userTokenTwoTemp = state.userToken + res.data
                    commit('SET_USER_TOKEN',userTokenTwoTemp)
                    sessionStorage.setItem("userTokenTwo", userTokenTwoTemp)
                    resolve()
                  }else{
                    Message({
                      message: '无权限',
                      type: 'error',
                      duration: 3 * 1000
                    })
                    commit('SET_USER_TOKEN','')
                    console.log('获取token失败2')
                    resolve()
                  }
                }).catch((err) => {
                  console.error(err);
                  commit('SET_USER_TOKEN','')
                  console.log('获取token失败2-1')
                  resolve()
                })
              }else{
                console.log('获取token失败1')
                resolve()
              }
            }).catch(err => {
              console.log('获取token失败1-1')
              resolve()
            })
        }else{
          commit('SET_USER_TOKEN',sessionStorage.getItem('userTokenTwo'))
          console.log('无需获取token')
          resolve()
        }
      })

    }

  }
}

export default user
