"use strict";
const common_vendor = require("../../common/vendor.js");
const api_user = require("../../api/user.js");
const common_assets = require("../../common/assets.js");
new Proxy({}, {
  get(_, key) {
    throw new Error(`Module "util" has been externalized for browser compatibility. Cannot access "util.${key}" in client code.  See https://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`);
  }
});
const _sfc_main = {
  data() {
    return {
      isLogin: false,
      userInfo: {
        username: "",
        userId: "",
        avatar: ""
      },
      menuItems: [
        { title: "个人资料", icon: "icon-user", action: "profile" },
        // { title: '我的订单', icon: 'icon-order', action: 'orders' },
        // { title: '我的收藏', icon: 'icon-star', action: 'favorites' },
        { title: "设置", icon: "icon-settings", action: "settings" },
        { title: "帮助中心", icon: "icon-help", action: "help" }
      ],
      showAuthModal: false,
      wxLoginCode: ""
      // 存储微信登录code
    };
  },
  onShow() {
    this.checkLoginStatus();
  },
  methods: {
    // 检查登录状态
    checkLoginStatus() {
      try {
        const token = common_vendor.index.getStorageSync("token");
        const userInfoStr = common_vendor.index.getStorageSync("userInfo");
        if (token && userInfoStr) {
          const userInfo = JSON.parse(userInfoStr);
          const loginTime = userInfo.loginTime || 0;
          const currentTime = (/* @__PURE__ */ new Date()).getTime();
          const loginExpireTime = 7 * 24 * 60 * 60 * 1e3;
          if (currentTime - loginTime > loginExpireTime) {
            console.log("登录已过期，需要重新登录");
            this.handleLogout(false);
            return;
          }
          this.isLogin = true;
          this.userInfo = userInfo;
          this.fetchUserDetail();
        } else {
          this.isLogin = false;
          this.userInfo = {
            username: "",
            userId: "",
            avatar: "",
            phone: ""
          };
        }
      } catch (e) {
        console.error("获取登录状态失败", e);
        this.isLogin = false;
      }
    },
    // 前往登录页
    goLogin() {
      common_vendor.index.showActionSheet({
        itemList: ["账号密码登录", "微信登录"],
        success: (res) => {
          if (res.tapIndex === 0) {
            common_vendor.index.navigateTo({
              url: "/pages/login/login"
            });
          } else if (res.tapIndex === 1) {
            this.wxLogin();
          }
        }
      });
    },
    // 微信登录
    wxLogin() {
      this.getWxLoginCode();
    },
    // 获取微信登录 code
    getWxLoginCode() {
      common_vendor.index.showLoading({ title: "登录中..." });
      common_vendor.index.login({
        provider: "weixin",
        success: (loginRes) => {
          console.log("获取微信登录code成功:", loginRes.code);
          this.wxLoginCode = loginRes.code;
          common_vendor.index.hideLoading();
          this.showAuthModal = true;
        },
        fail: (err) => {
          common_vendor.index.hideLoading();
          console.error("获取微信登录code失败:", err);
          common_vendor.index.showToast({
            title: "微信登录失败",
            icon: "none"
          });
        }
      });
    },
    // 用户点击授权按钮时调用
    getUserProfile() {
      common_vendor.wx$1.getUserProfile({
        desc: "用于完善用户资料",
        success: (profileRes) => {
          console.log("获取用户信息成功:", profileRes);
          const loginParams = {
            code: this.wxLoginCode,
            userInfo: profileRes.userInfo,
            signature: profileRes.signature,
            rawData: profileRes.rawData,
            encryptedData: profileRes.encryptedData,
            iv: profileRes.iv
          };
          this.showAuthModal = false;
          this.wxLoginRequest(loginParams);
        },
        fail: (err) => {
          console.error("获取用户信息失败:", err);
          this.showAuthModal = false;
          this.wxLoginRequest({
            code: this.wxLoginCode,
            userInfo: {
              nickName: "微信用户",
              avatarUrl: "",
              gender: 0,
              province: "",
              city: "",
              country: ""
            }
          });
        }
      });
    },
    // 取消授权
    cancelAuth() {
      this.showAuthModal = false;
      this.wxLoginRequest({
        code: this.wxLoginCode,
        userInfo: {
          nickName: "微信用户",
          avatarUrl: "",
          gender: 0,
          province: "",
          city: "",
          country: ""
        }
      });
    },
    // 头像选择回调
    onChooseAvatar(e) {
      const { avatarUrl } = e.detail;
      console.log("用户选择的头像:", avatarUrl);
    },
    // 发送微信登录请求并处理结果
    async wxLoginRequest(loginParams) {
      try {
        common_vendor.index.showLoading({ title: "登录中..." });
        console.log("发送登录请求，参数:", loginParams);
        const data = await api_user.wxLogin(loginParams);
        console.log("登录成功，返回数据:", data);
        const userData = this.buildUserData(data, loginParams);
        this.saveLoginState(data, userData);
        if (userData.userId) {
          this.fetchUserDetail();
        } else {
          console.log("无法获取用户ID，跳过获取详细信息");
        }
        if (!userData.phone) {
          console.log("用户未绑定手机号，可以提示用户绑定");
        }
      } catch (error) {
        this.handleLoginError(error, loginParams);
      }
    },
    /**
     * 构建用户数据对象
     * @param {Object} data - 后端返回的数据
     * @param {Object} loginParams - 登录参数
     * @returns {Object} - 构建的用户数据
     */
    buildUserData(data, loginParams) {
      console.log("构建用户数据，服务器返回:", data);
      let userData = {
        // 用户基本信息 - 优先使用服务器返回的数据
        username: data.username || data.nickName || (loginParams.userInfo ? loginParams.userInfo.nickName : "微信用户"),
        // 用户ID可能在不同字段
        userId: data.userId || data.user_id || data.id || data.openid || "",
        // 头像可能在不同字段
        avatar: data.avatar || data.avatarUrl || (loginParams.userInfo ? loginParams.userInfo.avatarUrl : "/static/avatar.png"),
        // 用户详细信息
        phone: data.phone || data.mobile || "",
        gender: data.gender || (loginParams.userInfo ? loginParams.userInfo.gender : 0),
        // 微信相关信息
        openid: data.openid || "",
        unionid: data.unionid || "",
        session_key: data.session_key || "",
        // 是否新用户
        is_new_user: data.is_new_user || false,
        // 登录时间
        loginTime: (/* @__PURE__ */ new Date()).getTime()
      };
      console.log("构建的用户数据:", userData);
      return userData;
    },
    /**
     * 保存登录状态和用户信息
     * @param {Object} data - 后端返回的数据
     * @param {Object} userData - 构建的用户数据
     */
    saveLoginState(data, userData) {
      const token = data.token || data.session_key || "";
      if (token) {
        common_vendor.index.setStorageSync("token", token);
        console.log("Token已保存:", token);
      }
      common_vendor.index.setStorageSync("userInfo", JSON.stringify(userData));
      console.log("用户信息已保存");
      this.isLogin = true;
      this.userInfo = userData;
      common_vendor.index.hideLoading();
      common_vendor.index.showToast({
        title: "登录成功",
        icon: "success"
      });
    },
    /**
     * 处理登录错误
     * @param {Error} error - 错误对象
     * @param {Object} loginParams - 登录参数
     */
    handleLoginError(error, loginParams) {
      common_vendor.index.hideLoading();
      if (error.message && (error.message.includes("code无效") || error.message.includes("已过期") || error.message.includes("已被使用") || error.status === 999)) {
        console.error("微信登录code无效，重新获取:", error);
        common_vendor.index.showToast({
          title: "code已过期，请重试",
          icon: "none",
          duration: 2e3
        });
        setTimeout(() => {
          this.getWxLoginCode();
        }, 1e3);
        return;
      }
      if (error.code === 10001) {
        common_vendor.index.navigateTo({
          url: "/pages/bind/bind?code=" + (loginParams.code || "")
        });
      } else if (error.message && error.message.includes("CSRF")) {
        console.error("CSRF验证失败:", error);
        common_vendor.index.showToast({
          title: "CSRF验证失败，请刷新页面重试",
          icon: "none",
          duration: 2e3
        });
        setTimeout(() => this.refreshCSRFToken(), 2e3);
      } else {
        console.error("微信登录失败:", error);
        common_vendor.index.showToast({
          title: error.message || "登录失败",
          icon: "none"
        });
      }
    },
    /**
     * 获取用户详细信息
     * 步骤6: 获取并更新用户详细信息
     */
    async fetchUserDetail() {
      try {
        if (!this.isLogin)
          return;
        const userId = this.userInfo.userId;
        const userDetail = await api_user.getUserInfo(userId);
        console.log("获取用户详细信息成功:", userDetail);
        if (userDetail) {
          this.updateUserInfo(userDetail);
        }
      } catch (error) {
        console.error("获取用户详细信息失败:", error);
      }
    },
    /**
     * 更新用户信息
     * @param {Object} userDetail - 用户详细信息
     */
    updateUserInfo(userDetail) {
      const updatedUserInfo = {
        ...this.userInfo,
        // 更新基本信息
        username: userDetail.username || userDetail.nickName || this.userInfo.username,
        avatar: userDetail.avatar || userDetail.avatarUrl || this.userInfo.avatar,
        phone: userDetail.phone || userDetail.mobile || this.userInfo.phone,
        // 更新详细信息
        email: userDetail.email || "",
        address: userDetail.address || "",
        birthday: userDetail.birthday || "",
        // 其他字段
        ...userDetail
      };
      this.userInfo = updatedUserInfo;
      common_vendor.index.setStorageSync("userInfo", JSON.stringify(updatedUserInfo));
      console.log("用户详细信息已更新");
    },
    /**
     * 获取用户手机号
     * @param {Object} e - 事件对象
     */
    async getPhoneNumber(e) {
      console.log("获取手机号事件:", e);
      if (e.detail.errMsg !== "getPhoneNumber:ok") {
        console.error("用户拒绝授权手机号");
        common_vendor.index.showToast({
          title: "获取手机号失败",
          icon: "none"
        });
        return;
      }
      try {
        common_vendor.index.showLoading({ title: "获取手机号中..." });
        const loginResult = await new Promise((resolve, reject) => {
          common_vendor.index.login({
            provider: "weixin",
            success: resolve,
            fail: reject
          });
        });
        const params = {
          code: loginResult.code,
          encryptedData: e.detail.encryptedData,
          iv: e.detail.iv,
          openid: JSON.parse(common_vendor.index.getStorageSync("userInfo")).openid
        };
        console.log("获取手机号请求参数:", JSON.parse(common_vendor.index.getStorageSync("userInfo")).openid);
        const phoneData = await api_user.getUserPhoneNumber(params);
        console.log("获取手机号成功:", phoneData);
        if (phoneData && phoneData.phoneNumber) {
          const updatedUserInfo = {
            ...this.userInfo,
            phone: phoneData.phoneNumber
          };
          this.userInfo = updatedUserInfo;
          common_vendor.index.setStorageSync("userInfo", JSON.stringify(updatedUserInfo));
          common_vendor.index.showToast({
            title: "手机号绑定成功",
            icon: "success"
          });
        } else {
          throw new Error("未能获取到手机号");
        }
      } catch (error) {
        console.error("获取手机号失败:", error);
        common_vendor.index.showToast({
          title: error.message || "获取手机号失败",
          icon: "none"
        });
      } finally {
        common_vendor.index.hideLoading();
      }
    },
    // 添加刷新 CSRF token 的方法
    refreshCSRFToken() {
      common_vendor.index.request({
        url: "your-api-endpoint/csrf-token",
        // 替换为获取 CSRF token 的 API
        method: "GET",
        success: (res) => {
          if (res.data && res.data.csrfToken) {
            common_vendor.index.setStorageSync("csrfToken", res.data.csrfToken);
            console.log("CSRF token 已刷新");
          }
        },
        fail: (err) => {
          console.error("获取 CSRF token 失败", err);
        }
      });
    },
    handleMenuClick(item) {
      const needLogin = ["profile", "orders", "favorites"];
      if (needLogin.includes(item.action) && !this.isLogin) {
        common_vendor.index.showToast({
          title: "请先登录",
          icon: "none"
        });
        setTimeout(() => {
          this.wxLogin();
        }, 1500);
        return;
      }
      switch (item.action) {
        case "profile":
          common_vendor.index.navigateTo({ url: "/pages/profile/profile" });
          break;
        case "orders":
          common_vendor.index.navigateTo({ url: "/pages/orders/orders" });
          break;
        case "favorites":
          common_vendor.index.navigateTo({ url: "/pages/favorites/favorites" });
          break;
        case "settings":
          common_vendor.index.navigateTo({ url: "/pages/settings/settings" });
          break;
        case "help":
          common_vendor.index.navigateTo({ url: "/pages/help/help" });
          break;
        default:
          common_vendor.index.showToast({
            title: `点击了${item.title}`,
            icon: "none"
          });
      }
    },
    // 处理退出登录 - 增强版
    handleLogout(showConfirm = true) {
      const doLogout = () => {
        api_user.logout().then(() => {
          try {
            common_vendor.index.removeStorageSync("token");
            common_vendor.index.removeStorageSync("userInfo");
            this.isLogin = false;
            this.userInfo = {
              username: "",
              userId: "",
              avatar: "",
              phone: ""
            };
            if (showConfirm) {
              common_vendor.index.showToast({
                title: "已退出登录",
                icon: "success"
              });
            }
          } catch (e) {
            console.error("退出登录失败", e);
            if (showConfirm) {
              common_vendor.index.showToast({
                title: "退出登录失败",
                icon: "none"
              });
            }
          }
        }).catch((err) => {
          console.error("退出登录请求失败", err);
          common_vendor.index.removeStorageSync("token");
          common_vendor.index.removeStorageSync("userInfo");
          this.isLogin = false;
          if (showConfirm) {
            common_vendor.index.showToast({
              title: err.message || "退出登录失败",
              icon: "none"
            });
          }
        });
      };
      if (showConfirm) {
        common_vendor.index.showModal({
          title: "提示",
          content: "确定要退出登录吗？",
          success: (res) => {
            if (res.confirm) {
              doLogout();
            }
          }
        });
      } else {
        doLogout();
      }
    },
    // 格式化手机号，例如：188****8888
    formatPhone(phone) {
      if (!phone || phone.length < 11)
        return phone;
      return phone.substring(0, 3) + "****" + phone.substring(7);
    }
  }
};
function _sfc_render(_ctx, _cache, $props, $setup, $data, $options) {
  return common_vendor.e({
    a: $data.isLogin
  }, $data.isLogin ? common_vendor.e({
    b: $data.userInfo.avatar || "/static/avatar.png",
    c: common_vendor.t($data.userInfo.username),
    d: $data.userInfo.phone
  }, $data.userInfo.phone ? {
    e: common_vendor.t($options.formatPhone($data.userInfo.phone))
  } : {}) : {
    f: common_assets._imports_0,
    g: common_vendor.o((...args) => $options.wxLogin && $options.wxLogin(...args))
  }, {
    h: common_vendor.f($data.menuItems, (item, index, i0) => {
      return {
        a: common_vendor.n(item.icon),
        b: common_vendor.t(item.title),
        c: index,
        d: common_vendor.o(($event) => $options.handleMenuClick(item), index)
      };
    }),
    i: $data.isLogin
  }, $data.isLogin ? {
    j: common_vendor.o((...args) => $options.handleLogout && $options.handleLogout(...args))
  } : {}, {
    k: $data.showAuthModal
  }, $data.showAuthModal ? {
    l: common_vendor.o((...args) => $options.getUserProfile && $options.getUserProfile(...args)),
    m: common_vendor.o((...args) => $options.cancelAuth && $options.cancelAuth(...args))
  } : {}, {
    n: $data.isLogin && !$data.userInfo.phone
  }, $data.isLogin && !$data.userInfo.phone ? {
    o: common_vendor.o((...args) => $options.getPhoneNumber && $options.getPhoneNumber(...args))
  } : {});
}
const MiniProgramPage = /* @__PURE__ */ common_vendor._export_sfc(_sfc_main, [["render", _sfc_render]]);
wx.createPage(MiniProgramPage);
