import { getToken, setToken, removeToken } from '@/utils/auth'
import Cookies from 'js-cookie'
import { Message } from 'element-ui'
import axios from 'axios'
import { getPayToken } from '@/utils/request'
const user = {
  state: {
    token: getToken(),
    name: Cookies.get('name'),
    roles: [],
    id: Cookies.get('id')
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_ID: (state, id) => {
      state.id = id
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim()
      const password = userInfo.password.trim()
      return new Promise((resolve, reject) => {
        var url = getPayToken + '?userName=' + username + '&passWord=' + password
        axios.get(url).then(response => {
          const data = response.data
          if (data.IsSuccess === false) {
            // const h = this.$createElement
            // this.$message({
            //   message: h('p', null, [
            //     h('span', null, '错误代码: '),
            //     h('i', { style: 'color: teal' }, `${{ data.ErrorCode }}`)
            //   ])
            // })
            // Message.error(`错误代码`+`${{ data.ErrorCode }}`+`,`+`${{ data.ErrorDesc }}`)
            var a = '错误' + response.data.ErrorCode + ',' + data.ErrorDesc
            Message({
              showClose: true,
              message: a,
              type: 'error'
            })
            this.$router.push({ path: '/login' })
          }
          if (data.token === '' || data.$id === '' || data === '') {
            Message.error('账号或密码错误，请重新登录')
            this.$router.push({ path: '/login' })
          } else { // 只有一个角色
            setToken(data.token)
            Cookies.set('id', data.$id, { expires: 1 })
            Cookies.set('name', username, { expires: 1 })
            commit('SET_TOKEN', data.token)
            commit('SET_NAME', username)
            commit('SET_ID', data.$id)
            resolve({ data, commit })
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    //  登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        Cookies.remove('name')
        Cookies.remove('id')
        removeToken()
        resolve()
      })
    }
  }
}

export default user
