<template>
  <ModuleBase :type="data.type">
    <template #content>
      <!-- <label>标题：</label>
      <RichText
        ref="richText"
        v-model="data.title_con"
        :inline="true"
        :placeholder="'输入标题'"
        :font-size="data?.unified_attrib?.font_size"
        :font-family="data?.unified_attrib?.font"
        toolbar="fontselect fontsizeselect forecolor backcolor | underline | bold italic strikethrough alignleft aligncenter alignright"
        class="title-box"
      /> -->
      <el-table :key="refreshKey" :data="data.option" border style="width: 100%">
        <el-table-column fixed prop="number" label="序号" width="70">
          <template slot-scope="scope">
            <el-input v-model="scope.row.number" />
          </template>
        </el-table-column>
        <el-table-column fixed prop="con" label="内容" width="200">
          <template slot-scope="scope">
            <RichText
              ref="richText"
              v-model="scope.row.con"
              :inline="true"
              :item-index="scope.$index"
              :font-size="data?.unified_attrib?.font_size"
              :font-family="data?.unified_attrib?.font"
              toolbar="fontselect fontsizeselect forecolor backcolor | underline | bold italic strikethrough alignleft aligncenter alignright"
              @handleRichTextBlur="handleBlurCon"
            />
          </template>
        </el-table-column>
        <el-table-column v-if="isEnable(data.property.view_pinyin)" prop="con" label="拼音" width="150">
          <template slot-scope="scope">
            <RichText
              ref="richText"
              v-model="scope.row.pinyin"
              :inline="true"
              :font-size="data?.unified_attrib?.font_size"
              :font-family="data?.unified_attrib?.font"
              toolbar="fontselect fontsizeselect forecolor backcolor | underline | bold italic strikethrough alignleft aligncenter alignright"
            />
          </template>
        </el-table-column>
        <el-table-column prop="interpret" label="翻译" width="200">
          <template slot-scope="scope">
            <RichText
              ref="richText"
              v-model="scope.row.interpret"
              :inline="true"
              :font-size="data?.unified_attrib?.font_size"
              :font-family="data?.unified_attrib?.font"
              toolbar="fontselect fontsizeselect forecolor backcolor | underline | bold italic strikethrough alignleft aligncenter alignright"
            />
          </template>
        </el-table-column>
        <el-table-column prop="note" label="注释" width="200">
          <template slot-scope="scope">
            <RichText
              ref="richText"
              v-model="scope.row.note"
              :inline="true"
              :font-size="data?.unified_attrib?.font_size"
              :font-family="data?.unified_attrib?.font"
              toolbar="fontselect fontsizeselect forecolor backcolor | underline | bold italic strikethrough alignleft aligncenter alignright"
            />
          </template>
        </el-table-column>
        <el-table-column prop="img_list" label="图片" width="300">
          <template slot-scope="scope">
            <UploadPicture
              :file-info="scope.row.file_list[0]"
              :item-index="scope.$index"
              :show-upload="!scope.row.file_list[0]"
              @upload="uploadPic"
              @deleteFile="deletePic"
            />
          </template>
        </el-table-column>

        <el-table-column label="操作" width="150">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="handleDelete(scope.$index)">删除</el-button>
            <el-button size="mini" type="text" @click="moveElement(scope.row, scope.$index, 'up')">上移</el-button>
            <el-button size="mini" type="text" @click="moveElement(scope.row, scope.$index, 'down')">下移</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-button icon="el-icon-plus" style="margin: 24px 0" @click="addElement">增加一个</el-button>
      <el-button @click="handleMultilingual">多语言</el-button>
      <MultilingualFill
        :visible.sync="multilingualVisible"
        :text="multilingualText"
        :translations="data.multilingual"
        @SubmitTranslation="handleMultilingualTranslation"
      />
    </template>
  </ModuleBase>
</template>

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

