<!--  -->
<template>
  <div
    class="NPC-Book-Article Big-Book-Maxwidth"
    v-if="curQue"
    v-loading="loading"
  >
    <div class="Big-Book-img">
      <UploadArt
        :change-fill-id="changeImage"
        :datafile-list="fileCon.img_list"
        upload-type="image"
        class="article_pdf"
        :filleNumber="imageNumber"
      />
      <ul
        class="uploadArt_list"
        v-if="curQue.img_list && curQue.img_list.length > 0"
      >
        <li
          v-for="(artItem, artIndex) in curQue.img_list"
          :key="'articleImgList' + artIndex"
        >
          <img :src="artItem.url" style="width: 26px" />
          <span class="art_name">{{ artItem.name }}</span>
          <p>
            图片放到第<el-input
              class="imgNumber"
              type="number"
              v-model="artItem.imgNumber"
              size="mini"
              @input="forceUpdate"
            ></el-input
            >段落的后面
          </p>
          <img
            src="@/assets/adult/del-close.png"
            class="del-close"
            @click="delImage(artIndex)"
          />
        </li>
      </ul>
    </div>
    <div class="Big-Book-mp3">
      <Upload
        type="mp3"
        :changeFillId="changeMp3"
        :datafileList="fileCon.mp3_list"
        :filleNumber="mp3Number"
        :uploadType="'mp3'"
      />
      <!-- 
        :handleMp3Base64="handleChange"

       -->
    </div>
    <div class="adult-book-input-item">
      <span class="adult-book-lable">功能配置：</span>
      <div class="adult-book-main" v-if="curQue.checkList">
        <el-checkbox-group v-model="curQue.checkList">
          <el-checkbox :label="1">显示生词功能</el-checkbox>
          <el-checkbox :label="2">语音练习模式</el-checkbox>
          <el-checkbox :label="3">取词功能</el-checkbox>
        </el-checkbox-group>
      </div>
    </div>
    <div class="NPC-Book-article">
      <ArticleChs
        :curQue="curQue"
        :isPara="isPara"
        :changeIsPara="changeIsPara"
      />
    </div>
    <template
      v-if="
        curQue.mp3_list &&
        curQue.mp3_list.length > 0 &&
        curQue.mp3_list[0].source
      "
    >
      <div class="create_mp3_list">
        <span>引擎音频：</span>
        <span class="mp3_file_name">{{ curQue.mp3_list[0].name }}</span>
        <img
          src="../../../../assets/adult/del-close.png"
          class="mp3_del"
          @click="delMp3"
        />
      </div>
    </template>
    <template v-else>
      <el-button :loading="CreadMp3loading" size="small" @click="CreadMp3"
        >生成音频</el-button
      >
    </template>
    <div class="NPC-Book-Paragraph" v-if="isPara">
      <Paragraph :curQue="curQue" :isClause="isClause" :sureSeg="sureSeg" />
    </div>
    <div class="NPC-Book-model">
      <span class="Big-Book-left-text">拼音位置</span>
      <el-radio-group v-model="curQue.pyPosition">
        <el-radio :label="'top'">字上面</el-radio>
        <el-radio :label="'bottom'">字下面</el-radio>
      </el-radio-group>
    </div>
    <!---上传rlc文件-->
    <!-- <div class="NPC-Book-Paragraph" v-if="isClause">
      <el-button
        type="warning"
        size="small"
        @click="uploadLRC"
        v-if="curQue.detail[0].timeList.length == 0"
        >上传lrc文件</el-button
      >
      <div v-else class="lrc-box">
        <span>已有字幕时间节点</span>
        <el-button type="text" @click="editTimeList">去编辑</el-button>
      </div>
    </div> -->
    <!---分句-->
    <div class="NPC-Book-Paragraph" v-if="isClause">
      <Clauseresult :curQue="curQue" :segByWord="segByWord" />
    </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>
        <el-button @click="compareTime('句子')" size="medium"
          >校对句子字幕时间</el-button
        >
        <el-button @click="compareTime('文字')" size="medium"
          >校对文字字幕时间</el-button
        >
      </div>
      <template v-else>
        <el-button v-if="!isWordTime" size="medium" @click="createWordTime"
          >自动生成字幕节点</el-button
        >
        <p v-else>字幕节点生成中...请等待</p>
      </template>
    </div>
    <!---分词-->
    <div class="NPC-Book-Word" v-if="isByWord">
      <Segbyword :curQue="curQue" :paraIndex="paraIndex" :segList="segList" />
    </div>
    <el-dialog title="段落分句字幕打点" :visible.sync="cTVisible" width="30%">
      <Createtimelist ref="createtimelist" :curQue="curQue" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="cTVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveTimeList">保 存</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="校对字幕时间"
      :visible.sync="compareShow"
      width="50%"
      :before-close="handleClose"
      top="0"
    >
      <CompareTime
        :data="compareData"
        :type="compareType"
        :changewordsResultList="changewordsResultList"
      />
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button :loading="compareloading" type="primary" @click="saveCompare"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  segSentences,
  BatchSegContent,
  createPinyin,
  prepareTranscribe,
  getWordTime,
  compareSenTenceTime,
  textCreadMp3,
  getContentFile,
} from "@/api/ajax";
const Base64 = require("js-base64").Base64;
import Upload from "../../common/Upload.vue";
import UploadArt from "../../common/UploadArt.vue";
import ArticleChs from "./components/ArticleChs.vue";
import Paragraph from "./components/ParagraphChs.vue";
import Clauseresult from "./components/ClauseresultChs.vue";
import Segbyword from "./components/SegbywordChs.vue";
import Createtimelist from "./components/CreatetimelistChs.vue";
import CompareTime from "./components/CompareTime.vue";

