<template>
  <el-dialog
    class="tts-dialog"
    :visible.sync="modalIsShow"
    title="语音合成"
    top="10px"
    width="600px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    @opened="initData"
    @closed="closed"
  >
    <el-input
      type="textarea"
      :rows="8"
      v-model="text"
      maxlength="2000"
      show-word-limit
    ></el-input>
    <div class="btns">
      <el-button
        :type="status === 'PLAY' ? 'danger' : 'primary'"
        @click="action"
        :disabled="!text"
        >{{ statusStr }}</el-button
      >
    </div>
    <div slot="footer">
      <el-button type="primary" :disabled="loading || !blob" @click="submit"
        >保存音频</el-button
      >
      <el-button type="danger" plain @click="cancel">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import TtsVoice from "@/plugins/tts";

export default {
  name: "TtsDialog",
  props: {},
  data() {
    return {
      loading: false,
      modalIsShow: false,
      ttsVoice: null,
      text: ``,
      status: "UNDEFINED",
      statusStr: "立即合成",
      blob: null,
    };
  },
  created() {
    this.ttsVoice = new TtsVoice({
      appId: "5cc0340f",
      apiSecret: "fb1702602169809fef3dc60a16d60493",
      apiKey: "e5b67c040d614b7bfb9aa852731947eb",
      cb: this.watchStatus,
      blobDoneCb: this.getBlob,
    });
  },
  beforeDestroy() {
    this.ttsVoice.ttsWS?.close();
  },
  methods: {
    action() {
      this.ttsVoice?.action(this.text);
    },
    watchStatus(obj) {
      this.status = obj.status;
      this.statusStr = obj.statusStr;
    },
    initData() {
      this.text = ``;
      this.status = "UNDEFINED";
      this.statusStr = "立即合成";
      this.blob = null;
    },
    closed() {
      this.ttsVoice?.reset();
    },
    cancel() {
      this.ttsVoice?.reset();
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    getBlob(blob) {
      this.blob = blob;
      console.log("done blob", blob);
    },
    async submit() {
      this.$emit("confirm", this.blob);
    },
  },
};
</script>
<style lang="scss" scoped>
.btns {
  padding-top: 10px;
}
</style>
