<script lang="ts">
import {body} from "@/utils/https";
import {groupByKey} from "@/utils/common";

export default <any>{
  globalData: {
    token: "",
    user: {},
    isLogin: false,
    last: {},
    device: {},
    deviceId: null,
    manualLogout: false
  },
  onLaunch(options: any) {
    let device =  uni.getWindowInfo();
    let initGlobalData = {
      token: "",
      user: {},
      isLogin: false,
      last: {},
      device: {
        windowWidth:device.windowWidth,
        windowHeight:device.windowHeight,
        screenTop: device.screenTop,
        windowTop: device.windowTop,
      },
      deviceId: null,
      manualLogout: false
    }
    this.globalData = Object.assign({},  initGlobalData)

    body(`/dict/list`).then((res: any) => {
      if (res) {
        let dicts = res.map((k: any) => {
          let {code, name, value, color} = k;
          return {code, name, value, color}
        })
        let dictMap = groupByKey(dicts, "code");
        uni.setStorage({key: 'dict', data: dictMap})
      }
    })

    // 处理专属优惠活动扫码进入（wxacode.getUnlimited 的 scene 参数）
    // #ifdef MP-WEIXIN
    const scene = options?.query?.scene;
    if (scene) {
      // 延迟跳转，确保页面初始化完毕
      setTimeout(() => {
        uni.navigateTo({
          url: `/pages-user/wallet/promotion?promotionToken=${encodeURIComponent(scene)}`,
          fail: () => {
            // 如果 navigateTo 失败（可能在 tabBar 页面），尝试用 reLaunch
          }
        });
      }, 800);
    }
    // #endif

    // this.globalData.token = fetchToken();
  },
  onShow(options: any) {
    let device = uni.getWindowInfo();
    let backup = uni.getStorageSync('backup')
    // console.log("backup", backup)
    this.globalData = Object.assign({}, this.globalData, {
      device: {
        windowWidth: device.windowWidth,
        windowHeight: device.windowHeight,
        screenTop: device.screenTop,
        windowTop: device.windowTop,
      }
    }, backup)
    // 从 backup 恢复 token 到 storage，确保 fetchToken() 在冷启动时能读取到
    if (backup && backup.token) {
      uni.setStorageSync("token", backup.token)
    }
  },
  onHide() {
    //backup
    let backup = {...getApp<any>().globalData}
    uni.setStorageSync('backup', backup)
  },
  onPageNotFound() {
    uni.switchTab({
      url: "/pages/index/index",
    });
  },
};
</script>
<style lang="scss">
@import '@climblee/uv-ui/index.scss';
@import './custom.scss';

</style>
