<!--  -->
<template>
  <div class="Big-Book-sentence" v-if="curQue">
    <div
      class="Big-Book-Single-content"
      style="margin-left: 20px; margin-top: 20px"
    >
      <div class="adult-book-input-item">
        <span class="adult-book-lable">标题：</span>
        <el-input
          class="adult-book-input"
          type="textarea"
          autosize
          placeholder="请输入标题"
          v-model="curQue.title"
          @blur="onBlur(curQue, 'title')"
        ></el-input>
      </div>
      <template v-if="type == 'sentence_listen_read_chs'">
        <div class="adult-book-input-item">
          <span class="adult-book-lable">题目音频：</span>
          <Upload
            :changeFillId="changeMp3"
            :datafileList="curQue.mp3_list"
            :filleNumber="mp3Number"
            :uploadType="'mp3'"
            :handleMp3Base64="handleChange"
          />
        </div>
      </template>
      <div
        class="Big-Book-main"
        v-for="(item, index) in curQue.option"
        :key="item + index"
        style="margin-bottom: 20px"
      >
        <SentenceModule
          :curQueItem="item"
          :curQue="curQue"
          :deleteOptionOne="deleteOptionOne"
          :index="index"
          :type="type"
          :fn_list="curQue.fn_list"
        />
      </div>
      <div class="Big-Book-addrole">
        <div class="addoption" @click="addOption">添加一个</div>
      </div>
      <div class="lrc-box">
        <div
          v-if="this.curQue.wordTime && this.curQue.wordTime.length > 0"
          class="lrc-box"
        >
          <span>已有字幕时间节点</span>
          <el-button type="text" @click="againWordTime">重新生成</el-button>
        </div>
        <template v-else>
          <el-button v-if="!isWordTime" size="medium" @click="createWordTime"
            >自动生成字幕节点</el-button
          >
          <p v-else>字幕节点生成中...请等待</p>
        </template>
      </div>
    </div>
  </div>
</template>

