import { BASE_URL } from "../../env";

Page({
  data: {
    webViewUrl: "",
    loading: true,
    backUrl: "",
    code: "",
    authCompleted: false, // 防止重复处理
  },

  onLoad(options: any) {
    if (options.back) {
      this.setData({ backUrl: decodeURIComponent(options.back) });
    }
    const code = options.code || "";
    this.setData({ code })

    setTimeout(() => {
      const authUrl = `${BASE_URL}/h5/oauth/auth-success.html?entryCode=${encodeURIComponent(code)}`
      this.setData({
        webViewUrl: authUrl,
        loading: true,
      });
    }, 50);
  },


  /** web-view 首次加载完成，隐藏骨架屏 */
  onWebViewLoad() {
    this.setData({ loading: false });
  },


  onMessage(e: any) {

    const dataList = e.detail?.data || [];
    console.log("onMessage===========》", dataList);
    if (dataList.length === 0) return;

    const data = dataList.reduce((acc: any, curr: any) => ({ ...acc, ...curr }), {});
console.log("onMessage", data);
    // 先存储缓存，再操作页面状态
    const fields: Record<string, string> = {
      openId: data.openId || '',
      unionId: data.unionId || '',
      appId: data.appId || '',
      userName: data.nickname || '微信用户',
      avatarUrl: data.avatar || '',
      code: data.code || '',
      userId: data.userId || '',
    };

    Object.entries(fields).forEach(([key, value]) => {
      if (value) {
        try {
          wx.setStorageSync(key, value);
        } catch (err: any) {
          console.log("缓存写入失败 key:", key, "error:", err?.message || err);
        }
      }
    });

    getApp<IAppOption>().globalData.isLogin = true;

    getApp<IAppOption>().globalData.store = {
      ...getApp<IAppOption>().globalData.store,
      ...fields,
    };

    try { this.setData({ authCompleted: true }); } catch (_) { }
  },

});
