<template>
  <slot style=""></slot>
  <!-- <div class="question"> -->
  <!-- 高级题型不显示 -->
  <!-- <div v-if="questionType <= 100" class="question-inner-wrapper"> -->
  <!-- <div class="title" :style="`color: ${themeColor.stemColor}`"> -->
  <!-- <span v-if="showTitle" class="question-inner-span" v-html="title"></span> -->
  <!--   question.stem      -->
  <!-- <div class="stem"> -->
  <!-- <rich-text :nodes="`${newTitle}${tip}`" isPreview :isMobile="isMobile" /> -->
  <!-- </div> -->
  <!-- </div> -->
  <!--      <Remark-->
  <!--        :title="title + '问题评论'"-->
  <!--        :type="3"-->
  <!--        :questionIndex="questionIndex"-->
  <!--        v-if="!isAnswer"-->
  <!--        style="margin-bottom: 22px"-->
  <!--      />-->
  <!-- </div> -->
  <!-- <LangTranslate v-if="error && questionType <= 100" :full-text="error" class="error" /> -->
  <!-- <LangTranslate v-if="warning" :full-text="warning" class="error warning" /> -->
  <!-- 题 -->

  <!-- </div> -->
</template>

<script>
// import RichText from '@/components/RichText.vue';
import { computed, defineComponent } from 'vue';
// import Remark from '../components/Remark/index.vue';
// import LangTranslate from '../LangTranslate.vue';
import { useQuestionStore } from '@/stores/Questions/useQuestionStore';
import { storeToRefs } from 'pinia';

