<!--  -->
<template>
  <div class="Big-Book-Single" v-if="curQue">
    <div class="Big-Book-Single-content" style="margin-top: 20px">
      <div class="adult-book-input-item">
        <span class="adult-book-lable">标题：</span>           
        <el-input
          style="width: 300px"
          placeholder="请输入标题"
          v-model="curQue.title"
          @blur="onBlur(curQue, 'title')"
          class="adult-book-input"
          :autosize="{ minRows: 2 }"
          maxlength="500"
          show-word-limit
        ></el-input>
      </div>
      <div class="adult-book-input-item">
        <span class="adult-book-lable">标题颜色：</span>  
        <div class="adult-book-main">
          <el-radio-group v-model="curQue.titleBg">
            <el-radio label="white">白色</el-radio>
            <el-radio label="themeColor">书的主题色</el-radio> </el-radio-group
          >  
        </div>
      </div>
      <div class="adult-book-input-item">
        <span class="adult-book-lable">详细信息：</span>  
        <div class="adult-book-main">
          <el-radio-group v-model="curQue.isInfor">
            <el-radio :label="true">有</el-radio>
            <el-radio :label="false">没有</el-radio> </el-radio-group
          >  
        </div>
              
      </div>
      <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>
      <div class="adult-book-input-item">
        <span class="adult-book-lable">题目lrc：</span>
        <Upload
          :changeFillId="changeLrc"
          :datafileList="curQue.lrc_list"
          :filleNumber="mp3Number"
          :uploadType="'lrc'"
        />
      </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 class="adult-book-input-item">
        <span class="adult-book-lable"></span>
        <el-button
          type="primary"
          size="small"
          class="distribution"
          @click="parseLrcFile"
        >
          分配时间
        </el-button>
      </div>

      <div
        class="Big-Book-main"
        v-for="(item, index) in curQue.option"
        :key="'newWord' + index"
        style="border-bottom: 1px #ccc solid; margin-bottom: 20px"
      >
        <div
          class="Big-Book-main-inner"
          v-for="(sItem, sIndex) in item"
          :key="'newWord_' + sIndex"
        >
          <NewordPhraseModule
            :curQue="curQue"
            :curQueItem="sItem"
            :index="index"
            :sIndex="sIndex"
            :type="curQue.type"
            :deleteGroup="deleteGroup"
          />
        </div>
        <div class="addoption addoption2" @click="saddoption(item)">
          添加字词
        </div>
        <el-button size="mini" type="danger" @click="delsItem(index)">
          删除本组
        </el-button>
      </div>
      <div class="addoption" @click="addoption">添加一组</div>
    </div>
  </div>
</template>

