<template>
  <ModuleBase ref="base" :type="data.type">
    <template #content>
      <!-- <div class="fun-type">
        <a
          v-for="{ value, label } in tableTypeList"
          :key="value"
          :class="[data.mode === value ? 'active' : '']"
          @click="data.mode = value"
          >{{ label }}</a
        >
      </div> -->
      <div v-loading="loading">
        <div class="table-rich-toolbar">
          <el-select
            v-model="data.styles.fontFamily"
            placeholder="请选择"
            style="width: 130px"
            @change="BatchSetFormat('fontFamily', data.styles.fontFamily)"
          >
            <el-option v-for="font in fontList" :key="font.value" :label="font.label" :value="font.value" />
          </el-select>
          <el-select
            v-model="data.styles.fontSize"
            placeholder="请选择"
            style="width: 130px"
            @change="BatchSetFormat('fontSize', data.styles.fontSize)"
          >
            <el-option
              v-for="(value, index) in 16"
              :key="index"
              :label="6 + value * 2 + 'pt'"
              :value="6 + value * 2 + 'pt'"
            />
          </el-select>
          <el-form :model="property" inline>
            <el-form-item label="文字颜色">
              <el-color-picker
                v-model="data.styles.fontColor"
                @change="BatchSetFormat('color', data.styles.fontColor)"
              />
            </el-form-item>
            <el-form-item label="背景色">
              <el-color-picker v-model="data.styles.bgColor" />
            </el-form-item>
          </el-form>
          <span
            :class="[data.styles.isUnderline ? 'active' : '']"
            @click="
              data.styles.isUnderline = !data.styles.isUnderline;
              BatchSetFormat('underline');
            "
          >
            <SvgIcon icon-class="underline" size="20" />
          </span>
          <span
            :class="[data.styles.isBold ? 'active' : '']"
            @click="
              data.styles.isBold = !data.styles.isBold;
              BatchSetFormat('bold');
            "
          >
            <SvgIcon icon-class="font-bold" size="20" />
          </span>
          <span
            :class="[data.styles.isItalic ? 'active' : '']"
            @click="
              data.styles.isItalic = !data.styles.isItalic;
              BatchSetFormat('italic');
            "
          >
            <SvgIcon icon-class="font-italic" size="20" />
          </span>
          <span
            :class="[data.styles.isStrikethrough ? 'active' : '']"
            @click="
              data.styles.isStrikethrough = !data.styles.isStrikethrough;
              BatchSetFormat('strikethrough');
            "
          >
            <SvgIcon icon-class="strikethrough" size="20" />
          </span>
          <span
            :class="[data.styles.textAlign === 'LEFT' ? 'active' : '']"
            @click="
              data.styles.textAlign = data.styles.textAlign === 'LEFT' ? '' : 'LEFT';
              BatchSetFormat('align', 'LEFT');
            "
          >
            <SvgIcon icon-class="align-left" size="20" />
          </span>
          <span
            :class="[data.styles.textAlign === 'MIDDLE' ? 'active' : '']"
            @click="
              data.styles.textAlign = data.styles.textAlign === 'MIDDLE' ? '' : 'MIDDLE';
              BatchSetFormat('align', data.styles.textAlign === 'MIDDLE' ? 'MIDDLE' : 'LEFT');
            "
          >
            <SvgIcon icon-class="align-center" size="20" />
          </span>
          <span
            :class="[data.styles.textAlign === 'RIGHT' ? 'active' : '']"
            @click="
              data.styles.textAlign = data.styles.textAlign === 'RIGHT' ? '' : 'RIGHT';
              BatchSetFormat('align', data.styles.textAlign === 'RIGHT' ? 'RIGHT' : 'LEFT');
            "
          >
            <SvgIcon icon-class="align-right" size="20" />
          </span>
        </div>
        <div class="option-list">
          <div v-for="(item, i) in data.option_list" :key="i" class="table-node">
            <el-color-picker v-model="data.rows_bg_list[i]" />
            <div v-for="(li, j) in item" :key="li.mark" class="table-item">
              <!-- eslint-disable max-len -->
              <RichText
                v-if="property.isGetContent"
                ref="richText"
                v-model="li.content"
                :font-size="data?.unified_attrib?.font_size"
                :font-family="data?.unified_attrib?.font"
                :font-color="data?.unified_attrib?.text_color"
                :inline="true"
                :item-index="i + '#' + j"
                toolbar="fontselect fontsizeselect forecolor backcolor | underline | bold italic strikethrough alignleft aligncenter alignright image media link"
                @createParsedTextInfoPinyin="handleParsedTextPinyin($event, i, j)"
              />
              <el-input v-else v-model="li.content" @blur="handleBlurCon" />
              <el-button size="mini" @click="editCell(li.cell)">设置</el-button>
            </div>
          </div>
          <div class="table-node">
            <div style="flex-shrink: 0; width: 32px"></div>
            <div v-for="(value, index) in data.col_width" :key="index" class="table-item table-items">
              <el-color-picker v-model="data.cols_bg_list[index]" />
              <el-input v-model="value.value">
                <template slot="prepend">列宽</template><template slot="append">%</template></el-input
              >
            </div>
          </div>
        </div>
        <el-input
          v-if="data.property.fill_type === fillTypeList[1].value"
          v-model="data.vocabulary"
          type="textarea"
          :autosize="{ minRows: 2, maxRows: 4 }"
          resize="none"
          placeholder="请输入词汇，用于选词填空"
        />
        <p class="tips">在需要作答的单元格内输入三个以上下划线“___”</p>
        <el-button @click="handleViewPinyin()">识别</el-button>
        <el-button @click="handleMultilingual">多语言</el-button>
        <template v-if="isEnable(data.has_identify)">
          <p class="tips">
            在需要作答的单元格内录入标准答案，多个填空答案用换行录入，同一个填空有多个答案用斜线“/”隔开
          </p>
          <div class="option-list">
            <div v-for="(item, i) in data.answer_lists" :key="i" class="table-node">
              <div v-for="(li, j) in item" :key="i + 'col' + j" class="table-item">
                <el-input v-model="li.answer" type="textarea" :readonly="!data.option_list[i][j].hasInput" />
                <span
                  v-if="data.option_list[i][j].cell.isCross"
                  style="display: flex; align-items: center; font-size: 14px"
                  >勾叉答案<i
                    :class="[
                      { 'el-icon-check': li.crossAnswer === statusList[1] },
                      { 'el-icon-close': li.crossAnswer === statusList[2] },
                    ]"
                    style="display: block; width: 14px; height: 14px; border: 1px solid #000"
                    @click="toggle(li)"
                  ></i
                ></span>
              </div>
            </div>
          </div>
        </template>
        <AnswerAnalysisList
          v-if="data.answer_list?.length > 0 || data.analysis_list?.length > 0"
          :answer-list="data.answer_list"
          :analysis-list="data.analysis_list"
          :unified-attrib="data.unified_attrib"
          @updateAnswerAnalysisFileList="updateAnswerAnalysisFileList"
          @deleteAnswerAnalysis="deleteAnswerAnalysis"
        />
        <MultilingualFill
          :visible.sync="multilingualVisible"
          :text="multilingualText"
          :translations="data.multilingual"
          @SubmitTranslation="handleMultilingualTranslation"
        />
        <el-divider v-if="isEnable(data.property.view_pinyin)" content-position="left">
          拼音效果
          <el-button
            v-show="isEnable(data.property.view_pinyin)"
            type="text"
            icon="el-icon-refresh"
            title="刷新"
            class="refresh-pinyin-btn"
            @click.native="handleViewPinyin(true)"
        /></el-divider>
        <template v-if="isEnable(data.property.view_pinyin)">
          <!-- <template v-for="(item, index) in data.option_list">
            <PinyinText
              v-for="(items, indexs) in item"
              :id="'table_pinyin_text_' + index + '_' + indexs"
              :key="index + '_' + indexs"
              ref="PinyinText"
              :rich-text-list="items.rich_text_list"
              :pinyin-position="data.property.pinyin_position"
              :pinyin-size="data?.unified_attrib?.pinyin_size"
              :font-size="data?.unified_attrib?.font_size"
              :font-family="data?.unified_attrib?.font"
              @fillCorrectPinyin="fillCorrectPinyin"
            />
          </template> -->

          <table class="proofread-table">
            <tbody>
              <template v-for="(row, i) in data.option_list">
                <tr v-for="(item, j) in row" :key="item.mark">
                  <td class="pinyin-cell">
                    <PinyinText
                      :id="'table_pinyin_text_' + i + '_' + j"
                      :key="i + '_' + j"
                      ref="PinyinText"
                      :paragraph-list="item.paragraph_list"
                      :rich-text-list="item.rich_text_list"
                      :pinyin-position="data.property.pinyin_position"
                      :pinyin-size="data?.unified_attrib?.pinyin_size"
                      :font-size="data?.unified_attrib?.font_size"
                      :font-family="data?.unified_attrib?.font"
                      @fillCorrectPinyin="fillCorrectPinyin($event, i, j)"
                    />
                  </td>
                  <td class="proofread-cell">
                    <WordProofread
                      button-text="分词校对"
                      :word-data="getOptionWordData(item)"
                      @save="saveOptionWord($event, i, j)"
                    />
                  </td>
                </tr>
              </template>
            </tbody>
          </table>
        </template>
      </div>
      <el-dialog
        v-if="editCellFlag"
        title="设置单元格"
        :visible="editCellFlag"
        width="460px"
        :close-on-click-modal="false"
        @close="editCellFlag = false"
      >
        <el-form :model="activeCell" :inline="true">
          <el-form-item label="背景色">
            <el-color-picker v-model="activeCell.bgColor" />
          </el-form-item>
          <el-form-item label="勾叉">
            <el-switch v-model="activeCell.isCross" />
          </el-form-item>
          <el-form-item label="合并行">
            <el-input v-model="activeCell.rowspan" class="rowspan" type="number" />
          </el-form-item>
          <el-form-item label="合并列">
            <el-input v-model="activeCell.colspan" class="colspan" type="number" />
          </el-form-item>
        </el-form>
        <div slot="footer">
          <el-button @click="editCellFlag = false">取消</el-button>
          <el-button type="primary" @click="editCellFlag = false">确定</el-button>
        </div>
      </el-dialog>
    </template>
  </ModuleBase>
