<script>
import { mapMutations, mapGetters } from "vuex";

let appReadyResolve;
const appReady = new Promise((resolve) => {
  appReadyResolve = resolve;
});
export default {
  data() {
    return {
      globalData: {},
      user: {},
      serverPart: {},
      openType: "",
    };
  },
  computed: {
    ...mapGetters({
      sessionUser: "user",
    }),
  },
  methods: {
    ...mapMutations({ setArea: "setHomeServer" }),
    getLocalServer() {
      // 根据定位获取周边服务区
      let _this = this;
      uni.choosePoi({
        // type: 'wgs84',
        success: function (res) {
          console.log(res);
          let latitude = res.latitude;
          let longitude = res.longitude;
          _this.$api
            .getCoop({
              action_type: "getServerPartByLocation",
              action_data: latitude,
              action_record: longitude,
              distance: 150,
              type: 1000,
            })
            .then(function (data) {
              if (data.ResultCode === "100") {
                let _data = data.Data.List;

                _this.setArea(_data[0]);
              }
            });
        },
        fail(res) {
          _this.openSetting = true;
        },
      });
    },
    login() {
      let _this = this;
      return new Promise((resolve, reject) => {
        uni.login({
          success(res) {
            console.log("uni.login", res);
            _this.$api
              .getCoop({
                action_type: "WeChatLogin",
                code: res.code,
              })
              .then(async (data) => {
                console.log("datalogin", 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,
        })
        .then(function (data) {
          if (data.ResultCode === "100") {
            let _data = data;
            console.log("_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);
          } else {
            // _this.setUser({});
            _this.$store.commit("setUser", user);
          }
        })
        .catch((err) => {
          console.error("获取会员信息失败", err);
          throw err; // 确保错误向上传递
        });
    },
    appLogin() {
      let _this = this;
      // 拿到缓存里面的user
      let sessionUser = this.sessionUser;
      console.log("sessionUser", sessionUser);
      if (sessionUser.MEMBERSHIP_ID) {
        this.$api
          .getCoop({
            action_type: "GetMembershipInfo",
            WechatUserId: sessionUser.MEMBERSHIP_ID || sessionUser.MemberShipID,
            MembershipId: sessionUser.MEMBERSHIP_ID || sessionUser.MemberShipID,
            Membership_Id:
              sessionUser.MEMBERSHIP_ID || sessionUser.MemberShipID,
          })
          .then(function (result) {
            _this.$store.commit("setUser", result.Data);
            uni.setStorageSync("userInfo", result.Data);
          });
      } else {
        // uni.showModal({
        //   title: "温馨提示",
        //   content: "请您登录后再操作。",
        //   success(res) {
        //     if (res.confirm) {
        //       uni.redirectTo({ url: "/pages/login/index" });
        //     }
        //   },
        // });
      }
    },
  },
  globalData: {
    initReady: null, // 用于页面等待初始化完成
  },
  onLaunch() {
    // uni.setStorageSync("seatInfo", null);
    // 这里是拿到 用户的手机信息
    let type = uni.getSystemInfoSync();
    // 拿到这是第几次 进入到小程序 或者 app  (用于权限的询问)
    let times = uni.getStorageSync("howTimes");
    if (times) {
      // 如果有值了 就说明是2
      uni.setStorageSync("howTimes", 2);
    } else {
      // 没有值 说明是第一次进来 给它存一个 1
      uni.setStorageSync("howTimes", 1);
    }

    if (type.platform === "android" && type.uniPlatform === "app") {
      let res = plus.navigator.getUserAgent();
      plus.navigator.setUserAgent(res + "wanmeiyizhan_APP");
      console.log("安卓");
      // 安卓
      uni.setStorageSync("loginType", "android");
      this.appLogin();
      // 等方法执行完再执行首页的
      // this.globalData.initReady = this.appLogin().then(() => {
      //   //   console.log("App 初始化完成");
      // });
    } else if (type.platform === "ios" && type.uniPlatform === "app") {
      console.log("ios");
      // 苹果
      uni.setStorageSync("loginType", "ios");
      this.appLogin();
    } else if (type.uniPlatform === "mp-weixin") {
      console.log("小程序");
      // 如果是小程序进来的话  开发版 体验版 正式版 判断一下
      // 且存个min  统一一下
      uni.setStorageSync("loginType", "min");

      // this.clearShopcart() // 清除上次留下来的购物车缓存
      this.setArea({});
      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(() => {
        //   console.log("App 初始化完成");
      });
      // _this.login(); // 获取用户数据

      const updateManager = uni.getUpdateManager();
      updateManager.onCheckForUpdate((res) => {
        // 请求完新版本信息的回调
        console.log("hasUpdate", res.hasUpdate);
        if (res.hasUpdate) {
          uni.showModal({
            title: "更新提示",
            content: "新版本已经准备好，是否重启应用？",
            success(res) {
              // if (res.confirm) { // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
              updateManager.applyUpdate();
              // }
            },
          });
        }
      });
    }
  },
  onHide() { },
};
</script>

<style>
/*每个页面公共css */
.vue-ref {
  z-index: 999 !important;
}
</style>
