<script>
// #ifdef APP-PLUS
import APPUpdate, { getCurrentNo } from "@/config/appUpdate";
// #endif
import { mapState, mapActions } from "vuex";
import { webSocketManager } from "@/utils/socket.js";
import { GetShopBaseInfo } from "@/api/shop.js";
export default {
  data() {
    return {
    version: "",
	  lastPlayTime: 0, // 记录最后一次播放语音的时间戳
	  playInterval: 20000 // 20秒的间隔限制
    };
  },
  onLaunch: function () {
    uni.setStorageSync("isImSound", true);

    this.globalData.isAppActive = true;
    // #ifdef APP-PLUS
    getCurrentNo((res) => {
      this.version = res.version;
    });

    const hasAgreed = uni.getStorageSync("isNeedAgreementDialog");
    if (hasAgreed) {
      this.onAPPUpdate();
    }
    this.initAppOrderPush();
    // #endif
  },
  computed: {
    ...mapState("user", ["uid", "userInfo"]),
  },
onShow: function () {
  this.globalData.isAppActive = true;
  const globalConnName = 'globalSocket'; 
  if (this.userInfo && Object.keys(this.userInfo).length > 0) {
    // 检查指定的全局连接是否已连接，未连接则重建
    if (!webSocketManager.isConnected(globalConnName)) {
      this.connectSocket(this.userInfo); // 这里的connectSocket应该会创建名为globalConnName的连接
    }
  } else {
    // 用户未登录时关闭所有全局连接
    webSocketManager.closeAllGlobalConnections();
  }
  // 重新注册推送监听
  this.initPushListener();
},


  onHide: function () {
    this.globalData.isAppActive = false;
    // webSocketManager.closeAllGlobalConnections();
  },
  globalData: {
    isAppActive: false,
  },
  onBackPress: function () {},
  methods: {
    ...mapActions("user", ["connectSocket"]),
    onAPPUpdate() {
      APPUpdate(this.version);
    },
    getCidAsync() {
      return new Promise(function (resolve, reject) {
        // 获取客户端推送信息
        plus.push.getClientInfoAsync(
          function (clientInfo) {
            // 获取CID
            var cid = clientInfo.clientid;
            // 调用resolve方法返回CID
            resolve(cid);
          },
          function (error) {
            // 获取CID失败，调用reject方法返回错误信息
            reject(error);
          }
        );
      });
    },
      // 新增推送监听初始化方法
  initPushListener() {
    const _self = this;
    // 先移除旧监听再添加新监听，避免重复注册
    uni.offPushMessage();
    uni.onPushMessage(async (res) => {
      console.log("收到推送消息：", res);
      
      // 检查用户登录状态，未登录直接返回
      if (!_self.userInfo || Object.keys(_self.userInfo).length === 0) {
        console.log("用户未登录，忽略推送");
        return;
      }

      if (res.data) {
        if (!_self.globalData.isAppActive) {
          if (res.type == "click") {
            _self.handlePushClick(res.data.payload);
          } else {
            let shopRes = await GetShopBaseInfo();
            if (shopRes.data.ringtone_is_enable === 1) {
              _self.handlePushSound(res.data);
              uni.setStorageSync("pendingPushData", res.data);
              uni.createPushMessage(res.data);
            }
          }
        } else {
          console.log("应用已打开，直接处理消息");
          _self.$store.dispatch("push/setPush", res.data);
        }
      }
    });
  },
    async initAppOrderPush() {
      uni.getPushClientId({
        success: (res) => {
          var push_clientid = res.cid;
          console.log("客户端推送标识cid:", push_clientid);
        },
        fail(err) {
          console.log(err);
        },
      });

      uni.onPushMessage(async (res) => {
        console.log("收到推送消息：", res); //监听推送消息

        if (res.data) {
          const app = getApp();
          if (!app.globalData.isAppActive) {
            //监听系统通知栏消息点击事件
            if (res.type == "click") {
              this.handlePushClick(res.data.payload);
            } else {
              let res = await GetShopBaseInfo();
              if (res.data.ringtone_is_enable === 1) {
                this.handlePushSound(res.data);
                uni.setStorageSync("pendingPushData", res.data);
                // 创建通知
                uni.createPushMessage(res.data);
              }
            }
          } else {
            console.log("应用已打开，直接处理消息");
            // 可以在这里直接更新 UI
            this.$store.dispatch("push/setPush", res.data);
          }
        }
      });

      const _self = this;
    },
    // 新增方法 - 处理通知栏点击
    handlePushClick(payload) {
      console.log("处理通知栏点击:", payload);

      console.log(payload.category);

      // 根据payload内容跳转页面
      switch (payload.category) {
        case "mchOnLineOrderList":
          uni.setStorageSync("currentTab2", 0);
          uni.switchTab({
            url: "/pages/order/order",
          });

          break;
        case "mchAbnormalOrderList":
          uni.setStorageSync("currentTab2", 1);
          uni.switchTab({
            url: "/pages/order/order",
          });
          break;
        case "mchRetrunOrderList":
          uni.setStorageSync("currentTab2", 2);
          uni.switchTab({
            url: "/pages/order/order",
          });
          break;
        default:
          uni.switchTab({
            url: "/pages/order/order",
          });
      }

      // 清除存储的推送数据
      uni.removeStorageSync("pendingPushData");
    },
    // 新增方法 - 处理推送声音
    // 修改handlePushSound方法
    async handlePushSound(pushData) {
      console.log(pushData.payload);
      try {
		const currentTime = Date.now();
	   // 检查是否在10秒内已经播放过语音
		if (currentTime - this.lastPlayTime < this.playInterval) {
		  console.log("10秒内已播放过语音，本次不播放");
		  return; // 10秒内不重复播放
		}
        // 获取category决定使用哪种声音
        const category = pushData.payload.category;
        var AUDIO = uni.createInnerAudioContext();
        // 设置音频源
        let soundFile = "";

        switch (category) {
          case "mchOnLineOrderList":
            AUDIO.src = "/static/mp3/jinxingzhong.MP3";
            AUDIO.play();
            break;
          case "mchAbnormalOrderList":
            AUDIO.src = "/static/mp3/yichang.MP3";
            AUDIO.play();
            break;
          case "mchRetrunOrderList":
            AUDIO.src = "/static/mp3/tuihuo.MP3";
            AUDIO.play();
            break;
        }
		this.lastPlayTime = currentTime; // 更新最后播放时间戳
        // 处理播放错误
        AUDIO.onError((res) => {
          console.error("播放声音失败:", res);
        });

        // 多次会调用播放新的文件时，提前销毁实例，可避免-99错误
        // 处理播放完成
        AUDIO.onEnded(() => {
          AUDIO.pause();
          AUDIO.destroy();
          AUDIO = null;
        });

        // Android平台原生播放备选方案
        // #ifdef APP-PLUS && ANDROID
        if (plus.os.name === "Android") {
          this.playNativeAndroidSound(soundFile);
        }
        // #endif
      } catch (e) {
        console.error("播放推送声音失败:", e);
      }
    },
    // Android原生播放方法
    playNativeAndroidSound(soundFile) {
      try {
        const main = plus.android.runtimeMainActivity();
        const MediaPlayer = plus.android.importClass(
          "android.media.MediaPlayer"
        );

        // 移除路径中的'/static'前缀，因为Android assets中不需要
        const androidAssetPath = soundFile.replace(/^\/static\//, "");

        const mediaPlayer = new MediaPlayer();
        const assetFileDescriptor = main
          .getAssets()
          .openFd("www/" + androidAssetPath);

        mediaPlayer.setDataSource(
          assetFileDescriptor.getFileDescriptor(),
          assetFileDescriptor.getStartOffset(),
          assetFileDescriptor.getLength()
        );

        mediaPlayer.prepare();
        mediaPlayer.start();

        mediaPlayer.setOnCompletionListener(
          new plus.android.Proxy(function () {
            mediaPlayer.release();
          })
        );
      } catch (e) {
        console.error("Android原生播放失败:", e);
      }
    },
  },
};
</script>

<style lang="scss">
// @import "./uni_modules/uview-ui/index.scss";
// @import "./uni_modules/uview-ui/theme.scss";
/*每个页面公共css */
@import "@/static/reset.css";
@import "@/styles/myui.scss";

@import "@/static/font/iconfont.css";

::v-deep.uni-tabbar-bottom {
  display: none;
}

::v-deep.uni-navbar {
  min-height: 110rpx;
}
</style>