export default {
  name: "ArticleTemChs",
  components: {
    Upload,
    UploadArt,
    ArticleChs,
    Paragraph,
    Clauseresult,
    Segbyword,
    Createtimelist,
    CompareTime,
  },
  props: ["curQue", "changeCurQue", "tmIndex"],
  data() {
    return {
      imageNumber: 1000,
      mp3Number: 1,
      fileCon: {
        img_list: [],
        mp3_list: [],
      },
      isPara: false,
      isClause: false,
      isByWord: false,
      paraIndex: 0, //段落索引
      cTVisible: false,
      loading: false,
      segList: null,
      data_structure: {
        type: "article_chs",
        name: "课文",
        model: 1,
        pyPosition: "top", //top 拼音在上面；bottom 拼音在下面
        mp3_list: [],
        img_list: [],
        article: "",
        detail: [],
        wordTime: [],
        taskId: "",
        checkList: [1, 2, 3],
      },
      isWordTime: false,
      compareType: "", //校对类型
      compareShow: false,
      compareData: null,
      compareloading: false,
      CreadMp3loading: false,
    };
  },
  computed: {},
  watch: {},
  //方法集合
  methods: {
    // 得到文件流
    getfillLiu() {
      this.loading = true;
      let _this = this;
      return new Promise(function (resolve, reject) {
        if (
          _this.curQue.mp3_list &&
          _this.curQue.mp3_list.length > 0 &&
          _this.curQue.mp3_list[0].id
        ) {
          let Mname = "file_store_manager-GetFileByteBase64Text";
          let id = _this.curQue.mp3_list[0].id
            .replace("[FID##", "")
            .replace("##FID]", "");
          let data = {
            file_id: id,
          };
          getContentFile(Mname, data).then((res) => {
            let taskIddata = {
              fileName: _this.curQue.mp3_list[0].name,
              speechBase64: res.base64_text,
              language: "ch",
            };
            prepareTranscribe(taskIddata).then((res) => {
              _this.$set(_this.curQue, "taskId", res.data.taskId);
              _this.loading = false;
              resolve();
            });
          });
        } else {
          _this.$message.warning("请先上传音频");
        }
      });
    },
    // 根据文章生成MP3
    CreadMp3() {
      let _this = this;
      if (_this.curQue.mp3_list.length > 0) {
        _this.$message.warning("已有音频,请勿重复生成");
        return;
      }
      if (!_this.curQue.article) {
        _this.$message.warning("请先输入内容，在生成音频");
        return;
      }
      _this.CreadMp3loading = true;
      textCreadMp3({
        text: _this.curQue.article,
      }).then((res) => {
        res.data.fileInfo.id = "[FID##" + res.data.fileInfo.file_id + "##FID]";
        res.data.fileInfo.name = res.data.fileInfo.file_name;
        let fileList = [res.data.fileInfo];
        _this.$set(_this.curQue, "mp3_list", fileList);
        _this.CreadMp3loading = false;
        _this.$message.success("生成成功");
      });
    },
    //删除生成的mp3
    delMp3() {
      this.curQue.mp3_list.splice(0, 1);
    },
    // 保存校对
    saveCompare() {
      if (this.compareType == "文字") {
        this.compareloading = false;
        return;
      }
      this.compareloading = true;
      compareSenTenceTime({ matchList: JSON.stringify(this.compareData) })
        .then((res) => {
          console.log(res);
          this.compareloading = false;
          this.curQue.wordTime = res.data.result;
        })
        .catch(() => {
          this.compareloading = false;
        });
    },
    // 校对时间
    compareTime(type) {
      this.compareType = type;
      this.compareData = JSON.parse(JSON.stringify(this.curQue.wordTime));
      this.compareShow = true;
    },
    handleClose() {
      this.compareShow = false;
      this.compareData = null;
      this.compareType = "";
    },
    // 校对每个字的时间
    changewordsResultList(index, item) {
      this.curQue.wordTime[index].wordsResultList = JSON.parse(
        JSON.stringify(item)
      );
    },
    changeMp3(fileList) {
      const articleImgList = JSON.parse(JSON.stringify(fileList));
      const articleImgRes = [];
      articleImgList.forEach((item) => {
        if (item.response) {
          const obj = {
            name: item.name,
            duration: item.response.file_info_list[0].media_duration,
            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));
    },

    changeImage(file) {
      console.log(file);
      if (file.response) {
        const obj = {
          name: file.name,
          url: file.response.file_info_list[0].file_url,
          id: "[FID##" + file.response.file_info_list[0].file_id + "##FID]",
          imgNumber: 0,
        };
        this.curQue.img_list.push(obj);
        this.$forceUpdate();
      }
    },
    forceUpdate() {
      this.$forceUpdate();
    },
    delImage(index) {
      this.curQue.img_list.splice(index, 1);
      this.fileCon.img_list.splice(index, 1);
    },
    changeIsPara() {
      this.isPara = true;
    },
    //生成分句
    sureSeg() {
      let detail = JSON.parse(JSON.stringify(this.curQue.detail));
      let leg = detail.length;
      let flag = false;
      for (let i = 0; i < leg; i++) {
        if (!detail[i].para) {
          flag = true;
          break;
        }
      }
      if (!flag) {
        let textList = [];
        detail.forEach((item) => {
          let str = Base64.encode(item.para);
          textList.push(str);
        });
        this.loading = true;
        let data = {
          textList: textList,
        };
        segSentences(data).then((res) => {
          this.loading = false;
          let result = res.data.result;
          result.forEach((item, index) => {
            this.$set(this.curQue.detail[index], "sentences", item);
          });
          this.isClause = true;
        });
      } else {
        this.$message.warning("段落不能为空");
      }
    },
    changeIsClause(isClause) {
      this.isClause = isClause;
    },
    //生成分词
    segByWord(sentences, paraIndex) {
      console.log(sentences);
      this.loading = true;
      let textList = [];
      sentences.forEach((item) => {
        let str = Base64.encode(item);
        textList.push(str);
      });
      let data = {
        textList: textList,
      };
      BatchSegContent(data).then((res) => {
        this.loading = false;
        let list = res.data.result.list;
        this.$set(this.curQue.detail[paraIndex], "segList", list);
        console.log(this.curQue);
        this.segList = list;
        this.isByWord = true;
        this.paraIndex = paraIndex;
      });
    },
    // 上传音频文件
    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],
          language: "ch",
        };
        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);
        };
      });
    },
    createWordTime() {
      this.getfillLiu().then(() => {
        if (this.curQue.taskId) {
          let verseList = [];
          this.curQue.detail.forEach((item) => {
            verseList = verseList.concat(item.sentences);
          });
          if (verseList.length > 0) {
            this.isWordTime = true;
            let data = {
              taskId: this.curQue.taskId,
              verseList: JSON.stringify(verseList),
              matchType: "chinese",
              language: "ch",
            };
            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", []);
    },
    uploadLRC() {
      this.cTVisible = true;
    },
    //保存字幕节点
    saveTimeList() {
      this.cTVisible = false;
      let detail = JSON.parse(JSON.stringify(this.$refs.createtimelist.detail));
      let detailRes = detail.map((item) => {
        let timeList = item.time_str.split("\n");
        item.timeList = this.handleTimeReg(timeList);
        return item;
      });
      this.curQue.detail = JSON.parse(JSON.stringify(detailRes));
      console.log(this.curQue.detail);
    },

    handleTimeReg(list) {
      list = list.map((item) => {
        let regArr = item.split("]");
        let reg = regArr[0];
        item = reg.replace("[", "");
        return item;
      });
      return list;
    },
    //点击字幕节点
    editTimeList() {
      this.cTVisible = true;
    },
    initCurQueData() {
      let res_data = JSON.parse(JSON.stringify(this.data_structure));
      this.changeCurQue(res_data);
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    console.log("文章编辑");
    console.log(this.curQue);
    if (this.curQue) {
      if (!this.curQue.hasOwnProperty("checkList")) {
        this.$set(this.curQue, "checkList", [1, 2, 3]);
      }
      if (!this.curQue.taskId) {
        this.curQue.taskId = "";
      }
      if (this.curQue.detail[0].para) {
        this.isPara = true;
      }
      if (this.curQue.detail[0].sentences.length > 0) {
        this.isClause = true;
      }
      if (this.curQue.detail[0].seg_words.length > 0) {
        this.isByWord = true;
      }
      if (!this.curQue.img_list) {
        this.curQue.img_list = [];
      }
      if (!this.curQue.mp3_list) {
        this.curQue.mp3_list = [];
      }
      this.fileCon.img_list = JSON.parse(JSON.stringify(this.curQue.img_list));
      let mp3_list = JSON.parse(JSON.stringify(this.curQue.mp3_list));
      this.fileCon.mp3_list = mp3_list.filter((item) => item.source !== "tts");
    } else {
      this.initCurQueData();
    }
  },
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style lang='scss' scoped>
//@import url(); 引入公共css类
.create_mp3_list {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  > span {
    font-size: 16px;
    font-weight: bold;
    margin-right: 10px;
  }
  > img {
    width: 24px;
    height: 24px;
    cursor: pointer;
  }
}
p {
  margin: 0;
  padding: 0;
}
.uploadArt_list {
  border: 1px #ccc solid;
  border-bottom: 0;
  margin-top: 10px;
  > li {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    border-bottom: 1px #ccc solid;

    > span {
      width: 320px;
      word-wrap: break-word;
      font-size: 14px;
      color: rgb(112, 110, 110);
      border-right: 1px #ccc solid;
      padding: 5px 10px;
    }
    > p {
      flex: 1;
      padding: 5px 10px;
    }
    .imgNumber {
      width: 80px;
    }
    .del-close {
      width: 24px;
      height: 24px;
      cursor: pointer;
      margin-right: 10px;
    }
  }
}
.NPC-Book-Article {
  > div {
    margin-bottom: 20px;
  }
}
.NPC-Book-model {
  display: flex;
  justify-content: flex-start;
  align-items: center;

  > span {
    margin: 0;
  }
}
.lrc-box {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  > span {
    font-size: 14px;
    margin-right: 16px;
  }
}
</style>