import { setApp } from "@src/config";
import { ResData } from "@src/interceptor"
import Taro from "@tarojs/taro"

/**
 * 用户登录初始化（用来获取应用相关信息，并获取登录token）
 * */
export function dyloginInit(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 dylogin() {
  if (!app.token) {
    log("执行登录====>")
    return new Promise((resolve, reject) => {
      //获取code
      Taro.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 },
            });
            if (response.code === 200) {
              setApp({token:response.data.token})//存放token
              resolve(response.data)
            }
          } else {
            log('登录失败！' + res.errMsg)
          }
        },
        fail: (err) => {
          log("获取code", err)
        }
      })
    })
  } else {
    log("已登录")
  }
}