<script>
import SentenceModule from "../common/SentenceModule.vue";
import Upload from "../common/Upload";
const Base64 = require("js-base64").Base64;
import {
  segSentences,
  BatchSegContent,
  createPinyin,
  prepareTranscribe,
  getWordTime,
} from "@/api/ajax";
export default {
  name: "Single",
  props: ["curQue", "fn_data", "changeCurQue", "type"],
  components: {
    SentenceModule,
    Upload,
  },
  data() {
    return {
      checkList: [],
      mp3Number: 1,
      form: {
        stem: {
          con: "",
          pinyin: "",
          english: "",
          highlight: "",
          underline: "",
          img_url: [],
          mp3_url: [],
        },
      },
      data_structure: {
        type: "recordHZ_inputPY_chs",
        name: "读汉字写拼音",
        title: "",
        option: [
          {
            number: "",
            con: "",
            answer: "",
            IsRecord: false,
            mp3_url: [],
          },
        ],
      },
      data_structure2: {
        type: "inputItem_chs",
        name: "输入选项",
        title: "",
        option: [
          {
            number: "",
            con: "",
            answer: "",
            detail: {
              pyPosition: "top", //top 拼音在上面；bottom 拼音在下面
              sentence: "", //句子
              segList: [], //分词结果
              seg_words: "",
              wordsList: [],
            },
          },
        ],
      },
      data_structure_sentence: {
        type: "sentence_chs",
        name: "句子模板",
        title: "",
        mp3_list: [],
        taskId: "",
        wordTime: [],
        detail: [],
        option: [
          {
            mp3_list: [],
            number: "",
            font: "",
            detail: {
              pyPosition: "top", //top 拼音在上面；bottom 拼音在下面
              sentence: "", //句子
              segList: [], //分词结果
              seg_words: "",
              wordsList: [],
            },
            en: "", //英文
            answer: [""],
            judge: true,
          },
        ],
        fn_list: [
          {
            type: "sentence_record_chs",
            name: "录音",
            isFn: false,
          },
          {
            type: "sentence_input_chs",
            name: "输入",
            isFn: false,
          },
          {
            type: "sentence_judge_chs",
            name: "判断",
            isFn: false,
          },
        ],
      },
      isWordTime: false,
    };
  },
  computed: {},
  watch: {},
  //方法集合
  methods: {
    createWordTime() {
      this.curQue.detail = [];
      this.curQue.option.forEach((item) => {
        this.curQue.detail.push(item.detail);
      });
      if (this.curQue.taskId) {
        let verseList = [];
        let numberArr = [];
        this.curQue.detail.forEach((item, i) => {
          numberArr.push(this.numberToChinese(i + 1));
        });
        for (let i = 0; i < this.curQue.detail.length; i++) {
          verseList = verseList.concat(
            `${numberArr[i]}` + this.curQue.detail[i].sentence
          );
        }
        if (verseList.length > 0) {
          this.isWordTime = true;
          let data = {
            taskId: this.curQue.taskId,
            verseList: JSON.stringify(verseList),
          };
          getWordTime(data).then((res) => {
            this.curQue.wordTime = res.data.result;
            this.isWordTime = false;
          });
        }
      } else {
        this.$message.warning("请先上传音频");
      }
    },
    againWordTime() {
      this.isWordTime = false;
      this.$set(this.curQue, "wordTime", []);
    },
    numberToChinese(num) {
      var AA = new Array(
        "零",
        "一",
        "二",
        "三",
        "四",
        "五",
        "六",
        "七",
        "八",
        "九",
        "十"
      );
      var BB = new Array("", "十", "百", "仟", "萬", "億", "点", "");
      var a = ("" + num).replace(/(^0*)/g, "").split("."),
        k = 0,
        re = "";
      for (var i = a[0].length - 1; i >= 0; i--) {
        switch (k) {
          case 0:
            re = BB[7] + re;
            break;
          case 4:
            if (
              !new RegExp("0{4}//d{" + (a[0].length - i - 1) + "}$").test(a[0])
            )
              re = BB[4] + re;
            break;
          case 8:
            re = BB[5] + re;
            BB[7] = BB[5];
            k = 0;
            break;
        }
        if (k % 4 == 2 && a[0].charAt(i + 2) != 0 && a[0].charAt(i + 1) == 0)
          re = AA[0] + re;
        if (a[0].charAt(i) != 0) re = AA[a[0].charAt(i)] + BB[k % 4] + re;
        k++;
      }

      if (a.length > 1) {
        // 加上小数部分(如果有小数部分)
        re += BB[6];
        for (var i = 0; i < a[1].length; i++) re += AA[a[1].charAt(i)];
      }
      if (re == "一十") re = "十";
      if (re.match(/^一/) && re.length == 3) re = re.replace("一", "");
      return re;
    },
    // 上传音频文件
    handleChange(file, fileList) {
      let _this = this;
      _this.getBase64(file.raw).then((res) => {
        let base_res = res.split("base64,");
        let data = {
          fileName: file.raw.name,
          speechBase64: base_res[1],
        };
        prepareTranscribe(data).then((res) => {
          _this.$set(_this.curQue, "taskId", res.data.taskId);
        });
      });
    },
    getBase64(file) {
      return new Promise(function (resolve, reject) {
        let reader = new FileReader();
        let imgResult = "";
        reader.readAsDataURL(file);
        reader.onload = function () {
          imgResult = reader.result;
        };
        reader.onerror = function (error) {
          reject(error);
        };
        reader.onloadend = function () {
          resolve(imgResult);
        };
      });
    },
    onBlur(item, field) {
      item[field] = item[field] ? item[field].trim() : "";
    },
    // 修改正确选项中得某一个为正确答案
    changAnswer(index) {
      this.curQue.option.forEach((item, i) => {
        if (index == i) {
          this.curQue.correct[0].input[index] = item.Answer;
        }
      });
    },
    // 删除其中一个选项
    deleteOptionOne(index) {
      if (this.curQue.option.length <= 1) {
        this.$message.warning("至少要保留1个选项");
        return;
      }
      this.curQue.option.splice(index, 1);
    },
    // 新增选项
    addOption() {
      let obj;
      if (this.type == "recordHZ_inputPY_chs") {
        obj = JSON.parse(JSON.stringify(this.data_structure.option[0]));
      } else if (this.type == "inputItem_chs") {
        obj = JSON.parse(JSON.stringify(this.data_structure2.option[0]));
      } else if (this.type.indexOf("sentence") > -1) {
        obj = JSON.parse(
          JSON.stringify(this.data_structure_sentence.option[0])
        );
      }
      this.curQue.option.push(obj);
    },
    // 更多配置选择
    handleCheckedFnChange(value) {
      //   let fn_list = JSON.parse(JSON.stringify(this.curQue.fn_list));
      //   this.curQue.fn_list = fn_list.map((item) => {
      //     if (value.indexOf(item.name) > -1) {
      //       this.checkList.push(item.name);
      //       item.isFn = true;
      //     } else {
      //       item.isFn = false;
      //       this.curQue.con.forEach((it) => {
      //         it.annotation = "";
      //       });
      //     }
      //     return item;
      //   });
    },
    //处理数据
    handleStructure(type) {
      let data = JSON.parse(JSON.stringify(this.data_structure_sentence));
      data.fn_list.map((item) => {
        if (item.type == type) {
          item.isFn = true;
        }
        if (type == "sentence_input_record_chs") {
          if (
            item.type == "sentence_record_chs" ||
            item.type == "sentence_input_chs"
          ) {
            item.isFn = true;
          }
        }
        if (
          type == "recordHZ_inputPY_chs" ||
          type == "sentence_listen_read_chs"
        ) {
          if (item.type == "sentence_record_chs") {
            item.isFn = true;
          }
        }
        return item;
      });
      return data;
    },
    initcurQue() {
      let data = null;
      if (this.type == "recordHZ_inputPY_chs") {
        // data = JSON.parse(JSON.stringify(this.data_structure));
        data = this.handleStructure(this.type);
      } else if (this.type == "inputItem_chs") {
        data = JSON.parse(JSON.stringify(this.data_structure2));
      } else if (this.type.indexOf("sentence_") > -1) {
        data = this.handleStructure(this.type);
      }
      console.log(data);
      this.changeCurQue(data);
    },
    changeMp3(fileList) {
      const articleImgList = JSON.parse(JSON.stringify(fileList));
      const articleImgRes = [];
      articleImgList.forEach((item) => {
        if (item.response) {
          const obj = {
            name: item.name,
            url: item.response.file_info_list[0].file_url,
            id: "[FID##" + item.response.file_info_list[0].file_id + "##FID]",

            media_duration: item.response.file_info_list[0].media_duration, //音频时长
          };
          articleImgRes.push(obj);
        }
      });
      this.curQue.mp3_list = JSON.parse(JSON.stringify(articleImgRes));
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    console.log("句子控件的录入");
    if (!this.curQue) {
      this.initcurQue();
    }
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style lang='scss' scope>
//@import url(); 引入公共css类
.Big-Book-sentence {
  &-content {
    &.m {
      display: flex;
      justify-content: flex-start;
      align-items: flex-start;
    }

    .Big-Book-title {
      font-size: 16px;
      line-height: 40px;
      color: #000;
      margin-right: 15px;
    }
    .Big-Book-main {
      > div {
        margin-bottom: 10px;
        &.Big-Book-pinyin {
          display: flex;
          justify-content: flex-start;
          align-items: center;
        }
      }
    }
  }

  .Big-Book-addrole {
    > div {
      width: 300px;
      height: 40px;
      background: #f3f3f3;
      border: 1px dashed rgba(0, 0, 0, 0.15);
      box-sizing: border-box;
      border-radius: 4px;
      text-align: center;
      line-height: 40px;
      cursor: pointer;
    }
  }
  .Big-Book-more {
    .Big-Book-more-text {
      position: relative;
      text-align: center;
    }
    .Big-Book-more-text:before,
    .Big-Book-more-text:after {
      position: absolute;
      background: #ccc;
      content: "";
      height: 1px;
      top: 50%;
      width: 45%;
    }
    .Big-Book-more-text:before {
      left: 10px;
    }
    .Big-Book-more-text:after {
      right: 10px;
    }
    .Big-Book-more-main {
      display: flex;
      > :not(:nth-child(1)) {
        margin-left: 30px;
      }
    }
  }
  .Big-Book-con {
    display: flex;
    align-items: center;
  }
}
.lrc-box {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  > span {
    font-size: 14px;
    margin-right: 16px;
  }
}
</style>
<style lang="scss">
</style>