<script>
import { mapMutations, mapGetters } from "vuex";
export default {
  data() {
    return {
      globalData: {},
      user: {},
      serverPart: {},
      openType: "",
    };
  },
  computed: {
    ...mapGetters({
      sessionUser: "user",
    }),
  },
  onLaunch: function (options) {
    console.log("onLaunch", options);
    this.setVisitChannels(options.scene);

    let _this = this;
    uni.getSystemInfo({
      success: (res) => {
        uni.setStorageSync("systemInfo", res);
        let ww = res.windowWidth;
        let hh = res.windowHeight;
        _this.globalData.ww = ww;
        _this.globalData.hh = hh;
      },
    });
    this.globalData.initReady = this.login().then(() => {});
    // this.globalData.recommendCode = "1";
    // this.globalData.recommendId = "2";

    this.globalData.recommendCode = options.query.recommendCode;
    this.globalData.recommendId = options.query.recommendId;
    const updateManager = uni.getUpdateManager();
    updateManager.onCheckForUpdate((res) => {
      // 请求完新版本信息的回调
      if (res.hasUpdate) {
        uni.showModal({
          title: "更新提示",
          content: "新版本已经准备好，是否重启应用？",
          success(res) {
            // if (res.confirm) { // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
            updateManager.applyUpdate();
            // }
          },
        });
      }
    });
  },
  onShow: function () {},
  onHide: function () {},
  onUnload: function () {
    this.globalData.recommendCode = null;
    this.globalData.recommendId = null;
  },
  methods: {
    ...mapMutations({
      setArea: "setHomeServer",
      setVisitChannels: "setVisitChannels",
    }),
    login() {
      let _this = this;
      return new Promise((resolve, reject) => {
        uni.login({
          success(res) {
            console.log("login", res);
            uni.setStorageSync("openId", res.code);
            _this.$api
              .getCoop({
                action_type: "WeChatLogin",
                code: res.code,
                // appId: "wx6a8173c6299c7a93",
              })
              .then(async (data) => {
                _this.$store.commit("setUser", data.Data);
                _this.user = data.Data;
                if (data.ResultCode === "100") {
                  try {
                    await _this.getMember(data.Data); // 确保 getMember 完成
                    resolve(data);
                  } catch (memberErr) {
                    reject(memberErr);
                  }
                } else {
                  // uni.showModal({
                  //   title: "温馨提示",
                  //   content: "请您授权登录后再操作。",
                  //   success(res) {
                  //     if (res.confirm) {
                  //       uni.redirectTo({ url: "/pages/register/index" });
                  //     }
                  //   },
                  // });
                  // reject(new Error("用户未授权"));
                }
              });
          },
          fail(err) {
            reject(err);
          },
        });
      });
    },

    getMember(user) {
      let _this = this;
      if (!user.WechatUserId) {
        return Promise.resolve(); // 如果条件不满足，直接返回一个已完成的 Promise
      }
      return _this.$api
        .getCoop({
          action_type: "GetMembershipInfo",
          WechatUserId: user.WechatUserId,
          // appId: "wx6a8173c6299c7a93",
        })
        .then(function (data) {
          if (data.ResultCode === "100") {
            let _data = data;
            _this.user.MEMBERSHIP_ID = _data.Data.MEMBERSHIP_ID || "";
            _this.user.MEMBERSHIP_NAME = _data.Data.MEMBERSHIP_NAME || "";
            _this.user.MEMBERSHIP_LEVEL_TEXT =
              _data.Data.MEMBERSHIP_LEVEL_TEXT || "";
            _this.user.COUPON_COUNT = _data.Data.COUPON_COUNT || "";
            _this.user.PENDORDER_COUNT = _data.Data.PENDORDER_COUNT || "";
            _this.user.RESERVATION_COUNT = _data.Data.RESERVATION_COUNT || "";
            _this.user.ACCOUNT_BALANCE = _data.Data.ACCOUNT_BALANCE || "";
            _this.user.ISPLUS = _data.Data.ISPLUS || "";
            _this.user.INDUSTRY_MEMBERSHIP_ID =
              _data.Data.INDUSTRY_MEMBERSHIP_ID || "";
            _this.user.MEMBERSHIP_TYPE = _data.Data.MEMBERSHIP_TYPE || "";
            _this.user.MEMBERSHIP_LEVEL = _data.Data.MEMBERSHIP_LEVEL || "";
            _this.user.InviteCode = _data.Data.InviteCode || "";
            _this.user.MEMBERSHIP_POINT = _data.Data.MEMBERSHIP_POINT || "";
            _this.user.MEMBERSHIP_MOBILEPHONE =
              _data.Data.MEMBERSHIP_MOBILEPHONE || "";
            // _this.setUser(user);
            _this.$store.commit("setUser", user);
            console.log("_this.globalData");

            
          } else {
            // _this.setUser({});
            _this.$store.commit("setUser", user);
          }
        })
        .catch((err) => {
          console.error("获取会员信息失败", err);
          throw err; // 确保错误向上传递
        });
    },
  },
  globalData: {
    initReady: null, // 用于页面等待初始化完成
  },
};
</script>

<style lang="scss">
/*每个页面公共css */
@import "@/uni_modules/uni-scss/index.scss";
/* #ifndef APP-NVUE */
@import "@/static/customicons.css";

// 设置整个项目的背景色
page {
  background-color: #f5f5f5;
}

/* #endif */
.example-info {
  font-size: 14px;
  color: #333;
  padding: 10px;
}
</style>
