<template>
  <div class="cread" v-loading="loading">
    <Header :projectShow="true" />
    <div class="main" v-if="!isPreview">
      <div class="from">
        <div class="type">
          <div :class="[typeIndex == 0 ? 'sele' : '']" @click="cutType(0)">
            字模式
          </div>
          <div :class="[typeIndex == 1 ? 'sele' : '']" @click="cutType(1)">
            句模式
          </div>
        </div>
        <div class="from_main">
          <div class="left">
            <el-input
              type="textarea"
              :placeholder="
                typeIndex == 0 ? '每行输入一个字' : '每行输入一个句子/词汇'
              "
              v-model="from.content"
              maxlength="100"
              show-word-limit
            >
            </el-input>
            <div class="submit">
              <span @click="creadEvent">生成</span>
            </div>
          </div>
          <div class="right">
            <div class="title">基础配置：</div>
            <div class="dv">
              <el-radio-group v-model="from.BoxbgType">
                <el-radio :label="0">田字格</el-radio>
                <el-radio :label="1">米字格</el-radio>
                <el-radio :label="2">空格</el-radio>
              </el-radio-group>
              <span class="title">文字大小</span>
              <el-select
                v-model="from.fontSize"
                placeholder=""
                style="width: 60px"
              >
                <el-option label="大" value="big"> </el-option>
                <el-option label="中" value="center"> </el-option>
                <el-option label="小" value="little"> </el-option>
              </el-select>
            </div>
            <div class="dv">
              <span class="title">边框颜色</span>
              <el-color-picker
                v-model="from.borderColor"
                style="margin-right: 16px"
              ></el-color-picker>
              <span class="title">文字颜色</span>
              <el-color-picker v-model="from.fontColor"></el-color-picker>
            </div>
            <div class="title" style="margin-top: 24px">功能配置：</div>
            <div class="dv">
              <el-switch
                active-color="#424242"
                v-model="from.playStorkes"
                active-text="笔顺动画"
                style="margin-right: 40px"
              >
              </el-switch>
              <template v-if="typeIndex == 0">
                <el-switch
                  active-color="#424242"
                  v-model="from.StorkesUnfold"
                  active-text="笔顺展开"
                >
                </el-switch>
              </template>
            </div>
            <div class="title" style="margin-top: 24px">书写配置：</div>
            <div class="dv">
              <div style="margin-right: 16px">
                <span class="title">书写格</span>
                <el-input
                  style="width: 60px; text-align: center"
                  v-model="from.writeBoxNumber"
                  onkeyup="value=value.replace(/^0+(\d)|[^\d]+/g,'')"
                  class="numbre-input"
                ></el-input>
                <span style="margin-left: 8px">{{
                  typeIndex == 0 ? "行" : "句"
                }}</span>
              </div>
              <div style="margin-right: 16px">
                <span class="title">描红</span>
                <el-input
                  style="width: 60px; text-align: center"
                  v-model="from.miaoRedBoxNumber"
                  class="numbre-input"
                  onkeyup="value=value.replace(/^0+(\d)|[^\d]+/g,'')"
                ></el-input>
                <span style="margin-left: 8px">{{
                  typeIndex == 0 ? "格" : "句"
                }}</span>
              </div>
              <div>
                <span class="title">文末空行</span>
                <el-input
                  style="width: 60px; text-align: center"
                  v-model="from.lastNullrow"
                  onkeyup="value=value.replace(/^0+(\d)|[^\d]+/g,'')"
                  class="numbre-input"
                ></el-input>
                <span style="margin-left: 8px">行</span>
              </div>
            </div>
            <div class="dv">
              <span class="title">描红底色</span>
              <el-color-picker
                v-model="from.miaoRedBgcolor"
                style="margin-right: 16px"
              ></el-color-picker>
              <span class="title">书写颜色</span>
              <el-color-picker v-model="from.writeColor"></el-color-picker>
            </div>
          </div>
        </div>
      </div>
      <div class="operation" v-if="isCread">
        <div @click="saveEvent">
          <img src="../../assets/teacherdev/word-save.png" alt="" /> 保存
        </div>
        <div @click="previewEvent">
          <img src="../../assets/teacherdev/word-eyes.png" alt="" /> 预览
        </div>
        <div @click="download2('pdfDom')">
          <img src="../../assets/teacherdev/word-download.png" alt="" /> 下载
        </div>
      </div>
      <div class="word_main" v-if="writeTableData && writeTableData.result">
        <div
          class="word_main_table"
          v-for="(itemT, indexT) in writeTableData.result"
          :key="indexT"
        >
          <writeTable
            :type="typeIndex"
            :dataConfig="writeTableData"
            :data="itemT"
            :pageNumber="indexT + 1"
            :totalNumber="writeTableData.result.length"
          />
        </div>
      </div>
    </div>
    <div class="preview_dv" v-if="isPreview">
      <img
        class="close"
        src="../../assets/teacherdev/creadCad-close.png"
        alt=""
        @click="closepreviewEvent"
      />
      <div class="preview_main">
        <img
          class="left"
          src="../../assets/teacherdev/creadCad-left.png"
          alt=""
          @click="changepreviewIndex('remove')"
        />
        <div class="word_main">
          <div class="word_main_table">
            <writeTable
              :type="typeIndex"
              :dataConfig="writeTableData"
              :data="writeTableData.result[previewIndex]"
              :pageNumber="previewIndex + 1"
              :totalNumber="writeTableData.result.length"
            />
          </div>
        </div>
        <img
          class="right"
          src="../../assets/teacherdev/creadCad-right.png"
          alt=""
          @click="changepreviewIndex('add')"
        />
      </div>
    </div>
    <el-dialog
      title="保存为"
      :visible.sync="saveShow"
      width="30%"
      :before-close="handleClose"
      :modal="false"
    >
      <el-input placeholder="请输入" v-model="saveName"> </el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其它文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》from ‘《组件路径》';
