<script>
// #ifdef APP-PLUS
import APPUpdate, { getCurrentNo } from "@/config/appUpdate";
// #endif
import { mapState, mapActions } from "vuex";
import { webSocketManager } from "@/utils/socket.js";
export default {
  data() {
    return {
      version: "",
    };
  },
  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;
    webSocketManager.closeAllGlobalConnections();
    setTimeout(() => {
      if (this.userInfo && Object.keys(this.userInfo).length > 0) {
        this.connectSocket(this.userInfo);
      }
    });
  },
  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);
          }
        );
      });
    },
    initAppOrderPush() {
      uni.getPushClientId({
        success: (res) => {
          var push_clientid = res.cid;
          console.log("客户端推送标识cid:", push_clientid);
        },
        fail(err) {
          console.log(err);
        },
      });

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

        if (res.data) {
          const app = getApp();
          if (!app.globalData.isAppActive) {
            //监听系统通知栏消息点击事件
            if (res.type == "click") {
              this.handlePushClick(res.data.payload);
            } else {
              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方法
    handlePushSound(pushData) {
      console.log(pushData.payload);
      try {
        // 获取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;
        }

        // 处理播放错误
        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>
