<!--  -->
<template>
  <div class="Big-Book-prev-Textdes NewWordShow" v-if="curQue">
    <h2 v-if="curQue.title">{{ curQue.title }}</h2>
    <div class="item-box">
      <div class="item-pre" v-for="(item, index) in curQue.option" :key="index">
        <div class="item" style="margin-right: 20px">
          <p v-if="item.pinyin || item.en">
            <span>{{ item.pinyin }}</span>
            <span>{{ item.en }}</span>
          </p>
          <div class="con-box">
            <template v-if="item.imgOrText == 'text'">
              <template v-if="item.con">
                <div
                  :key="conindex"
                  class="strockplay-newWord"
                  v-for="(conItem, conindex) in item.con"
                  @click="writeWord(conItem, item.pinyin)"
                >
                  <Strockplayredline
                    :Book_text="conItem"
                    :playStorkes="true"
                    :targetDiv="
                      'bwcHanziIntp' + index + conItem + conindex + indexStr
                    "
                  />
                  <div
                    class="bwc-line"
                    v-if="conindex < item.con.length - 1"
                  ></div>
                </div>
              </template>
              <template v-else>
                <div class="blank-item" @click="freeWrite('', index, 0)">
                  <img :src="freeImg[index][0]" v-if="freeImg[index][0]" />
                </div>
              </template>
            </template>
            <template v-else>
              <div
                class="img-box"
                v-for="(imgItem, imgIndex) in item.img_list"
                :key="imgIndex"
                @click="freeWrite(imgItem.url, imgIndex, 0)"
              >
                <el-image :src="imgItem.url" fit="scale-down" class="img_url">
                  <div slot="placeholder" class="image-slot">
                    <img src="../../../assets/common/icon-imgloading.png" />
                  </div>
                </el-image>
              </div>
            </template>
          </div>
        </div>
        <template v-if="item.type && item.type.indexOf('lm') > -1">
          <div
            class="con-box"
            v-for="(items, indexs) in item.imgarr"
            :key="indexs"
          >
            <div
              class="strockplay-newWord"
              @click="freeWrite(items, index, indexs)"
            >
              <!-- <div
                @click.stop="playHanzi(index, indexs, items)"
                :class="[
                  'strock-play-box',
                  themeColor == 'green'
                    ? 'green-border'
                    : themeColor == 'red'
                    ? 'red-border'
                    : themeColor == 'brown'
                    ? 'brown-border'
                    : 'red-border',
                ]"
              ></div> -->
              <img
                v-if="!playStatus && items && items.strokes_image_url"
                :src="items.strokes_image_url"
                alt=""
              />
              <!-- <FreeWriteQP
                :id="'cans' + index + indexs"
                :ref="'cans'"
                :height="256"
                :width="256"
              /> -->
            </div>
          </div>
        </template>
      </div>
    </div>
    <div class="practiceBox practiceBoxStrock" v-if="isPraShow">
      <Practice
        :changePraShow="changePraShow"
        :cur="curData"
        :themeColor="themeColor"
      />
    </div>
    <div class="practiceBox practiceBoxStrock" v-if="ifFreeShow">
      <FreewriteLettle
        :changePraShow="changePraShow"
        ref="freePaint"
        :themeColor="themeColor"
        :currentTreeID="currentTreeID"
        :currentHz="currentHz"
        :currenHzData="currenHzData"
        :rowIndex="activeIndex"
        :colIndex="activeColIndex"
        :closeifFreeShow="closeifFreeShow"
        :TaskModel="TaskModel"
        @changeCurQue="changeCurQue"
        @deleteWriteRecord="deleteWriteRecord"
      />
    </div>
  </div>
</template>

