<template>
  <ModuleBase :type="data.type">
    <template #content>
      <!-- eslint-disable max-len -->
      <div class="fill-wrapper">
        <el-input v-model="data.content" placeholder="输入汉字" @blur="handleChineseStrokes(data)"></el-input>
        <el-input
          v-model="data.pinyin"
          placeholder="输入拼音"
          @blur="handleSplitPy(data)"
          @change="changePinyin(data)"
          v-if="isEnable(data.property.is_enable_pinyin)"
        ></el-input>
        <el-input v-model="data.definition" placeholder="输入释义或描述" type="textarea"></el-input>

        <template v-if="isEnable(data.property.is_enable_voice)">
          <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="handleMatic">
                <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>
        </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 { getCharacterBaseData } from '@/views/book/courseware/data/characterBase';
import { addTone, handleToneValue } from '@/views/book/courseware/data/common';

import { GetStaticResources } from '@/api/app';

export default {
  name: 'CharacterBasePage',
  components: {
    SoundRecord,
    UploadAudio,
  },
  mixins: [ModuleMixin],
  data() {
    return {
      data: getCharacterBaseData(),
      matically_pinyin_obj: {}, // 存放转成声调的拼音
    };
  },
  methods: {
    // 生成汉字
    handleChineseStrokes(item, i) {
      if (item.content.trim()) {
        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;
          });
        });

        item.hz_strokes_list = content_arr_strokes;
      }
    },
    // 切割拼音
    handleSplitPy(item) {
      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('输入的拼音有误，请重新输入');
            item.pinyin = '';
            this.matically_pinyin_obj[item.mark] = '';
          } else {
            item.pinyin = this.matically_pinyin_obj[item.mark];
          }
        }, 10);
      }
      let pinyin_list = item.pinyin.trim().split(' ');
      item.pinyin_item_list = [];
      pinyin_list.forEach((itemp) => {
        let obj = {
          pinyin_item: itemp,
        };
        item.pinyin_item_list.push(obj);
      });
    },
    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.property.audio_generation_method === 'auto') {
        item.audio_file_id = '';
      }
    },
    uploads(file_id) {
      this.data.audio_file_id = file_id;
    },
    deleteFiles() {
      this.data.audio_file_id = '';
    },
    // 自动生成音频
    handleMatic() {
      GetStaticResources('tool-TextToVoiceFile', {
        text: this.data.content.replace(/<[^>]+>/g, ''),
      })
        .then(({ status, file_id }) => {
          if (status === 1) {
            this.data.audio_file_id = file_id;
          }
        })
        .catch(() => {});
    },
  },
};
</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;
      }
    }
  }
}
</style>
