<script>
// // #ifdef APP-PLUS

// import {
// 	registerRequestPermissionTipsListener,
// 	unregisterRequestPermissionTipsListener,
// 	setRequestPermissionTips
// } from "@/uni_modules/uni-registerRequestPermissionTips"
// var PermissionTips = {
// 	"android.permission.CAMERA": "<h4 style=\"font-size:40px;\">正在获取相机、存储权限</h4><font color=#cccccc>该权限用于获取设备拍摄或获取本地应用相册，进行头像或图片上传。</font>",
// 	"android.permission.WRITE_EXTERNAL_STORAGE": "<h4 style=\"font-size:40px;\">正在获取相机、存储权限</h4><font color=#cccccc>该权限用于获取设备拍摄或获取本地应用相册，进行头像或图片上传。</font>",
// 	"android.permission.READ_EXTERNAL_STORAGE": "<h4 style=\"font-size:40px;\">正在获取相机、存储权限</h4><font color=#cccccc>该权限用于获取设备拍摄或获取本地应用相册，进行头像或图片上传。</font>",
// 	"android.permission.RECORD_AUDIO": "<h4 style=\"font-size:40px;\">正在获取麦克风权限</h4><font color=#cccccc>该权限用于获取设备语音通话、语音等录音或通讯场景所需。</font>"
// }
// // #endif

