// components/login/login.ts
import { BASE_URL, appId } from "../../env";
import { LoginRes } from "./login.d";
import { wxGetUserInfo, wxLogin, wxRequest } from "../../utils/wx-api";

interface LoginComponent {
  data: {
    mbuId: number;
    userName: string;
  };
  setData: (data: Partial<{ mbuId: number; userName: string }>) => void;
  triggerEvent: (name: string, detail?: any) => void;
  handleLogin: () => Promise<void>;
}
const app = getApp<IAppOption>();

Component({
  data: {
    mbuId: wx.getStorageSync("mbuId"),
    userName: wx.getStorageSync("userName"),
  },

  methods: {
    async handleLogin(this: LoginComponent) {
      try {
        wx.showLoading({ title: "登录中" });
        const loginRes = await wxLogin();
        const infoRes = await wxGetUserInfo();
        if (!loginRes.code) throw new Error(loginRes.errMsg);

        const loginResult = await wxRequest<LoginRes>({
          url: `${BASE_URL}/auth/app-login?appId=${appId}&code=${loginRes.code}`,
          method: "POST",
          data: {
            ...infoRes.userInfo,
          },
        });

        if (
          loginResult?.statusCode !== 200 ||
          (loginResult.data.code && loginResult.data.code !== 200)
        ) {
          throw new Error(loginResult?.msg || "登录失败");
        }

        const { mpUserId, id, openId, unionId, nickName } = loginResult.data;
        wx.setStorageSync("openId", openId);
        wx.setStorageSync("userId", mpUserId);
        wx.setStorageSync("mbuId", id);
        wx.setStorageSync("unionId", unionId);
        wx.setStorageSync("userName", nickName);
        wx.setStorageSync("avatarUrl", infoRes.userInfo.avatarUrl);

        this.setData({ mbuId: id, userName: nickName });
        app.globalData.isLogin = true;
        this.triggerEvent("loginSuccess", {
          userName: nickName,
          avatarUrl: infoRes.userInfo.avatarUrl,
        });
        console.log("登录成功");
      } catch (err: any) {
        console.log("登录失败:", err);
        app.globalData.isLogin = false;
        wx.showToast({
          title: `登录失败：${err.message || err.errMsg}`,
          icon: "none",
        });
      } finally {
        wx.hideLoading();
      }
    },
  },
});
