<template>
  <QuestionBase>
    <template #content>
      <div class="stem">
        <RichText v-model="data.stem" :font-size="18" placeholder="输入题干" />

        <RichText
          v-if="isEnable(data.property.is_enable_description)"
          v-model="data.description"
          placeholder="输入提示"
        />
      </div>

      <div class="content">
        <label class="title-little">字词：</label>
        <ul>
          <li v-for="(item, i) in data.option_list" :key="i" class="content-word-card">
            <div v-if="item.picture_file_id" class="item-left">
              <el-image
                style="width: 72px; height: 72px"
                :src="pic_list[item.picture_file_id]"
                :preview-src-list="[pic_list[item.picture_file_id]]"
                fit="contain"
              />
              <el-button size="small" class="delete-btn" @click="delectOptions(i, item.picture_file_id)">
                <i class="el-icon-delete"></i>删除
              </el-button>
            </div>
            <UploadDrag v-else ref="uploadDrag" :item-index="i" :limit="1" @fileUploadSuccess="fileUploadSuccess" />
            <div v-loading="loading_list[i] ? loading_list[i].loadings : false" class="word-card-item">
              <div class="word-card">
                <el-input
                  v-model="item.content"
                  :placeholder="'输入汉字或词汇'"
                  @blur="handleChineseStrokes(item, i)"
                />
                <el-input
                  v-model="item.pinyin"
                  :placeholder="'拼音间用空格隔开，如: ni3 hao3'"
                  @change="changePinyin(item)"
                />
                <div v-if="item.audio_file_id">
                  <SoundRecord :wav-blob.sync="item.audio_file_id" />
                </div>
                <template v-else>
                  <div :class="['upload-audio-play']">
                    <UploadAudio
                      v-if="data.other.audio_generation_method === 'upload'"
                      :key="item.audio_file_id || i"
                      :file-id="item.audio_file_id"
                      :item-index="i"
                      :show-upload="!item.audio_file_id"
                      @upload="uploads"
                      @deleteFile="deleteFiles"
                    />
                    <div
                      v-else-if="data.other.audio_generation_method === 'auto'"
                      v-loading="loading_list[i] ? loading_list[i].loading : false"
                      class="auto-matically"
                      @click="handleMatically(item, i)"
                    >
                      <SvgIcon icon-class="voiceprint-line" class="record" />
                      <span class="auto-btn">{{ item.audio_file_id ? '已生成' : '生成音频' }}</span>
                    </div>
                    <SoundRecord v-else :wav-blob.sync="item.audio_file_id" />
                  </div>
                </template>
                <el-input v-model="item.definition" placeholder="输入释义" type="textarea" :rows="1" />
                <el-input v-model="item.collocation" placeholder="输入搭配" />
              </div>
              <SvgIcon
                icon-class="delete"
                class="delete pointer"
                @click="deleteOption(i, item.audio_file_id, item.picture_file_id)"
              />
            </div>

            <div class="example-sentence-box">
              <div v-for="(items, indexs) in item.example_sentence" :key="indexs" class="example-sentence">
                <span class="question-number" title="双击切换序号类型" @dblclick="changeOptionType(data)">
                  {{ computedQuestionNumber(indexs, data.option_number_show_mode) }}
                </span>
                <el-input v-model="item.example_sentence[indexs]" placeholder="输入例句" />
                <SvgIcon icon-class="delete" class="delete pointer" @click="deleteSentence(item, indexs)" />
              </div>
              <span class="add-option" @click="addSentence(item)">
                <SvgIcon icon-class="add-circle" size="14" /> <span>增加例句</span>
              </span>
            </div>
          </li>
        </ul>
      </div>
      <div class="footer">
        <span class="add-option" @click="addOption">
          <SvgIcon icon-class="add-circle" size="14" /> <span>增加字词</span>
        </span>
      </div>
    </template>

    <template #property>
      <el-form :model="data.property" label-width="72px" label-position="left">
        <el-form-item label="题号">
          <el-input v-model="data.property.question_number" />
        </el-form-item>
        <el-form-item>
          <el-radio
            v-for="{ value, label } in questionNumberTypeList"
            :key="value"
            v-model="data.other.question_number_type"
            :label="value"
          >
            {{ label }}
          </el-radio>
        </el-form-item>
        <el-form-item label="题干题号">
          <el-select v-model="data.property.stem_question_number_font_size">
            <el-option v-for="item in fontSizeList" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="提示">
          <el-radio
            v-for="{ value, label } in switchOption"
            :key="value"
            v-model="data.property.is_enable_description"
            :label="value"
          >
            {{ label }}
          </el-radio>
        </el-form-item>
        <el-form-item label="分值">
          <el-radio
            v-for="{ value, label } in scoreTypeList"
            :key="value"
            v-model="data.property.score_type"
            :label="value"
          >
            {{ label }}
          </el-radio>
        </el-form-item>
        <el-form-item>
          <el-input-number
            v-model="data.property.score"
            :min="0"
            :step="data.property.score_type === scoreTypeList[0].value ? 1 : 0.1"
          />
        </el-form-item>
        <el-form-item label="音频">
          <el-radio
            v-for="{ value, label } in audioGenerationMethodList"
            :key="value"
            v-model="data.other.audio_generation_method"
            :label="value"
          >
            {{ label }}
          </el-radio>
        </el-form-item>
      </el-form>
    </template>
  </QuestionBase>
