import createPersistedState from 'vuex-persistedstate';
import {
  login,
  logout,
  getProfile
} from '@/api/login'
import {
  getMenuRole
} from '@/api/menu'


const user = {
  plugins: [
    createPersistedState({
      storage: window.localStorage, // 或者使用 sessionStorage
      paths: ['user']
    }),
  ],
  state: {
    companyName: localStorage.getItem('companyName'),
    token: '',
    name: '',
    welcome: '',
    avatar: '',
    roles: [],
    info: {}
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_INFO: (state, info) => {
      state.info = info
    },
    SET_NAME: (state, companyName) => {
      state.companyName = companyName
    }
  },

  actions: {
    // user login
    Login({
      commit
    }, userInfo) {
      return new Promise((resolve, reject) => {
        // api/user
        // 连接后端接口，根据前端请求的用户信息，后端返回唯一对应的随机token
        login(userInfo).then(response => {
          console.log(response,9)
          const data = response
          if (data.code == 200) {
            // commit会触发mutations，存储token
            commit('SET_TOKEN', data.token)
            // setToken(data.token)
            localStorage.setItem('T_tokey', data.token);
            getProfile().then(userRes => {
              var company = userRes.data.user.dept.name
              commit('SET_NAME', company)
              localStorage.setItem('companyName', company);
            })
            resolve()
          } else {
            reject(data)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 获取权限路由
    GetInfo({
      commit,
      state
    }) {
      return new Promise((resolve, reject) => {
        const roles = [{
          action: 'add',
          describe: '新增',
          defaultCheck: false
        }]
        // 存储用户信息，方便用于全局
        commit('SET_ROLES', roles)
        resolve(roles)
      })
    },
    // 登出
    Logout({
      commit,
      state
    }) {
      return new Promise((resolve) => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        localStorage.removeItem('T_tokey');
        localStorage.removeItem('username');
        resolve()
      })
    }
  }
}

export default user
