<template>
  <Form
    class="multi-selection-form"
    ref="questionForm"
    :model="editQuestion"
    :label-colon="false"
    @on-validate="onValidate"
  >
    <div class="config-header">
      <!-- Row 1: 此题必填 | 此题占分 | 此题计星 -->
      <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">
          <Checkbox
            @on-change="scoringEnabledChange"
            v-model="editQuestion.options.scoringEnabled"
          >
            {{ t("survey_creator.question.scoringEnabled") }}
          </Checkbox>
        </div>
        <div class="config-item">
          <Checkbox
            v-if="enabledSpeciallyQuestions"
            @on-change="starEnabledChange"
            v-model="editQuestion.options.starEnabled"
          >
            <span>
              {{ t("survey_creator.question.starEnabled") }}
              <Icon type="md-star" color="orange" :size="16" />
            </span>
          </Checkbox>
        </div>
      </div>
      <!-- Star expand -->
      <div
        v-if="enabledSpeciallyQuestions"
        v-show="editQuestion.options.starEnabled"
        class="input-expand"
      >
        <span>{{ t("survey_creator.question.starMinCountPrefix") }}</span>
        <Select
          v-model="editQuestion.options.starMinCount"
          size="small"
          style="width: 50px"
        >
          <Option
            v-for="item in selectStarList"
            :value="item.value"
            :key="item.value"
            >{{ item.label }}</Option
          >
        </Select>
        <span>{{ t("survey_creator.question.starMinCountSuffix") }}</span>
      </div>
      <!-- Row 2: 选项后增加输入项 | 添加互斥项 | 评教类别 -->
      <div class="config-row">
        <div v-if="enabledInputChoice" class="config-item">
          <Checkbox
            @on-change="inputEnabledChange"
            v-model="editQuestion.options.inputtedEnabled"
          >
            {{ t("survey_creator.question.inputted_enabled") }}
          </Checkbox>
        </div>
        <div v-if="enabledExclusiveChoice" class="config-item">
          <Checkbox
            @on-change="exclusiveEnabledChange"
            v-model="editQuestion.options.exclusiveEnabled"
          >
            <span>
              {{ t("survey_creator.question.exclusive_enabled") }}
              <Tooltip
                max-width="200"
                :content="t('survey_creator.question.exclusive_option_tooltip')"
                placement="bottom"
              >
                <Icon custom="i-icon icon-exclamation-mark-outline" size="16" />
              </Tooltip>
            </span>
          </Checkbox>
        </div>
        <div class="config-item config-item-wide">
          <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>
      <!-- Input expand -->
      <div
        v-if="enabledInputChoice"
        v-show="editQuestion.options.inputtedEnabled"
        class="input-expand"
      >
        <span>{{ t("survey_creator.question.inputted_enabled_prefix") }}</span>
        <InputNumber
          :max="999"
          :min="1"
          :precision="0"
          class="inputing"
          v-model="editQuestion.options.inputMinLength"
        />
        <span>{{ t("survey_creator.question.inputted_enabled_suffix") }}</span>
      </div>
    </div>
    <Alert v-if="enabledRichText" show-icon
      >{{ t("survey_creator.question.rich_text.alert") }}
    </Alert>
    <Row>
      <Form-item
        :label-width="60"
        :label="t('survey_creator.page.question')"
        :prop="'header.text.' + primaryLanguage"
        :rules="{
          required: true,
          message: t('survey_creator.question.titleRequiredTip'),
        }"
      >
        <Row>
          <Col span="24">
            <rich-text
              v-if="enabledRichText"
              ref="richText"
              v-model="editQuestion.header.text[primaryLanguage]"
              :placeholder="t('survey_creator.question.titleRequiredTip')"
              @input="onRichTextInput"
            />
            <Input
              v-else
              v-model="editQuestion.header.text[primaryLanguage]"
              :maxlength="500"
              :placeholder="t('survey_creator.question.titleRequiredTip')"
            />
          </Col>
        </Row>
      </Form-item>
    </Row>
    <div class="option-header">
      <div class="choice">
        {{ t("survey_creator.question.option_header_choice") }}
      </div>
      <div class="scoring" v-show="editQuestion.options.scoringEnabled">
        {{ t("survey_creator.question.option_header_scoring") }}
      </div>
      <div class="inputing" v-show="editQuestion.options.inputtedEnabled">
        {{ t("survey_creator.question.option_header_inputing") }}
      </div>
    </div>
    <draggable
      v-model="editQuestion.choices"
      class="question-choices-wrapper"
      draggable=".question-choice"
      @start="drag = true"
      @end="drag = false"
    >
      <div v-for="(option, index) in editQuestion.choices" :key="index">
        <div v-if="!option.options.exclusiveEnabled" class="choice-row">
          <FormItem
            :label-width="60"
            :label="t('survey_creator.question.optional')"
            :prop="'choices.' + index + '.text.' + primaryLanguage"
            :rules="{
              required: true,
              message: t('survey_creator.question.optionalRequiredTip'),
            }"
          >
            <div class="question-choice">
              <div class="choice">
                <Input v-model.trim="option.text[primaryLanguage]" />
              </div>
              <div class="scoring" v-show="editQuestion.options.scoringEnabled">
                <Form-item
                  :prop="'choices.' + index + '.options.score'"
                  :label-width="60"
                  v-show="editQuestion.options.scoringEnabled"
                  :rules="[
                    {
                      required: editQuestion.options.scoringEnabled,
                      message: t('survey_creator.question.scoreRequiredTip'),
                    },
                    {
                      pattern: /^(100|0(\.\d{1,2})?|[1-9]?\d(\.\d{1,2})?)$/,
                      message: t('survey_creator.question.scoreErrorTip'),
                    },
                  ]"
                >
                  <Input v-model="option.options.score" type="number" />
                </Form-item>
              </div>
              <div
                class="inputing"
                v-show="editQuestion.options.inputtedEnabled"
              >
                <Form-item
                  :prop="'choices.' + index + '.options.inputEnabled'"
                  :label-width="80"
                  v-show="editQuestion.options.inputtedEnabled"
                  :rules="[
                    {
                      message: t('survey_creator.question.inputLeastOneTip'),
                      validator: validatedInput,
                    },
                  ]"
                >
                  <Checkbox v-model="option.options.inputEnabled" />
                </Form-item>
              </div>
              <div class="buttons">
                <Button
                  class="button"
                  @click.native="addOption()"
                  v-if="editQuestion.choices.length < choiceLimit.max"
                  icon="md-add"
                />
                <Button
                  class="button"
                  @click.native="deleteOption(index)"
                  v-if="editQuestion.choices.length > choiceLimit.min"
                  icon="md-remove"
                />
              </div>
            </div>
          </FormItem>
          <div class="option-input" v-if="option.options.inputEnabled">
            <Input
              disabled
              :placeholder="t('survey_creator.question.inputEnabledTip')"
            />
          </div>
        </div>
        <div v-else class="choice-row exclusive-choice">
          <FormItem
            :label-width="60"
            :label="t('survey_creator.question.optional')"
            :prop="'choices.' + index + '.text.' + primaryLanguage"
            :rules="{
              required: true,
              message: t('survey_creator.question.optionalRequiredTip'),
            }"
          >
            <div class="question-choice">
              <div class="choice">
                <Input v-model.trim="option.text[primaryLanguage]" />
              </div>
              <div class="scoring" v-show="editQuestion.options.scoringEnabled">
                <Form-item
                  :prop="'choices.' + index + '.options.score'"
                  :label-width="60"
                  v-show="editQuestion.options.scoringEnabled"
                  :rules="[
                    {
                      required: editQuestion.options.scoringEnabled,
                      message: t('survey_creator.question.scoreRequiredTip'),
                    },
                    {
                      pattern: /^(100|0(\.\d{1,2})?|[1-9]?\d(\.\d{1,2})?)$/,
                      message: t('survey_creator.question.scoreErrorTip'),
                    },
                  ]"
                >
                  <Input v-model="option.options.score" type="number" />
                </Form-item>
              </div>
              <div
                class="inputing"
                v-show="editQuestion.options.inputtedEnabled"
              >
                <Form-item
                  :prop="'choices.' + index + '.options.inputEnabled'"
                  :label-width="80"
                  v-show="editQuestion.options.inputtedEnabled"
                  :rules="[
                    {
                      message: t('survey_creator.question.inputLeastOneTip'),
                      validator: validatedInput,
                    },
                  ]"
                >
                  <Checkbox v-model="option.options.inputEnabled" />
                </Form-item>
              </div>
            </div>
          </FormItem>
          <div class="option-input" v-if="option.options.inputEnabled">
            <Input
              disabled
              :placeholder="t('survey_creator.question.inputEnabledTip')"
            />
          </div>
        </div>
      </div>
    </draggable>
  </Form>
