import {
  wxLogin,
  bindUserPhone,
  checkUserPhone,
} from "../request/api/LoginApi";
import { getWeChatAuthCode } from "./AuthManager";
import { useAppStore } from "@/store";
import { clientId } from "@/constant/base";

const loginAuth = () => {
  return new Promise(async (resolve, reject) => {
    const openIdCode = await getWeChatAuthCode();
    console.log("获取到的微信授权code:", openIdCode);
    const params = {
      openIdCode: [openIdCode],
      grant_type: "wechat",
      scope: "server",
      clientId: clientId,
    };
    console.log("获取到的微信授权params:", JSON.stringify(params));
    const response = await wxLogin(params);
    console.log("获取到的微信授权response:", response);

    if (response.access_token) {
      uni.setStorageSync("token", response.access_token);
      const appStore = useAppStore();
      appStore.setHasToken(true);
      resolve();
    } else {
      reject(response.message || "登录失败");
    }
  });
};

const bindPhone = async (params) => {
  try {
    const response = await bindUserPhone(params);
    return response;
  } catch (error) {
    throw err;
  }
};

const checkPhone = async (phone) => {
  try {
    const response = await checkUserPhone(phone);
    return response;
  } catch (error) {
    throw err;
  }
};

export { loginAuth, bindPhone, checkPhone };
