<template>
  <div>
    <div v-if="showPresetReplies" class="preset-reply-area">
      <div class="preset-reply-tip">
        {{
          t(
            "survey_creator.question.presetReplyTip",
            $rootComponent.currentLanguage
          )
        }}
      </div>
      <div class="preset-reply-buttons">
        <span
          v-for="(reply, index) in question.options.presetReplies"
          :key="index"
          class="preset-reply-btn"
          @click="applyPresetReply(reply)"
          >{{ reply }}</span
        >
      </div>
    </div>
    <quill-rich-text
      ref="richText"
      :disabled="question.options.readonly"
      :placeholder="
        t(
          'survey_creator.common.tips.please_input_answer',
          $rootComponent.currentLanguage
        )
      "
      :maxlength="question.options.wordLimit"
    ></quill-rich-text>
  </div>
</template>

<script lang="ts">
import Vue from "vue";
import _ from "lodash";
import LocaleMixin from "../../../mixins/locale-mixin";
import { BaseQuestionModel } from "@wg-npm/survey-core";
import QuillRichText from "./quill-rich-text.vue";

export default Vue.extend({
  name: "short-answer",
  components: { QuillRichText },
  mixins: [LocaleMixin],
  inject: ["$rootComponent"],
  props: {
    question: {
      type: Object as () => BaseQuestionModel,
      required: true,
    },
  },
  data() {
    return {
      enabledPresetReplies: false,
    };
  },
  computed: {
    showPresetReplies(): boolean {
      return (
        this.enabledPresetReplies &&
        !this.question.options.readonly &&
        Array.isArray(this.question.options.presetReplies) &&
        this.question.options.presetReplies.length > 0
      );
    },
  },
  created() {
    // @ts-ignore
    this.enabledPresetReplies = _.get(
      this.$rootComponent,
      "options.enabledPresetReplies",
      false
    );
  },
  methods: {
    applyPresetReply(text: string) {
      const quill = (this.$refs.richText as any).quill;
      if (quill) {
        // 获取当前光标位置，若无光标则插入到末尾
        let range = quill.getSelection();
        if (!range) {
          range = { index: quill.getLength() - 1, length: 0 };
        }
        // 在光标位置插入预设回复标签
        quill.insertEmbed(range.index, "preset-reply", text, "user");
        // Embed 在 Delta 中占 1 个字符长度
        quill.setSelection(range.index + 1);
      }
    },
  },
});
</script>

<style scoped lang="less">
.preset-reply-area {
  margin-bottom: 12px;

  .preset-reply-tip {
    color: #999;
    font-size: 13px;
    margin-bottom: 8px;
  }

  .preset-reply-buttons {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;

    .preset-reply-btn {
      display: inline-block;
      padding: 4px 12px;
      border: 1px solid #dcdee2;
      border-radius: 4px;
      font-size: 13px;
      color: #515a6e;
      cursor: pointer;
      background: #fff;
      transition: all 0.2s;

      &:hover {
        border-color: #2d8cf0;
        color: #2d8cf0;
      }
    }
  }
}
</style>