<script>
import Inputmodule from "../common/Inputmodule.vue";
import NewordPhraseModule from "../common/NewordPhraseModule.vue";
import { getWordTime, getContentFile, prepareTranscribe } from "@/api/ajax";
import Upload from "../common/Upload";
export default {
  name: "Single",
  props: ["curQue", "changeCurQue"],
  components: {
    Inputmodule,
    NewordPhraseModule,
    Upload,
  },
  data() {
    return {
      mp3Number: 1,
      isWordTime: false,
      data_structure: {
        type: "NewWord_chs",
        name: "生词",
        title: "",
        isInfor: true,
        titleBg: "themeColor", //标题背景颜色
        mp3_list: [],
        lrc_list: [],
        taskId: [],
        wordTime: null,
        option: [
          [
            {
              new_word: "",
              cixing: "", //词性
              definition_list: [""], //需要增加词性
              pinyin: "",
              img_list: [],
              mp3_list: [],
              pinyin_site: "first", //拼音位置
              motif_color: false, //主题色
            },
          ],
        ],
      },
    };
  },
  computed: {},
  watch: {},
  //方法集合
  methods: {
    onBlur(item, field) {
      item[field] = item[field] ? item[field].trim() : "";
    },
    addoption() {
      let leg = this.curQue.option.length;
      let last = this.curQue.option[leg - 1];
      let res_data = JSON.parse(JSON.stringify(this.data_structure));
      let obj = res_data.option[0];
      obj.index = this.curQue.option.push(obj);
    },
    deleteGroup(index, sIndex) {
      if (this.curQue.option[0].length == 1) {
        this.$message.warning("至少剩余1个，不能全部删除");
        return;
      }
      this.curQue.option[index].splice(sIndex, 1);
    },
    saddoption(item) {
      let con = {
        new_word: "",
        cixing: "", //词性
        definition_list: [""], //需要增加词性
        pinyin: "",
        img_list: [],
        mp3_list: [],
      };
      item.push(con);
    },
    delsItem(index) {
      this.curQue.option.splice(index, 1);
    },
    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));
    },
    parseLrcFile() {
      let lrcList = this.curQue.lrc_list;
      if (lrcList.length === 0) {
        if (this.curQue.wordTime.length > 0) {
          this.handleNewwordList();
        } else {
          this.$message.warning("请先上传lrc文件或自动生成字幕节点");
        }
      } else {
        getContentFile("tool-ParseLRCFile", {
          content_type: "FILE",
          file_id: this.curQue.lrc_list[0].file_id,
        }).then(({ lrc_list }) => {
          let lrc_list_res = [];
          lrc_list.forEach((item) => {
            let obj = {
              bg: item.begin_time,
              ed: item.end_time,
            };
            lrc_list_res.push(obj);
          });
          this.handleNewwordList();
          this.curQue.wordTime = lrc_list_res;
        });
      }
    },
    handleNewwordList() {
      let index = 0;
      // let option = JSO
      this.curQue.option.map((item) => {
        item.map((sItem) => {
          this.$set(sItem, "index", index);
          index++;
          return sItem;
        });
        return item;
      });
      console.log(this.curQue.option);
    },
    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() {
      if (this.curQue.taskId) {
        let verseList = [];
        this.curQue.option.forEach((item, index) => {
          item.forEach((sItem, sIndex) => {
            verseList.push(sItem.new_word);
          });
        });
        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", []);
    },
    // 上传音频文件
    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);
        });
      });
    },
    changeLrc(fileList) {
      let lrc_list = [];
      fileList.forEach(({ response, name }) => {
        if (response) {
          let fileList = response.file_info_list[0];
          lrc_list.push({
            name,
            duration: fileList.media_duration,
            url: fileList.file_url,
            id: "[FID##" + fileList.file_id + "##FID]",
            file_id: fileList.file_id,
          });
        }
      });
      this.curQue.lrc_list = lrc_list;
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    if (!this.curQue) {
      let res_data = JSON.parse(JSON.stringify(this.data_structure));
      this.changeCurQue(res_data);
    } else {
      if (!this.curQue.hasOwnProperty("isInfor")) {
        this.$set(this.curQue, "isInfor", true);
      }
      if (!this.curQue.hasOwnProperty("titleBg")) {
        this.$set(this.curQue, "titleBg", "themeColor");
      }
      if (!this.curQue.hasOwnProperty("mp3_list")) {
        this.$set(this.curQue, "mp3_list", []);
      }
      if (!this.curQue.hasOwnProperty("lrc_list")) {
        this.$set(this.curQue, "lrc_list", []);
      }
      if (!this.curQue.hasOwnProperty("taskId")) {
        this.$set(this.curQue, "taskId", "");
      }
      if (!this.curQue.hasOwnProperty("wordTime")) {
        this.$set(this.curQue, "wordTime", null);
      }

      // let data = JSON.parse(JSON.stringify(this.curQue));
      this.curQue.option.forEach((item) => {
        if (!item[0].pinyin_site) {
          item[0].pinyin_site = "first"; //拼音位置
        }
        if (!item[0].motif_color) {
          item[0].motif_color = false; //主题色
        }
      });
      // this.curQue = JSON.parse(JSON.stringify(data));
    }
  },
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style lang='scss' scope>
//@import url(); 引入公共css类
.Big-Book-Single {
  &-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 {
      background: rgba(230, 229, 229, 0.3);
      border: 1px #999 solid;
      border-radius: 8px;
      padding: 20px;
      > div {
        margin-bottom: 10px;
        &.Big-Book-pinyin {
          display: flex;
          justify-content: flex-start;
          align-items: center;
        }
      }
      .Big-Book-main-inner {
      }
    }
  }
  .addoption {
    width: 565px;
    height: 40px;
    left: 40px;
    top: 304px;
    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;
    &.addoption2 {
      width: 200px;
    }
  }
  .Big-Book-con {
    padding-bottom: 6px;
    border-bottom: 1px dashed rgba(0, 0, 0, 0.15);
  }
}
</style>
<style lang="scss">
</style>