import Header from "@/components/Header";
import { getLogin, LearnWebSI } from "@/api/api";
import writeTable from "./writeTable.vue";
import html2canvas from "html2canvas";
import { jsPDF } from "jspdf";
import canvg from "canvg";

import FileSaver from "file-saver";
import htmlDocx from "html-docx-js/dist/html-docx";
export default {
  //import引入的组件需要注入到对象中才能使用
  components: {
    Header,
    writeTable,
  },
  props: {},
  data() {
    //这里存放数据
    return {
      saveName: "",
      typeIndex: 0,
      from: {
        content: "",
        BoxbgType: 0,
        fontSize: "center",
        playStorkes: true,
        StorkesUnfold: true,
        writeBoxNumber: "0", //书写行
        miaoRedBoxNumber: "0", //描红格
        lastNullrow: "0", //文本末空行数
        miaoRedBgcolor: "#E1E1E1", //描红底色
        writeColor: "#000000", //书写颜色
        borderColor: "#D65353", //边框颜色
        fontColor: "#000000", //文字颜色
      },
      loading: false,
      writeTableData: null,
      isCread: false,
      isPreview: false,
      previewIndex: 0,
      htmlTitle: "1",
      saveShow: false,
      writetableShow: true,
    };
  },
  //计算属性 类似于data概念
  computed: {},
  //监控data中数据变化
  watch: {},
  //方法集合
  methods: {
    saveEvent() {
      this.saveShow = true;
    },
    handleClose() {
      this.saveShow = false;
    },
    // 保存
    save() {
      this.loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      if (this.$route.query.id) {
        // 编辑
        let Mname = "tr_tool-wsc_manager-UpdateMyWordSentenceCard";
        LearnWebSI(Mname, {
          id: this.$route.query.id,
          name: this.saveName,
          type: this.typeIndex == 0 ? "WORD" : "SENTENCE",
          text: this.from.content,
          content: JSON.stringify(this.writeTableData),
        })
          .then((res) => {
            this.loading.close();
            this.loading = false;
            this.saveShow = false;
            this.$message.success("保存成功");
          })
          .catch((res) => {
            this.loading.close();
            this.loading = false;
          });
      } else {
        // 新建
        let Mname = "tr_tool-wsc_manager-CreateMyWordSentenceCard";
        LearnWebSI(Mname, {
          name: this.saveName,
          type: this.typeIndex == 0 ? "WORD" : "SENTENCE",
          text: this.from.content,
          content: JSON.stringify(this.writeTableData),
        })
          .then((res) => {
            this.$router.replace({
              path: "/wordcard/cread",
              query: {
                id: res.id,
              },
            });
            this.loading.close();
            this.loading = false;
            this.saveShow = false;
            this.$message.success("保存成功");
          })
          .catch((res) => {
            this.loading.close();
            this.loading = false;
          });
      }
    },
    download(dom) {
      let content = document.getElementById(dom);
      content = content ? content : null;
      // 条件判断是否打印
      if (!content) {
        alert("打印失败，请重新操作");
        return false;
      }
      // 开始打印
      console.log(content);
      var contentWidth = content.width;
      var contentHeight = content.height;
      //以下是对svg的处理
      var nodesToRecover = [];
      var nodesToRemove = [];
      var svgElem = $("#pdfDom").find("svg-icon"); //divReport为需要截取成图片的dom的id
      console.log(svgElem);
      svgElem.each(function (index, node) {
        var parentNode = node.parentNode;
        var svg = node.outerHTML.trim();
        var canvas2 = document.createElement("canvas");
        canvg(canvas2, svg);
        if (node.style.position) {
          canvas2.style.position += node.style.position;
          canvas2.style.left += node.style.left;
          canvas2.style.top += node.style.top;
        }
        nodesToRecover.push({
          parent: parentNode,
          child: node,
        });
        parentNode.removeChild(node);
        nodesToRemove.push({
          parent: parentNode,
          child: canvas2,
        });
        parentNode.appendChild(canvas2);
      });
      var canvas = document.createElement("canvas");
      canvas.width = contentWidth;
      canvas.height = contentHeight;
      var context = canvas.getContext("2d");
      html2canvas(content, {
        allowTaint: true,
        scale: 2, // 提升画面质量，但是会增加文件大小
      }).then(function (canvas) {
        var pdfWidth = canvas.width;
        var pdfHeight = canvas.height;
        var pageHeight = (pdfWidth / 592.28) * 841.89;
        var leftHeight = pdfHeight;
        var position = 0;
        var imgWidth = 595.28;
        var imgHeight = (595.28 / pdfWidth) * pdfHeight;
        var pageData = canvas.toDataURL("img/jpeg", 1.0);
        var pdf = new jsPDF("", "pt", "a4");
        // 判断打印dom高度是否需要分页，如果需要进行分页处理
        if (leftHeight < pageHeight) {
          pdf.addImage(pageData, "JPEG", 0, 0, imgWidth, imgHeight);
        } else {
          while (leftHeight > 0) {
            pdf.addImage(pageData, "JPEG", 0, position, imgWidth, imgHeight);
            leftHeight -= pageHeight;
            position -= 841.89;
            if (leftHeight > 0) {
              pdf.addPage();
            }
          }
        }
        pdf.save("案例.pdf");
      });
    },
    download2() {
      this.$nextTick(() => {
        if (this.writeTableData) {
          let str = JSON.stringify(this.writeTableData);
          localStorage.setItem("writeTableData", str);
          this.$router.replace("/wordcard/print");
        }
      });

      // var printBox = document.getElementById("pdfDom");
      // // var printBox = document.getElementsByClassName("pdfDom")[0];
      // //拿到打印的区域的html内容
      // var newContent = printBox.innerHTML;
      // //将旧的页面储存起来，当打印完成后返给给页面。
      // var oldContent = document.body.innerHTML;
      // //赋值给body
      // document.body.innerHTML = newContent;
      // //执行window.print打印功能
      // window.print();
      // // 重新加载页面，以刷新数据。以防打印完之后，页面不能操作的问题
      // window.location.reload();
      // document.body.innerHTML = oldContent;
      // return false;
    },
    changepreviewIndex(type) {
      if (type == "add") {
        if (this.previewIndex == this.writeTableData.result.length - 1) {
          this.$message.warning("当前已经是最后一页");
          return;
        }
        this.previewIndex++;
      } else {
        if (this.previewIndex == 0) {
          this.$message.warning("当前已经是第一页");
          return;
        }
        this.previewIndex--;
      }
      this.$forceUpdate();
    },
    // 预览
    previewEvent() {
      this.previewIndex = 0;
      this.isPreview = true;
    },
    // 关闭预览
    closepreviewEvent() {
      this.isPreview = false;
    },
    // 切换类型
    cutType(index) {
      this.typeIndex = index;
      this.writeTableData = null;
    },
    // 生成
    creadEvent() {
      this.writeTableData = null;
      if (this.from.content == "") {
        this.$message.warning("请先输入内容");
        return;
      }
      if (
        !(
          this.from.writeBoxNumber ||
          this.from.miaoRedBoxNumber ||
          this.from.lastNullrow
        )
      ) {
        this.$message.warning("请先输入配置内容");
        return;
      }
      // 大 一行8个    中 一行10个  小 一行12个
      let data = {
        option: [],
        typeIndex: this.typeIndex,
        playStorkes: this.from.playStorkes,
        StorkesUnfold: this.from.StorkesUnfold,
        BoxbgType: this.from.BoxbgType,
        miaoRedBgcolor: this.from.miaoRedBgcolor,
        writeColor: this.from.writeColor,
        borderColor: this.from.borderColor,
        fontColor: this.from.fontColor,
        writeBoxNumber: this.from.writeBoxNumber,
        miaoRedBoxNumber: this.from.miaoRedBoxNumber,
        lastNullrow: this.from.lastNullrow,
      };
      if (this.from.fontSize == "big") {
        data.width = "62px";
        data.fontSize = "48px";
        data.rowNumber = 8;
        data.pageNumber = 9;
        data.marginBottom = "15px";
        data.playWidth = "11px";
      } else if (this.from.fontSize == "center") {
        data.width = "49px";
        data.fontSize = "38px";
        data.rowNumber = 10;
        data.pageNumber = 12;
        data.marginBottom = "8px";
        data.playWidth = "9px";
      } else {
        data.width = "41px";
        data.fontSize = "31px";
        data.rowNumber = 12;
        data.pageNumber = 14;
        data.marginBottom = "7px";
        data.playWidth = "8px";
      }
      if (
        this.from.writeBoxNumber < this.from.miaoRedBoxNumber &&
        this.typeIndex == 1
      ) {
        this.$message.warning("书写格数不能小于描红数");
        return;
      } else if (
        this.from.writeBoxNumber <
          Math.ceil(this.from.miaoRedBoxNumber / data.rowNumber) &&
        this.typeIndex == 0
      ) {
        this.$message.warning("书写格数不能小于描红所用行数");
        return;
      }
      let contentArr = this.from.content.split("\n");
      for (let i = 0; i < contentArr.length; i++) {
        if (data.typeIndex == 0) {
          if (contentArr[i].length == 1) {
            if (/^[\u4e00-\u9fa5]/.test(contentArr[i])) {
              let obj = {
                con: contentArr[i],
              };
              data.option.push(obj);
            }
          } else {
            for (let m = 0; m < contentArr[i].length; m++) {
              if (/^[\u4e00-\u9fa5]/.test(contentArr[i][m])) {
                let obj = {
                  con: contentArr[i][m],
                };
                data.option.push(obj);
              }
            }
          }
        } else {
          let contentItem = "";
          for (let s = 0; s < contentArr[i].length; s++) {
            if (/^[\u4e00-\u9fa5]/.test(contentArr[i][s])) {
              contentItem += contentArr[i][s];
            }
          }
          if (contentItem) data.option.push(contentItem);
        }
      }
      //   字模式 笔顺打开
      if (data.typeIndex == 0) {
        this.loading = true;
        let MethodName = "hz_resource_manager-GetHZStrokesContent";
        data.option.forEach((item, i) => {
          let obj = {
            hz: item.con,
          };
          item.hzDetail = {
            hz_json: null,
          };
          getLogin(MethodName, obj)
            .then((res) => {
              this.$set(data.option[i].hzDetail, "hz_json", res);
              this.$forceUpdate();
              if (i == data.option.length - 1) {
                this.loading = false;
              }
            })
            .catch(() => {
              this.loading = false;
            });
        });
        let hzTimer = setInterval(() => {
          if (!this.loading) {
            clearInterval(hzTimer);
            hzTimer = null;
            if (data.StorkesUnfold) {
              let allArr = [];
              let timer = setInterval(() => {
                if (!this.loading) {
                  data.option.forEach((item) => {
                    let arr = [];
                    let hzLength = 1;
                    let arrOption = [];
                    // 拆分字和笔画为每一项
                    arr.push({
                      con: item.con,
                      hzDetail: JSON.parse(
                        JSON.stringify(item.hzDetail.hz_json)
                      ),
                    });
                    if (
                      item.hzDetail &&
                      item.hzDetail.hz_json &&
                      item.hzDetail.hz_json.medians
                    ) {
                      hzLength += item.hzDetail.hz_json.medians.length;
                      item.hzDetail.hz_json.medians.forEach((items, indexs) => {
                        arr.push({
                          con: item.con,
                          answer: indexs + 1,
                          hzDetail: JSON.parse(
                            JSON.stringify(item.hzDetail.hz_json)
                          ),
                        });
                      });
                    }
                    // 如果不满一行则补满
                    let newarr = [];
                    if (arr.length % data.rowNumber != 0) {
                      let num = data.rowNumber - (arr.length % data.rowNumber);
                      for (let i = 0; i < num; i++) {
                        arr.push({});
                      }
                      if (arr.length > data.rowNumber) {
                        newarr = this.arrSplice(arr, data.rowNumber);
                        newarr.forEach((itemss) => {
                          allArr.push(itemss);
                        });
                      } else {
                        allArr.push(arr);
                      }
                    } else {
                      allArr.push(arr);
                    }
                    // 添加书写行
                    if (data.writeBoxNumber) {
                      for (let i = 0; i < data.writeBoxNumber; i++) {
                        let numrow = [];
                        for (let k = 0; k < data.rowNumber; k++) {
                          numrow.push({
                            con: item.con,
                            write: true,
                          });
                        }
                        // 描红格
                        if (i == 0 && data.miaoRedBoxNumber) {
                          let m =
                            Math.ceil(data.miaoRedBoxNumber / data.rowNumber) >
                            data.writeBoxNumber
                              ? data.writeBoxNumber
                              : Math.ceil(
                                  data.miaoRedBoxNumber / data.rowNumber
                                );
                          for (let j = 0; j < m; j++) {
                            let miaoArr = [];
                            for (let l = 0; l < data.rowNumber; l++) {
                              if (
                                j * data.rowNumber + l <
                                data.miaoRedBoxNumber
                              ) {
                                miaoArr[l] = {
                                  con: item.con,
                                  miaoRed: true,
                                  write: true,
                                };
                              } else {
                                miaoArr[l] = {
                                  con: item.con,
                                  write: true,
                                };
                              }
                            }
                            arrOption.push(JSON.parse(JSON.stringify(miaoArr)));
                          }
                        }
                        arrOption.push(numrow);
                        arrOption = arrOption.slice(0, data.writeBoxNumber);
                      }
                      arrOption.forEach((itemA) => {
                        allArr.push(itemA);
                      });
                    }
                  });
                  if (data.lastNullrow) {
                    for (let i = 0; i < data.lastNullrow; i++) {
                      let numrow = [];
                      for (let k = 0; k < data.rowNumber; k++) {
                        numrow.push({
                          write: true,
                        });
                      }
                      allArr.push(numrow);
                    }
                  }
                  data.result = this.arrSplice(allArr, data.pageNumber);
                  this.writeTableData = data;
                  clearInterval(timer);
                  timer = null;
                }
              }, 100);
            } else {
              let allArr = [];
              data.option.forEach((item) => {
                let arr = [];
                let arrOption = [];
                // 拆分字和笔画为每一项
                arr.push({
                  con: item.con,
                  hzDetail: JSON.parse(JSON.stringify(item.hzDetail.hz_json)),
                });
                // 如果不满一行则补满
                let newarr = [];
                let areadyMiao = 0;
                if (arr.length % data.rowNumber != 0) {
                  let num = data.rowNumber - (arr.length % data.rowNumber);
                  for (let i = 0; i < num; i++) {
                    if (data.miaoRedBoxNumber && i < data.miaoRedBoxNumber) {
                      arr.push({
                        con: item.con,
                        miaoRed: true,
                        write: true,
                      });
                      areadyMiao++;
                    } else {
                      arr.push({});
                    }
                  }
                  if (arr.length > data.rowNumber) {
                    newarr = this.arrSplice(arr, data.rowNumber);
                    newarr.forEach((itemss) => {
                      allArr.push(itemss);
                    });
                  } else {
                    allArr.push(arr);
                  }
                } else {
                  allArr.push(arr);
                }
                // 添加书写行
                if (data.writeBoxNumber) {
                  for (let i = 0; i < data.writeBoxNumber; i++) {
                    let numrow = [];
                    for (let k = 0; k < data.rowNumber; k++) {
                      numrow.push({
                        con: item.con,
                        write: true,
                      });
                    }
                    // 描红格
                    if (i == 0 && data.miaoRedBoxNumber) {
                      let m =
                        Math.ceil(
                          (data.miaoRedBoxNumber - areadyMiao) / data.rowNumber
                        ) > data.writeBoxNumber
                          ? data.writeBoxNumber
                          : Math.ceil(
                              (data.miaoRedBoxNumber - areadyMiao) /
                                data.rowNumber
                            );
                      for (let j = 0; j < m; j++) {
                        let miaoArr = [];
                        for (let l = 0; l < data.rowNumber; l++) {
                          if (
                            j * data.rowNumber + l <
                            data.miaoRedBoxNumber - areadyMiao
                          ) {
                            miaoArr[l] = {
                              con: item.con,
                              miaoRed: true,
                              write: true,
                            };
                          } else {
                            miaoArr[l] = {
                              con: item.con,
                              write: true,
                            };
                          }
                        }
                        arrOption.push(JSON.parse(JSON.stringify(miaoArr)));
                      }
                    }
                    arrOption.push(numrow);
                    arrOption = arrOption.slice(0, data.writeBoxNumber);
                  }
                  arrOption.forEach((itemA) => {
                    allArr.push(itemA);
                  });
                }
              });
              if (data.lastNullrow) {
                for (let i = 0; i < data.lastNullrow; i++) {
                  let numrow = [];
                  for (let k = 0; k < data.rowNumber; k++) {
                    numrow.push({
                      write: true,
                    });
                  }
                  allArr.push(JSON.parse(JSON.stringify(numrow)));
                }
              }
              data.result = this.arrSplice(allArr, data.pageNumber);
              this.writeTableData = data;
            }
            this.$forceUpdate();
            this.isCread = true;
          }
        }, 100);
      } else {
        // 处理句模式数据
        let allArr = [];
        data.option.forEach((item) => {
          let sentenceArr = []; // 每一句的内容
          let sentence = Math.ceil(item.length / data.rowNumber);
          for (let k = 0; k < sentence; k++) {
            let sentenceItem = [];
            for (let s = 0; s < data.rowNumber; s++) {
              if (k * data.rowNumber + s < item.length) {
                sentenceItem.push({
                  con: item[k * data.rowNumber + s],
                });
              } else {
                sentenceItem.push({});
              }
            }
            this.loading = true;
            let MethodName = "hz_resource_manager-GetHZStrokesContent";
            sentenceItem.forEach((items, index) => {
              let obj = {
                hz: items.con,
              };
              items.hzDetail = null;
              getLogin(MethodName, obj)
                .then((res) => {
                  this.$set(sentenceItem[index], "hzDetail", res);
                  this.$forceUpdate();
                  if (index == sentenceItem.length - 1) {
                    this.loading = false;
                    allArr.push(JSON.parse(JSON.stringify(sentenceItem)));
                  }
                })
                .catch(() => {
                  this.loading = false;
                });
            });
          }
          let hzTimer = setInterval(() => {
            if (!this.loading) {
              clearInterval(hzTimer);
              hzTimer = null;

              if (data.miaoRedBoxNumber > 0 && data.writeBoxNumber > 0) {
                let sentenceMiao = [];
                for (let k = 0; k < sentence; k++) {
                  let sentenceItemMiao = [];
                  this.loading = true;
                  for (let s = 0; s < data.rowNumber; s++) {
                    if (k * data.rowNumber + s < item.length) {
                      sentenceItemMiao[s] = {
                        con: item[k * data.rowNumber + s],
                        miaoRed: true,
                      };
                      let MethodName =
                        "hz_resource_manager-GetHZStrokesContent";
                      getLogin(MethodName, { hz: item[k * data.rowNumber + s] })
                        .then((res) => {
                          this.$set(sentenceItemMiao[s], "hzDetail", {
                            hz_json: res,
                          });
                        })
                        .catch(() => {
                          this.loading = false;
                        });
                    } else {
                      sentenceItemMiao[s] = {};
                    }
                  }
                  sentenceMiao.push(
                    JSON.parse(JSON.stringify(sentenceItemMiao))
                  );
                }
                this.loading = false;
                // 描红内容
                for (let l = 0; l < data.miaoRedBoxNumber; l++) {
                  for (let j = 0; j < sentenceMiao.length; j++) {
                    sentenceArr.push(
                      JSON.parse(JSON.stringify(sentenceMiao[j]))
                    );
                  }
                }
              }
              // 书写内容
              if (data.writeBoxNumber > 0) {
                for (
                  let w = 0;
                  w < Number(sentence) * Number(data.writeBoxNumber);
                  w++
                ) {
                  let sentenceItemWrite = [];
                  for (let j = 0; j < data.rowNumber; j++) {
                    sentenceItemWrite.push({});
                  }
                  sentenceArr.push(
                    JSON.parse(JSON.stringify(sentenceItemWrite))
                  );
                }
              }
              sentenceArr = sentenceArr.slice(
                0,
                Number(sentence) * Number(data.writeBoxNumber)
              );
              sentenceArr.forEach((itemS, indexS) => {
                allArr.push(JSON.parse(JSON.stringify(itemS)));
              });
            }
          });
        });
        let hzTimer = setInterval(() => {
          if (!this.loading) {
            clearInterval(hzTimer);
            hzTimer = null;
            if (data.lastNullrow > 0) {
              for (let t = 0; t < data.lastNullrow; t++) {
                let sentenceItemNull = [];
                for (let j = 0; j < data.rowNumber; j++) {
                  sentenceItemNull.push({});
                }
                allArr.push(JSON.parse(JSON.stringify(sentenceItemNull)));
              }
            }

            data.result = this.arrSplice(allArr, data.pageNumber);
            this.writeTableData = data;
            this.$forceUpdate();
            this.isCread = true;
          }
        });
      }
      // // 定时 接口请求结束再执行
      // let hzTimer = setInterval(() => {
      //   if (!this.loading) {
      //     clearInterval(hzTimer);
      //     hzTimer = null;
      //     if (data.typeIndex == 0) {
      //       if (data.StorkesUnfold) {
      //         let allArr = [];
      //         let timer = setInterval(() => {
      //           if (!this.loading) {
      //             data.option.forEach((item) => {
      //               let arr = [];
      //               let hzLength = 1;
      //               let arrOption = [];
      //               // 拆分字和笔画为每一项
      //               arr.push({
      //                 con: item.con,
      //                 hzDetail: JSON.parse(
      //                   JSON.stringify(item.hzDetail.hz_json)
      //                 ),
      //               });
      //               if (
      //                 item.hzDetail &&
      //                 item.hzDetail.hz_json &&
      //                 item.hzDetail.hz_json.medians
      //               ) {
      //                 hzLength += item.hzDetail.hz_json.medians.length;
      //                 item.hzDetail.hz_json.medians.forEach((items, indexs) => {
      //                   arr.push({
      //                     con: item.con,
      //                     answer: indexs + 1,
      //                     hzDetail: JSON.parse(
      //                       JSON.stringify(item.hzDetail.hz_json)
      //                     ),
      //                   });
      //                 });
      //               }
      //               // 如果不满一行则补满
      //               let newarr = [];
      //               if (arr.length % data.rowNumber != 0) {
      //                 let num = data.rowNumber - (arr.length % data.rowNumber);
      //                 for (let i = 0; i < num; i++) {
      //                   arr.push({});
      //                 }
      //                 if (arr.length > data.rowNumber) {
      //                   newarr = this.arrSplice(arr, data.rowNumber);
      //                   newarr.forEach((itemss) => {
      //                     allArr.push(itemss);
      //                   });
      //                 } else {
      //                   allArr.push(arr);
      //                 }
      //               } else {
      //                 allArr.push(arr);
      //               }
      //               // 添加书写行
      //               if (data.writeBoxNumber) {
      //                 for (let i = 0; i < data.writeBoxNumber; i++) {
      //                   let numrow = [];
      //                   for (let k = 0; k < data.rowNumber; k++) {
      //                     numrow.push({
      //                       con: item.con,
      //                       write: true,
      //                     });
      //                   }
      //                   // 描红格
      //                   if (i == 0 && data.miaoRedBoxNumber) {
      //                     let m =
      //                       Math.ceil(data.miaoRedBoxNumber / data.rowNumber) >
      //                       data.writeBoxNumber
      //                         ? data.writeBoxNumber
      //                         : Math.ceil(
      //                             data.miaoRedBoxNumber / data.rowNumber
      //                           );
      //                     for (let j = 0; j < m; j++) {
      //                       let miaoArr = [];
      //                       for (let l = 0; l < data.rowNumber; l++) {
      //                         if (
      //                           j * data.rowNumber + l <
      //                           data.miaoRedBoxNumber
      //                         ) {
      //                           miaoArr[l] = {
      //                             con: item.con,
      //                             miaoRed: true,
      //                             write: true,
      //                           };
      //                         } else {
      //                           miaoArr[l] = {
      //                             con: item.con,
      //                             write: true,
      //                           };
      //                         }
      //                       }
      //                       arrOption.push(JSON.parse(JSON.stringify(miaoArr)));
      //                     }
      //                   }
      //                   arrOption.push(numrow);
      //                   arrOption = arrOption.slice(0, data.writeBoxNumber);
      //                 }
      //                 arrOption.forEach((itemA) => {
      //                   allArr.push(itemA);
      //                 });
      //               }
      //             });
      //             if (data.lastNullrow) {
      //               for (let i = 0; i < data.lastNullrow; i++) {
      //                 let numrow = [];
      //                 for (let k = 0; k < data.rowNumber; k++) {
      //                   numrow.push({
      //                     write: true,
      //                   });
      //                 }
      //                 allArr.push(numrow);
      //               }
      //             }
      //             data.result = this.arrSplice(allArr, data.pageNumber);
      //             this.writeTableData = data;
      //             clearInterval(timer);
      //             timer = null;
      //           }
      //         }, 100);
      //       } else {
      //         let allArr = [];
      //         data.option.forEach((item) => {
      //           let arr = [];
      //           let arrOption = [];
      //           // 拆分字和笔画为每一项
      //           arr.push({
      //             con: item.con,
      //             hzDetail: JSON.parse(JSON.stringify(item.hzDetail.hz_json)),
      //           });
      //           // 如果不满一行则补满
      //           let newarr = [];
      //           let areadyMiao = 0;
      //           if (arr.length % data.rowNumber != 0) {
      //             let num = data.rowNumber - (arr.length % data.rowNumber);
      //             for (let i = 0; i < num; i++) {
      //               if (data.miaoRedBoxNumber && i < data.miaoRedBoxNumber) {
      //                 arr.push({
      //                   con: item.con,
      //                   miaoRed: true,
      //                   write: true,
      //                 });
      //                 areadyMiao++;
      //               } else {
      //                 arr.push({});
      //               }
      //             }
      //             if (arr.length > data.rowNumber) {
      //               newarr = this.arrSplice(arr, data.rowNumber);
      //               newarr.forEach((itemss) => {
      //                 allArr.push(itemss);
      //               });
      //             } else {
      //               allArr.push(arr);
      //             }
      //           } else {
      //             allArr.push(arr);
      //           }
      //           // 添加书写行
      //           if (data.writeBoxNumber) {
      //             for (let i = 0; i < data.writeBoxNumber; i++) {
      //               let numrow = [];
      //               for (let k = 0; k < data.rowNumber; k++) {
      //                 numrow.push({
      //                   con: item.con,
      //                   write: true,
      //                 });
      //               }
      //               // 描红格
      //               if (i == 0 && data.miaoRedBoxNumber) {
      //                 let m =
      //                   Math.ceil(
      //                     (data.miaoRedBoxNumber - areadyMiao) / data.rowNumber
      //                   ) > data.writeBoxNumber
      //                     ? data.writeBoxNumber
      //                     : Math.ceil(
      //                         (data.miaoRedBoxNumber - areadyMiao) /
      //                           data.rowNumber
      //                       );
      //                 for (let j = 0; j < m; j++) {
      //                   let miaoArr = [];
      //                   for (let l = 0; l < data.rowNumber; l++) {
      //                     if (
      //                       j * data.rowNumber + l <
      //                       data.miaoRedBoxNumber - areadyMiao
      //                     ) {
      //                       miaoArr[l] = {
      //                         con: item.con,
      //                         miaoRed: true,
      //                         write: true,
      //                       };
      //                     } else {
      //                       miaoArr[l] = {
      //                         con: item.con,
      //                         write: true,
      //                       };
      //                     }
      //                   }
      //                   arrOption.push(JSON.parse(JSON.stringify(miaoArr)));
      //                 }
      //               }
      //               arrOption.push(numrow);
      //               arrOption = arrOption.slice(0, data.writeBoxNumber);
      //             }
      //             arrOption.forEach((itemA) => {
      //               allArr.push(itemA);
      //             });
      //           }
      //         });
      //         if (data.lastNullrow) {
      //           for (let i = 0; i < data.lastNullrow; i++) {
      //             let numrow = [];
      //             for (let k = 0; k < data.rowNumber; k++) {
      //               numrow.push({
      //                 write: true,
      //               });
      //             }
      //             allArr.push(JSON.parse(JSON.stringify(numrow)));
      //           }
      //         }
      //         data.result = this.arrSplice(allArr, data.pageNumber);
      //         this.writeTableData = data;
      //       }
      //     } else {
      //       // 处理句模式数据
      //       let allArr = [];
      //       data.option.forEach((item) => {
      //         let sentenceArr = []; // 每一句的内容
      //         let sentence = Math.ceil(item.length / data.rowNumber);
      //         for (let k = 0; k < sentence; k++) {
      //           let sentenceItem = [];
      //           for (let s = 0; s < data.rowNumber; s++) {
      //             if (k * data.rowNumber + s < item.length) {
      //               sentenceItem.push({
      //                 con: item[k * data.rowNumber + s],
      //               });
      //             } else {
      //               sentenceItem.push({});
      //             }
      //           }
      //           this.loading = true;
      //           let MethodName = "hz_resource_manager-GetHZStrokesContent";
      //           sentenceItem.forEach((items, index) => {
      //             let obj = {
      //               hz: items.con,
      //             };
      //             if (items.con) {
      //               items.hzDetail = {
      //                 hz_json: null,
      //               };
      //             }
      //             getLogin(MethodName, obj)
      //               .then((res) => {
      //                 if (items.con) {
      //                   this.$set(sentenceItem[index].hzDetail, "hz_json", res);
      //                   this.$forceUpdate();
      //                 }
      //                 if (index == sentenceItem.length - 1) {
      //                   this.loading = false;
      //                   allArr.push(JSON.parse(JSON.stringify(sentenceItem)));
      //                   console.log(allArr);
      //                 }
      //               })
      //               .catch(() => {
      //                 this.loading = false;
      //               });
      //           });
      //         }
      //         if (data.miaoRedBoxNumber > 0 && data.writeBoxNumber > 0) {
      //           let sentenceMiao = [];
      //           for (let k = 0; k < sentence; k++) {
      //             let sentenceItemMiao = [];
      //             this.loading = true;
      //             for (let s = 0; s < data.rowNumber; s++) {
      //               if (k * data.rowNumber + s < item.length) {
      //                 sentenceItemMiao[s] = {
      //                   con: item[k * data.rowNumber + s],
      //                   miaoRed: true,
      //                 };
      //                 let MethodName =
      //                   "hz_resource_manager-GetHZStrokesContent";
      //                 getLogin(MethodName, { hz: item[k * data.rowNumber + s] })
      //                   .then((res) => {
      //                     this.$set(sentenceItemMiao[s], "hzDetail", {
      //                       hz_json: res,
      //                     });
      //                   })
      //                   .catch(() => {
      //                     this.loading = false;
      //                   });
      //               } else {
      //                 sentenceItemMiao[s] = {};
      //               }
      //             }
      //             sentenceMiao.push(
      //               JSON.parse(JSON.stringify(sentenceItemMiao))
      //             );
      //           }
      //           this.loading = false;
      //           // 描红内容
      //           for (let l = 0; l < data.miaoRedBoxNumber; l++) {
      //             for (let j = 0; j < sentenceMiao.length; j++) {
      //               sentenceArr.push(
      //                 JSON.parse(JSON.stringify(sentenceMiao[j]))
      //               );
      //             }
      //           }
      //         }
      //         // 书写内容
      //         if (data.writeBoxNumber > 0) {
      //           for (
      //             let w = 0;
      //             w < Number(sentence) * Number(data.writeBoxNumber);
      //             w++
      //           ) {
      //             let sentenceItemWrite = [];
      //             for (let j = 0; j < data.rowNumber; j++) {
      //               sentenceItemWrite.push({});
      //             }
      //             sentenceArr.push(
      //               JSON.parse(JSON.stringify(sentenceItemWrite))
      //             );
      //           }
      //         }
      //         sentenceArr = sentenceArr.slice(
      //           0,
      //           Number(sentence) * Number(data.writeBoxNumber)
      //         );
      //         sentenceArr.forEach((itemS, indexS) => {
      //           allArr.push(JSON.parse(JSON.stringify(itemS)));
      //         });
      //       });
      //       if (data.lastNullrow > 0) {
      //         for (let t = 0; t < data.lastNullrow; t++) {
      //           let sentenceItemNull = [];
      //           for (let j = 0; j < data.rowNumber; j++) {
      //             sentenceItemNull.push({});
      //           }
      //           allArr.push(JSON.parse(JSON.stringify(sentenceItemNull)));
      //         }
      //       }
      //       data.result = this.arrSplice(allArr, data.pageNumber);
      //       this.writeTableData = data;
      //     }
      //     this.$forceUpdate();
      //     this.isCread = true;
      //   }
      // }, 100);
    },
    arrSplice(arr, chunkSize) {
      //定义一个空数组来接收返回值
      const resSplice = [];
      while (arr.length > 0) {
        //注意：splice方法的返回值为删除的值，在这边即为原数组中切割掉的index为0-chunkSize的值
        const chunk = arr.splice(0, chunkSize);
        //将返回值添加到resSplice数组
        resSplice.push(chunk);
      }
      //return出去
      return resSplice;
    },
    // 字句详情
    getdetai() {
      this.loading = true;
      let Mname = "tr_tool-wsc_manager-GetWordSentenceCard";
      LearnWebSI(Mname, {
        id: this.$route.query.id,
      })
        .then((res) => {
          this.saveName = res.name;
          this.from.content = res.text;
          this.writeTableData = JSON.parse(res.content);
          // 初始化 from 表单
          for (let key in this.from) {
            if (this.writeTableData[key]) {
              if (key == "fontSize") {
                if (this.writeTableData[key] == "48px") {
                  this.from[key] = "big";
                } else if (this.writeTableData[key] == "38px") {
                  this.from[key] = "center";
                } else {
                  this.from[key] = "little";
                }
              } else {
                this.from[key] = this.writeTableData[key];
              }
            }
          }
          if (res.type == "WORD") {
            this.typeIndex = 0;
          } else {
            this.typeIndex = 1;
          }
          this.loading = false;
          this.isCread = true;
        })
        .catch((res) => {
          this.loading = false;
        });
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  //生命周期-创建之前
  beforeCreated() {},
  //生命周期-挂载之前
  beforeMount() {},
  //生命周期-更新之前
  beforUpdate() {},
  //生命周期-更新之后
  updated() {},
  //生命周期-销毁之前
  beforeDestory() {},
  //生命周期-销毁完成
  destoryed() {},
  //如果页面有keep-alive缓存功能，这个函数会触发
  activated() {
    if (this.$route.query.cachesType == "pop") {
      this.saveName = "";
      this.typeIndex = 0;
      this.from = {
        content: "",
        BoxbgType: 0,
        fontSize: "center",
        playStorkes: true,
        StorkesUnfold: true,
        writeBoxNumber: "0", //书写行
        miaoRedBoxNumber: "0", //描红格
        lastNullrow: "0", //文本末空行数
        miaoRedBgcolor: "#E1E1E1", //描红底色
        writeColor: "#000000", //书写颜色
        borderColor: "#D65353", //边框颜色
        fontColor: "#000000", //文字颜色
      };
      this.loading = false;
      this.writeTableData = null;
      this.isCread = false;
      this.isPreview = false;
      this.previewIndex = 0;
      this.htmlTitle = "1";
      this.saveShow = false;
      this.writetableShow = true;
      if (this.$route.query.id) {
        // 需要请求详情接口
        this.getdetai();
      }
    }
  },
};
</script>
<style lang="scss" scoped>
/* @import url(); 引入css类 */
.cread {
  height: 100%;
  position: relative;

  .main {
    min-height: 100%;
    background: #f7f7f7;
    padding: 24px 0;
    .from {
      width: 1200px;
      margin: 0 auto;
      background: #ffffff;
      border-radius: 8px;
      padding: 16px 24px 24px 18px;
      box-sizing: border-box;
      .type {
        display: flex;
        width: 108px;
        height: 28px;
        background: #eeeeee;
        border-radius: 4px;
        padding: 2px;
        > div {
          width: 52px;
          font-weight: 400;
          font-size: 12px;
          line-height: 28px;
          text-align: center;
          color: #888888;
          cursor: pointer;
        }
        .sele {
          font-weight: 500;
          line-height: 28px;
          font-size: 12px;
          text-align: center;
          color: #000000;
          background: #ffffff;
          box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.08);
          border-radius: 2px;
        }
      }
      .from_main {
        margin-top: 12px;
        display: flex;
        .left {
          width: 668px;
          .submit {
            display: flex;
            justify-content: flex-end;
            span {
              margin-top: 16px;
              display: inline-block;
              width: 80px;
              height: 40px;
              background: #669aff;
              border-radius: 4px;
              font-weight: 500;
              font-size: 16px;
              display: flex;
              align-items: center;
              justify-content: center;
              color: #ffffff;
              cursor: pointer;
            }
          }
        }
        .right {
          flex: 1;
          margin-left: 24px;
          > .title {
            font-weight: 400;
            font-size: 14px;
            line-height: 20px;
            color: #000000;
          }
          .dv {
            margin-top: 8px;
            width: 466px;
            height: 48px;
            background: #f0f0f0;
            border-radius: 8px;
            display: flex;
            align-items: center;
            padding: 0 16px;
            .title {
              margin-right: 8px;
            }
            > span {
              font-weight: 400;
              font-size: 14px;
              line-height: 20px;
            }
          }
        }
      }
    }
    .operation {
      width: 1200px;
      height: 72px;
      margin: 24px auto 0 auto;
      background: #ffffff;
      border-radius: 8px;
      display: flex;
      justify-content: center;
      align-items: center;
      div {
        width: 96px;
        height: 40px;
        background: #ffffff;
        border: 1px solid rgba(0, 0, 0, 0.08);
        border-radius: 4px;
        display: flex;
        justify-content: center;
        align-items: center;
        cursor: pointer;
        margin-right: 16px;
        img {
          width: 24px;
          height: 24px;
          margin-right: 8px;
        }
      }
    }
    .word_main {
      width: 1200px;
      margin: 0 auto;
      display: flex;
      flex-flow: wrap;
      justify-content: space-between;
      &_table {
        margin-top: 10px;
      }
    }
  }
  .preview_dv {
    position: absolute;
    left: 0;
    top: 64px;
    width: 100%;
    min-height: 100%;
    background: #f2f2f2;
    > img {
      width: 40px;
      height: 40px;
      cursor: pointer;
      position: absolute;
      top: 24px;
      right: 31px;
    }
    .preview_main {
      padding: 24px 0;
      width: 740px;
      margin: 0 auto;
      display: flex;
      align-items: center;
      height: 100%;
      > div {
        margin: 0 24px;
      }
      img {
        width: 48px;
        height: 48px;
        cursor: pointer;
      }
    }
  }
}
</style>
<style lang="scss">
.cread {
  .from_main {
    // input
    .el-textarea__inner {
      height: 388px;
    }
    // 单选
    .el-radio {
      margin-right: 46px;
    }
    .el-radio__inner {
      border: 1px solid #000000;
    }
    .el-radio__inner:hover {
      border: 1px solid #000000;
    }
    .el-radio__input.is-checked .el-radio__inner {
      background-color: #fff;
    }
    .el-radio__inner::after {
      background-color: #000000;
      width: 6px;
      height: 6px;
    }
    .el-radio,
    .el-radio__input.is-checked + .el-radio__label {
      color: #000000;
    }
    // 选择颜色
    .el-color-picker__trigger {
      background: #fff;
    }
    .el-color-picker__trigger {
      height: 32px;
      width: 60px;
    }
    .el-color-picker__empty,
    .el-color-picker__icon {
      left: 134%;
    }
    .el-color-picker__icon {
      color: gray;
      left: 77%;
    }
    .el-color-picker__color {
      border: none;
      width: 28px;
    }
    .el-color-picker__color-inner {
      border-radius: 2px;
    }
    // 开关
    .el-switch__core {
      width: 26px !important;
      height: 16px;
    }
    .el-switch__core:after {
      width: 8px;
      height: 8px;
      top: 2px;
    }
    .el-switch.is-checked .el-switch__core::after {
      margin-left: -10px;
    }
    .el-switch__label.is-active {
      color: #000000;
    }
    .numbre-input {
      .el-input__inner {
        padding: 0;
        text-align: center;
      }
    }
  }
}
</style>