<template>
  <ModuleBase ref="base" :type="data.type">
    <template #content>
      <div v-loading="loading" class="select-wrapper">
        <ul class="option-list">
          <li v-for="(item, i) in data.option_list" :key="item.mark" class="option-item">
            <span
              v-if="!('enable_serial' in data.property) || isEnable(data.property.enable_serial)"
              class="serial-number"
              >{{ computedOptionNumber(i) }}.</span
            >
            <div class="option-contnet">
              <span
                :class="[isSingle ? 'radio' : 'checkbox', { active: isAnswer(item.mark) }]"
                @click="selectAnswer(item.mark)"
              >
                <SvgIcon icon-class="check-mark" width="10" height="7" />
              </span>
              <RichText
                v-if="property.isGetContent"
                ref="richText"
                v-model="item.content"
                :font-size="data?.unified_attrib?.font_size"
                :font-family="data?.unified_attrib?.font"
                :font-color="data?.unified_attrib?.text_color"
                placeholder="输入内容"
                :inline="true"
                :height="32"
              />
            </div>
            <span class="multilingual" @click="openMultilingual(i)">
              <SvgIcon icon-class="multilingual" class-name="multilingual" width="12" height="12" />
            </span>
            <span class="delete" @click="deleteOption(i)">
              <SvgIcon icon-class="delete-2" width="12" height="12" />
            </span>
          </li>
        </ul>
        <div class="add">
          <SvgIcon icon-class="add-circle" width="14" height="14" />
          <span class="add-button" @click="addOption">增加选项</span>
        </div>

        <el-divider v-if="isEnable(data.property.view_pinyin)" content-position="left">
          <span>显示效果</span>
          <el-button
            type="text"
            icon="el-icon-refresh"
            title="刷新"
            class="refresh-pinyin-btn"
            @click.native="handleViewPinyin(true)"
          />
        </el-divider>
        <PinyinText
          v-for="(item, i) in data.option_list"
          v-show="isEnable(data.property.view_pinyin)"
          :key="i"
          ref="PinyinText"
          :paragraph-list="item.paragraph_list"
          :rich-text-list="item.rich_text_list"
          :pinyin-position="data.property.pinyin_position"
          @fillCorrectPinyin="fillCorrectPinyin($event, i)"
        />
      </div>

      <MultilingualFill
        v-if="curSelectIndex !== -1"
        :visible.sync="multilingualVisible"
        :text="data.option_list[curSelectIndex].content"
        :translations="data.option_list[curSelectIndex].multilingual"
        @SubmitTranslation="handleMultilingualTranslation"
      />

      <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"
      />
    </template>
  </ModuleBase>
</template>

<script>
import ModuleMixin from '../../common/ModuleMixin';
import PinyinText from '@/components/PinyinText.vue';

import { getSelectData, getOption, arrangeTypeList, selectTypeList } from '@/views/book/courseware/data/select';
import { serialNumberTypeList, computeOptionMethods } from '@/views/book/courseware/data/common';

