<template>
  <ModuleBase :type="data.type">
    <template #content>
      <!-- eslint-disable max-len -->
      <div class="fill-wrapper">
        <div class="content-box">
          <el-input
            v-if="data.property.audio_generation_method === 'auto'"
            v-model="data.character"
            :placeholder="'汉字'"
            style="flex-shrink: 0; width: 80px"
          />
          <el-input
            v-model="data.content"
            placeholder="拼音间用空格隔开，如：ni3 hao3"
            @blur="handleItemAnswer(data)"
            @change="changePinyin(data)"
          />
          <el-input
            v-model="matically_pinyin_str[data.mark]"
            :placeholder="'拼音预览'"
            :readonly="true"
            style="width: 200px"
          />
        </div>
        <div v-if="data.audio_file_id">
          <SoundRecord :wav-blob.sync="data.audio_file_id" />
        </div>
        <template v-else>
          <div :class="['upload-audio-play']">
            <UploadAudio
              v-if="data.property.audio_generation_method === 'upload'"
              :file-id="data.audio_file_id"
              :show-upload="!data.audio_file_id"
              @upload="uploads"
              @deleteFile="deleteFiles"
            />
            <div
              v-else-if="data.property.audio_generation_method === 'auto'"
              class="auto-matic"
              @click="handleMatically"
            >
              <SvgIcon icon-class="voiceprint-line" class="record" />
              <span class="auto-btn">{{ data.audio_file_id ? '已生成' : '生成音频' }}</span
              >{{ data.audio_file_id ? '成功' : '' }}
            </div>
            <SoundRecord v-else :wav-blob.sync="data.audio_file_id" />
          </div>
        </template>
      </div>
    </template>
  </ModuleBase>
</template>

<script>
import ModuleMixin from '../../common/ModuleMixin';
import SoundRecord from '@/views/book/courseware/create/components/question/fill/components/SoundRecord.vue';
import UploadAudio from '@/views/book/courseware/create/components/question/fill/components/UploadAudio.vue';

import { getPinyinBaseData } from '@/views/book/courseware/data/pinyinBase';
import { addTone, handleToneValue } from '@/views/book/courseware/data/common';
import { getRandomNumber } from '@/utils';
import { GetStaticResources } from '@/api/app';