</template>

<script>
import { isEnable } from '@/views/book/courseware/data/common';
import ModuleMixin from '../../common/ModuleMixin';
import { PinyinBuild_OldFormat } from '@/api/book';

import { getRandomNumber } from '@/utils';
import PinyinText from '@/components/PinyinText.vue';
import WordProofread from '@/views/book/courseware/create/components/common/WordProofread.vue';
import { buildWordProofreadData } from '@/views/book/courseware/create/components/common/wordProofread';

import {
  getTableData,
  getOption,
  tableTypeList,
  getAnswerOption,
  fillTypeList,
} from '@/views/book/courseware/data/table';
import { fontList } from '@/common/data';

export default {
  name: 'TablePage',
  components: {
    PinyinText,
    WordProofread,
  },
  mixins: [ModuleMixin],
  data() {
    return {
      isEnable,
      data: getTableData(),
      tableTypeList,
      fontList,
      multilingualText: '',
      isViewExplanatoryNoteDialog: false,
      oldRichData: {},
      fillTypeList,
      activeCell: null,
      editCellFlag: false,
      statusList: ['normal', 'tick', 'cross'],
      editContentIndex: '', // 编辑内容的单元格索引
      loading: false,
      optionWordDataMap: {},
      optionWordDataSourceMap: {},
      inited: false,
    };
  },
  watch: {
    'data.property.row_count': {
      handler(val) {
        if (val < this.data.option_list.length) {
          this.data.option_list = this.data.option_list.slice(0, val);
          this.data.answer_lists = this.data.answer_lists.slice(0, val);
          this.data.rows_bg_list = this.data.rows_bg_list.slice(0, val);
        } else {
          const diff = val - this.data.option_list.length;
          for (let i = 0; i < diff; i++) {
            this.data.option_list.push(Array.from({ length: this.data.property.column_count }, getOption));
            this.data.answer_lists.push(Array.from({ length: this.data.property.column_count }, getAnswerOption));
            this.data.rows_bg_list.push('');
          }
        }
      },
    },
    'data.property.column_count': {
      handler(val) {
        const diff = val - this.data.option_list[0].length;
        for (let i = 0; i < diff; i++) {
          this.data.col_width.push({
            value: '',
          });
          this.data.cols_bg_list.push('');
        }
        this.data.cols_bg_list = this.data.cols_bg_list.slice(0, val);
        this.data.option_list = this.data.option_list.map((row) => {
          if (val < row.length) {
            this.data.col_width = this.data.col_width.slice(0, val);
            return row.slice(0, val);
          }
          const diff = val - row.length;

          return row.concat(Array.from({ length: diff }, getOption));
        });
        this.data.answer_lists = this.data.answer_lists?.map((row) => {
          if (val < row.length) {
            return row.slice(0, val);
          }
          const diff = val - row.length;

          return row.concat(Array.from({ length: diff }, getAnswerOption));
        });
      },
    },
    'data.property.view_pinyin': {
      handler(val) {
        // 下面都是原来的处理方式
        // let text = '';
        // this.data.option_list.forEach((item) => {
        //   item.forEach((items) => {
        //     text += `${items.content.replace(/<[^>]+>/g, '')}\n`;
        //   });
        // });
        // if (!isEnable(val)) {
        //   this.data.paragraph_list = [];
        //   return;
        // }
        // if (isEnable(val) && text && this.data.paragraph_list.length <= 0) {
        //   this.data.paragraph_list_parameter.text = text;
        //   this.data.paragraph_list_parameter.is_first_sentence_first_hz_pinyin_first_char_upper_case =
        //     this.data.property.is_first_sentence_first_hz_pinyin_first_char_upper_case;
        //   this.data.option_list.forEach((item, index) => {
        //     item.forEach((items, indexs) => {
        //       this.createParsedTextInfoPinyin(items.content, `${index}#${indexs}`);
        //     });
        //   });
        // }

        if (this.property.isSilentPropertyWatch) return;
        if (!this.isEnable(val)) {
          this.data.option_list.forEach((row) => {
            row.forEach((item) => {
              item.paragraph_list = [];
              item.paragraph_list_parameter = {
                text: '',
                pinyin_proofread_word_list: [],
              };
            });
          });
          this.optionWordDataMap = {};
          this.optionWordDataSourceMap = {};
          return;
        }
        this.handleViewPinyin().finally(() => {
          this.inited = true;
        });
      },
      deep: true,
    },
    // 'data.property.is_first_sentence_first_hz_pinyin_first_char_upper_case': {
    //   handler(val, oldVal) {
    //     if (val === oldVal) return;
    //     let text = '';
    //     this.data.option_list.forEach((item) => {
    //       item.forEach((items) => {
    //         text += `${items.content.replace(/<[^>]+>/g, '')}\n`;
    //       });
    //     });
    //     if (!isEnable(this.data.property.view_pinyin)) {
    //       this.data.paragraph_list = [];
    //       return;
    //     }
    //     if (text && isEnable(this.data.property.view_pinyin)) {
    //       this.data.paragraph_list_parameter.text = text;
    //       this.data.paragraph_list_parameter.is_first_sentence_first_hz_pinyin_first_char_upper_case = val;
    //       this.data.option_list.forEach((item, index) => {
    //         item.forEach((items, indexs) => {
    //           this.createParsedTextInfoPinyin(items.content, `${index}#${indexs}`);
    //         });
    //       });
    //     }
    //   },
    //   deep: true,
    // },
    'data.vocabulary': {
      handler(val) {
        if (!val) return;
        this.data.word_list = val
          .split(/[\n\r]+/)
          .map((item) => item.split(' ').filter((s) => s))
          .flat()
          .map((content) => {
            return {
              content,
              mark: getRandomNumber(),
            };
          });
      },
    },
    'data.unified_attrib': {
      handler(val) {
        if (val) {
          this.data.styles.fontFamily = this.data?.unified_attrib?.font || '楷体,微软雅黑';
          this.data.styles.fontSize = this.data?.unified_attrib?.font_size || '12pt';
          this.data.styles.fontColor = this.data?.unified_attrib?.text_color || '#1d2129';
          this.data.styles.textAlign = this.data?.unified_attrib?.align || '';
        }
      },
      deep: true,
      immediate: true,
    },
    'data.option_list': {
      handler(newVal) {
        if (this.loading) return;
        if (this.inited || !Array.isArray(newVal) || newVal.length <= 0) return;
        if (!this.isEnable(this.data.property.view_pinyin)) return;
        this.ensureOptionWordProofreadData();
        this.inited = true;
      },
      deep: true,
    },
  },
  methods: {
    toggle(status) {
      const index = this.statusList.findIndex((item) => status.crossAnswer === item);
      status.crossAnswer = index === this.statusList.length - 1 ? this.statusList[0] : this.statusList[index + 1];
    },
    editCell(cell) {
      this.activeCell = cell;
      this.editCellFlag = true;
    },
    // 设置样式
    BatchSetFormat(text, val = '') {
      this.$refs.richText.forEach((richText) => {
        richText.setRichFormat(text, val, true);
      });
    },
    ensureOptionWordProofreadData() {
      this.data.option_list.forEach((row) => {
        row.forEach((option) => {
          if (!option?.mark) return;
          const wordData = { detail: [{ sentences: [], segList: [] }] };
          option.rich_text_list?.forEach((item) => {
            const sentence = (item.word_list || []).reduce((acc, itemss) => `${acc + itemss.text}`, '');
            const seg = (item.word_list || []).map((itemss) => itemss.text);
            wordData.detail[0].sentences.push(sentence);
            wordData.detail[0].segList.push(seg);
          });
          this.$set(this.optionWordDataMap, option.mark, wordData);
          this.$set(this.optionWordDataSourceMap, option.mark, option.content);
        });
      });
    },
    async handleViewPinyin(isPrompt = false) {
      this.data.has_identify = 'false';
      if (isPrompt) {
        try {
          await this.$confirm('刷新将会重置分词和拼音，是否刷新？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          });
        } catch (e) {
          return;
        }
      }
      this.loading = true;
      try {
        if (!this.isEnable(this.data.property.view_pinyin)) {
          this.data.option_list.forEach((row) => {
            row.forEach((item) => {
              item.paragraph_list = [];
              item.paragraph_list_parameter = {
                text: '',
                pinyin_proofread_word_list: [],
              };
              item.model_essay = [];
              // this.data.answer_list[index][indexs].answer_list = [];
              if (item.content) {
                let inputIndex = 0;
                item.content
                  .split(/<(p|div)[^>]*>(.*?)<\/(p|div)>/g)
                  .filter((s) => s && !s.match(/^(p|div)$/))
                  .forEach((itemss) => {
                    if (itemss.charCodeAt() === 10) return;
                    let strArr = itemss.split(/_{3,}/g);
                    strArr.forEach((itemS, index) => {
                      item.model_essay.push({
                        value: itemS,
                        type: 'text',
                      });
                      if (index !== strArr.length - 1) {
                        item.model_essay.push({
                          value: '',
                          type: 'input',
                          mark: getRandomNumber(),
                          inputIndex,
                          write_base64: '',
                          audio_answer_list: [],
                        });
                        inputIndex += 1;
                        this.$set(item, 'hasInput', true);
                        this.data.has_identify = 'true';
                      }
                    });
                    // // 去除所有的 font-size 样式
                    // .replace(/font-size:\s*\d+(\.\d+)?px;/gi, '')
                    // // 匹配 class 名为 rich-fill 的 span 标签和三个以上的_，并将它们组成数组
                    // .replace(/<span class="rich-fill".*?>(.*?)<\/span>|([_]{3,})/gi, '###$1$2###');
                  });
              }
              item.crossAnswer = 'normal';
            });
          });
          this.optionWordDataMap = {};
          this.optionWordDataSourceMap = {};
          return;
        }

        const tasks = [];
        this.data.option_list.forEach((row, i) => {
          row.forEach((col, j) => {
            const text = col.content;
            if (!text) return;
            let obj = {
              text,
              pinyin_proofread_word_list: [],
            };
            this.$set(col, 'paragraph_list_parameter', obj);
            tasks.push(
              this.createParsedTextInfoPinyin(text, i, j).then(({ parsed_text, rich_text }) => {
                this.$set(this.optionWordDataMap, col.mark, buildWordProofreadData(parsed_text?.paragraph_list || []));
                this.$set(this.optionWordDataSourceMap, col.mark, text);
                let list = rich_text.text_list;
                list.forEach((item) => {
                  let inputIndex = 0;
                  if (item.word_list) {
                    item.word_list.forEach((items, index) => {
                      let isUnderline = /^_{3,}$/.test(items.text);
                      if (isUnderline) {
                        let obj = {
                          value: '',
                          type: 'input',
                          mark: getRandomNumber(),
                          inputIndex,
                          write_base64: '',
                          audio_answer_list: [],
                        };
                        inputIndex++;
                        item.word_list[index] = { ...items, ...obj };
                        this.$set(col, 'hasInput', true);
                        this.data.has_identify = 'true';
                      } else {
                        items.type = 'text';
                      }
                    });
                  } else {
                    item.type = 'text';
                  }
                });
                this.$set(col, 'rich_text_list', list);
              }),
            );
          });
        });
        await Promise.all(tasks);
      } finally {
        this.loading = false;
      }
      // this.identifyText();
    },
    // 识别文本
    identifyText(editIndex) {
      let text = '';
      this.data.has_identify = 'true';
      this.data.option_list.forEach((item, index) => {
        item.forEach((items, indexs) => {
          items.model_essay = [];
          // this.data.answer_list[index][indexs].answer_list = [];
          if (items.content) {
            let inputIndex = 0;
            items.content
              .split(/<(p|div)[^>]*>(.*?)<\/(p|div)>/g)
              .filter((s) => s && !s.match(/^(p|div)$/))
              .forEach((itemss) => {
                if (itemss.charCodeAt() === 10) return;
                let strArr = itemss.split(/_{3,}/g);
                strArr.forEach((itemS, index) => {
                  items.model_essay.push({
                    value: itemS,
                    type: 'text',
                  });
                  if (index !== strArr.length - 1) {
                    items.model_essay.push({
                      value: '',
                      type: 'input',
                      mark: getRandomNumber(),
                      inputIndex,
                      write_base64: '',
                      audio_answer_list: [],
                    });
                    inputIndex += 1;
                    this.$set(items, 'hasInput', true);
                  }
                });
                // // 去除所有的 font-size 样式
                // .replace(/font-size:\s*\d+(\.\d+)?px;/gi, '')
                // // 匹配 class 名为 rich-fill 的 span 标签和三个以上的_，并将它们组成数组
                // .replace(/<span class="rich-fill".*?>(.*?)<\/span>|([_]{3,})/gi, '###$1$2###');
              });
          }
          items.crossAnswer = 'normal';
          // text += `${items.content.replace(/<[^>]+>/g, '')}\n`;
          text += `${items.content}\n`;
        });
      });
      if (isEnable(this.data.property.view_pinyin)) {
        if (editIndex) {
          let arr = editIndex.split('#');
          text = this.data.option_list[arr[0]][arr[1]].content;
          this.createParsedTextInfoPinyin(text, editIndex);
        } else {
          this.data.option_list.forEach((item, index) => {
            item.forEach((items, indexs) => {
              this.createParsedTextInfoPinyin(items.content, `${index}#${indexs}`, true);
            });
          });
        }
      }
    },
    // 获取拼音解析文本
    // createParsedTextInfoPinyin(text, editIndex, flag) {
    //   if (text === '') {
    //     this.data.paragraph_list_parameter.pinyin_proofread_word_list = [];
    //     return;
    //   }
    //   // .replace(/<[^>]+>/g, '')
    //   this.data.paragraph_list_parameter.text = text;
    //   this.data.paragraph_list_parameter.is_first_sentence_first_hz_pinyin_first_char_upper_case =
    //     this.data.property.is_first_sentence_first_hz_pinyin_first_char_upper_case;
    //   this.data.paragraph_list_parameter.is_rich_text = 'true';
    //   if (flag) this.loading = true;
    //   PinyinBuild_OldFormat(this.data.paragraph_list_parameter).then((res) => {
    //     if (flag) {
    //       this.loading = false;
    //     }
    //     if (res.parsed_text) {
    //       const mergedData = res.parsed_text.paragraph_list.map((outerArr, i) =>
    //         outerArr.map((innerArr, j) =>
    //           innerArr.map((newItem, k) => {
    //             // 从 originalData 中找到对应的项
    //             const originalItem = this.data.paragraph_list[i]?.[j]?.[k];

    //             // 如果 originalItem 有 activeTextStyle，就合并到 newItem
    //             if (originalItem?.activeTextStyle) {
    //               return {
    //                 ...newItem,
    //                 activeTextStyle: originalItem.activeTextStyle,
    //               };
    //             }
    //             // 否则直接返回 newItem
    //             return newItem;
    //           }),
    //         ),
    //       );
    //       this.data.paragraph_list = mergedData;
    //       if (editIndex) {
    //         let arr = editIndex.split('#');
    //         let list = res.rich_text.text_list;
    //         list.forEach((item) => {
    //           let inputIndex = 0;
    //           if (item.word_list) {
    //             item.word_list.forEach((items, index) => {
    //               let isUnderline = /^_{3,}$/.test(items.text);
    //               if (isUnderline) {
    //                 let obj = {
    //                   value: '',
    //                   type: 'input',
    //                   mark: getRandomNumber(),
    //                   inputIndex,
    //                   write_base64: '',
    //                   audio_answer_list: [],
    //                 };
    //                 inputIndex++;
    //                 item.word_list[index] = { ...items, ...obj };
    //               } else {
    //                 items.type = 'text';
    //               }
    //             });
    //           } else {
    //             item.type = 'text';
    //           }
    //         });
    //         this.$set(this.data.option_list[arr[0]][arr[1]], 'rich_text_list', list);
    //       } else {
    //         this.$set(this.data, 'rich_text_list', res.rich_text.text_list);
    //       }
    //       let pinyin_index = 0;
    //       this.data.option_list.forEach((item, index) => {
    //         item.forEach((items, indexs) => {
    //           items.model_pinyin = [];
    //           let inputIndex = 0;
    //           if (items.content && mergedData[pinyin_index] && mergedData[pinyin_index][0]) {
    //             mergedData[pinyin_index][0].forEach((itemP) => {
    //               let isUnderline = /^_{3,}$/.test(itemP.text);
    //               if (isUnderline) {
    //                 items.model_pinyin.push({
    //                   value: '',
    //                   type: 'input',
    //                   mark: getRandomNumber(),
    //                   inputIndex,
    //                 });
    //                 inputIndex++;
    //               } else {
    //                 items.model_pinyin.push(itemP);
    //               }
    //             });
    //             pinyin_index++;
    //           }
    //         });
    //       });
    //       if (this.editContentIndex) {
    //         this.editContentIndex = '';
    //       }
    //     }
    //   });
    // },
    // // 填充校对后的拼音
    // fillCorrectPinyin({ selectContent: { text, pinyin, activeTextStyle }, i, j, k }) {
    //   this.data.paragraph_list_parameter.pinyin_proofread_word_list.push({
    //     paragraph_index: i,
    //     sentence_index: j,
    //     word_index: k,
    //     word: text,
    //     pinyin,
    //   });
    //   if (pinyin) this.data.paragraph_list[i][j][k].pinyin = pinyin;
    //   if (activeTextStyle) this.data.paragraph_list[i][j][k].activeTextStyle = activeTextStyle;
    // },
    // 思维导图数据
    handleMindMap() {
      let node_list = [];
      this.data.option_list.forEach((item) => {
        item.forEach((items) => {
          node_list.push({
            name: items.content.replace(/<[^>]*>?/gm, ''),
            id: Math.random().toString(36).substring(2, 12),
          });
        });
      });
      this.data.mind_map.node_list = node_list;
    },
    handleBlurCon(index) {
      this.editContentIndex = index;
      this.identifyText(index);
      this.handleMindMap();
    },
    handleMultilingual() {
      this.multilingualText = '';
      this.data.option_list.forEach((item) => {
        item.forEach((items) => {
          this.multilingualText += items.content ? `<p>${items.content}</p>` : '<p>&nbsp;</p>';
        });
      });
      this.multilingualVisible = true;
    },
    getOptionWordData(option) {
      if (!option || !option.mark) return { detail: [] };
      return this.optionWordDataMap[option.mark] || { detail: [] };
    },
    async saveOptionWord(saveArr, rowIndex, colIndex) {
      const option = this.data.option_list[rowIndex]?.[colIndex];
      if (!option) return;
      const { parsed_text } = await this.createParsedTextInfoPinyin(
        option.content,
        rowIndex,
        colIndex,
        'option_list',
        saveArr,
      ).then(({ rich_text }) => {
        let list = rich_text.text_list;
        list.forEach((item) => {
          let inputIndex = 0;
          if (item.word_list) {
            item.word_list.forEach((items, index) => {
              let isUnderline = /^_{3,}$/.test(items.text);
              if (isUnderline) {
                let obj = {
                  value: '',
                  type: 'input',
                  mark: getRandomNumber(),
                  inputIndex,
                  write_base64: '',
                  audio_answer_list: [],
                };
                inputIndex++;
                item.word_list[index] = { ...items, ...obj };
              } else {
                items.type = 'text';
              }
            });
          } else {
            item.type = 'text';
          }
        });
        this.$set(this.data.option_list[rowIndex][colIndex], 'rich_text_list', list);
      });
      this.$set(this.optionWordDataMap, option.mark, buildWordProofreadData(parsed_text?.paragraph_list || []));
      this.$set(this.optionWordDataSourceMap, option.mark, option.content || '');
    },
    handleParsedTextPinyin(text, i, j) {
      if (!this.isEnable(this.data.property.view_pinyin)) return;
      if (this.data.option_list?.length > 0 && this.data.option_list[0].paragraph_list?.length > 0) return;
      if (!text) return;
      this.data.option_list[i][j].paragraph_list_parameter.text = text.replace(/<[^>]+>/g, '').replace(/&nbsp;/g, ' ');
      this.createParsedTextInfoPinyin(text, i, j);
    },
  },
};
</script>

<style lang="scss" scoped>
.option-list {
  margin-bottom: 12px;

  .table-node {
    display: flex;
    row-gap: 16px;

    .table-item {
      flex: 1;
      min-width: 140px;
      padding: 8px;
      border: 1px solid $border-color;

      &:not(:last-child) {
        border-right: 0;
      }

      :deep p {
        margin: 0;
      }

      :deep .el-input-group__append,
      :deep .el-input-group__prepend {
        padding: 0 5px;
      }

      &.table-items {
        display: flex;
        align-items: center;
      }
    }
  }
}

.fun-type {
  display: flex;
  gap: 5px;
  width: 100%;
  padding-bottom: 10px;
  border-bottom: 1px solid #e5e6eb;

  a {
    padding: 5px 10px;
    font-weight: normal;
    color: #1d2129;
    cursor: pointer;
    background: #f2f3f5;
    border: 1px solid #f2f3f5;
    border-radius: 2px;

    &.active {
      color: #165dff;
      background: #e7eeff;
      border-color: #165dff;
    }
  }
}

.table-rich-toolbar {
  display: flex;
  gap: 5px;
  padding: 5px 0;

  /* align-items: center; */

  :deep .el-form-item--small.el-form-item {
    margin: 0 5px 0 0;
  }

  :deep .el-form-item__label {
    padding-right: 3px;
  }

  > span {
    height: 30px;
    padding: 5px 6px;
    color: #222f3e;
    cursor: pointer;
    border-radius: 5px;

    &:hover {
      background: #cce2fa;
    }

    &.active {
      background: #a6ccf7;
    }
  }
}

.tips {
  font-size: 12px;
  color: #999;
}

:deep .el-input-group--append .el-input__inner {
  padding: 0;
  text-align: center;
}

.proofread-table {
  width: 100%;
  border-collapse: collapse;

  td {
    padding: 8px;
    vertical-align: top;
    border: 1px solid #ebeef5;
  }

  .pinyin-cell {
    width: calc(100% - 140px);
  }

  .proofread-cell {
    width: 140px;
    text-align: center;
    white-space: nowrap;
  }
}
</style>
