import api from '@/utils/api'
import router from '@/router'
import { Message } from 'element-ui'

export default {
  namespaced: true,
  state: {
    token: null,
    id: null,
    name: null,
    uname: null,
    photo: null,
    shop_id: null,
    power: null,
    lasttime: null
  },
  mutations: {
    // 用户信息初始化
    initUser (state) {
      if (state.token == null) {
        if (localStorage.getItem('token') != null) {
          state.token = localStorage.getItem('token')
          state.id = localStorage.getItem('id')
          state.name = localStorage.getItem('name')
          state.uname = localStorage.getItem('uname')
          state.photo = localStorage.getItem('photo')
          state.shop_id = localStorage.getItem('shop_id')
          state.power = localStorage.getItem('power')
          state.lasttime = localStorage.getItem('lasttime')
        }
      }
    },
    // 清除用户信息
    destroyUser (state) {
      state.token = null
      state.id = null
      state.name = null
      state.uname = null
      state.photo = null
      state.shop_id = null
      state.power = null
      state.lasttime = null
      localStorage.removeItem('token')
    }
  },
  actions: {
    // 异步 清除用户信息
    async destroyUserAsync (context) {
      await context.commit('destroyUser')
    },
    /**
     * @description: 登录
     * @param {*} params 表单.用户登录信息
     */
    async fetchLogin ({ commit }, params) {
      const data = new URLSearchParams()// post对象参数 转成 字符串连接
      data.append('username', params.username)
      data.append('password', params.password)
      api.post('login', data, 'Login').then(
        res => {
          if (res.data.status === 1) {
            localStorage.setItem('token', res.data.token)
            localStorage.setItem('id', res.data.adminInfo.id)
            localStorage.setItem('name', res.data.adminInfo.name)
            localStorage.setItem('uname', res.data.adminInfo.uname)
            localStorage.setItem('photo', res.data.adminInfo.photo)
            localStorage.setItem('shop_id', res.data.adminInfo.shop_id)
            localStorage.setItem('power', res.data.adminInfo.power)
            localStorage.setItem('lasttime', res.data.adminInfo.lasttime)
            router.replace('/')
          } else {
            Message.error(res.data.msg)
          }
        }
      )
    }
  }
}