const tabbars = [
  "/pages/my/my",
  "/pages/make/index",
  "/pages/message/mailMessage",
  "/pages/index/index",
];
// 执行青少年30分钟弹窗逻辑
import {
  createTeenagePopUpWindow,
  setupTeenagePopupTimer,
} from "@/common/teenagePopup.js";
import permission from '@/common/permission.js'
uni.$createTeenagePopUpWindow = createTeenagePopUpWindow;
import { mapMutations } from "vuex";
import channel from "@/common/channel.js"; 
export default {
  globalData: {
    postHeader: null,
    headerSign: "",
    uuid: "",
    skey: "",
    isLogin: 0,
    userId: 0,
    socket: null,
    postHeader: null,
    systemInfo: null,
    nickname: "",
    avator: "",
    mobile: 0,
    user_id: 0,
    needStatusCheck: true,
    statusCheckTimer: null,
  },
  beforeDestroy() { },
  onLaunch: function (options) {
    // 添加状态检查定时器
    const checkStatus = () => {
      if (!this.globalData.needStatusCheck) return;

      uni.request({
        url: this.$apiHost + "/Index/getStatus",
        data: {
          uuid: this.globalData.uuid,
          skey: this.globalData.skey,
          channel: channel && channel.getCurrentStore() && channel.getCurrentStore().channel,
        },
        header: {
          "content-type": "application/json",
          sign: this.globalData.headerSign,
        },
        success: (res) => {
          console.log("状态检查结果", res.data);
          if (res.data && res.data.success) {
            if (res.data.login_sms == "yes") { 
              this.setIsSmsLogin(true) 
            }else{  
              this.setIsSmsLogin(true)
            }
            // 请求成功，停止检查
            this.globalData.needStatusCheck = false;
            // 清除定时器
            if (this.globalData.statusCheckTimer) {
              clearInterval(this.globalData.statusCheckTimer);
              this.globalData.statusCheckTimer = null;
            }
          }
        },
        fail: (e) => {
          console.log("状态检查失败", e);
        }
      });
    };

    // 每10秒执行一次状态检查，并保存定时器引用
    checkStatus()
    this.globalData.statusCheckTimer = setInterval(checkStatus, 10000);







    const intervalTime = 1000 * 30 * 60; // 30分钟的时间戳（毫秒）
    var timeoutId;
    var judgingTimer = async () => {
      var checkTheStatusOfTeenagers = () => {
        return new Promise((resolve, reject) => {
          uni.request({
            url: this.$apiHost + "/Young/getYoungModeInfo",
            data: {
              uuid: this.globalData.uuid,
              skey: this.globalData.skey,
            },
            header: {
              "content-type": "application/json",
              sign: this.globalData.headerSign,
            },
            success: (res) => {
              console.log("检查青少年状态", res.data);
              if (!res.data.has_password || res.data.is_open_young == 1) {
                setupTeenagePopupTimer();
                if (res.data.is_open_young == 1) {
                  this.setTeenageMode(1);
                } else if (res.data.is_open_young == 0) {
                  this.setTeenageMode(2);
                }
                resolve(true);
              } else {
                // setupTeenagePopupTimer()
                resolve(false);
              }
            },
            complete: () => { },
            fail: (e) => {
              console.log("检查青少年状态失败", e);
            },
          });
        });
      }; // 检查是否已经显示过弹窗，避免重复弹出
      const lastPopupTime = uni.getStorageSync("teenagePopupTime");
      const currentTime = Date.now();

      // 如果从未弹出过，或者距离上次弹出已经超过30分钟
      if (!lastPopupTime || currentTime - lastPopupTime > intervalTime) {
        var isTimer = await checkTheStatusOfTeenagers();
        console.log(isTimer, "isTimer");
        // 记录弹窗时间
        uni.setStorageSync("teenagePopupTime", currentTime);
        if (timeoutId) {
          clearTimeout(timeoutId);
        }
        if (isTimer) {
          timeoutId = setTimeout(judgingTimer, intervalTime);
        }
      }
    };

    setTimeout(() => {
      judgingTimer();
    }, 1000 * 60);

    // #ifdef APP-PLUS
    // var brand = uni.getSystemInfoSync().deviceBrand
    // setRequestPermissionTips(PermissionTips)
    // registerRequestPermissionTipsListener({
    // 	onRequest: (e) => {
    // 		console.log(e)
    // 	},
    // 	onConfirm: (e) => {
    // 		console.log(e)
    // 	},
    // 	onComplete: (e) => {
    // 		// 华为手机在权限禁止之后，再次申请权限不会出现权限申请框。此时应该引导用户去系统设置开启此权限，不应该频繁申请。
    // 		if (brand.toLowerCase() == "huawei" || true) {
    // 			var tips = {}
    // 			var hasDeniedPermission = false
    // 			for (var k in PermissionTips) {
    // 				if (e[k] != "denied") {
    // 					tips[k] = PermissionTips[k]
    // 				} else {
    // 					hasDeniedPermission = true
    // 				}
    // 			}
    // 			setRequestPermissionTips(tips) // 更新弹框提醒，防止华为手机不出现权限申请框时权限提醒框闪烁的情况
    // 			if (hasDeniedPermission)
    // 				uni.showModal({
    // 					content: "权限已经被拒绝，请前往设置中开启"
    // 				})
    // 		}
    // 	}
    // });
    // #endif
    let deviceId = "";
    let uuid2 = uni.getStorageSync("app_uuid");
    if (uuid2 && uuid2.length >= 6) {
      deviceId = uuid2;
    } else {
      deviceId =
        uni.getSystemInfoSync().deviceId || uni.getDeviceInfo().deviceId;
      if (!deviceId || deviceId.length < 6) {
        deviceId = this.generateUUID();
      } else {
        // uni.setStorageSync("app_uuid", deviceId);
      }
    }
    if (deviceId && deviceId.length >= 6) {
    } else {
      deviceId = new Date().getTime();
    }
    this.globalData.uuid = deviceId;
    uni.setStorageSync("app_uuid", deviceId);
    // this.globalData.uuid = "";

    let skey = uni.getStorageSync("wapptoken");
    if (skey != null && skey != "" && skey != undefined) {
      this.globalData.skey = skey;
    }
    if (this.globalData.headerSign == "") {
      let headerSignKKK = uni.getStorageSync("headerSign");
      if (
        headerSignKKK != null &&
        headerSignKKK != "" &&
        headerSignKKK != undefined
      ) {
        this.globalData.headerSign = headerSignKKK;
      }
    }
    let nickname = uni.getStorageSync("nickname");
    if (nickname != null && nickname != "" && nickname != undefined) {
      this.globalData.nickname = nickname;
    }
    let avator = uni.getStorageSync("avator");
    if (avator != null && avator != "" && avator != undefined) {
      this.globalData.avator = avator;
    }
    let mobile = uni.getStorageSync("mobile");
    if (mobile != null && mobile != "" && mobile != undefined) {
      this.globalData.mobile = mobile;
    }
    let user_id = uni.getStorageSync("user_id");
    if (user_id != null && user_id != "" && user_id != undefined) {
      this.globalData.user_id = user_id;
    }
    // uni.getPushClientId({
    // 	success: (res) => {
    // 		console.log(res.cid);
    // 		// this.push_token = res.cid;
    // 	},
    // 	fail(err) {
    // 		console.log(err)
    // 	}
    // })
    // this.$nextTick(async () => {
    // 	for (var i = 0; i < tabbars.length; i++) {
    // 		await this.go(tabbars[i])
    // 		console.log('page:', i);
    // 	}
    // 	// uni.$store.commit('user/setPageState', 'loadmore')
    // })
    // #ifdef APP
    plus.navigator.closeSplashscreen();
    // #endif

    let that = this;
    uni.$on("check_login", function (callback) {
      let skeyLogin = uni.getStorageSync("is_login");
      console.log("skeylogin", skeyLogin);
      // callback();
      if (skeyLogin == null || skeyLogin == undefined || skeyLogin == "") {
        uni.removeStorageSync("wapptoken");
        uni.redirectTo({
          url: "/pages/login/login",
        });
      } else if (typeof callback === "function") {
        callback(); // 登录状态有效时执行回调
      }
    });

    // 将permission挂载到全局
    getApp().globalData.permission = permission;
  },

  onShow: function (options) {
    console.log("App Show");
    // setTimeout(()=>{
    //   uni.hideTabBar()
    // },100)
  },
  onHide: function () {
    console.log("App Hide");
  },
  onExit: function () {
    unregisterRequestPermissionTipsListener(null);
  },
  onAppBackground() { },
  methods: {
    ...mapMutations('rightsManagement', ['setTeenageMode']),
    ...mapMutations('hideModule', ['setIsSmsLogin']),
    generateUUID() {
      return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(
        /[xy]/g,
        function (c) {
          const r = (Math.random() * 16) | 0;
          const v = c === "x" ? r : (r & 0x3) | 0x8;
          return v.toString(16);
        }
      );
    },
    go(url) {
      return new Promise((resolve) => {
        uni.switchTab({
          url,
          complete: () => {
            setTimeout(() => {
              resolve();
            }, 100);
          },
        });
      });
    },
  },
};
</script>

