import { getStore, setStore } from '@/util/store'
// import { isURL, validatenull } from '@/util/validate'
import { login, nameLogin, phoneLogin, logout, getInfo } from '@/api/system/login'
// import { deepClone, encryption } from '@/util/util'

const user = {
  state: {
    token:  getStore({name: 'token'}) || '',//登录tokenken
    logindate: getStore({name: 'logindate'}) || '',//登录时间
    userinform: getStore({name: 'userinform'}) || '',//用户信息
    name: getStore({name: 'name'}) || '',//用户名
    avatar:getStore({name: 'avatar'}) || '',//用户头像
    userId:getStore({name: 'userId'}) || 0,//用户id
    roles:getStore({name: 'roles'}) || [],//身份
    permissions:getStore({name: 'permissions'}) || [],//权限
    cartCount:getStore({name: 'cartCount'}) || 0,//购物车数量
    messageCount:getStore({name: 'messageCount'}) || 0,//站内消息
    companyStatus:getStore({name: 'companyStatus'}) || 0,//身份状态
    testerStatus:getStore({name: 'testerStatus'}) || 0,
    activeName:'',
    activeNameManager: '',
    websiteDomain:''
  },
  actions: {
    // 根据用户名登录
    NameLogin({ commit, state}, userInfo) {
      const username = userInfo.username.trim()
      const password = userInfo.password
     
      return new Promise((resolve, reject) => {
        // return;
        nameLogin(username, password).then(res => {
            commit('SET_TOKEN', res.token);
            const data=Date.parse(new Date());       
            commit('SET_LOGINDATE', data);
            resolve()
        }).catch(error => {
          reject({msg: '稍后再试'})
        })
      })
    },
    // 根据手机号登录
    PhoneLogin({ commit,state}, userInfo) {
      const mobile = userInfo.mobile
      const code = userInfo.code
      const uuid = userInfo.uuid
      // console.log('手机登录传的参数：',mobile,code,uuid)
      return new Promise((resolve, reject) => {
        phoneLogin(mobile, code, uuid).then(res => {
            // console.log('手机登录成功',res);
            commit('SET_TOKEN', res.token);
            const data=Date.parse(new Date());       
            commit('SET_LOGINDATE', data);
            resolve()    
        }).catch(error => {
          reject({msg: '稍后再试'})
        })
      })
    },
    // 账号+验证码登录 暂时没用
    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({msg: '稍后再试'})
        })
      })
    },
    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo().then(res => {
          // console.log('用户信息',res)
          const user = res.user
          // const avatar = (user.avatar== null || user.avatar == "") ? require("../../../public/assets/home/picture.png") : 'https://www.keyitest.cn/'+user.avatar.substr(user.avatar && user.avatar.indexOf('g'));
          const avatar = (user.avatar== null || user.avatar == "") ? require("../../../public/assets/home/defaultAva.jpg") : 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_USERINFORM', user)
          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)
        }).catch(error => {
          reject({msg: '稍后再试'})
        })
      })
    },

    // 退出系统
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_LOGINDATE', '')
          commit('SET_ROLES', [])
          commit('SET_PERMISSIONS', [])
          commit('SET_USERINFORM', {})
          commit('SET_COMPANY', '')
          resolve()
        }).catch(error => {
          reject({msg: '稍后再试'})
        })
      })
    },
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
      setStore({
        name: 'token',
        content: state.token,
        type: 'session'
      })
    },
    SET_LOGINDATE: (state, logindate) => {
      state.logindate = logindate
      setStore({
        name: 'logindate',
        content: state.logindate,
      })
    },
    SET_USERINFORM: (state, userinform) => {
      state.userinform = userinform
      setStore({
        name: 'userinform',
        content: state.userinform,
      })
    },
    SET_NAME: (state, name) => {
      state.name = name
      setStore({
        name: 'name',
        content: state.name,
      })
    },
    SET_USERID:(state, userId) => {
      state.userId = userId
      setStore({
        name: 'userId',
        content: state.userId,
      })
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
      setStore({
        name: 'avatar',
        content: state.avatar,
      })
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
      setStore({
        name: 'roles',
        content: state.roles,
      })
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
      setStore({
        name: 'permissions',
        content: state.permissions,
      })
    },
    SET_CARTCOUNT: (state, cartcount) => {
      state.cartCount = cartcount
      setStore({
        name: 'cartcount',
        content: state.cartcount,
      })
    },
    SET_COMPANY: (state, companyStatus) => {
      state.companyStatus = companyStatus
      setStore({
        name: 'companyStatus',
        content: state.companyStatus,
      })
    },
    SET_TESTER: (state, testerStatus) => {
      state.testerStatus = testerStatus
      setStore({
        name: 'testerStatus',
        content: state.testerStatus,
      })
    },
    SET_MESSAGECOUNT: (state, count) => {
      state.messageCount = count
      setStore({
        name: 'messageCount',
        content: state.messageCount,
      })
    },
    
    SET_ACTIVENAME: (state, activeName) => {
      state.activeName = activeName
    },
    SET_ACTIVENAMEMANAGER: (state, activeName) => {
      state.activeNameManager = activeName
    },
    SET_WEBSITE_DOMAIN: (state, websiteDomain) => {
      state.websiteDomain = websiteDomain
    }
    // SET_PERMISSIONS: (state, permissions) => {
    //   const list = {}
    //   for (let i = 0; i < permissions.length; i++) {
    //     list[permissions[i]] = true
    //   }
    //   state.permissions = list
    // }
  }

}
export default user
