<template>
  <view class="voice-message" @click="Play">
    <view class="voice-message-content" v-if="senderId == userId">
      <view>{{ floor(message.duration) }}"</view>
      <image
        v-if="NumberClicks == 0"
        class="voice-message-avatar"
        src="https://vv-1317974657.cos.ap-shanghai.myqcloud.com/util/voice.png"
        mode="scaleToFill"
      />
      <view class="voice-message-name" v-if="NumberClicks == 1">播放中...</view>
      <view class="voice-message-name" v-if="NumberClicks == 2">暂停中...</view>
    </view>

    <view class="voice-message-content" v-else>
      <image
        v-if="NumberClicks == 0"
        class="voice-message-avatar"
        src="https://vv-1317974657.cos.ap-shanghai.myqcloud.com/util/voice.png"
        mode="scaleToFill"
      />
      <view class="voice-message-name" v-if="NumberClicks == 1">播放中...</view>
      <view class="voice-message-name" v-if="NumberClicks == 2">暂停中...</view>
      <view>"{{ floor(message.duration) }}"</view>
    </view>
  </view>
</template>

<script>
export default {
  props: {
    message: {
      type: Object,
      default: () => ({}),
    },
    senderId: {
      type: String,
      default: "",
    },
    userId: {
      type: Number,
    },
    playbackStatus: {
      type: Boolean,
    },
  },
  data() {
    return {
      innerAudioContext: null,
      NumberClicks: 0,
    };
  },
  watch: {
    playbackStatus(newVal) {
      if (!newVal) {
        if (this.innerAudioContext) {
          this.innerAudioContext.pause();
          this.innerAudioContext.destroy();
          this.innerAudioContext = null;
          this.NumberClicks = 0;
          this.$emit("notplayVoice", true);
        } else {
          this.$emit("notplayVoice", true);
        }
      } else {
        this.$emit("notplayVoice", true);
      }
    },
  },
  methods: {
    floor(num) {
      return Math.floor(num);
    },
    Play() {
      this.$emit("notplayVoice", false);
      setTimeout(() => {
        this.innerAudioContext = uni.createInnerAudioContext();
        this.innerAudioContext.src = this.message.url;
        this.innerAudioContext.onEnded(() => {
          this.NumberClicks = 0;
          this.innerAudioContext.destroy();
          this.innerAudioContext = null;
        });
        this.innerAudioContext.onError((res) => {
          this.NumberClicks = 0;
          this.innerAudioContext.destroy();
          this.innerAudioContext = null;
        });

        this.innerAudioContext.play();
        this.NumberClicks = 1;
      }, 500);
    },
  },
};
</script>

<style scoped>
.voice-message {
  padding: 0 20rpx 0 20rpx;
}

.voice-message-avatar {
  width: 100rpx;
  height: 80rpx;
  margin-left: 10rpx;
}

.voice-message-content {
  display: flex;
  align-items: center;
}

.voice-message-name {
  height: 80rpx;
  margin-left: 10rpx;
  font-size: 28rpx;
  color: #999;
  line-height: 80rpx;
}
</style>
