import config from '@/config'
import storage from '@/utils/storage'
import constant from '@/utils/constant'
import { login, logout, getUserInfoAPI, loginAPI } from '@/api'
import { getToken, setToken, removeToken } from '@/utils/auth'

const baseUrl = config.baseUrl

const user = {
  state: {
    token: getToken(),
    name: storage.get(constant.name),
    avatar: storage.get(constant.avatar),
    roles: storage.get(constant.roles),
    permissions: storage.get(constant.permissions),
    user: storage.get(constant.user)
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
      setToken(token)
    },
    SET_NAME: (state, name) => {
      state.name = name
      storage.set(constant.name, name)
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
      storage.set(constant.avatar, avatar)
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
      storage.set(constant.roles, roles)
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
      storage.set(constant.permissions, permissions)
    },
    SET_USER: (state, user) => {
      state.user = user
      storage.set(constant.user, user)
    },
    SET_OPENID: (state, openid) => {
      state.openid = openid
      storage.set(constant.loginOpenId, openid)
    }
  },

  actions: {
    // 微信登录（获取 openId）
    getOpenId({ commit }) {
      return new Promise(async (resolve, reject) => {
        // 调用微信登录接口，获取一次性 code
        const [loginErr, loginRes] = await uni.login({
          provider: 'weixin'
        })

        // 通过 code 获取永久唯一身份标识 openid
        const [openErr, openRes] = await uni.request({
          url: `https://api.weixin.qq.com/sns/jscode2session?appid=${config.wxAppId}&secret=${config.wxSecret}&js_code=${loginRes.code}&grant_type=authorization_code`
        });

        if (loginErr || openErr) {
          reject(loginErr || openErr)
        } else {
          commit('SET_OPENID', openRes.data.openid)
          resolve(openRes.data.openid)
        }
      })
    },

    // 手机号+openId 促销员登录，获取 token 和个人信息
    Login({ commit }, { phoneNumber, openId }) {
      return new Promise(async (resolve, reject) => {
        const { data } = await loginAPI({
          phone: phoneNumber,
          openId: openId
        })
        commit('SET_TOKEN', data.token)
        commit('SET_USER', data.user)

        resolve(data)
      })
    },

    // 获取用户信息
    // GetInfo({ commit, state }) {
    //   return new Promise((resolve, reject) => {
    //     getUserInfoAPI().then(res => {
    //       console.log('用户信息', res)
    //       // const user = res.user
    //       // const avatar = ''
    //       // const username = (user == null || user.userName == "" || user.userName == null) ? "" : user.userName
    //       // if (res.roles && res.roles.length > 0) {
    //       //   commit('SET_ROLES', res.roles)
    //       //   commit('SET_PERMISSIONS', res.permissions)
    //       // } else {
    //       //   commit('SET_ROLES', ['ROLE_DEFAULT'])
    //       // }
    //       // commit('SET_NAME', username)
    //       // commit('SET_AVATAR', avatar)
    //       // commit('SET_USER', user)
    //       resolve(res)
    //     }).catch(error => {
    //       reject(error)
    //     })
    //   })
    // },

    // 退出系统
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_PERMISSIONS', [])
          commit('SET_USER', {})
          removeWxAccessToken()
          storage.clean()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    }
  }
}

export default user
