<template>
  <view class="container global-audio-box" v-if="showAudioPop">
    <view class="bg-overlay" @click="isShowMaskHandler"></view>
    <view class="audio-box">
      <view class="activity-title">
        {{ activityTitle }}
        <view class="icon-cross" @click.stop="isShowMaskHandler">
          <van-icon name="cross" font-size="32" />
        </view>
      </view>
      <view class="audio-card">
        <view class="slider-paly">
          <image @click="speedReverseHandler('reverse')" class="speed-img" src="https://hzchart.oss-cn-shanghai.aliyuncs.com/cygx/fastReverse_icon.png"></image>
          <view style="flex: 1; margin: 0 30rpx 0 38rpx; padding-top: 20rpx">
            <slider
              activeColor="#376cbb"
              :max="audioTime"
              :value="curTime"
              @touchstart="touchstartHandler"
              @change="handleAudioSliderChange($event)"
              @changing="handleAudioSliderChangeing($event)"
              block-size="16"
              class="slider"
            />
            <view class="card-time">
              <text class="time">{{ curTime | formatVoiceTime }}</text>
              <text class="time">{{ audioTime | formatVoiceTime }}</text>
            </view>
          </view>
          <image @click="speedReverseHandler('speed')" class="speed-img" src="https://hzchart.oss-cn-shanghai.aliyuncs.com/cygx/speed_icon.png"></image>
        </view>
        <view class="fast-reverse">
          <block v-for="(item, index) in timesTheSpeed" :key="item.value">
            <view class="speed-button multiple-button global_content_center" v-if="isTimes == item.value" @click="isTimesHandler(index)">
              {{ item.name }}
            </view>
          </block>
          <view>
            <image v-if="PreviousNextSong == 0" class="previous_play_next" src="https://hzchart.oss-cn-shanghai.aliyuncs.com/new_cygx/previous_disable.png"></image>
            <image
              v-else
              @click="isPreviousNextSongHandler(PreviousNextSong == 0, '上')"
              class="previous_play_next"
              src="https://hzchart.oss-cn-shanghai.aliyuncs.com/new_cygx/previous_play.png"
            ></image>
          </view>
          <view class="is-paly-card" @click="handleChangePlayStatus">
            <image v-if="playImg" src="https://hzchart.oss-cn-shanghai.aliyuncs.com/new_cygx/suspend_play.png"></image>
            <image v-else src="https://hzchart.oss-cn-shanghai.aliyuncs.com/new_cygx/play_circle_filled.png"></image>
          </view>
          <view>
            <image v-if="PreviousNextSong == playlistData.length - 1" class="previous_play_next" src="https://hzchart.oss-cn-shanghai.aliyuncs.com/new_cygx/next_disable.png"></image>
            <image
              @click="isPreviousNextSongHandler(PreviousNextSong == playlistData.length - 1, '下')"
              v-else
              class="previous_play_next"
              src="https://hzchart.oss-cn-shanghai.aliyuncs.com/new_cygx/next_play.png"
            ></image>
          </view>
          <view class="speed-button global_content_center play-list-content" @click="showTabulation = true">
            <image src="https://hzchart.oss-cn-shanghai.aliyuncs.com/new_cygx/paly_list_play.png"></image>
          </view>
        </view>
      </view>
    </view>
    <van-popup :show="showTabulation" closeable position="bottom" round custom-style="height: 50%;" @close="onCloseHandler">
      <view class="play-ul">
        <view class="global_title play-ul_title">播放列表</view>
        <view class="play-li-box">
          <view class="play-li" v-for="(item, index) in playlistData" :key="item.indexId" @click="palyHandler(item)">
            <view class="item-content-play-list">
              <view :class="['text_oneLine', 'play-li-name', audioInit.indexId == item.indexId && 'active-play-li-name']">{{ item.Name }}</view>
              <image v-if="audioInit.indexId == item.indexId" class="play_audio" src="https://hzchart.oss-cn-shanghai.aliyuncs.com/new_cygx/play_audio.gif"></image>
            </view>
            <view class="delete_play">
              <image @click.native.stop="removeAudioListHandler(item, index)" class="delete_play" src="https://hzchart.oss-cn-shanghai.aliyuncs.com/new_cygx/delete_play.png"></image>
            </view>
          </view>
        </view>
      </view>
    </van-popup>
  </view>
</template>