</template>

<script>
import QuestionMixin from '../common/QuestionMixin.js';
import UploadAudio from '../common/UploadAudio.vue';
import SoundRecord from '../common/SoundRecord.vue';
import { GetStaticResources, GetFileStoreInfo } from '@/api/app';
import { changeOptionType, handleInputNumber, addTone } from '@/views/exercise_questions/data/common';
import UploadDrag from '../common/UploadDrag.vue';

import {
  analysisRecognitionWordCardData,
  wordCardData,
  learnTypeList,
  audioGenerationMethodList,
  getOption,
} from '@/views/exercise_questions/data/wordCard';

export default {
  name: 'WordCardQuestion',
  components: {
    UploadAudio,
    SoundRecord,
    UploadDrag,
  },
  mixins: [QuestionMixin],
  data() {
    return {
      learnTypeList,
      audioGenerationMethodList,
      data: JSON.parse(JSON.stringify(wordCardData)),
      changeOptionType,
      handleInputNumber,
      pic_list: {},
      is_first: true,
      loading_list: [
        {
          loading: false,
          loadings: false,
        },
        {
          loading: false,
          loadings: false,
        },
        {
          loading: false,
          loadings: false,
        },
      ],
      matically_pinyin_obj: {},
    };
  },
  watch: {
    'data.file_id_list': {
      handler() {
        if (this.is_first) {
          this.handleData();
        }
      },
      deep: true,
    },
    'data.option_list.length': {
      handler(val) {
        this.loading_list = [];
        for (let i = 0; i < val; i++) {
          let obj = {
            loading: false,
            loadings: false,
          };
          this.loading_list.push(obj);
        }
      },
      deep: true,
      immediate: true,
    },
  },
  methods: {
    // 初始化数据
    handleData() {
      this.data.file_id_list.forEach((item) => {
        GetFileStoreInfo({ file_id: item }).then(({ file_id, file_url }) => {
          this.$set(this.pic_list, file_id, file_url);
        });
      });
      this.is_first = false;
    },
    addOption() {
      this.data.option_list.push(getOption());
    },
    uploads(file_id, index) {
      this.data.option_list[index].audio_file_id = file_id;
      this.data.file_id_list.push(file_id);
    },
    deleteFiles(file_id, itemIndex) {
      this.data.option_list[itemIndex].audio_file_id = '';
      this.data.file_id_list.splice(this.data.file_id_list.indexOf(file_id), 1);
    },
    /**
     * 删除音频 id
     * @param {number} i 选项下标
     */
    deleteAudio(i) {
      this.data.file_id_list.splice(this.data.file_id_list.indexOf(this.data.option_list[i].audio_file_id), 1);
      this.data.option_list[i].audio_file_id = '';
    },
    // 删除小题
    deleteOption(i, file_id, pic_id) {
      this.$confirm('是否删除该条内容？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.data.option_list.splice(i, 1);
          if (file_id && this.data.file_id_list.indexOf(file_id) > -1) {
            this.data.file_id_list.splice(this.data.file_id_list.indexOf(file_id), 1);
          }
          if (pic_id && this.data.file_id_list.indexOf(pic_id) > -1) {
            this.data.file_id_list.splice(this.data.file_id_list.indexOf(pic_id), 1);
          }
          this.loading_list.splice(i, 1);
        })
        .catch(() => {});
    },
    // 删除
    delectOptions(i, id) {
      this.$confirm('是否删除该图片？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          delete this.pic_list[id];
          this.data.file_id_list.splice(this.data.file_id_list.indexOf(id), 1);
          this.data.option_list[i].picture_file_id = '';
          this.$refs.uploadDrag.clearFiles();
        })
        .catch(() => {});
    },
    // 删除例句
    deleteSentence(item, index) {
      this.$confirm('是否删除该条例句？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          item.example_sentence.splice(index, 1);
        })
        .catch(() => {});
    },
    // 自动生成音频
    handleMatically(item, i) {
      let MethodName = 'tool-TextToVoiceFile';
      let data = {};
      if (item.content.trim()) {
        data = {
          text: item.content.trim(),
        };
      } else if (item.pinyin.trim()) {
        MethodName = 'tool-PinyinToVoiceFile';
        data = {
          pinyin: item.pinyin.trim().split(' ').join(','),
        };
      }
      this.loading_list[i].loading = true;
      GetStaticResources(MethodName, data)
        .then((res) => {
          this.loading_list[i].loading = false;
          if (res.status === 1) {
            item.audio_file_id = res.file_id;
            this.data.file_id_list.push(res.file_id);
          }
        })
        .catch(() => {
          this.loading_list[i].loading = false;
        });
    },
    fileUploadSuccess(file_id, file_url, index) {
      this.data.file_id_list.push(file_id);
      this.data.option_list[index].picture_file_id = file_id;
      this.$set(this.pic_list, file_id, file_url);
    },
    // 生成汉字
    handleChineseStrokes(item, i) {
      if (item.content.trim()) {
        this.loading_list[i].loadings = true;
        let content_arr = item.content.trim().split('');
        let content_arrs = [];
        let content_arr_strokes = [];
        content_arr.forEach((itemc) => {
          if (itemc.trim()) {
            content_arrs.push(itemc.trim());
          }
        });
        content_arrs.forEach((itemc, indexc) => {
          content_arr_strokes.push(null);
          let MethodName = 'hz_resource_manager-GetHZStrokesContent';
          let data = {
            hz: itemc,
          };
          GetStaticResources(MethodName, data).then((res) => {
            let obj = {
              hz: itemc.trim(),
              strokes: res,
            };
            content_arr_strokes[indexc] = obj;
          });
        });
        this.loading_list[i].loadings = false;

        item.hz_strokes_list = content_arr_strokes;
      }
    },
    // 增加例句
    addSentence(item) {
      item.example_sentence.push('');
    },
    handleReplaceTone(value, mark) {
      if (!value) return;
      value.split(/\s+/).forEach((item) => {
        this.handleValue(item);
      });
      this.matically_pinyin_obj[mark] = this.res_arr
        .map((item) =>
          item.map(({ number, con }) => (number && con ? addTone(Number(number), con) : number || con || '')),
        )
        .filter((item) => item.length > 0)
        .join(' ');
    },
    handleValue(valItem) {
      let numList = [];
      if (/[A-Za-zü]+\d/g.test(valItem)) {
        valItem.split('').forEach((item, i) => {
          if (/\d/.test(item)) {
            let con = valItem.replace(/\d/g, '');
            numList.push({
              index: i,
              number: item,
              con,
              isTran: true,
            });
          }
        });
      } else {
        numList = [];
      }

      this.res_arr.push(numList.length === 0 ? [{ con: valItem }] : numList);
    },
    handleItemPinyin(content, mark) {
      let content_arr = content.trim().split(' ');
      this.res_arr = [];
      this.$set(this.matically_pinyin_obj, mark, []);
      content_arr.forEach((items, index) => {
        let items_trim = items.trim();
        if (items_trim) {
          this.handleReplaceTone(items_trim, mark);
        }
      });
    },
    // 修改拼音
    changePinyin(item) {
      if (this.data.other.audio_generation_method === 'auto') {
        item.audio_file_id = '';
      }
      let index = item.pinyin.search(/0|1|2|3|4/);
      if (index > -1) {
        this.handleItemPinyin(item.pinyin, item.mark);
        setTimeout(() => {
          if (this.matically_pinyin_obj[item.mark].indexOf(',') > -1) {
            this.$message.warning('输入的拼音有误，请重新输入');
            this.matically_pinyin_obj[item.mark] = '';
          }
          item.pinyin = this.matically_pinyin_obj[item.mark];
        }, 10);
      }
    },
    /**
     * 智能识别
     * @param {String} text 识别数据
     */
    async recognition(text) {
      let arr = this.recognitionCommon(text);
      let obj = await analysisRecognitionWordCardData(arr);
      this.recognitionCommonSetObj(obj);
    },
  },
};
</script>