</template>
<script lang="ts">
import Vue from "vue";
import _ from "lodash";
import {
  Alert,
  Button,
  ButtonGroup,
  Checkbox,
  Col,
  Form,
  FormItem,
  Icon,
  Input,
  InputNumber,
  Option,
  Radio,
  RadioGroup,
  Row,
  Select,
  Tooltip,
} from "view-design";
import { QuestionFactory, SurveyLayout } from "@wg-npm/survey-core";
import draggable from "vuedraggable";
import questionFormMixin from "../../../mixins/question-form-mixin";
import RichText from "./rich-text.vue";

export default Vue.extend({
  name: "multi-selection-form",
  components: {
    Form,
    FormItem,
    ButtonGroup,
    Button,
    Input,
    Checkbox,
    Radio,
    RadioGroup,
    Row,
    Col,
    Icon,
    Select,
    Option,
    Tooltip,
    draggable,
    InputNumber,
    RichText,
    Alert,
  },
  mixins: [questionFormMixin],
  data() {
    return {
      choiceLimit: {
        max: 20,
        min: 1,
      },
      layoutOptions: [SurveyLayout.HORIZONTAL, SurveyLayout.VERTICAL],
      selectStarList: [],
      enabledExclusiveChoice: false,
      enabledInputChoice: false,
      enabledRichText: false,
      enabledSpeciallyQuestions: true,
      enabledEvaluationTag: false,
    };
  },
  created() {
    this.resetStarList();
    // @ts-ignore
    this.enabledExclusiveChoice = _.get(
      this.$rootComponent,
      "options.enabledExclusiveChoice",
      false
    );
    // @ts-ignore
    this.enabledInputChoice = _.get(
      this.$rootComponent,
      "options.enabledInputChoice",
      false
    );
    // @ts-ignore
    this.enabledRichText = _.get(
      this.$rootComponent,
      "options.enabledPlanSurveyTeacherSetting",
      false
    );
    this.editQuestion.options.richTextEnabled = this.enabledRichText;
    // @ts-ignore
    this.enabledSpeciallyQuestions = _.get(
      this.$rootComponent,
      "options.enabledSpeciallyQuestions",
      true
    );
    // @ts-ignore
    this.enabledEvaluationTag = _.get(
      this.$rootComponent,
      "options.enabledEvaluationTag",
      false
    );
    if (this.enabledEvaluationTag && !this.editQuestion.options.evaluationTag) {
      this.$set(this.editQuestion.options, "evaluationTag", "COURSE");
    }
  },
  methods: {
    handleExclusiveChoice(callback) {
      if (this.editQuestion.options.exclusiveEnabled) {
        const exclusiveChoice = this.editQuestion.choices.pop();
        callback();
        this.editQuestion.choices.push(exclusiveChoice);
      } else {
        callback();
      }
    },
    addOption() {
      this.handleExclusiveChoice(() => {
        this.editQuestion.choices.push(
          QuestionFactory.createDefault(this.$rootComponent.primaryLanguage)
        );
      });
      this.resetStarList();
    },
    deleteOption(position) {
      this.editQuestion.choices.splice(position, 1);
      this.resetStarList();
    },
    scoringEnabledChange() {
      if (!this.editQuestion.options.scoringEnabled) {
        _.each(this.editQuestion.choices, (choice) => {
          choice.options.score = null;
        });
      }
    },
    starEnabledChange() {
      if (!this.editQuestion.options.starEnabled) {
        this.editQuestion.options.starMinCount = null;
      } else {
        this.editQuestion.options.starMinCount = 1;
      }
    },
    inputEnabledChange() {
      if (!this.editQuestion.options.inputtedEnabled) {
        this.editQuestion.options.inputMinLength = null;
      } else {
        this.editQuestion.options.inputMinLength = 10;
      }

      if (!this.editQuestion.options.inputtedEnabled) {
        _.each(this.editQuestion.choices, (choice) => {
          choice.options.inputEnabled = false;
        });
      }
    },
    resetStarList() {
      this.selectStarList = [];
      _.each(this.editQuestion.choices, (choices, index) => {
        this.selectStarList.push({
          label: index + 1,
          value: index + 1,
        });
      });
      this.editQuestion.options.starMinCount = 1;
    },
    exclusiveEnabledChange() {
      const exclusiveChoice = QuestionFactory.createExclusiveChoice(
        this.$rootComponent.primaryLanguage
      );
      exclusiveChoice.text[this.$rootComponent.primaryLanguage] = this.t(
        "survey_creator.question.exclusive_choice"
      );
      if (this.editQuestion.options.exclusiveEnabled) {
        this.editQuestion.choices.push(exclusiveChoice);
      } else {
        this.editQuestion.choices.pop();
      }
      this.resetStarList();
    },
    validatedInput(rule, value, callback, source, options) {
      if (this.editQuestion.options.inputtedEnabled) {
        let existInput = false;
        _.each(this.editQuestion.choices, (choice) => {
          if (choice.options.inputEnabled) {
            existInput = true;
          }
        });
        if (existInput) {
          callback();
        }
        callback(new Error(this.t("survey_creator.question.inputLeastOneTip")));
      }
      callback();
    },
    onValidate(prop, status, error) {
      if (
        this.enabledRichText &&
        prop === `header.text.${this.primaryLanguage}`
      ) {
        this.$refs.richText.onValidate(!status);
      }
    },
    onRichTextInput() {
      this.$refs.questionForm.validateField(
        `header.text.${this.primaryLanguage}`,
        (valid) => {
          this.$refs.richText.onValidate(valid);
        }
      );
    },
  },
});
</script>
<style lang="less" scoped>
.multi-selection-form {
  .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;
      }
    }
  }

  .config-item-wide {
    flex: 2;
  }

  .input-expand {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
    padding: 8px;
    border-radius: 4px;
    background: #f7f7f7;

    span {
      margin: 0 4px;
    }

    .inputing {
      width: 64px;
    }
  }

  .question-options {
    padding-bottom: 10px;
    padding-left: 80px;
  }

  /deep/ .ivu-form-item {
    width: 100%;
  }

  /deep/ .ivu-form-item-content {
    line-height: normal;
  }

  .option-header {
    background: #f0f1f3;
    border-radius: 4px;
    width: 100%;
    height: 32px;
    margin-bottom: 24px;
    display: flex;
    flex-direction: row;
    color: #70748c;
    align-items: center;
    padding: 0 84px 0 16px;

    .choice {
      width: 100%;
    }

    .scoring {
      width: 100px;
      display: flex;
      justify-content: center;
    }

    .inputing {
      width: 145px;
      min-width: 42px;
      display: flex;
      justify-content: center;
    }
  }

  .choice-row {
    .question-choice {
      display: flex;
      flex-direction: row;
      align-items: center;
      padding-right: 8px;

      .choice {
        display: flex;
        flex-direction: row;
        width: 100%;
        margin-right: 8px;
      }

      .buttons {
        width: 68px;
        flex-shrink: 0;
        margin-left: 8px;
        display: flex;
        gap: 4px;
      }

      .scoring {
        width: 100px;
      }

      .inputing {
        width: 145px;
        text-align: center;

        .ivu-checkbox-wrapper {
          margin-right: 0px;
        }
      }
    }
  }

  .exclusive-choice {
    border-top: 1px solid #e8eaec;
    padding-top: 16px;
  }

  .option-input {
    margin: 0px 50px 30px 60px;
  }
}

/deep/ .ivu-form-item-error-tip {
  min-width: 170px;
}
</style>
