<template>
  <div
    v-if="judgeAnswer == 'standardAnswer' ? (userError ? true : false) : true"
    class="config-table"
  >
    <table
      :style="{
        'box-shadow': `${
          curQue.isShadow ? '4px 4px 4px rgba(0, 0, 0, 0.3)' : ''
        }`,
        border: `${curQue.marginHighlight ? '1.1px solid #949494' : ''}`,
      }"
    >
      <colgroup>
        <col
          v-for="(col, i) in curQue.tableData.colsConfig.width"
          :key="`col-${i}`"
          :style="{ width: `${col.val}px` }"
        />
      </colgroup>

      <caption v-if="curQue.isTitle">
        {{
          curQue.title
        }}
      </caption>

      <thead>
        <tr
          v-for="({ content }, i) in curQue.tableData.headers"
          :key="`thead-${i}`"
          :style="{
            'background-color': `${curQue.headerBgColor}`,
          }"
        >
          <template v-for="({ text, colspan, rowspan }, j) in content">
            <th
              v-if="thIsShow(i, j)"
              :key="`th-${i}-${j}`"
              :colspan="colspan"
              :rowspan="rowspan"
            >
              {{ text }}
            </th>
          </template>
        </tr>
      </thead>

      <tbody
        :style="{
          'text-align': `${curQue.textAlign}`,
        }"
      >
        <tr v-for="(row, i) in curQue.tableData.body" :key="`tr-${i}`">
          <template v-for="(col, j) in row.content">
            <td
              v-if="tdIsShow(i, j)"
              :key="`td-${i}-${j}`"
              :colspan="col.colspan"
              :rowspan="col.rowspan"
              :class="[
                { underline: col.isUnderline },
                judgeAnswer == 'standardAnswer' ? 'correct' : '',
                judgeAnswer == 'studentAnswer' || judgeAnswer == 'userAnswer'
                  ? curQue.Bookanswer[i].content[j].userAnswerJudge
                    ? curQue.Bookanswer[i].content[j].userAnswerJudge ==
                      '[JUDGE##T##JUDGE]'
                      ? 'correct'
                      : 'error'
                    : ''
                  : '',
              ]"
              :style="{ 'background-color': `${col.background}` }"
            >
              <div class="cell-wrap">
                <template v-if="col.type === 'content'">
                  <span v-if="col.text.length > 0" class="content">
                    {{ col.text }}
                  </span>
                  <template v-else>
                    <el-input
                      v-model="
                        judgeAnswer == 'standardAnswer'
                          ? col.answer
                          : curQue.Bookanswer[i].content[j].answer
                      "
                      type="textarea"
                      :class="[`text-${curQue.textAlign}`]"
                      :placeholder="`${isAnswerMode ? '' : ''}`"
                      :disabled="isAnswerMode"
                      :autosize="{ minRows: 1, maxRows: 6 }"
                      @blur="
                        judgeAnswer == 'standardAnswer'
                          ? (col.answer = col.answer.trim())
                          : (curQue.Bookanswer[i].content[j].answer =
                              curQue.Bookanswer[i].content[j].answer.trim())
                      "
                      @input="enterAnswer(i, j, 'input')"
                    />
                  </template>
                </template>

                <div v-else-if="col.type === 'preContent'" class="preContent">
                  <span>{{ col.prefix }}</span>
                  <template v-if="col.text.length > 0">
                    {{ col.text }}
                  </template>
                  <template v-else>
                    <el-input
                      v-model="
                        judgeAnswer == 'standardAnswer'
                          ? col.answer
                          : curQue.Bookanswer[i].content[j].answer
                      "
                      type="textarea"
                      :class="[`text-${curQue.textAlign}`]"
                      :placeholder="`${isAnswerMode ? '' : ''}`"
                      :disabled="isAnswerMode"
                      :autosize="{ minRows: 1, maxRows: 6 }"
                      @input="enterAnswer(i, j, 'input')"
                    />
                  </template>
                </div>

                <div
                  v-else-if="
                    col.type === 'pinyin' || col.type === 'twoAnnotation'
                  "
                  class="sentence"
                  :style="pinyinStyle"
                >
                  <div>
                    <span
                      v-for="({ pinyin, chs }, k) in col.sentence_data
                        .wordsList"
                      :key="`${
                        curQue.pinyinPosition === 'top' ||
                        curQue.pinyinPosition === 'left'
                          ? 'pinyin'
                          : 'chs'
                      }-${k}`"
                      :class="[
                        `${
                          curQue.pinyinPosition === 'top' ||
                          curQue.pinyinPosition === 'left'
                            ? 'pinyin'
                            : 'chs'
                        }`,
                      ]"
                    >
                      {{
                        curQue.pinyinPosition === "top" ||
                        curQue.pinyinPosition == "left"
                          ? pinyin
                          : chs
                      }}
                    </span>
                    <span
                      v-if="
                        col.type === 'twoAnnotation' &&
                        (curQue.pinyinPosition === 'right' ||
                          curQue.pinyinPosition === 'bottom')
                      "
                      class="english"
                    >
                      ({{ col.text }})
                    </span>
                  </div>
                  <div>
                    <span
                      v-for="({ pinyin, chs }, k) in col.sentence_data
                        .wordsList"
                      :key="`${
                        curQue.pinyinPosition === 'top' ||
                        curQue.pinyinPosition === 'left'
                          ? 'chs'
                          : 'pinyin'
                      }-${k}`"
                      :class="[
                        `${
                          curQue.pinyinPosition === 'top' ||
                          curQue.pinyinPosition === 'left'
                            ? 'chs'
                            : 'pinyin'
                        }`,
                      ]"
                    >
                      {{
                        curQue.pinyinPosition === "top" ||
                        curQue.pinyinPosition == "left"
                          ? chs
                          : pinyin
                      }}
                    </span>
                    <span
                      v-if="
                        col.type === 'twoAnnotation' &&
                        (curQue.pinyinPosition === 'top' ||
                          curQue.pinyinPosition === 'left')
                      "
                      class="english"
                    >
                      ({{ col.text }})
                    </span>
                  </div>
                </div>

                <div v-else-if="col.type === 'prePinyin'" class="pre-pinyin">
                  <span>{{ col.prefix }}</span>
                  <div
                    class="right-pinyin"
                    :style="{
                      'grid-template-columns': `repeat(${col.sentence_data.wordsList.length}, auto)`,
                    }"
                  >
                    <span
                      v-for="({ pinyin }, k) in col.sentence_data.wordsList"
                      :key="`pre-pinyin-${k}`"
                      class="pinyin"
                    >
                      {{ pinyin }}
                    </span>
                    <span
                      v-for="({ pinyin, chs }, k) in col.sentence_data
                        .wordsList"
                      :key="`pre-chs-${k}`"
                      class="chs"
                    >
                      {{ chs }}
                    </span>
                  </div>
                </div>
                
                <div class="stem-content" v-else-if="col.type === 'mulText'">
                    <div
                        :class="[
                            'sent-main',
                        ]"
                        v-for="(sdItem, sdIndex) in col.mulText.detail"
                        :key="'sent-option-items' + j + sdIndex"
                        >
                        <div class="sent-que-box">
                            <div
                            class="sent-que"
                            v-for="(sddItem, sddIndex) in sdItem.detail"
                            :key="'sent-option-items' + j + sdIndex + sddIndex"
                            :style="{
                                paddingLeft:
                                sddItem.config.wordPadding.indexOf('left') > -1
                                    ? '4px'
                                    : '0px',
                                paddingRight:
                                sddItem.config.wordPadding.indexOf('right') > -1
                                    ? '4px'
                                    : '0px',
                            }"
                            >
                            <!-- 补全句子 -->
                            <OneSentenceTemp
                                :detail="sddItem"
                                :pyPosition="curQue.pinyinPosition"
                                :TaskModel="TaskModel"
                                :Bookanswer="curQue.Bookanswer[i].content[j]"
                                :judgeAnswer="judgeAnswer"
                                :correctAnswer="col.mulText.correct.complateArr"
                                :isInput="true"
                                :fn_check_list="[]"
                                :pyNumber="col.pyNumber && col.pyNumber[sdIndex]"
                                :hengLeg="sdItem.hengLeg"
                                :maxFontsize="sdItem.maxFontsize"
                            />
                            <template
                                v-if="
                                sddItem.img_list &&
                                sddItem.img_list.length > 0 &&
                                sddItem.img_list[0].id
                                "
                            >
                                <img
                                :src="sddItem.img_list[0].id"
                                class="sddItem_img_list"
                                :style="[imgStyle(sddItem)]"
                                />
                            </template>
                            </div>
                        </div>
                    </div>
                </div>
                <CrossTick
                  v-if="col.isCross"
                  :index="i"
                  :indexs="j"
                  :data="
                    judgeAnswer == 'standardAnswer'
                      ? col
                      : curQue.Bookanswer[i].content[j]
                  "
                  :is-answer-mode="isAnswerMode"
                  @enterAnswer="enterAnswer"
                />
              </div>
            </td>
          </template>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
import CrossTick from "./HeaderSparate/CrossTick.vue";
import AnswerTitle from "../preview/components/AnswerTitle.vue";
import OneSentenceTemp from "./components/OneSentenceTemp.vue";

export default {
  components: { CrossTick, AnswerTitle, OneSentenceTemp },
  props: {
    curQue: {
      type: Object,
      required: true,
    },
    themeColor: {
      type: String,
      required: true,
    },
    judgeAnswer: {
      type: String,
    },
    TaskModel: {
      type: String,
    }
  },
  data() {
    return {
      isAnswerMode: false,
      userError: false,
      userAnswer: {
        completeInput: []
      },
      userBookanswer:[],
      chsFhList: ["，", "。", "”", "：", "》", "？", "！", "；"],
    };
  },
  computed: {
    pinyinStyle() {
      let pyPos = this.curQue.pinyinPosition;
      if (pyPos === "left") {
        return {
          "column-gap": "16px",
        };
      }

      if (pyPos === "top") {
        return {
          "flex-direction": "column",
        };
      }

      if (pyPos === "right") {
        return {
          "column-gap": "16px",
        };
      }

      if (pyPos === "bottom") {
        return {
          "flex-direction": "column",
        };
      }
    },
  },
  created() {
    if (this.judgeAnswer) {
      this.isAnswerMode = true;
    }
    if (!this.curQue.Bookanswer) {
      let arr = [];
      let flag = false // 是否含有多个句子类型
      this.curQue.tableData.body.forEach((item, i) => {
        arr.push({
          content: [],
        });
        item.content.forEach((items) => {
            if(items.type === 'mulText'){
                flag = true
            }
          arr[i].content.push({
            answer: "",
            CrossAnswer: "",
            userAnswerJudge:
              items.answer || items.isCross ? "[JUDGE##F##JUDGE]" : "",
          });
        });
      });
      if(!flag){
        this.$set(this.curQue, "Bookanswer", arr);
      }
    } else {
      this.curQue.Bookanswer.forEach((item) => {
        item.content.forEach((item) => {
          if (item.userAnswerJudge == "[JUDGE##F##JUDGE]") {
            this.userError = true;
            return;
          }
        });
      });
    }
  },
  mounted() {
    this.handleData();
  },
  methods: {
    enterAnswer(i, j, type) {
      if (type == "input") {
        this.$forceUpdate();
        if (
          this.curQue.Bookanswer[i].content[j].answer.trim() ==
          this.curQue.tableData.body[i].content[j].answer
        ) {
          if (this.curQue.tableData.body[i].content[j].isCross) {
            if (
              this.curQue.Bookanswer[i].content[j].CrossAnswer ==
              this.curQue.tableData.body[i].content[j].CrossAnswer
            ) {
              this.curQue.Bookanswer[i].content[j].userAnswerJudge =
                "[JUDGE##T##JUDGE]";
            } else {
              this.curQue.Bookanswer[i].content[j].userAnswerJudge =
                "[JUDGE##F##JUDGE]";
            }
          } else {
            this.curQue.Bookanswer[i].content[j].userAnswerJudge =
              "[JUDGE##T##JUDGE]";
          }
        } else if (this.curQue.tableData.body[i].content[j].answer) {
          this.curQue.Bookanswer[i].content[j].userAnswerJudge =
            "[JUDGE##F##JUDGE]";
        }
      } else if (
        this.curQue.Bookanswer[i].content[j].CrossAnswer ==
        this.curQue.tableData.body[i].content[j].CrossAnswer
      ) {
        if (this.curQue.tableData.body[i].content[j].answer) {
          if (
            this.curQue.Bookanswer[i].content[j].answer ==
            this.curQue.tableData.body[i].content[j].answer
          ) {
            this.curQue.Bookanswer[i].content[j].userAnswerJudge =
              "[JUDGE##T##JUDGE]";
          } else {
            this.curQue.Bookanswer[i].content[j].userAnswerJudge =
              "[JUDGE##F##JUDGE]";
          }
        } else {
          this.curQue.Bookanswer[i].content[j].userAnswerJudge =
            "[JUDGE##T##JUDGE]";
        }
      } else {
        this.curQue.Bookanswer[i].content[j].userAnswerJudge =
          "[JUDGE##F##JUDGE]";
      }
    },
    // th 是否生成
    thIsShow(i, j) {
      let headers = this.curQue.tableData.headers;
      let col = 1;
      let colIndex = headers[i].content.findIndex(({ colspan }, index) => {
        if (index > j) return false;
        let num = colspan === undefined ? 1 : Number(colspan);
        if (num > 1) {
          col = num;
          return false;
        }
        if (index === j && col > 1) return true;
        if (col > 0) col -= 1;
        return false;
      });
      let row = 1;
      let rowIndex = headers.findIndex((item, index) => {
        let rowspan = item.content[j].rowspan;
        let num = rowspan === undefined ? 1 : Number(rowspan);
        if (num > 1) {
          row = num;
          return false;
        }
        if (index === i && row > 1) return true;
        if (row > 0) row -= 1;
        return false;
      });
      return colIndex === -1 && rowIndex === -1;
    },
    // rowspan colspan 控制td是否生成
    tdIsShow(i, j) {
      let body = this.curQue.tableData.body;
      let col = 1;
      let colIndex = body[i].content.findIndex(({ colspan }, index) => {
        if (index > j) return false;
        let num = colspan === undefined ? 1 : Number(colspan);
        if (num > 1) {
          col = num;
          return false;
        }
        if (index === j && col > 1) return true;
        if (col > 0) col -= 1;
        return false;
      });
      let row = 1;
      let rowIndex = body.findIndex((item, index) => {
        let rowspan = item.content[j].rowspan;
        let num = rowspan === undefined ? 1 : Number(rowspan);
        if (num > 1) {
          row = num;
          return false;
        }
        if (index === i && row > 1) return true;
        if (row > 0) row -= 1;
        return false;
      });
      return colIndex === -1 && rowIndex === -1;
    },
    handleData() {
      let Bookanswer = [];
      let itemLeg = 0;
      this.totalHasPy = false;
      let option = JSON.parse(JSON.stringify(this.curQue.tableData.body));
      let completeImage = [];
      option.forEach((item, index) => {
        Bookanswer.push({content: []});
        completeImage = [];
        itemLeg = item.length > itemLeg ? item.length : itemLeg;
        item.content.forEach((items, indexs) => {
            if(items.mulText){
                let userAnswer = JSON.parse(JSON.stringify(this.userAnswer));
                let correct = JSON.parse(JSON.stringify(items.mulText.correct));
                let complateArr = correct.completeInput.split("\n");
                complateArr.forEach((itemI, indexI) => {
                    if (itemI == "??" || itemI == "？？") {
                    complateArr[indexI] = "";
                    }
                });
                items.mulText.correct.complateArr = complateArr;
                this.curQue.tableData.body[index].content[indexs].mulText.correct.complateArr = complateArr;
                Bookanswer[index].content.push(userAnswer);
                let hengIndex = 0;
                items.pyNumber = [];

                items.mulText.detail.forEach((sdItem, sdIndex) => {
                    let isHasPY = 0;
                    let maxFontsize = 0;
                    sdItem.detail.forEach((sddItem) => {
                    if (sddItem.wordsList.length > 0) {
                        sddItem.wordsList.forEach((sItem, sIndex) => {
                        let reg = /_{2,}/g;
                        if (reg.test(sItem.chs)) {
                            sItem.index = sIndex;
                            sItem.isHeng = true;
                            sItem.hengIndex = hengIndex;
                            hengIndex++;
                        }
                        //补全句子
                        if (
                            !this.curQue.Bookanswer 
                        ) {
                            let reg = /_{2,}/g;
                            if (reg.test(sItem.chs)) {
                            let bool = false;
                            if (sddItem.hasOwnProperty("input_Isexample")) {
                                bool = sddItem.input_Isexample;
                            } else {
                                bool = items.Isexample;
                            }
                            let obj = null;
                            if (!sddItem.input_tian) {
                                obj = {
                                answer:
                                    bool && complateArr[sItem.hengIndex]
                                    ? complateArr[sItem.hengIndex]
                                    : "",
                                userAnswerJudge:
                                    bool || !complateArr[sItem.hengIndex]
                                    ? ""
                                    : "[JUDGE##F##JUDGE]",
                                input_Isexample: bool ? true : false,
                                };
                                Bookanswer[index].content[indexs].completeInput.push(
                                JSON.parse(JSON.stringify(obj))
                                );
                            } else {
                                if (sddItem.hengLeg == "-1") {
                                completeImage.push(obj);
                                } else {
                                for (let i = 0; i < Number(sddItem.hengLeg); i++) {
                                    completeImage.push(obj);
                                }
                                }
                                Bookanswer[index].content[indexs].completeInput.push(
                                JSON.parse(JSON.stringify(completeImage))
                                );
                            }
                            }
                        }

                        this.mergeWordSymbol(sItem);
                        if (sItem.pinyin) {
                            isHasPY++;
                            this.totalHasPy = true;
                        }
                        let fontSize = JSON.parse(JSON.stringify(sItem.fontSize));
                        fontSize = Number(fontSize.replace("px", ""));
                        maxFontsize = fontSize > maxFontsize ? fontSize : maxFontsize;
                        });
                    } else {
                        if (sddItem.sentence) {
                        let fontSize = JSON.parse(
                            JSON.stringify(sddItem.config.fontSize)
                        );
                        fontSize = Number(fontSize.replace("px", ""));
                        maxFontsize = fontSize > maxFontsize ? fontSize : maxFontsize;
                        }
                    }
                    });
                    sdItem.maxFontsize = maxFontsize;
                    items.pyNumber.push(isHasPY);
                });
            }
          
        });
      });
      if (!this.curQue.Bookanswer) {
        this.$set(
          this.curQue,
          "Bookanswer",
          JSON.parse(JSON.stringify(Bookanswer))
        );
      } else {
        let BookanswerStr = JSON.stringify(this.curQue.Bookanswer);
        let errReg = /\[JUDGE##F##JUDGE\]/g;
        if (errReg.test(BookanswerStr)) {
          let errorArr = BookanswerStr.match(/\[JUDGE##F##JUDGE\]/g);
          this.userErrorNumberTotal = errorArr.length;
        }
      }

      this.$set(this.curQue.tableData, "body", option);
      let contentWidth = 780;
      if (this.curQue.img_list && this.curQue.img_list.length > 0) {
        contentWidth = 780 - this.curQue.img_size;
      }
      if(itemLeg==1){
        this.itemsWidth = 780
      }else{
        this.itemsWidth = Math.floor(contentWidth / itemLeg) - 16;
      }
      

      // 把答错的挑出来
      if (this.judgeAnswer == "standardAnswer") {
        this.userErrorList = [];
        this.userBookanswer = [];
        this.curQue.tableData.body.forEach((item, index) => {
            item.content.forEach((items, indexs) => {
            if(items.mulText){
                let flag = false;
                // 句子填空
                items.mulText.correct.complateArr.forEach((itemI, indexI) => {
                if (
                    itemI &&
                    itemI !=
                    this.curQue.Bookanswer[index].content[indexs].completeInput[indexI]
                ) {
                    flag = true;
                }
                });

                if (flag) {
                    this.userErrorList.push(items);
                    this.userBookanswer.push(this.curQue.Bookanswer[index][indexs]);
                    this.userError = true;
                }
            }
            
          });
        });
      }
    },
    //词和标点合一起
    mergeWordSymbol(sItem) {
      if (this.chsFhList.indexOf(sItem.chs) > -1) {
        sItem.isShow = false;
      } else {
        sItem.isShow = true;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.config-table {
  width: 100%;
  margin-bottom: 16px;

  table {
    table-layout: fixed;
    font-size: 16px;
    color: #404040;
    border-collapse: collapse;

    caption {
      font-size: 20px;
      color: #000;
      font-weight: bold;
      line-height: 1.95;
    }

    th {
      font-family: "FZJCGFKTK", "GB-PINYINOK-B", "robot";
    }

    th,
    td {
      font-weight: normal;
      border: 1px solid #e6e6e6;
      padding: 8px 12px;
    }

    .thead-merge {
      display: flex;
      justify-content: space-evenly;
    }

    .preContent {
      font-family: "FZJCGFKTK", "GB-PINYINOK-B", "robot";
      display: flex;
      align-items: center;

      ::v-deep .el-textarea__inner {
        padding-top: 2px;
      }
    }

    td {
      // min-height: 51px;
      // height: 51px;

      .cell-wrap {
        display: flex;
        align-items: center;
        column-gap: 4px;
        justify-content: space-between;

        .content {
          width: 100%;
          font-family: "FZJCGFKTK", "GB-PINYINOK-B", "robot";
        }

        ::v-deep .el-textarea__inner {
          font-family: "FZJCGFKTK", "GB-PINYINOK-B", "robot";
          padding: 5px 0;
        }

        @each $type in left, center, right {
          .text-#{$type} {
            ::v-deep .el-textarea__inner {
              text-align: $type;
            }
          }
        }
      }

      .content {
        width: 100%;
        font-family: "FZJCGFKTK", "GB-PINYINOK-B", "robot";
      }

      .sentence {
        display: flex;

        .english {
          font-family: "robot";
          opacity: 0.6;
          word-break: break-word;
        }
      }

      .pinyin {
        font-family: "GB-PINYINOK-B";
        opacity: 0.6;
        word-break: break-word;
      }

      .chs {
        font-family: "FZJCGFKTK";
      }

      // 下划线
      &.underline {
        text-decoration: underline;
      }

      // 前缀 + 拼音
      .pre-pinyin {
        display: flex;
        align-items: flex-end;

        .right-pinyin {
          margin-left: 4px;
          column-gap: 2px;
          text-align: center;
          display: grid;
        }
      }
      .stem-content {
        flex: 1;
      }
      .number-box {
        // &-hasPY {
        //   margin-top: 19px;
        // }
      }
      .sent-main {
        position: relative;
        width: 100%;
        display: flex;
        flex-wrap: wrap;

        box-sizing: border-box;
        &-138 {
          padding-right: 138px;
        }
        &-bottom {
          margin-bottom: 9px;
        }
      }
      .sent-que-box {
        display: flex;
        flex-wrap: wrap;
        padding: 4px 0;
      }
      .sent-que {
        // font-size: 0;
        &-flex {
          flex: 1;
          display: flex;
          justify-content: space-between;
          align-items: stretch;
        }
        .sentence-part {
          flex: 1;
        }
        .sddItem_img_list {
          height: 32px;
        }
      }
    }
  }
}
</style>
<style lang="scss">
.config-table {
  .correct {
    .el-textarea.is-disabled .el-textarea__inner {
      color: #2ca767 !important;
    }
    .cross-tick {
      border-color: #2ca767 !important;
      .el-icon-check:before {
        color: #2ca767 !important;
      }
      .el-icon-close:before {
        color: #2ca767 !important;
      }
    }
  }
  .error {
    .el-textarea.is-disabled .el-textarea__inner {
      color: #ed342d !important;
    }
    .cross-tick {
      border-color: #ed342d !important;
      .el-icon-check:before {
        color: #ed342d !important;
      }
      .el-icon-close:before {
        color: #ed342d !important;
      }
    }
  }
}
</style>