export default {
  name: 'SelectPage',
  components: {
    PinyinText,
  },
  mixins: [ModuleMixin],
  data() {
    return {
      data: getSelectData(),
      curSelectIndex: -1,
      loading: false,
    };
  },
  computed: {
    isSingle() {
      return this.data.property?.select_type === selectTypeList[0].value;
    },
  },
  watch: {
    'data.property.arrange_type': 'handlerMindMap',
    'data.answer.answer_list': 'handlerMindMap',
    'data.property': {
      handler(val) {
        if (this.property.isSilentPropertyWatch) return;
        if (val.view_pinyin === 'true') {
          this.handleViewPinyin();
        }
      },
      deep: true,
    },
    'data.property.select_type': {
      handler() {
        if (this.isSingle && this.data.answer.answer_list.length > 1) {
          this.data.answer.answer_list = [this.data.answer.answer_list[0]];
        }
      },
    },
  },
  methods: {
    async handleViewPinyin(isPrompt = false) {
      if (isPrompt) {
        try {
          await this.$confirm('刷新将会重置分词和拼音，是否刷新？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          });
        } catch (e) {
          return;
        }
      }
      this.loading = true;
      if (!this.isEnable(this.data.property.view_pinyin)) {
        this.data.option_list.forEach((item) => {
          item.paragraph_list = [];
          item.paragraph_list_parameter = {
            text: '',
            pinyin_proofread_word_list: [],
          };
        });
        this.loading = false;
        return;
      }
      if (this.data.option_list.length > 0 && this.data.option_list[0].paragraph_list.length > 0) return;
      this.data.option_list.forEach((item, i) => {
        const text = item.content;
        if (!text) return;
        item.paragraph_list_parameter.text = text;
        this.createParsedTextInfoPinyin(text, i);
      });
      this.loading = false;
    },
    computedOptionNumber(number) {
      let type = serialNumberTypeList.find((item) => item.value === this.data.property.option_serial_type)?.value;
      if (!type) return number + 1;
      return computeOptionMethods[type](number);
    },
    // 将数字转换为小写字母
    convertNumberToLetter(number) {
      return String.fromCharCode(97 + number);
    },
    /**
     * @description 判断是否为答案
     * @param {string} mark 选项标记
     */
    isAnswer(mark) {
      return this.data.answer.answer_list.includes(mark);
    },
    /**
     * @description 选择答案
     * @param {string} mark 选项标记
     */
    selectAnswer(mark) {
      if (mark === null || mark === undefined) return;

      const list = this.data.answer.answer_list || [];
      const isSelected = list.includes(mark);

      if (this.isSingle) {
        this.data.answer.answer_list = isSelected ? [] : [mark];
        return;
      }

      this.data.answer.answer_list = isSelected ? list.filter((item) => item !== mark) : list.concat(mark);
    },
    /**
     * @description 添加选项
     */
    addOption() {
      this.data.option_list.push(getOption());
    },
    /**
     * @description 删除选项
     * @param {number} index 选项索引
     */
    deleteOption(index) {
      if (this.data.option_list.length <= 2) {
        this.$message.warning('请至少保留两个选项');
        return;
      }
      this.data.option_list.splice(index, 1);
    },
    handlerMindMap() {
      const direction = this.data.property.arrange_type === arrangeTypeList[0].value ? '横排' : '竖排';
      const select =
        this.data.property?.select_type === selectTypeList[1].value ? selectTypeList[1].label : selectTypeList[0].label;
      this.data.mind_map.node_list = [{ name: `${direction}${select}选择题` }];
    },
    openMultilingual(i) {
      this.curSelectIndex = i;
      this.multilingualVisible = true;
    },
    handleMultilingualTranslation(translations) {
      this.$set(this.data.option_list[this.curSelectIndex], 'multilingual', translations);
    },
  },
};
</script>

<style lang="scss" scoped>
.option-list {
  display: flex;
  flex-direction: column;
  row-gap: 8px;

  .option-item {
    display: flex;
    column-gap: 8px;
    align-items: center;
    min-height: 36px;

    .serial-number {
      width: 40px;
      height: 36px;
      padding: 4px 8px;
      color: $text-color;
      background-color: $fill-color;
      border-radius: 2px;
    }

    .option-contnet {
      display: flex;
      flex: 1;
      column-gap: 6px;
      align-items: center;
      padding: 0 12px;
      overflow: hidden;
      background-color: $fill-color;

      .radio,
      .checkbox {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 16px;
        height: 16px;
        cursor: pointer;
        background-color: #fff;
        border: 1px solid #dcdfe6;
        border-radius: 2px;

        .svg-icon {
          display: none;
        }

        &.active {
          color: #fff;
          background-color: #000;

          .svg-icon {
            display: block;
          }
        }
      }

      .radio {
        border-radius: 50%;

        &.active {
          background-color: #fff;
          box-shadow: inset 0 0 0 4px #000;
        }
      }
    }

    .delete,
    .multilingual {
      margin-left: 8px;
      cursor: pointer;
    }
  }
}

.add {
  display: flex;
  column-gap: 6px;
  align-items: center;
  justify-content: center;
  margin-top: 12px;

  .svg-icon {
    cursor: pointer;
  }

  .add-button {
    font-size: 14px;
    color: $main-color;
    cursor: pointer;
  }
}
</style>
