/* eslint-disable no-param-reassign */
import { getUserInfo, setPvInfo } from '@/api/modules/common'
import QuickStorage from '@/utils/QuickStorage'
import { CUSTOM_SOURCE_TYPE } from '@/utils/constant'
import Bus from '@/utils/Bus'

export const state = () => ({
  uin: 0,
  isLogin: false,
  isBindPhone: null,
  userInfo: {}
})
export const mutations = {
  SET_USERINFO: (state, info) => {
    state.userInfo = info
  },
  SET_ISLOGIN: (state, isLogin) => {
    state.isLogin = isLogin
  },
  SET_UIN: (state, uin) => {
    state.uin = uin
  },
  SET_ISBINDPHONE: (state, isBind) => {
    state.isBindPhone = isBind
  }
}
export const actions = {
  async getUerInfo({ commit }, params = {}) {
    const res = await getUserInfo(params)
    const { code, errorCode, errorMessage, data } = res
    const isReqSuccess = code === 200 && errorCode === 0
    if (isReqSuccess) {
      if (data.id) {
        commit('SET_USERINFO', res.data)
        commit('SET_ISLOGIN', true)
        if (data.phone && data.phone.length > 7) {
          commit('SET_ISBINDPHONE', true)
        } else {
          commit('SET_ISBINDPHONE', false)
        }
      } else {
        commit('SET_ISLOGIN', false)
      }
    }
    return new Promise((resolve, reject) => {
      if (isReqSuccess) {
        return resolve(data)
      }
      reject(new Error(JSON.stringify({ errorCode, errorMessage })))
    })
  },
  // eslint-disable-next-line no-unused-vars
  postInfo({ state }, id = 0) {
    const params = {
      channelId: id, // 资源id
      uin: state.uin,
      userId: state.userInfo?.id || 0,
      type: CUSTOM_SOURCE_TYPE.lottery,
      deviceid: QuickStorage.localGet('DEVICE_ID')
    }
    return setPvInfo(params)
  },
  jumpToLogin({ state }) {
    // 登录跳转地址
    if (!state.uin) {
      return false
    }
    const origin = window.location.origin
    const backUrl = encodeURIComponent(window.location.href)
    if (window.top !== window.self) {
      Bus.$emit('BusToLogin')
      return
    }
    window.location.href = `${origin}/my/login?uin=${state.uin}&backUrl=${backUrl}`
  },
  jumpToBinding({ state }) {
    // 登录跳转地址
    if (!state.uin) {
      return false
    }
    const origin = window.location.origin
    const backUrl = encodeURIComponent(window.location.href)
    if (window.top !== window.self) {
      Bus.$emit('BusToBindPhone')
      return
    }
    window.location.href = `${origin}/my/login/binding?uin=${state.uin}&backUrl=${backUrl}`
  }
}
export const getters = {
  isLogin: state => state.isLogin, // 是否登录
  isBindPhone: state => state.isBindPhone, // 是否绑定手机
  userInfo: state => state.userInfo, // 用户信息
  uin: state => state.uin
}