export default defineComponent({
  components: {
    /*  RichText, */
    /* Remark, */
    /* LangTranslate */
  },
  props: {
    // 标题
    stem: {
      type: String,
      default: ''
    },
    title: {
      type: String,
      default: ''
    },
    // 标题
    tip: {
      type: String,
      default: ''
    },
    // 错误
    error: {
      type: String,
      default: ''
    },
    // 警告
    warning: {
      type: String,
      default: ''
    },
    // 题型
    questionType: {
      type: Number,
      default: 0
    },
    // 题号
    questionIndex: {
      type: Number,
      default: 0
    },
    // 问卷列表
    questions: {
      type: Array,
      default: () => []
    },
    // 是否显示题号
    showTitle: {
      type: [Boolean, Number],
      default: false
    },
    // 是否移动端
    isMobile: {
      type: Boolean,
      default: false
    },
    // 是否答题模式
    isAnswer: {
      type: Boolean,
      default: false
    }
  },
  setup(props) {
    // 主题颜色
    // const themeColor = inject('themeColor');
    const { themeColor } = storeToRefs(useQuestionStore());
    // 按钮颜色
    const buttonColor = themeColor.value?.buttonColor;
    // 按钮文字颜色
    const buttonTextColor = themeColor.value?.buttonTextColor;
    // 答案颜色
    const answerColor = themeColor.value?.answerColor || '#333333';
    // 背景颜色(透明度30s)
    const answerColor30 = toRgba(answerColor, 0.3);
    // 背景颜色(透明度10)
    const answerColor10 = toRgba(answerColor, 0.1);
    // 边框颜色
    const answerBorder = answerColor === '#333333' ? '#d9d9d9' : answerColor;
    // placeholder颜色
    const answerPlaceholder = toRgba(answerColor, 0.3);
    // 鼠标 hover 时的背景色，目前用于：单选、多选、图片单选、图片多选的选项
    const hoverBackgroundColor = `${themeColor.value?.buttonColor}1E`;

    // 16进制转rgba
    function toRgba(color, opacity) {
      return `rgba(${parseInt(color.substring(1, 3), 16)},${parseInt(
        color.substring(3, 5),
        16
      )},${parseInt(color.substring(5, 7), 16)},${opacity})`;
    }

    const replaceStr = (str, firIndex, lastIndex, char) => {
      if (str.length === 0) {
        return '';
      }
      if (str.indexOf('<p>') < 0) {
        return str;
      }
      const strAry = str.split('');
      strAry[firIndex] = char;
      strAry[lastIndex] = char;
      return strAry.join('');
    };

    const newTitle = computed(() => {
      // 有循环体组的题，需要在没找到被关联的题目情况下，在循环题组内再查找一次
      const cycleIndexStr = props.title?.match(/\.\d/)?.[0] || '';
      let title = props.stem;
      const matchArr = title.match(/(\[%cite\(.*?\)%\])/g) || [];
      matchArr.forEach((matchValue) => {
        const value = matchValue.replace('[%cite(', '').replace(')%]', '');
        // 替换文本
        let replacement = '';
        // 查找引用问题
        const question =
          props.questions.find((question) => {
            // 矩阵题
            if (question.question_type >= 8 && question.question_type <= 11) {
              return question.title === value.split('_R')[0].split('_C')[0];
            }
            // 排序题
            if (question.question_type === 16) {
              return question.title === value.split('_A')[0];
            }
            return question.title === value;
          }) ||
          props.questions.find((question) => {
            // 矩阵题
            if (question.question_type >= 8 && question.question_type <= 11) {
              return question.title === (value + cycleIndexStr).split('_R')[0].split('_C')[0];
            }
            // 排序题
            if (question.question_type === 16) {
              return question.title === (value + cycleIndexStr).split('_A')[0];
            }
            return question.title === value + cycleIndexStr;
          });
        if (question) {
          // 选项
          let options = [];
          question.list.forEach((list) => {
            options = [...options, ...list.options];
          });
          if (question.answer) {
            const { answer } = question;
            if (question.question_type === 1) {
              // 查找引用选项(单选)
              const option = options.find((option) => option.option_key === Object.keys(answer)[0]);
              if (answer[option.option_key] === '1') {
                replacement = option.option;
              } else {
                replacement = answer[option.option_key];
              }
            } else if (
              question.question_type === 2 &&
              Object.keys(answer).length >= question.config.min_select
            ) {
              // 查找引用选项(多选)
              options.forEach((option) => {
                if (answer[option.option_key] === '1') {
                  replacement += option.option;
                } else if (answer[option.option_key]) {
                  replacement += answer[option.option_key];
                }
              });
            } else if (question.question_type === 4) {
              // 查找引用选项(填空)
              replacement = answer.value;
            } else if (question.question_type === 5 && options.length > 0) {
              // 查找引用选项(打分)
              options.forEach((option) => {
                replacement += option.value;
              });
            } else if (question.question_type === 17) {
              // 查找引用选项(恒定总和)
              options.forEach((option) => {
                replacement += option.option;
              });
            } else if (question.question_type >= 8 && question.question_type <= 11) {
              // 查找引用选项(矩阵题)
              // const val = value.split("_").reverse()[0];
              // let row = [];
              // let col = [];
              // question.list.forEach((list) => {
              //   if (list.type === 1) {
              //     row = [...row, ...list.options];
              //   } else if (list.type === 2) {
              //     col = [...col, ...list.options];
              //   }
              // });
              // if (val[0] === "R") {
              //   col.forEach((colItem) => {
              //     replacement += colItem.option;
              //   });
              // } else if (val[0] === "C") {
              //   row.forEach((rowItem) => {
              //     replacement += rowItem.option;
              //   });
              // }
            } else if (question.question_type === 16) {
              // 查找引用选项(排序)
              let optionKey;
              const sort = value.split('_A')[1] * 1;
              Object.keys(answer).forEach((key) => {
                if (answer[key] === sort) {
                  optionKey = key;
                }
              });
              const option = options.find((option) => option.option_key === optionKey);
              replacement += option?.option || '';
            }
          }
        }
        // 引用的p标签变成span标签
        replacement = replaceStr(replacement, 1, replacement.length - 2, 'span');

        replacement = replacement.replace(/<\/{0,1}(?!img).+?>/gi, '');

        title = title.replace(`${matchValue}`, replacement);
        // .replaceAll("<label><p ", "<label><span ")
        // .replaceAll("<label><p>", "<label><span>")
        // .replaceAll("</p></label>", "</span></label>");
        // console.log('title', title);
      });
      return title;
    });

    return {
      newTitle,
      buttonColor,
      buttonTextColor,
      themeColor,
      answerColor,
      answerColor30,
      answerColor10,
      hoverBackgroundColor,
      answerBorder,
      answerPlaceholder
    };
  }
});
</script>

<style lang="scss" scoped>
.question {
  .question-inner-wrapper {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .title {
    display: flex;
    flex: 1;
    min-height: 24px;
    margin-bottom: 24px;

    > span {
      flex-shrink: 0;
    }

    .stem {
      flex: 1;
    }
  }

  .error {
    margin: -22px 0 10px;
    padding-left: 2em;
    color: #ff374f;
    font-size: 12px;
    line-height: 20px;
  }

  .warning {
    color: #f7860f;
  }

  :deep(p) {
    margin-bottom: 0;
  }
}
</style>