<script>
import Strockplayredline from "../preview/components/Strockplayredline.vue";
import Practice from "../preview/components/Practice.vue";
import FreewriteLettle from "../preview/components/FreewriteLettle.vue";
import { getContentFile, LearnWebSI } from "../../../api/ajax";
import FreeWriteQP from "./components/FreeWriteQP.vue";
export default {
  components: { Strockplayredline, Practice, FreewriteLettle, FreeWriteQP },
  props: ["curQue", "themeColor", "indexStr", "currentTreeID", "TaskModel"],
  data() {
    return {
      isPraShow: false,
      curData: null,
      ifFreeShow: false,
      freeImg: [],
      activeIndex: null,
      activeColIndex: null,
      currentHz: "", //当前汉字
      currenHzData: null, //当前汉字数据
      playStatus: false, //播放状态
      userAnswer: {
        writeModel: {}, //生词/取词模式
      },
    };
  },
  computed: {},
  watch: {},
  //方法集合
  methods: {
    playHanzi(rowIndex, colIndex, item) {
      if (this.playStatus) {
        this.$message.warning("请等待播放完成");
        return;
      }
      this.playStatus = true;
      console.log(this.$refs.cans);
      let ref = null;
      this.$refs.cans.forEach((item) => {
        if (item.$el.id == `cans${rowIndex}${colIndex}`) {
          ref = item;
        }
      });
      ref.reset();

      let c = document.getElementById(`cans${rowIndex}${colIndex}`);
      let cxt = document
        .getElementById(`cans${rowIndex}${colIndex}`)
        .getContext("2d");
      cxt.clearRect(0, 0, c.width, c.height);
      let history = item.history;
      const len = item.history.length;
      let i = 0;
      const runner = () => {
        i++;
        if (i < len) {
          ref.draw(null, history[i][0], history[i][1]);
          requestAnimationFrame(runner);
        } else {
          console.log("播放完成");
          this.playStatus = false;
        }
      };
      requestAnimationFrame(runner);
    },
    // 处理数据
    handleData() {
      let _this = this;
      let MethodName = "teaching-practice_manager-GetMyHZHandwrittenRecordList";
      this.curQue.option.forEach((item, index) => {
        let data = {
          courseware_id: this.currentTreeID,
          hz: item.con,
          search_scope: 1,
          count_limit: 6,
        };
        LearnWebSI(MethodName, data).then((res) => {
          let imgarr = res.hz_handwritten_record_list;
          let newimgarr = imgarr.map((it) => {
            it.history = JSON.parse(it.strokes_content);
            return it;
          });
          if (newimgarr.length < 6) {
            let num = 6 - newimgarr.length;
            for (let i = 0; i < num; i++) {
              newimgarr.push({});
            }
          }
          item.imgarr = newimgarr;
          this.$forceUpdate();
        });
      });
    },
    // 处理数据
    handleAnswerData() {
      let _this = this;
      _this.curQue.option.forEach((item, index) => {
        let con = item.con;
        let arr = [];
        if (
          _this.curQue.Bookanswer.writeModel &&
          _this.curQue.Bookanswer.writeModel[con]
        ) {
          arr = _this.curQue.Bookanswer.writeModel[con].map((it) => {
            if (it && it.strokes_content) {
              it.history = JSON.parse(it.strokes_content);
            }

            return it;
          });
        } else {
          arr = [null, null, null, null, null, null];
        }
        item.imgarr = arr;
      });
      console.log(_this.curQue.option);
    },
    changePraShow() {
      this.isPraShow = false;
      this.ifFreeShow = false;
      // this.freeImg[this.activeIndex][this.activeColIndex] =
      //   this.$refs.freePaint.imgSrc;
    },
    async writeWord(words, pinyin) {
      this.activeIndex = null;
      this.activeColIndex = null;
      const MethodName = "tool-ChineseSCConvert";
      const data = {
        text: words,
        swap_mode: "S-C",
      };
      let TChinese = await getContentFile(MethodName, data);
      this.curData = {
        stem: [
          {
            con: words ? words : "",
            pinyin: pinyin && pinyin ? pinyin : "",
            mp3_url: "",
            TChinese: TChinese.text,
          },
        ],
      };
      this.isPraShow = true;
    },
    closeifFreeShow(data, rowIndex, colIndex) {
      this.curQue.option[rowIndex].imgarr[colIndex] = data;
      this.ifFreeShow = false;
      this.freeWrite(data, rowIndex, colIndex);
      this.$forceUpdate();
    },
    freeWrite(imgUrl, index, indexs) {
      let _this = this;
      if (_this.TaskModel == "ANSWER" && !imgUrl) {
        return;
      }
      _this.ifFreeShow = true;
      _this.activeIndex = index;
      _this.activeColIndex = indexs;
      _this.currentHz = _this.curQue.option[index].con;
      _this.currenHzData = imgUrl;
      //console.log(this.currenHzData);
    },
    //删除记录
    deleteWriteRecord(rowIndex, colIndex) {
      this.$set(this.curQue.option[rowIndex].imgarr, colIndex, {});
    },
    changeCurQue(answer, colIndex) {
      if (answer) {
        let writeModel = this.curQue.Bookanswer.writeModel;
        let hz = answer.hz;
        if (writeModel.hasOwnProperty(hz)) {
          writeModel[hz][colIndex] = answer;
        } else {
          writeModel[hz] = [];
          for (let i = 0; i < 6; i++) {
            writeModel[hz].push(null);
          }
          writeModel[hz][colIndex] = answer;
        }
        console.log(this.curQue.Bookanswer);
      }
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    let _this = this;
    if (!_this.curQue.Bookanswer) {
      _this.curQue.Bookanswer = JSON.parse(JSON.stringify(_this.userAnswer));
    }
    if (_this.TaskModel != "ANSWER") {
      _this.handleData();
    } else {
      _this.handleAnswerData();
    }
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style lang='scss' scoped>
//@import url(); 引入公共css类
.NewWordShow {
  width: 100%;
  margin-bottom: 24px;
  h2 {
    margin: 0 0 8px 0;
    font-weight: 500;
    font-size: 16px;
    line-height: 24px;
    color: #000000;
  }
  .item-box {
    padding-bottom: 8px;
    padding: 0 4px;
    background: #f7f7f7;
    border: 1px solid rgba(0, 0, 0, 0.1);
    border-radius: 8px;
    .item-pre {
      display: flex;
      flex-flow: wrap;
      align-items: flex-end;
      padding: 9px 20px;
    }
    .item {
      box-sizing: border-box;
      // width: 66px;
      cursor: pointer;
      > p {
        white-space: nowrap;
        :nth-child(1) {
          font-family: "GB-PINYINOK-B";
        }
        :nth-child(2) {
          font-family: "robot";
          margin-left: 4px;
        }
        color: #2c2c2c;
        font-size: 14px;
        line-height: 130%;
        text-align: center;
        margin: 0 0 8px 0;
      }
      .strockplay {
        display: flex;
        justify-content: center;
        align-items: center;
        position: relative;
        width: 64px;
        height: 64px;
      }
      .strockplayRedInner {
        width: 64px;
        height: 64px;
      }
      .bwc-line {
        width: 1px;
        height: 62px;
        background: #de4444;
      }
    }
    .con-box {
      width: 66px;
      display: flex;
      border: 1px solid #de4444;
      border-radius: 8px;
      overflow: hidden;
      margin: 0 auto;
      .img-box {
        background: #fff url("../../../assets/NPC/chinaTianRed.png") center
          no-repeat;
        background-size: cover;
        .img_url {
          width: 64px;
          height: 64px;
        }
      }
    }
    .strockplay-newWord {
      width: 64px;
      height: 64px;
      background: #fff url("../../../assets/NPC/chinaTianRed.png") center
        no-repeat;
      background-size: cover;
      position: relative;
      .strock-play-box {
        position: absolute;
        cursor: pointer;
      }
      canvas {
        width: 64px;
        height: 64px;
      }
      img {
        width: 100%;
        height: 100%;
      }
    }
  }
  .practiceBox {
    position: fixed;
    left: 0;
    top: 0;
    z-index: 1000;
    width: 100%;
    height: 100vh;
    background: rgba(0, 0, 0, 0.19);
    box-sizing: border-box;
    overflow: hidden;
    overflow-y: auto;
    &.practiceBoxStrock {
      display: flex;
      justify-content: center;
      align-items: center;
      padding-top: 0px;
    }
  }
}
.NPC-Big-Book-preview-brown {
  .NewWordShow {
    .item-box {
      .item {
        .bwc-line {
          background: #bf875e;
        }
      }
      .con-box {
        border: 1px solid #bf875e;
        .img-box {
          background: #fff url("../../../assets/NPC/chinaTianYellow.png") center
            no-repeat;
          background-size: cover;
        }
        .blank-item {
          background: #fff url("../../../assets/NPC/chinaTianYellow.png") center
            no-repeat;
          background-size: cover;
        }
      }
    }
  }
}
.NPC-Big-Book-preview-green {
  .NewWordShow {
    .item-box {
      .item {
        .bwc-line {
          background: #24b99e;
        }
      }
      .con-box {
        border: 1px solid #24b99e;
        .img-box {
          background: #fff url("../../../assets/NPC/chinaTianGreen.png") center
            no-repeat;
          background-size: cover;
        }
        .blank-item {
          background: #fff url("../../../assets/NPC/chinaTianGreen.png") center
            no-repeat;
          background-size: cover;
        }
      }
    }
  }
}
</style>
<style lang="scss">
.NPC-Big-Book-preview-red {
  .strockplay-newWord {
    .strock-play-box {
      width: 16px !important;
      height: 16px !important;
      right: -1px;
      top: 0;
      background: url("../../../assets/NPC/strock-play-red-click.png") center
        no-repeat;
      background-size: cover;
    }
    .character-target-div {
      // background-color: initial;
    }
  }
}
.NPC-Big-Book-preview-green {
  .strockplay-newWord {
    .strock-play-box {
      width: 16px !important;
      height: 16px !important;
      right: -1px;
      top: 0;
      background: url("../../../assets/NPC/strock-play-green-click.png") center
        no-repeat;
      background-size: cover;
    }
    .character-target-div {
      // background-color: initial;
    }
  }
}
.NPC-Big-Book-preview-brown {
  .strockplay-newWord {
    .strock-play-box {
      width: 16px !important;
      height: 16px !important;
      right: -1px;
      top: 0;
      background: url("../../../assets/NPC/strock-play-yellow-click.png") center
        no-repeat;
      background-size: cover;
    }
    .character-target-div {
      // background-color: initial;
    }
  }
}
</style>