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

// package-live/login/login.ts
const app = getApp<IAppOption>();
const defaultAvatarUrl =
  'https://oss.rsjk.org.cn/ruo-shan/image/425663f8-55eb-4aa9-b3dc-dcae6a963b71.png'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showPopup: false,
    avatarUrl: defaultAvatarUrl,
    nickname: '',
    userId: null,
    activityId: null,
    show: null,
    msg: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options: any) {
    if (options) {
      this.setData({
        userId: options.userId,
        activityId: options.activityId,
        show: options.show,
        msg: options.msg
      })
      if (options.show) {
        this.setData({
          avatarUrl: wx.getStorageSync('avatarUrl') || defaultAvatarUrl,
          nickname: wx.getStorageSync('userName') || '',
        })
      }
    }
  },


  goBack() {
    const pages = getCurrentPages();
    if (pages.length > 1) {
      wx.navigateBack({
        delta: 1,
      });
      return;
    }
    wx.switchTab({
      url: "/pages/tab-bar/medicine-box/index",
    });
  },
  async handOpen() {
    try {
      wx.showLoading({ title: "登录中" });
      const loginRes = await wxLogin();
      if (!loginRes.code) throw new Error(loginRes.errMsg);

      let loginResult: LoginRes;

      const reqData: Record<string, any> = {
        state: loginRes.code,
      };

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

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

      // 判断方式 1：仅判断是否存在（当前逻辑）
      if (loginResult.data.avatarUrl !== defaultAvatarUrl) {
        const storageData = {
          openId: loginResult.data.openId,
          userId: loginResult.data.mpUserId,
          mbuId: loginResult.data.id,
          unionId: loginResult.data.unionId,
          userName: loginResult.data.nickName,
          avatarUrl: loginResult.data.avatarUrl,
        };
        Object.entries(storageData).forEach(([key, value]) => {
          wx.setStorageSync(key, value);
        });

        app.globalData.isLogin = true;

        wx.showToast({
          title: "登录成功",
          duration: 2000,
        });
        // 跳转到直播页面
        const { userId, activityId } = this.data;
        wx.redirectTo({
          url: `/package-live/wxroom/index?userId=${userId}&activityId=${activityId}`
        })
      } else {
        wx.hideToast()
        this.setData({
          showPopup: true
        })
      }

    } catch (err: any) {
      app.globalData.isLogin = false;
      wx.showToast({
        title: `登录失败：${err.message || err.errMsg}`,
        icon: "none",
      });
    } finally {
      setTimeout(() => wx.hideToast(), 3000);
    }

  },
  closePopup() {
    this.setData({
      showPopup: false
    })
  },

  // 获取头像
  onChooseAvatar(e: any) {
    const { avatarUrl } = e.detail;
    this.setData({
      avatarUrl
    });
  },

  // 获取昵称（微信系统填入后失焦触发 bindblur）
  onNicknameInput(e: any) {
    const { value } = e.detail;
    this.setData({
      nickname: value
    });
  },


  // 提交登录
  async submitLogin() {
    const { avatarUrl, nickname } = this.data;
    if (!avatarUrl) {
      wx.showToast({
        title: '请选择头像',
        icon: 'none'
      });
      return;
    }
    if (!nickname) {
      wx.showToast({
        title: '请选择昵称',
        icon: 'none'
      });
      return;
    }
    try {
      wx.showLoading({ title: "登录中" });
      const loginRes = await wxLogin();
      if (!loginRes.code) throw new Error(loginRes.errMsg);

      let loginResult: LoginRes;

      const reqData: Record<string, any> = {
        state: loginRes.code,
        avatarUrl,
        nickName: nickname
      };

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

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

      const storageData = {
        openId: loginResult.data.openId,
        userId: loginResult.data.mpUserId,
        mbuId: loginResult.data.id,
        unionId: loginResult.data.unionId,
        userName: loginResult.data.nickName,
        avatarUrl: loginResult.data.avatarUrl,
      };

      Object.entries(storageData).forEach(([key, value]) => {
        wx.setStorageSync(key, value);
      });

      app.globalData.isLogin = true;

      wx.showToast({
        title: "登录成功",
        duration: 2000,
      });
      // 跳转到直播页面
      const { userId, activityId } = this.data;
      wx.redirectTo({
        url: `/package-live/wxroom/index?userId=${userId}&activityId=${activityId}`
      })

    } catch (err: any) {
      app.globalData.isLogin = false;
      wx.showToast({
        title: `登录失败：${err.message || err.errMsg}`,
        icon: "none",
      });
    } finally {
      setTimeout(() => wx.hideToast(), 3000);
    }

    // 关闭弹窗
    this.closePopup();
  },
  async refresh() {
    const { userId, activityId } = this.data;
    const params = userId ? { mpUserId: wx.getStorageSync("userId"), userId } : { mpUserId: wx.getStorageSync("userId") };
    const dataRes = await request<any>({
      options: {
        url: "/app/saas/refresh",
        method: "GET",
        data: params
      },
      isLoading: false,
    });
    if (dataRes.pass) {
      wx.redirectTo({
        url: `/package-live/wxroom/index?userId=${userId}&activityId=${activityId}`
      })
    }
  },
  /**
  * 生命周期函数--监听页面初次渲染完成
  */
  onReady() {

  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  }
})