// pages/live/h5Room/index.ts
import { appId } from "../../../env";
Page({
  /**
   * 页面的初始数据
   */
  data: {
    webViewUrl: "",
    webViewHeight: 0,
    statusBarHeight: 0,
    navBarHeight: 0,
  },
  async onLoad(options: any) {
    const windowInfo = (wx as any).getWindowInfo
      ? (wx as any).getWindowInfo()
      : wx.getSystemInfoSync();
    const menuButtonRect = wx.getMenuButtonBoundingClientRect();
    const statusBarHeight =
      windowInfo.safeArea?.top || windowInfo.statusBarHeight || 0;
    const navBarHeight = menuButtonRect?.top
      ? menuButtonRect.bottom + menuButtonRect.top - statusBarHeight
      : statusBarHeight + 44;
    const webViewHeight = Math.max(
      (windowInfo.windowHeight || 0) - navBarHeight,
      0,
    );

    this.setData({
      statusBarHeight,
      navBarHeight,
      webViewHeight,
    });
    const app = getApp<IAppOption>();
    const bool = await app.login("room");
    if (!bool) return;
    try {
      // const baseUrl = "http://localhost:5173/pages/room";
      const baseUrl = "https://live.byteoc.com/1859506470730939/1425285?platform=mobile";

      const openId = wx.getStorageSync("openId");
      const roomId = options?.roomId;
      const params: Record<string, string> = {};
      if (openId) params.openId = openId;
      if (appId) params.appId = appId;
      if (roomId) params.roomId = roomId;

      if (options?.extraParams) {
        try {
          const extraParams = JSON.parse(
            decodeURIComponent(options.extraParams),
          );
          Object.entries(extraParams).forEach(([key, value]) => {
            params[key] = String(value);
          });
        } catch (e) {
          console.warn("Failed to parse extra parameters");
        }
      }
      const queryString = Object.entries(params)
        .map(
          ([key, value]) =>
            `${encodeURIComponent(key)}=${encodeURIComponent(value)}`,
        )
        .join("&");
      const finalUrl = `${baseUrl}?${queryString}`;
      this.setData({
        webViewUrl: finalUrl,
      });
    } catch (error) {
      console.error("Error generating URL:", error);
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
});