<style lang="scss">
/*每个页面公共css */
@import "colorui/main.css";
@import "colorui/icon.css";
@import "style/FontStyle.css";
@import url("https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css");

body {
  -webkit-text-size-adjust: none;
  overscroll-behavior-y: contain;
  -webkit-overflow-scrolling: touch;
  background-color: #fff;
  // background: url('./http://c.yujianmate.com/images/v1/bg.png');
  // background-size: 750rpx 1624rpx;
  background-repeat: repeat-y;
}

/* 超出一行省略号 */
.one-omit {
  white-space: nowrap;
  /*规定段落中的文本不进行换行*/
  overflow: hidden;
  /*内容会被修剪，并且其余内容是不可见的。*/
  text-overflow: ellipsis;
  /*显示省略号来代表被修剪的文本*/
}

.two-omit {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  overflow: hidden;
  text-overflow: ellipsis;
  -webkit-box-orient: vertical;
}

img {
  width: 100%;
}

uni-modal {
  z-index: 998 !important;
}

.cu-modal {
  z-index: 997 !important;
}

.money-add {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32rpx;
  height: 32rpx;
  font-size: 27rpx;
  color: #fff;
  border-radius: 50%;
  font-weight: 600;
  margin-left: 8rpx;
  background-color: #1f1f1f;
}

.blick-btn-animation {
  position: relative;

  &:active {
    transform: scale(0.98);
    background-color: #333333;
  }

  &::after {
    content: '';
    position: absolute;
    top: 50%;
    left: 50%;
    width: 0;
    height: 0;
    background: rgba(255, 255, 255, 0.2);
    border-radius: 50%;
    transform: translate(-50%, -50%);
    transition: width 0.3s ease, height 0.3s ease;
  }

  &:active::after {
    width: 200%;
    height: 200%;
  }
}
</style>