import { getToken, setToken, removeToken } from '@/utils/auth'
import {Login} from '@/api/index'
// 村赤用户令牌和角色信息
const state ={
    token: getToken(),
    roles: [], //角色
    use_name:'',
}

const mutations ={
    SET_TOKEN: (state,token) => {
        state.token = token;
    },
    SET_ROLES: (state,roles) => {
        state.roles = roles;
    },
    SET_USE_NAME:(state,use_name) =>{
      state.use_name = use_name
    }
};

const actions = {
    // 用户登录
    login({ commit }, userInfo) {
      const {username} = userInfo
        return new Promise((resolve,reject) => {
          Login(userInfo).then((response) =>{
            sessionStorage.setItem('username',userInfo.account)
            sessionStorage.setItem('password',userInfo.password)
            const is_admin = response.data.admin.is_admin
            const role_type = response.data.admin.role_type
            const use_name = response.data.admin.name
            sessionStorage.setItem('use_name',use_name)
            console.log('2222222',response.data);
            commit('SET_USE_NAME',use_name)
            commit('SET_TOKEN',is_admin);
            setToken(is_admin)
            resolve()
          }).catch(error => {
              reject(error)
          })
          // setTimeout(() => {
          //     if(username === 'admin' || username === 'jerry'){
          //         // 保存状态 
          //         console.log('2222222',username);
          //         commit('SET_TOKEN',username);
          //         // 写入cookie
          //         setToken(username)
          //         resolve()
          //     }else{
          //         reject('用户名或密码错误')
          //     }
          // },1000)
      })
    },

    // 获取用户角色信息
    getInfo({ commit, state }){
        return new Promise((resolve) => {
            setTimeout(() => {
                console.log('yyyyyy',state.token)
                const roles =[]
                if(state.token == '1'){
                  // roles.push('1')
                  roles.push('管理员')
                  // return roles
                }else if(state.token == '2'){
                  // roles.push('2')
                  roles.push('销售')
                  // return roles
                }else if(state.token == '3'){
                  // roles.push('3')
                  roles.push('运营')
                  // return roles
                }
                console.log('0000',roles);
                commit('SET_ROLES',roles)
                resolve({roles})
                // roles.length = 0
            },1000)
        })
    },
    // 重置令牌
    resetToken({ commit }){
        return new Promise(resolve => {
            commit('SET_TOKEN','')
            commit('SET_ROLES',[])
            removeToken();
            resolve()
        })
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}