<style lang="scss" scoped>
.content {
  display: flex;
  flex-direction: column;

  :deep .el-upload {
    width: 100%;

    &-dragger {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      width: 100%;
      height: 90px;
      font-size: 14px;

      :first-child {
        color: #000;
      }

      :last-child {
        color: $text-color;
      }
    }
  }

  .content-word-card {
    .item-left {
      display: flex;
      column-gap: 8px;
      align-items: flex-end;
    }

    .word-card-item {
      display: flex;
      column-gap: 8px;
      margin: 16px 0;
    }

    .word-card {
      display: flex;
      flex: 1;
      flex-wrap: wrap;
      gap: 8px 4px;

      .el-input {
        flex: 1;
      }
    }

    .example-sentence-box {
      .example-sentence {
        display: flex;
        column-gap: 8px;
        margin-bottom: 8px;

        .question-number {
          min-width: 40px;
          height: 32px;
          padding: 4px 0;
          color: $text-color;
          text-align: center;
          cursor: pointer;
          background-color: $fill-color;
          border-radius: 2px;
        }
      }
    }

    .upload-wrapper {
      margin-top: 0;
      overflow: hidden;
    }

    :deep .file-name {
      width: 205px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .auto-matically,
    .upload-audio-play {
      .audio-wrapper {
        // margin-right: 12px;

        :deep .audio-play {
          width: 16px;
          height: 16px;
          color: #000;
          background-color: initial;
        }

        :deep .audio-play.not-url {
          color: #a1a1a1;
        }

        :deep .voice-play {
          width: 16px;
          height: 16px;
        }
      }
    }

    .upload-audio-play {
      display: flex;
      flex-shrink: 0;
      align-items: center;
      width: 200px;
      background-color: $fill-color;
      border-radius: 2px;

      .upload-play {
        display: flex;
        column-gap: 8px;
        align-items: center;

        .svg-icon {
          cursor: pointer;
        }
      }
    }

    .auto-matically {
      display: flex;
      flex-shrink: 0;
      column-gap: 12px;
      align-items: center;
      width: 200px;
      padding: 5px 12px;
      background-color: $fill-color;
      border-radius: 2px;

      .auto-btn {
        font-size: 16px;
        font-weight: 400;
        line-height: 22px;
        color: #1d2129;
        cursor: pointer;
      }
    }

    .delete {
      flex-shrink: 0;
      width: 16px;
      height: 16px;
    }
  }
}
</style>