<script>
import { activity, Reports } from "@/config/api";
export default {
  name: "",
  filters: {
    formatVoiceTime(e) {
      let m = parseInt(e / 60);
      let s = parseInt(e % 60);
      return `${m > 9 ? m : "0" + m}:${s > 9 ? s : "0" + s}`;
    },
  },
  components: {},
  props: {
    showAudioPop: {
      type: Boolean,
      default: false,
      required: true,
    },
  },
  data() {
    return {
      curTime: 0,
      audioTime: 0, //当前音频总时长
      title: "", //当前音频标题
      activityTitle: "", //当前活动标题
      playImg: false,
      isosName: "",
      palyTimeout: null,
      palyTime: 0,
      timesTheSpeed: [
        { name: "倍速", value: 1 },
        { name: "1.25", value: 1.25 },
        { name: "1.5", value: 1.5 },
        { name: "2", value: 2 },
      ],
      isRecord: true, //是否记录播放
      showTabulation: false,
      isCommunication: false,
    };
  },
  computed: {
    //重新
    audioInit() {
      return {
        activityId: this.$store.state.audioBg.activityId,
        reportId: this.$store.state.audioBg.reportId,
        indexId: this.$store.state.audioBg.indexId,
      };
    },
    // 几倍的播放速度
    isTimes() {
      return this.$store.state.audioBg.multiple;
    },
    //进度条是否在滑动
    isSlide() {
      return this.$store.state.audioBg.isDragSlide;
    },
    isEnded() {
      return this.$store.state.audioBg.isAudioEnded;
    },
    // 播放列表数据
    playlistData() {
      return this.$store.state.audioJoinPlaylist.playlist;
    },
    // 上、下一首歌曲禁用
    PreviousNextSong() {
      const curAudio = this.$store.state.audioBg.list;
      let indexId = this.audioInit.indexId;
      let indexPlay = this.playlistData.findIndex((_) => _.Name === curAudio.Name && _.indexId === indexId);
      return indexPlay;
    },
  },
  watch: {
    audioInit: {
      // 切换了音频播放 重置下数据
      handler(nval) {
        this.init();
      },
      immediate: true,
    },
  },

  created() {},
  mounted() {
    uni.getSystemInfo({
      //判断机型
      success: (res) => {
        this.isosName = res.osName;
      },
    });
    uni.$on("play-list-emit", () => {
      this.showTabulation = true;
      this.isCommunication = true;
    });
  },
  methods: {
    //点击隐藏事件
    isShowMaskHandler() {
      this.$emit("update:showAudioPop", false);
    },
    //数据初次加载
    init() {
      const curAudio = this.$store.state.audioBg.list;
      this.isExistList(curAudio);
      if ((this.globalBgAudioManager.src != curAudio.Url && curAudio.Url) || (this.isEnded && this.isosName !== "ios" && curAudio.Url)) {
        this.$store.commit("audioBg/setAudioEnd", false);
        this.globalBgAudioManager.playbackRate = 1;
        this.$store.commit("audioBg/setMultiple", 1);
        this.$store.commit("audioBg/updateAudioTime", 0);
        this.globalBgAudioManager.src = curAudio.Url;
        this.globalBgAudioManager.title = curAudio.Name;
        this.globalBgAudioManager.startTime = 0;
        this.curTime = 0;
      } else {
        this.curTime = parseInt(this.globalBgAudioManager.currentTime);
      }
      this.audioTime = curAudio.PlaySeconds;
      this.title = curAudio.Name ? curAudio.Name.replace(/<\/?font.*?>/g, "") : "";
      let activityTitle = this.$store.state.audioBg.activityTitle;
      this.activityTitle = activityTitle ? activityTitle.replace(/<\/?font.*?>/g, "") : "";
      this.playImg = !this.globalBgAudioManager.paused;
      this.listenAudio();
    },
    //音频播放事件
    listenAudio() {
      // 音频播放
      this.globalBgAudioManager.onPlay(async () => {
        if (this.isRecord) {
          this.palyTime = 0;
          this.backAudioPlay();
          this.palyTimeout = setInterval(() => {
            this.palyTime++;
          }, 1000);
        }
        this.playImg = true;
        this.$store.commit("audioBg/updateAudioPause", false);
        this.isRecord = true;
      });
      // 音频暂停
      this.globalBgAudioManager.onPause(() => {
        this.backAudioPlay();
        clearInterval(this.palyTimeout);
        this.playImg = false;
        this.$store.commit("audioBg/updateAudioPause", true);
      });
      // 音频停止
      this.globalBgAudioManager.onStop(() => {
        this.showTabulation = false;
        this.backAudioPlay();
        clearInterval(this.palyTimeout);
        this.$emit("update:showAudioPop", false);
        this.playImg = false;
        this.$store.commit("audioBg/removeAudio");
        if (this.isosName !== "ios") {
        } else {
          this.$store.commit("audioBg/updateAudioPause", true);
        }
      });
      // 音频onEnded
      this.globalBgAudioManager.onEnded(() => {
        const curAudio = this.$store.state.audioBg.list;
        let indexId = this.audioInit.indexId;
        this.onEndedpalyHandler(curAudio, indexId);
        this.backAudioPlay();
        clearInterval(this.palyTimeout);
      });
      // 音频onError
      this.globalBgAudioManager.onError((e) => {
        this.$store.commit("audioBg/removeAudio");
        this.$store.commit("audioBg/setMultiple", 1);
        uni.showToast({
          title: "音频播放错误",
          icon: "none",
        });
      });

      // 音频的播放时间更新
      this.globalBgAudioManager.onTimeUpdate(() => {
        if (this.globalBgAudioManager.src && parseInt(this.globalBgAudioManager.currentTime) !== 0 && !this.isSlide) {
          this.curTime = parseInt(this.globalBgAudioManager.currentTime);
          this.$store.commit("audioBg/updateAudioTime", this.curTime);
        }
      });
    },

    // 拖动进度条
    handleAudioSliderChangeing(e) {
      this.curTime = e.detail.value;
    },

    // 拖动进度条
    handleAudioSliderChange(e) {
      const value = e.detail.value;
      this.globalBgAudioManager.seek(value);
      this.isRecord = false;
      setTimeout(() => {
        this.$store.commit("audioBg/setSlide", false);
      }, 300);
    },

    // 音频点击暂停播放
    handleChangePlayStatus() {
      if (!this.globalBgAudioManager.paused) {
        this.globalBgAudioManager.pause();
      } else {
        this.globalBgAudioManager.play();
      }
    },

    // 倍速播放
    isTimesHandler(i) {
      let index = i == 3 ? 0 : i + 1;
      this.$store.commit("audioBg/setMultiple", this.timesTheSpeed[index].value);
      this.globalBgAudioManager.playbackRate = this.isTimes;
      this.globalBgAudioManager.startTime = this.curTime;
      if (this.globalBgAudioManager.paused) {
        this.globalBgAudioManager.play();
      }
      this.isRecord = false;
    },

    //快进 快退
    speedReverseHandler(type) {
      let isTime = type == "reverse" ? this.curTime - 15 : this.curTime + 15;
      isTime = isTime <= 0 ? 0 : isTime >= this.audioTime ? this.audioTime - 1 : isTime;
      this.globalBgAudioManager.seek(isTime);
      this.isRecord = false;
    },

    // 播放了记录
    backAudioPlay() {
      let recordList = this.$store.state.audioBg.recordList;
      if ((this.$store.state.audioBg.activityId || this.audioInit.indexId) && this.palyTime >= 0) {
        activity.backAudioPlay({
          SourceId: recordList.SourceId || recordList.ActivityId,
          SourceType: recordList.Type ? recordList.Type : 1,
          PlaySeconds: this.palyTime,
          PageRouter: this.$store.state.pageRouterReport,
        });
      } else if (this.$store.state.audioBg.reportId && this.palyTime >= 0) {
        Reports.reportVoiceHistoryAdd({
          ArticleId: this.$store.state.audioBg.reportId,
          PlaySeconds: this.palyTime,
          PageRouter: this.$store.state.pageRouterReport,
        });
      }
    },
    // 手指离开了拖动进度条
    touchstartHandler() {
      this.$store.commit("audioBg/setSlide", true);
    },
    // 关闭播放列表
    onCloseHandler() {
      this.showTabulation = false;
      if (this.isCommunication) {
        this.isCommunication = false;
        this.isShowMaskHandler();
      }
    },
    // 点击了播放列表
    palyHandler(item) {
      console.log(item);
      if (this.audioInit.indexId == item.indexId) {
      } else {
        this.playlistDataInit(item);
      }
    },
    // 播放结束后 播放下一首
    onEndedpalyHandler(curAudio, indexId) {
      let item = this.playlistData[this.PreviousNextSong + 1];
      if (item) {
        this.playlistDataInit(item);
      } else {
        this.$emit("update:showAudioPop", false);
        this.$store.commit("audioBg/setAudioEnd", true);
        this.$store.commit("audioBg/parseIntAudio", false);
        this.$store.commit("audioBg/removeAudio");
      }
    },
    // 上一首 下一首
    isPreviousNextSongHandler(isPlay, type) {
      if (isPlay) return;
      let item = this.playlistData[type == "上" ? this.PreviousNextSong - 1 : this.PreviousNextSong + 1];
      this.playlistDataInit(item);
    },
    // 处理播放列表的数据
    playlistDataInit(item) {
      if (item) {
        let VoiceList = {
          Url: item.Url,
          Name: item.Name,
          PlaySeconds: item.PlaySeconds,
        };
        this.$store.commit("audioBg/addAudio", { list: VoiceList, indexId: item.indexId, activityTitle: item.activityTitle, recordList: item.recordList });
        this.init();
      }
    },
    // 数据是否存在
    isExistList(item) {
      const playlist = this.playlistData.some((key) => key.indexId === this.audioInit.indexId);
      if (!playlist && item.Url) {
        let dataList = {
          Url: item.Url,
          Name: item.Name,
          PlaySeconds: item.PlaySeconds,
          indexId: this.audioInit.indexId,
          activityTitle: item.Name,
          recordList: this.$store.state.audioBg.recordList,
        };
        this.$store.commit("audioJoinPlaylist/addUnshiftPlaylist", { dataList });
      }
    },
    // 点击删除列表
    removeAudioListHandler(item, index) {
      const indexKey = this.playlistData.findIndex((key) => key.indexId === this.audioInit.indexId);
      let list = this.playlistData.filter((_) => _.indexId != item.indexId);
      this.$store.commit("audioJoinPlaylist/removeAudio", { list });
      if (index === this.playlistData.length && indexKey === index) {
        this.globalBgAudioManager.stop();
      } else if (indexKey < index) {
      } else if (indexKey === index) {
        this.playlistDataInit(this.playlistData[index]);
      }
    },
  },
};
</script>
<style scoped lang="scss">
.global-audio-box {
  display: flex;
  height: 100%;
  position: fixed;
  width: 100%;
  top: 0;
  left: 0;
  z-index: 111;
  .bg-overlay {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    background-color: rgba(0, 0, 0, 0.7);
  }
  .activity-title {
    position: relative;
    width: 100%;
    font-size: 30rpx;
    font-weight: 500;
    margin-bottom: 35rpx;
    padding-right: 50rpx;
    .icon-cross {
      position: absolute;
      right: 0;
      top: 50%;
      transform: translateY(-50%);
      padding: 10rpx;
    }
  }
  .audio-box {
    position: absolute;
    bottom: 0;
    left: 0;
    padding: 30rpx;
    padding-bottom: constant(safe-area-inset-bottom);
    padding-bottom: env(safe-area-inset-bottom);
    width: 100%;
    background: #ffffff;
    box-sizing: border-box;
    border-radius: 30rpx 30rpx 0 0;
  }
  .audio-card {
    width: 100%;
    height: 282rpx;
    background: #f9f9f9;
    border-radius: 16rpx;
    margin: 0 auto;
    padding: 30rpx 0;
    .slider {
      width: 100%;
      margin: 0;
    }
    .slider-paly {
      display: flex;
      height: 80rpx;
      align-items: center;
    }
    .card-title {
      color: #376cbb;
      font-size: 28rpx;
      padding: 0 40rpx;
      text-align: center;
      margin-bottom: 35rpx;
    }
    .card-time {
      display: flex;
      justify-content: space-between;
      color: #999999;
      font-size: 20rpx;
    }
    .is-paly-card {
      width: 150rpx;
      height: 150rpx;
      flex-shrink: 0;
      image {
        width: 150rpx;
        height: 150rpx;
      }
    }
    .fast-reverse {
      display: flex;
      align-items: center;
      justify-content: space-around;
      margin-top: 30rpx;
      .speed-button {
        width: 88rpx;
        height: 58rpx;
        background: #e5efff;
        border-radius: 8rpx;
        color: $uni-color-new;
        font-size: 36rpx;
      }
      .multiple-button {
        font-size: 30rpx;
      }
      .play-list-content {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 64rpx;
        image {
          width: 48rpx;
          height: 48rpx;
        }
      }
    }
  }
  .speed-img {
    width: 50rpx;
    height: 50rpx;
  }
  .play-ul {
    padding: 30rpx 0;
    .play-ul_title {
      padding-left: 30rpx;
    }
    .play-li-box {
      height: 880rpx;
      overflow: hidden;
      margin-top: 35rpx;
      border-top: 1rpx solid #dcdfe6;
      overflow-y: auto;
    }
    .play-li {
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 92rpx;
      padding: 0 30rpx;
      border-bottom: 1rpx solid #dcdfe6;
      .delete_play {
        flex-shrink: 0;
        width: 36rpx;
        height: 36rpx;
        margin-left: 5rpx;
        image {
          width: 36rpx;
          height: 36rpx;
        }
      }
      .item-content-play-list {
        width: 600rpx;
        display: flex;
        align-items: center;
        flex-shrink: 0;
        .play-li-name {
          display: inline-block;
        }
        .active-play-li-name {
          color: $uni-color-new;
        }
        .play_audio {
          display: inline-block;
          width: 36rpx;
          height: 36rpx;
          margin-left: 2rpx;
          flex-shrink: 0;
        }
      }
    }
  }
  .previous_play_next {
    width: 100rpx;
    height: 100rpx;
  }
}
</style>
