<script setup lang='ts'>
import request from '~/request'
import { showFailToast, showSuccessToast, showDialog } from 'vant';


const props = defineProps<{
  id: string
}>()
console.log('任务ID : ', props.id)

const router = useRouter()

function onClickLeft() {
  showDialog({
    title: '提醒',
    message: '没有完成全部的流程，确定退出吗？',
    showCancelButton: true,
    confirmButtonText: '确定',
    cancelButtonText: '取消',
  }).then(() => {
    router.back()
  })
}

const loading = ref(true)

const current = ref(0)

// {
//   audioId: '1',
//   demoAudio:
//     'http://nls-cloud-cn-shanghai.oss-cn-shanghai.aliyuncs.com/portal/tts/text_audio/wave/tonghua/300001.wav?Expires=1703561504&OSSAccessKeyId=LTAIiIg37IN8xeMa&Signature=guvV7UOLaCby%2FYKjuIfQAzGa4DY%3D&response-content-disposition=attachment%3Bfilename%3Dportal%2Ftts%2Ftext_audio%2Fwave%2Ftonghua%2F300001.wav',
//   text: '希望我们大家都能像他一样。'
// }
const list = ref<any[]>([])

request({
  url: '/aimooc/xnszr_audio/get_demo_text',
  data: {
    voiceId: props.id,
  }
}).then(res => {
  console.log('完整信息 : ', res.data)
  if (props.id !== res.data?.pre_data?.axa_sycj_zdysyid_v2) {
    showFailToast('任务ID不匹配');
    setTimeout(() => {
      router.replace({ name: 'caiji-sy-name' })
    }, 1000);
  }

  list.value = Object.values(res.data.data).sort((a: any, b: any) => a.audioId - b.audioId)
  console.log('文本列表 : ', list.value)
  let _current = res.data.pre_data?.axa_sycj_scbz_v2 ? parseInt(res.data.pre_data?.axa_sycj_scbz_v2) : 0
  console.log('上次已读到 : ', _current + 1)
  if (_current === list.value.length) {
    // showSuccessToast('已完成全部录音')
    showDialog({
      title: '提醒',
      message: '已完成全部录音,直接提交',
      showCancelButton: true,
      confirmButtonText: '确定',
    }).then(() => {
      handleSubmitTask()
    }).catch(() => {
      router.back()
    })
  }
  current.value = _current
  loading.value = false
})

// let audio = $ref<HTMLVideoElement>();
let audio = new Audio();
// let audio: HTMLVideoElement = document.createElement('video');
audio!.addEventListener('ended', () => {
  console.log('播放结束')
});
audio!.addEventListener('paused', () => {
  console.log('播放手动停止')
});
function breforeAudioPlay() {
  if (isRecording.value) {
    showFailToast('正在录制中，无法播放');
    throw Error('正在录制中，无法播放')
  }
  if (audio) {
    console.log('停止正在进行的播放')
    audio!.pause();
  }
}

function playDemoAudio() {
  breforeAudioPlay()
  console.log('开始播放demo录音')
  audio!.src = list.value[current.value].demoAudio;
  audio!.load();
  console.log('load成功', audio)
  audio!.play().then(() => {
    console.log('播放成功')
  }).catch((error) => {
    console.error('播放失败: ' + error);
    showFailToast('播放失败');
  })
}

const userAudio = ref<string | undefined>()
function playUserAudio() {
  breforeAudioPlay()
  if (!userAudio.value) {
    showFailToast('录音后才能预览');
    return
  }
  console.log('开始播放用户录音')
  audio!.src = userAudio.value;
  audio!.load();
  console.log('load成功', audio?.outerHTML)
  audio!.play().then(() => {
    console.log('播放成功')
  }).catch((error) => {
    console.error('播放失败: ' + error);
    showFailToast('播放失败');
  })
}



let mediaRecorder: MediaRecorder | null = null
let isRecording = ref(false)

let audioChunks: any[] = []

// if (MediaRecorder.isTypeSupported('audio/wav')) {
//   console.log('Opus codec in a wav container is supported');
// } else {
//   console.log('Opus codec in a wav container is not supported');
// }

function startAudioRecord() {
  console.log('点击 开始录音')
  breforeAudioPlay()
  audioChunks = []
  if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
    console.log('浏览器支持相关 API')
    navigator.mediaDevices.getUserMedia({ audio: true })
      .then((stream) => {
        console.log('stream 生成成功')
        isRecording.value = true

        mediaRecorder = new MediaRecorder(stream);
        console.log('mediaRecorder 初始化成功 ')

        mediaRecorder.addEventListener("dataavailable", (event: any) => {
          audioChunks.push(event.data);
        });

        mediaRecorder.addEventListener("stop", function (event: any) {
          audioChunks.push(event.data);
        });

        console.log("mediaRecorder 开始录音")
        mediaRecorder.start(500);
      })
      .catch((err) => {
        console.error(err);
      });
  } else {
    console.log("浏览器不支持相关 API", navigator.mediaDevices);
    showFailToast('你的浏览器版本过低，不支持录音功能');
    // showFailToast('请先去设置中打开浏览器录音权限');
  }
}

