import { login, nameLogin, phoneLogin, logout, getInfo } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { Notification, MessageBox, Message } from 'element-ui'
import Cookies from 'js-cookie'
import { encrypt, decrypt } from '@/utils/encrypt.js'
const user = {
  state: {
    token: getToken(),
    name: '',
    avatar: '',
    roles: [],
    permissions: [],
    companyStatus: 0,
    testerStatus: 0,
    messageCount:0,
    cartCount:0,
    userId:0,
    activeName:'',
    activeNameManager: '',
    websiteDomain:''
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_USERID:(state, userId) => {
      state.userId = userId
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
    },
    SET_COMPANY: (state, companyStatus) => {
      state.companyStatus = companyStatus
    },
    SET_TESTER: (state, testerStatus) => {
      state.testerStatus = testerStatus
    },
    SET_MESSAGECOUNT: (state, count) => {
      state.messageCount = count
    },
    SET_CARTCOUNT: (state, count) => {
      state.cartCount = count
    },
    SET_ACTIVENAME: (state, activeName) => {
      state.activeName = activeName
    },
    SET_ACTIVENAMEMANAGER: (state, activeName) => {
      state.activeNameManager = activeName
    },
    SET_WEBSITE_DOMAIN: (state, websiteDomain) => {
      state.websiteDomain = websiteDomain
    }
  },

  actions: {
    // 手机登录
    PhoneLogin({ commit,state}, userInfo) {
      const mobile = userInfo.mobile.trim()
      const password = userInfo.password
      const code = userInfo.code
      const uuid = userInfo.uuid
      return new Promise((resolve, reject) => {
        phoneLogin(mobile, password, code, uuid).then(res => {
          setToken(res.token, state.websiteDomain);
          commit('SET_TOKEN', res.token)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 只需要账号和密码登录
    NameLogin({ commit, state}, userInfo) {
      const username = userInfo.username.trim()
      const password = userInfo.password
      // const password = encrypt(userInfo.password)
      const code = userInfo.code
      const uuid = userInfo.uuid
      return new Promise((resolve, reject) => {
        nameLogin(username, password, code, uuid).then(res => {
          if(res.code==200){

            // console.log('登录成功--',res)
            setToken(res.token,  state.websiteDomain)
            commit('SET_TOKEN', res.token)
            resolve(res)
          }else{
            resolve(res)
            // Message({
            //   message: res.msg,
            //   type: 'error'
            // })
          }
        }).catch(error => {
          console.log('error---',error)
          reject(error)
        })
      })
    },
    // 账号+验证码登录
    Login({ commit,state}, userInfo) {
      const username = userInfo.username.trim()
      const password = userInfo.password
      const code = userInfo.code
      const uuid = userInfo.uuid
      return new Promise((resolve, reject) => {
        login(username, password, code, uuid).then(res => {
          setToken(res.token,  state.websiteDomain)
          commit('SET_TOKEN', res.token)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo().then(res => {
          // console.log('用户信息res---',res)
          if(res){
            const user = res.user
            const avatar = (user.avatar== null || user.avatar == "") ? require("@/assets/pic/nobody.png") : user.avatar;
            if (res.roles && res.roles.length > 0) { // 验证返回的roles是否是一个非空数组
              commit('SET_ROLES', res.roles)
              commit('SET_PERMISSIONS', res.permissions)
            } else {
              commit('SET_ROLES', ['ROLE_DEFAULT'])
            }
            commit('SET_NAME', user.userName)
            commit('SET_USERID', user.userId)
            commit('SET_AVATAR', avatar)
            commit('SET_COMPANY', user.companyStatus)
            commit('SET_TESTER', user.testerStatus)
            commit('SET_MESSAGECOUNT', 0)
            commit('SET_CARTCOUNT', 0)
            resolve(res)
          }else{

          }
        }).catch(error => {
          reject(error)
          console.log('用户信息失败---',error)
          // location.href = '/index';
        })
      })
    },

    // 退出系统
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        // console.log('9999---',state)
        // return;
        logout(state.token).then((res) => {
          // console.log('8888---',res)
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_PERMISSIONS', [])

          removeToken(state.websiteDomain)
          Cookies.set('Admin-Token', '');
          // console.log('6666+---',getToken())
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken(this.state.websiteDomain)
        resolve()
      })
    }
  }
}

export default user
