import http from "./http";
import Vue from "vue";

/**
 * 用户登录信息
 */
export const user = {
  state: () => ({}),
  mutations: {
    setUser(state, user) {
      for (const key in user) {
        Vue.set(state, key, user[key])
      }
    },
  },
  actions: {
    getUserInfo({commit}, way = "std") {
      //获取企业微信后台账号信息
      //党员认证状态 partyStatusForWX:0、未认证 1、认证中 2、已认证
      const actions = {
        std: "/app/appwechatuser/check",
        qujing: "/app/appwechatuserqujing/check",
      }
      return http.post(actions[way]).then(res => {
        if (res?.data) {
          commit('setUser', res.data)
          return Promise.all([])
        }
      })
    },
    getCode({dispatch}, count = 0) {
      if (count > 3) {
        return Promise.reject("无法获取code")
      } else return new Promise((resolve, reject) => {
        uni.login({
          success: res => {
            if (res?.code) {
              resolve(res.code);
            } else {
              reject(res);
            }
          },
          fail: () => resolve(dispatch("getCode", ++count))
        })
      })
    },
    getToken({commit}, params) {
      if (params?.code) {
        return http.post("/auth/wechat-con/token", params, {
          headers: {"Authorization": "Basic d2VjaGF0OndlY2hhdA=="},
          withoutToken: true
        }).then(res => {
          if (res?.access_token) {
            const token = [res?.token_type, res?.access_token].join(" ").trim()
            commit("setToken", token)
            return token
          } else {
            uni.showToast({title: res?.msg})
            return Promise.reject(res?.msg)
          }
        })
      } else return Promise.reject("缺少登录code")
    },
    autoLogin({dispatch}, params = {nickName: '微信用户'}) {
      const {loginWay = 'std'} = params
      return dispatch("getCode").then(code => dispatch("getToken", {...params, code})).then(() => dispatch('getUserInfo', loginWay))
    },
    authCheck({state, dispatch, rootState}, {checkType, modulePath}) {
      //用于进入应用的权限判断
      //checkType  1、登录认证 2、居民认证 3、党员认证 4、丰都个人认证
      //判断是否需要校验认证信息
      let {user: userInfo, token} = rootState
      console.log();
      if (!checkType) {
        //如果需要校验认证信息，必定要先验证是否登录
        uni.navigateTo({url: modulePath});
      } else if (checkType == 1) {
        if (!token) {
          return dispatch('autoLogin').then(() => dispatch('authCheck', {checkType, modulePath}));
        }
        uni.navigateTo({url: modulePath});
      } else if (checkType == 2) {
        if (!token) {
          return dispatch('autoLogin').then(() => dispatch('authCheck', {checkType, modulePath}));
        }
        if (!(userInfo.residentId && userInfo.status == 2)) {
          return uni.navigateTo({url: '/mods/AppAuth/AppAuth'});
        }
        uni.navigateTo({url: modulePath});
      } else if (checkType == 3) {
        if (!token) {
          return dispatch('autoLogin').then(() => dispatch('authCheck', {checkType, modulePath}));
        }
        if (!userInfo?.partyId) {
          return uni.showToast({title: "您还不是党员，暂时无法使用该功能", icon: "none"});
        }
        uni.navigateTo({url: modulePath});
      } else if (checkType == 4) {
        if (!token) {
          return dispatch('autoLogin', { loginWay: 'qujing' }).then(() => dispatch('authCheck', { checkType, modulePath }));
        }
        if (!userInfo.areaId) {
          return uni.showModal({
            title: '温馨提示',
            content: '您只有完成信息认证后，才可进行相关操作。',
            confirmText: '去认证',
            success: (res)=> {
              if (res.confirm) {
                uni.reLaunch({ url: `/pages/AppMine/userInfo?isFromTabbar=1&path=/pages/AppHome/AppHome` })
              } else if (res.cancel) {
                // 停留
              }
            }
          })
        }
        uni.navigateTo({ url: modulePath });
      }
    }
  }
}
