<template>
  <Form ref="questionForm" :model="editQuestion" :label-colon="false">
    <div class="config-header">
      <div class="config-row">
        <div class="config-item">
          <Checkbox v-model="editQuestion.options.required">
            {{ t("survey_creator.question.questionRequired") }}
          </Checkbox>
        </div>
        <div class="config-item">
          <template v-if="enabledEvaluationTag">
            <span class="config-label"
              >{{ t("survey_creator.question.evaluation_tag.label") }}:</span
            >
            <RadioGroup v-model="editQuestion.options.evaluationTag">
              <Radio label="TEACHER">{{
                t("survey_creator.question.evaluation_tag.TEACHER")
              }}</Radio>
              <Radio label="COURSE">{{
                t("survey_creator.question.evaluation_tag.COURSE")
              }}</Radio>
            </RadioGroup>
          </template>
        </div>
        <div class="config-item"></div>
      </div>
    </div>
    <Form-item
      :prop="'header.text.' + primaryLanguage"
      :rules="{
        required: true,
        message: t('survey_creator.question.titleRequiredTip'),
      }"
    >
      <label slot="label">
        <span></span>
        <span>{{ t("survey_creator.page.question") }}</span>
      </label>
      <Input
        v-model.trim="editQuestion.header.text[primaryLanguage]"
        :placeholder="t('survey_creator.question.titleRequiredTip')"
      />
    </Form-item>
    <div class="preset-replies" v-if="showPresetReplies">
      <Button
        type="primary"
        icon="md-add"
        :disabled="hasEmptyReply"
        @click="addPresetReply"
        >{{ t("survey_creator.question.addPresetReply") }}
      </Button>
      <div class="preset-reply-list">
        <Form-item
          v-for="(reply, index) in editQuestion.options.presetReplies"
          :key="index"
          class="preset-reply-item"
          :prop="'options.presetReplies.' + index"
          :rules="[
            {
              required: true,
              message: t('survey_creator.question.presetReplyRequiredTip'),
            },
            {
              validator: validateDuplicate(index),
            },
          ]"
        >
          <div
            class="preset-reply-input"
            :style="{
              width: replyInputWidth(editQuestion.options.presetReplies[index]),
            }"
          >
            <Input
              v-model.trim="editQuestion.options.presetReplies[index]"
              :placeholder="t('survey_creator.question.presetReply')"
            />
            <Icon
              type="md-close"
              class="preset-reply-close"
              @click="removePresetReply(index)"
            />
          </div>
        </Form-item>
      </div>
    </div>
  </Form>
</template>
<script lang="ts">
import Vue from "vue";
import {
  Button,
  ButtonGroup,
  Checkbox,
  Form,
  FormItem,
  Icon,
  Input,
  Radio,
  RadioGroup,
} from "view-design";
import { QuestionType } from "@wg-npm/survey-core";
import _ from "lodash";
import questionFormMixin from "../../../mixins/question-form-mixin";

export default Vue.extend({
  name: "short-answer-form",
  components: {
    Form,
    FormItem,
    ButtonGroup,
    Button,
    Input,
    Checkbox,
    Radio,
    RadioGroup,
    Icon,
  },
  mixins: [questionFormMixin],
  data() {
    return {
      enabledPresetReplies: false,
      enabledEvaluationTag: false,
    };
  },
  computed: {
    isShortAnswer(): boolean {
      return this.editQuestion.type === QuestionType.SHORT_ANSWER;
    },
    showPresetReplies(): boolean {
      return this.isShortAnswer && this.enabledPresetReplies;
    },
    hasEmptyReply(): boolean {
      const replies = this.editQuestion?.options?.presetReplies;
      if (!replies || replies.length === 0) return false;
      return replies.some((r: string) => !r || r.trim() === "");
    },
  },
  created() {
    // @ts-ignore
    this.enabledPresetReplies = _.get(
      this.$rootComponent,
      "options.enabledPresetReplies",
      false
    );
    // @ts-ignore
    this.enabledEvaluationTag = _.get(
      this.$rootComponent,
      "options.enabledEvaluationTag",
      false
    );

    if (!this.editQuestion.options.presetReplies) {
      this.$set(this.editQuestion.options, "presetReplies", []);
    }
    if (this.enabledEvaluationTag && !this.editQuestion.options.evaluationTag) {
      this.$set(this.editQuestion.options, "evaluationTag", "COURSE");
    }
  },
  methods: {
    addPresetReply() {
      if (this.hasEmptyReply) return;
      this.editQuestion.options.presetReplies.push("");
    },
    removePresetReply(index: number) {
      this.editQuestion.options.presetReplies.splice(index, 1);
    },
    replyInputWidth(text: string): string {
      if (!text) return "200px";
      // 每个字符约 8px，加上 padding 和关闭按钮的空间
      const width = Math.max(200, text.length * 15 + 44);
      return width + "px";
    },
    validateDuplicate(index: number) {
      return (rule: any, value: string, callback: Function) => {
        if (value) {
          const replies = this.editQuestion.options.presetReplies;
          // Check if value exists in other indices
          const isDuplicate = replies.some(
            (r: string, i: number) => r === value && i !== index
          );
          if (isDuplicate) {
            callback(
              new Error(
                this.t("survey_creator.question.presetReplyDuplicateTip")
              )
            );
            return;
          }
        }
        callback();
      };
    },
  },
});
</script>

<style scoped lang="less">
/deep/ .ivu-form-item {
  width: 100%;
}

.config-header {
  border-bottom: 1px solid #e8eaec;
  margin-bottom: 16px;
  padding: 8px 8px 0;
}

.config-row {
  display: flex;
  align-items: center;
  margin-bottom: 8px;

  .config-item {
    flex: 1;
    display: flex;
    align-items: center;
    gap: 8px;

    .config-label {
      font-size: 14px;
      color: #525566;
      white-space: nowrap;
    }
  }
}

.preset-replies {
  .preset-reply-list {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    margin-top: 20px;

    /deep/ .ivu-form-item {
      margin-bottom: 14px;
    }
  }

  .preset-reply-item {
    /deep/ .ivu-form-item {
      margin-bottom: 0;

      .ivu-form-item-error-tip {
        white-space: nowrap; // 防止错误提示换行导致布局错乱
      }
    }

    .preset-reply-input {
      position: relative;
      min-width: 200px;

      /deep/ .ivu-input {
        padding-right: 28px;
      }

      .preset-reply-close {
        position: absolute;
        right: 8px;
        top: 50%;
        transform: translateY(-50%);
        font-size: 16px;
        cursor: pointer;
        color: #999;

        &:hover {
          color: #ed4014;
        }
      }
    }
  }
}
</style>