import { getNotesData, getOption } from '@/views/book/courseware/data/notes';
import cnchar from 'cnchar';
export default {
  name: 'NotesPage',
  components: { UploadPicture },
  mixins: [ModuleMixin],
  data() {
    return {
      isEnable,
      data: getNotesData(),
      multilingualText: '',
      refreshKey: '',
    };
  },
  watch: {
    'data.option': 'handleMindMap',

    'data.property.is_first_sentence_first_hz_pinyin_first_char_upper_case': {
      handler(val, oldVal) {
        if (val === oldVal) return;

        if (isEnable(this.data.property.view_pinyin)) {
          this.handlePinyin();
        }
      },
      deep: true,
    },
  },
  methods: {
    // 删除行
    handleDelete(index) {
      this.data.option.splice(index, 1);
    },
    // 上移下移
    moveElement(dItem, index, type) {
      let obj = JSON.parse(JSON.stringify(dItem));
      if (type === 'up' && index > 0) {
        this.data.option.splice(index - 1, 0, obj);
        this.data.option.splice(index + 1, 1);
      }
      if (type === 'down' && index < this.data.option.length - 1) {
        this.data.option[index] = this.data.option.splice(index + 1, 1, this.data.option[index])[0];
      }
    },
    // 增加
    addElement() {
      this.data.option.push(getOption());
    },
    handleMindMap() {
      // 思维导图数据
      let node_list = [];
      this.data.option.forEach((item) => {
        node_list.push({
          name: item.con.replace(/<[^>]*>?/gm, ''),
          id: Math.random().toString(36).substring(2, 12),
        });
      });
      this.data.mind_map.node_list = node_list;
    },
    handleBlurCon(i) {
      let text = this.data.option[i].con.replace(/<[^>]+>/g, '');
      this.data.option[i].pinyin = cnchar
        .spell(
          text,
          'array',
          this.data.property.is_first_sentence_first_hz_pinyin_first_char_upper_case === 'true' ? 'high' : 'low',
          'tone',
        )
        .join(' ');

      this.handleMindMap();
    },
    handlePinyin() {
      this.data.option.forEach((item) => {
        let text = item.con.replace(/<[^>]+>/g, '');
        item.pinyin = cnchar
          .spell(
            text,
            'array',
            this.data.property.is_first_sentence_first_hz_pinyin_first_char_upper_case === 'true' ? 'high' : 'low',
            'tone',
          )
          .join(' ');
      });
    },
    handleMultilingual() {
      this.multilingualText = this.data.title_con ? this.data.title_con : '<p>&nbsp;</p>';
      this.data.option.forEach((item) => {
        this.multilingualText += item.con ? item.con : '<p>&nbsp;</p>';
        this.multilingualText += item.note ? item.note : '<p>&nbsp;</p>';
      });
      this.multilingualVisible = true;
    },
    // 获取拼音解析文本
    createParsedTextInfoPinyin(text) {
      if (text === '') {
        this.data.paragraph_list_parameter.pinyin_proofread_word_list = [];
        return;
      }
      this.data.paragraph_list_parameter.text = text.replace(/<[^>]+>/g, '');
      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;
      PinyinBuild_OldFormat(this.data.paragraph_list_parameter).then((res) => {
        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;
          let pinyin_index = 0;
          this.data.option.forEach((items, index) => {
            items.model_pinyin = [];
            if (items.content && mergedData[pinyin_index] && mergedData[pinyin_index][0]) {
              mergedData[pinyin_index][0].forEach((itemP) => {
                items.model_pinyin.push(itemP);
              });
              pinyin_index++;
            }
          });
        }
      });
    },
    // 填充校对后的拼音
    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;
    },
    uploadPic(file_id, index, file) {
      this.data.option[index].file_list[0] = file;
      this.data.file_id_list.push(file_id);
      this.refreshKey = Math.random();
    },
    deletePic(file_id, index) {
      this.data.option[index].file_list[0] = '';
      this.data.file_id_list = this.data.file_id_list.filter((item) => item !== file_id);
    },
  },
};
</script>
<style lang="scss" scoped>
.upload-file {
  display: flex;
  column-gap: 12px;
  align-items: center;
  margin: 8px 0;

  .file-name {
    display: flex;
    column-gap: 14px;
    align-items: center;
    justify-content: space-between;
    max-width: 360px;
    padding: 8px 12px;
    font-size: 14px;
    color: #1d2129;
    background-color: #f7f8fa;

    span {
      display: flex;
      column-gap: 14px;
      align-items: center;
    }
  }

  .svg-icon {
    cursor: pointer;
  }
}

.title-box {
  padding: 5px;
  margin: 5px 0;
  background-color: #f2f3f5;
  border: 1px solid #f2f3f5;
  border-radius: 4px;

  :deep p {
    margin: 0;
  }
}
</style>
<style lang="scss">
.tox .tox-editor-header {
  z-index: 3 !important;
}
</style>