function stopAudioRecord() {
  if (!isRecording.value) {
    console.log('停止录音 录音机未启动时触发')
    return
  }
  console.log('停止录音')
  mediaRecorder?.stop();
  mediaRecorder = null

  const blob = new Blob(audioChunks, { type: 'audio/mp4' });
  if (userAudio.value) {
    window.URL.revokeObjectURL(userAudio.value);
  }
  userAudio.value = window.URL.createObjectURL(blob);
  console.log('用户录制音频 : ', blob.type, userAudio.value)
  isRecording.value = false
}

onUnmounted(() => {
  if (isRecording.value) {
    mediaRecorder!.stop();
  }
  mediaRecorder = null
})

function handleSubmitTask() {
  request({
    url: '/aimooc/xnszr_audio/submit_job',
    data: {
      voiceId: props.id,
    }
  }).then((res: any) => {
    if (res?.code === '1') {
      console.log('提交成功')
      showDialog({
        title: '成功提醒',
        message: '声音采集成功',
        showCancelButton: false,
        confirmButtonText: '确定',
      }).then(() => {
        router.back()
      })
    } else {
      console.info(res?.msg)
      // showFailToast(res?.msg)
      showDialog({
        title: '失败提醒',
        message: res?.msg,
        showCancelButton: false,
        confirmButtonText: '重新提交',
      }).then(() => {
        handleSubmitTask()
      })
    }
  })
}

function submitAudio() {
  return new Promise((resolve, reject) => {

    stopAudioRecord()
    console.log('audioChunks : ', audioChunks.length)
    if (audioChunks.length === 0) {
      showFailToast('请先录音');
      return reject()
    }
    setTimeout(() => {
      {
        userAudio.value = undefined
        current.value++
        return
      }
      // 其实浏览器不支持wav 交给后端转换
      const audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
      const filedata = new File([audioBlob], 'audio.wav', { type: 'audio/wav' });
      mediaRecorder = null
      audioChunks = []
      request({
        url: '/aimooc/xnszr_audio/detect_audio',
        data: {
          voiceId: props.id,
          audioRecordId: list.value[current.value].audioId,
          file: filedata,
        },
        transformRequest: [
          function (data: any) {
            const formData = new FormData();
            Object.keys(data).forEach(key => formData.append(key, data[key]))
            return formData;
          },
        ],
      })
        .then((res: any) => {
          console.log('声音采集识别结果 : ', res)
          if (res?.code === '1') {
            console.log('声音采集识别成功 当前读到: ', current.value + 1)
            if (current.value === list.value.length - 1) {
              handleSubmitTask()
            } else {
              showSuccessToast('声音采集识别成功')
              userAudio.value = undefined
              current.value++
            }
          } else {
            console.info('声音采集识别失败')
            showFailToast(res?.msg ? res?.msg : '网络错误，请重新录制')
          }
          resolve(res?.data)
        }).catch(err => {
          reject(err)
          showFailToast('网络错误，请重新录制');
        })
    }, 0);
  })

}

</script>

<template>
  <van-nav-bar title="声音采集" left-arrow @click-left="onClickLeft"></van-nav-bar>
  <div class="flex-auto w-full flex flex-col items-center justify-between py-72px px-6 box-border">
    <van-loading v-if="loading" size="36px" vertical class="text-xl">加载中...</van-loading>
    <template v-else>
      <div class="w-full flex flex-col items-center mb-12">
        <div class="text-xl mt-26px"><span class="text-hex-DB664D">{{ current + 1 }}</span> / {{ list.length }}</div>
        <p class="text-base indent mt-28px mb-32px">
          {{ list[current]?.text }}
        </p>
        <van-button size="small" @click="playDemoAudio">试听demo</van-button>
      </div>


      <div class="flex w-full justify-around text-hex-242731">
        <div :class="['p-4 rounded-8 bg-white', userAudio ? '' : 'opacity-20']" @click="playUserAudio">
          <van-icon name="volume" size="28" />
        </div>
        <div class="p-4 rounded-8 bg-white " @click="() => isRecording ? stopAudioRecord() : startAudioRecord()">
          <van-icon v-show="!isRecording" name="play" size="28" />
          <!-- <van-icon name="pause" size="28" /> -->
          <van-icon v-show="isRecording" name="stop" size="28" />
        </div>
        <div class="p-4 rounded-8 bg-white " @click="submitAudio">
          <van-icon name="success" size="28" />
        </div>
      </div>
    </template>

  </div>
  <!-- <audio ref="audio"></audio> -->
</template>
