import { setApp } from "@src/config";
import { ResData } from "@src/interceptor"
import userInfoStore from '@src/store/userInfo'
import { login } from '@src/utils/compatibility';
import Taro from "@tarojs/taro";

/**
 * 用户登录初始化（用来获取应用相关信息，并获取登录token）
 * */
export function wxloginInit(appId?: string) {
  return new Promise(async (resolve, reject) => {
    try {
      // 初始化
      let loginInitialize: any = await Taro.request<ResData>({
        url: '/app/wechatMiniappUser/loginInitialize',
        method: 'POST',
        data: { wechatAppId: appId || app.appId },
      })
      resolve(loginInitialize)
    } catch (error) {
      reject(error);
    }
  })
}
/***
 * 登录
 * */

export function wxlogin() {
  if (!app.token) {
    log("执行登录====>")
    return new Promise((resolve, reject) => {
      //获取code
      login({
        success: async function (res) {
          if (res.code) {
            //后台登录
            let response: any = await Taro.request<ResData>({
              url: '/app/wechatMiniappUser/jsCodeLogin',
              method: 'POST',
              data: { jsCode: res.code, params: {...app.pathParams,system:app.system} },
            });
            if (response.code === 200) {
              setApp({ token: response.data.token,appInfo:response.data.appInfo, userInfo: response.data.userInfo ,tokenValid:true})//存放token
              userInfoStore.setData({ userInfo: response.data.userInfo, isVip: response.data?.userInfo?.userStanding?.includes("vip") })
              resolve(response.data)
            }
          } else {
            log('登录失败！' + res.errMsg)
          }
        },
        fail: (err) => {
          log("获取code", err)
        }
      })
    })
  } else {
    log("已登录")
    return getUserInfo()
  }
}

/***
 * 获取个人信息
 * */
export function getUserInfo() {
 return new Promise((resolve, reject) => {
    Taro.request({
      url: "/app/wechatMiniappUser/refreshUserInfo",
      method: "POST",
      success: (res) => {
        if (res.data.code === 200) {
          let { token, userInfo,appInfo,payVersion } = res?.data?.data
          setApp({ token, userInfo ,appInfo,payVersion})//存放token
          userInfoStore.setData({ userInfo: userInfo, isVip: userInfo?.userStanding?.includes("vip") })
          resolve(res?.data?.data.userInfo)
        }else{
          resolve(null)
        }
      },
      fail: (err) => {
        reject(err);
      }
    })
  })
}