<template>
<div class="audio-record">
  <van-button v-if="!readonly" size="small" type="success" @click="record">
    <template v-if="!recording">
      <span style="display: inline-block; width: 2.2rem">{{label || "说几句吧"}}(&lt=1分钟)</span>
    </template>
    <audio-wave v-if="recording"></audio-wave>
    <template #icon><i class="fas fa-microphone"></i></template>
  </van-button>
  <audio-play v-if="localAudioMedia.audio_url || localAudioMedia.media_id || local_id" @click="play" :playing="playing === key"></audio-play>
</div>
</template>

<script lang="ts">
import {computed, defineComponent, getCurrentInstance, reactive, ref, watch} from 'vue'
import {Button} from 'vant'
import AudioPlay from './audio-play.vue'
import AudioWave from './audio-wave.vue'
import {wxUtil} from "~/utils/wx";
import useAudio from "~/store/audio";
import {uuid} from "~/utils";
export default defineComponent({
  name: "audio-record",
  props: ['modelValue', 'readonly', "label"],
  emits: ['update:ModelValue'],
  components: {
    [Button.name]: Button,
    [AudioPlay.name]: AudioPlay,
    [AudioWave.name]: AudioWave
  },
  setup(props) {
    wxUtil.init(['startRecord', 'stopRecord', 'onVoiceRecordEnd', 'playVoice', 'pauseVoice', 'stopVoice', 'onVoicePlayEnd', 'uploadVoice', 'downloadVoice']);
    let data = props.modelValue;
    const instance = getCurrentInstance();
    const key = uuid();
    const usingAudio = useAudio();
    const local_id = ref('')
    const localAudioMedia = reactive({
      audio_url: data?.audio_url,
      media_id: data?.media_id
    });
    watch(() => props.modelValue, () => {
      localAudioMedia.media_id = props.modelValue?.media_id;
      localAudioMedia.audio_url = props.modelValue?.audio_url;
    })

    const recording = computed(() => usingAudio.recorder.recording);
    const playing = computed(() => usingAudio.store.target)
    const play = () => {
      if (playing.value === key) {
        usingAudio.stop();
      } else {
        usingAudio.play({target: key, audio_url: localAudioMedia.audio_url, serverId: localAudioMedia.media_id})
      }
    }

    const record = async () => {
      await usingAudio.startRecord(media_id => instance?.emit("update:modelValue", {media_id}));
    }

    return { local_id, record, play, playing, recording, key, localAudioMedia}
  }
});
</script>

<style scoped lang="less">


.audio-record {
  width: 100%;
  padding: 0.16rem;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>