export default {
  name: 'PinyinBasePage',
  components: {
    SoundRecord,
    UploadAudio,
  },
  mixins: [ModuleMixin],
  watch: {
    'data.property.answer_mode': {
      handler(val) {
        this.handleChangeType();
      },
      deep: true,
    },
  },
  data() {
    return {
      data: getPinyinBaseData(),
      matically_pinyin_obj: {}, // 存放转成声调的拼音
      matically_pinyin_str: {}, // 存放转成声调的字符串
      res_arr: [],
    };
  },
  methods: {
    uploads(file_id) {
      this.data.audio_file_id = file_id;
    },
    deleteFiles() {
      this.data.audio_file_id = '';
    },
    // 自动生成音频
    handleMatically() {
      let MethodName = 'tool-TextToVoiceFile';
      let data = {};
      if (this.data.character.trim() || this.data.content_hz) {
        data = {
          text: this.data.character.trim() || this.data.content_hz,
        };
      } else if (this.data.content.trim()) {
        if (!this.matically_pinyin_obj[this.data.mark]) {
          this.handleItemAnswer(this.data);
        }
        MethodName = 'tool-PinyinToVoiceFile';
        data = {
          pinyin: this.matically_pinyin_obj[this.data.mark],
        };
      }
      GetStaticResources(MethodName, data)
        .then((res) => {
          if (res.status === 1) {
            this.data.audio_file_id = res.file_id;
          }
        })
        .catch(() => {});
    },
    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(',');
      this.matically_pinyin_str[mark] = this.res_arr
        .map((item) =>
          item.map(({ number, con }) => (number && con ? addTone(Number(number), con) : number || con || '')),
        )
        .filter((item) => item.length > 0)
        .join(' ');
      if (this.matically_pinyin_str[mark].indexOf(',') > -1) {
        this.$message.warning('输入的拼音有误，请重新输入');
        this.matically_pinyin_obj[mark] = [];
        this.matically_pinyin_str[mark] = '';
        this.data.content = '';
      }
    },
    handleValue(valItem) {
      let numList = [];
      if (/[A-Za-zü]+\d/g.test(valItem)) {
        valItem.split('').forEach((item, i) => {
          if (/\d/.test(item)) {
            let numIndex = numList.length === 0 ? 0 : numList[numList.length - 1].index;
            let con = valItem.substring(numIndex, i).replace(/\d/g, '');
            numList.push({
              index: i,
              number: item,
              con,
              isTran: true,
            });
          }
        });
      } else {
        numList = [];
      }

      this.res_arr.push(numList.length === 0 ? [{ con: valItem }] : numList);
    },
    // 答案
    handleItemAnswer(item) {
      let content = item.content.trim();
      const regex = /[\u4e00-\u9fa5]/g;
      item.content_hz = content.match(regex) ? content.match(regex).join('') : '';
      let content_arr = content.replace(regex, '').trim().split(' ');
      let select_item = '';
      let content_preview = '';
      this.res_arr = [];
      this.$set(this.matically_pinyin_obj, item.mark, []);
      this.$set(this.matically_pinyin_str, item.mark, '');
      this.data.answer.answer_list = [];
      content_arr.forEach((items, index) => {
        let items_trim = items.trim();
        if (items_trim) {
          let items_yuan = JSON.parse(JSON.stringify(items_trim)).replace(/0|1|2|3|4/, '');
          let indexs = items.search(/0|1|2|3|4/);
          if (this.data.property.answer_mode === 'select') {
            // 如果是选择声调 把声调放在拼音后面
            // select_item += `${items_yuan + items_trim.substring(indexs, indexs + 1)} `;
            select_item += `${items_trim.substring(indexs, indexs + 1)}${index === content_arr.length - 1 ? '' : ' '}`;
          } else if (this.data.property.answer_mode === 'label') {
            // 如果是标注声调 把声调放在对应字母后面
            // select_item += `${items_trim}${index === content_arr.length - 1 ? '' : ' '}`;
          }
          content_preview += `${items_yuan}${index === content_arr.length - 1 ? '' : ' '}`;
          this.handleReplaceTone(items_yuan + items_trim.substring(indexs, indexs + 1), item.mark);
        }
      });
      if (this.data.property.answer_mode === 'label') {
        content_preview.split(' ').forEach((items, index) => {
          let items_trim = items.trim();
          if (items_trim) {
            let indexs = content_arr[index].search(/0|1|2|3|4/);
            let items_tone = this.matically_pinyin_str[item.mark].split(' ')[index].split('');
            for (let i = 0; i < items_trim.length; i++) {
              if (items_trim[i] === items_tone[i]) {
                select_item += `${items_trim[i]}`;
              } else {
                select_item += `${items_trim[i]}${content_arr[index].substring(indexs, indexs + 1)}`;
              }
            }
            select_item += `${index === content_preview.split(' ').length - 1 ? '' : ' '}`;
          }
        });
      }
      let obj = {
        mark: item.mark,
        value: select_item.split(' '),
      };
      this.data.answer.answer_list.push(obj);
      item.content_view = content_preview.trim().split(' ');
      // item.matically_pinyin = matically_pinyin.trim().split(' ').join(',');
    },
    // 改变类型
    handleChangeType() {
      this.handleItemAnswer(this.data);
    },
    // 修改拼音
    changePinyin(item) {
      if (this.data.property.audio_generation_method === 'auto') {
        item.audio_file_id = '';
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.fill-wrapper {
  display: flex;
  flex-direction: column;
  row-gap: 16px;
  align-items: flex-start;

  :deep .rich-wrapper {
    width: 100%;
  }

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

  .auto-matic,
  .upload-audio-play {
    :deep .upload-wrapper {
      margin-top: 0;
    }

    .audio-wrapper {
      :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;
      }
    }
  }

  .auto-matic {
    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;
    }
  }

  .correct-answer {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;

    .el-input {
      width: 180px;

      :deep &__prefix {
        display: flex;
        align-items: center;
        color: $text-color;
      }
    }
  }
}

.content-box {
  display: flex;
  column-gap: 8px;
}
</style>
