import { login, logout, getInfo } from '@/api/login'
import auth from '@/utils/auth'
import Vue from 'vue'
import cacheMixin from '@/components/Cache/mx-cache-mixin'

const user = {
  state: auth.getUserInfo(),

  mutations: {
    RELOAD: (state, newInfo) => {
      console.log('RELOAD this', state, newInfo)
      Object.keys(newInfo).forEach(key => {
        if (!state.hasOwnProperty(key)) {
          // NOTE:使用Vue.set动态添加监控属性
          Vue.set(state, key, newInfo[key])
        }
        state[key] = newInfo[key]
      })
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim()
      const password = userInfo.password

      return new Promise((resolve, reject) => {
        login(username, password).then(res => {
          auth.setToken(res.token)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo().then(res => {
          console.log('xxxxxxxxxxx', res);
          const user = res.data
          user.avatar == user.avatar || require("@/assets/images/profile.jpg")
          commit('RELOAD', user)
          auth.setUserInfo(user)
          cacheMixin.methods.clearUserCache() // NOTE：纯作为静态方法在调用，有更优雅的方式？
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 退出系统
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          auth.removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    }
  }
}

export default user
