import { ACCESS_TOKEN, USER_ID, FLAG } from '@/store/mutation-types'
import storage from '@/utils/storage'
import * as LoginApi from '@/api/login'

const user = {
  state: {
    token: '',
    buyerId: null,
    flag: null,
  },

  mutations: {
    SET_USER_INFO: (state, value) => {
        state.token = value.token
        state.buyerId = value.buyerId
        state.flag = value.flag
    }
  },

  actions: {
    // 用户登录 (普通登录: 输入手机号和验证码)
    Login({ commit }, data) {
      return new Promise((resolve, reject) => {
        LoginApi.login({ form: data })
          .then(response => {
            const result = response.data
            storage.set('user_info', result.buyer)
            commit('SET_USER_INFO', result.buyer)
            resolve(response)
          })
          .catch(reject)
      })
    },

    // 微信小程序一键授权登录 (获取用户基本信息)
    LoginMpWx({ commit }, data) {
      return new Promise((resolve, reject) => {
        // LoginApi.loginMpWx({ form: data }, { isPrompt: true })
        LoginApi.quickLogin(data)
          .then(response => {
            const result = response.data
            storage.set('user_info', result.buyer)
            commit('SET_USER_INFO', result.buyer)
            resolve(response)
          })
          .catch(reject)
      })
    },

    // 微信小程序一键授权登录 (授权手机号)
    LoginMpWxMobile({ commit }, data) {
      return new Promise((resolve, reject) => {
        LoginApi.loginMpWxMobile({ form: data }, { isPrompt: true })
          .then(response => {
            const result = response.data
            uni.setStorageSync('user_info', result.buyer)
            commit('SET_USER_INFO', result.buyer)
            resolve(response)
          })
          .catch(reject)
      })
    },

    // 退出登录
    Logout({ commit }, data) {
      const store = this
      return new Promise((resolve, reject) => {
        if (store.getters.userId > 0) {
          storage.remove('user_info')
          commit('SET_USER_INFO', { token: '', flag: '', buyerId: '' })
          resolve()
        }
      })
    }

  }
}

export default user
