<template>
  <Form
    ref="questionForm"
    :label-colon="false"
    :model="editQuestion"
    @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
            v-model="editQuestion.options.scoringEnabled"
            @on-change="scoringEnabledChange"
          >
            {{ t("survey_creator.question.scoringEnabled") }}
          </Checkbox>
        </div>
        <div class="config-item">
          <Checkbox
            v-if="enabledSpeciallyQuestions"
            v-model="editQuestion.options.starEnabled"
            @on-change="starEnabledChange"
          >
            <span>
              {{ t("survey_creator.question.starEnabled") }}
              <Icon :size="16" color="orange" type="md-star" />
            </span>
          </Checkbox>
        </div>
      </div>
      <!-- Row 2: 选项后增加输入项 | 评教类别 | (placeholder) -->
      <div class="config-row">
        <div v-if="enabledInputChoice" class="config-item">
          <Checkbox
            v-model="editQuestion.options.inputtedEnabled"
            @on-change="inputEnabledChange"
          >
            {{ t("survey_creator.question.inputted_enabled") }}
          </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>
      <!-- inputtedEnabled expand -->
      <div
        v-if="enabledInputChoice"
        v-show="editQuestion.options.inputtedEnabled"
        class="input-expand"
      >
        <span>{{ t("survey_creator.question.inputted_enabled_prefix") }}</span>
        <InputNumber
          v-model="editQuestion.options.inputMinLength"
          :max="999"
          :min="1"
          :precision="0"
          class="inputing"
        />
        <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="t('survey_creator.page.question')"
        :label-width="80"
        :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 v-show="editQuestion.options.scoringEnabled" class="scoring">
        {{ t("survey_creator.question.option_header_scoring") }}
      </div>
      <div v-show="editQuestion.options.inputtedEnabled" class="inputing">
        {{ t("survey_creator.question.option_header_inputing") }}
      </div>
      <div v-show="editQuestion.options.starEnabled" class="inputing">
        {{ t("survey_creator.question.starEnabled") }}
      </div>
    </div>
    <draggable
      v-model="editQuestion.choices"
      class="question-choices-wrapper"
      draggable=".question-choice"
      @end="drag = false"
      @start="drag = true"
    >
      <div v-for="(option, index) in editQuestion.choices" :key="index">
        <FormItem
          :label="t('survey_creator.question.optional')"
          :label-width="80"
          :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 v-show="editQuestion.options.scoringEnabled" class="scoring">
              <Form-item
                v-show="editQuestion.options.scoringEnabled"
                :label-width="80"
                :prop="'choices.' + index + '.options.score'"
                :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"> </Input>
              </Form-item>
            </div>
            <div v-show="editQuestion.options.inputtedEnabled" class="inputing">
              <Form-item
                v-show="editQuestion.options.inputtedEnabled"
                :label-width="80"
                :prop="'choices.' + index + '.options.inputEnabled'"
                :rules="[
                  {
                    message: t('survey_creator.question.inputLeastOneTip'),
                    validator: validatedInput,
                  },
                ]"
              >
                <Checkbox v-model="option.options.inputEnabled" />
              </Form-item>
            </div>
            <div v-show="editQuestion.options.starEnabled" class="inputing">
              <Form-item
                v-show="editQuestion.options.starEnabled"
                :label-width="80"
                :prop="'choices.' + index + '.options.star'"
                :rules="[
                  {
                    message: t('survey_creator.question.starLeastOneTip'),
                    validator: validatedStar,
                  },
                ]"
              >
                <Checkbox
                  v-model="option.options.star"
                  @on-change="starChange(option.id)"
                />
              </Form-item>
            </div>
            <div class="buttons">
              <Button
                v-if="editQuestion.choices.length < choiceLimit.max"
                class="button"
                icon="md-add"
                @click.native="addOption()"
              ></Button>
              <Button
                v-if="editQuestion.choices.length > choiceLimit.min"
                class="button"
                icon="md-remove"
                @click.native="deleteOption(index, option.id)"
              ></Button>
            </div>
          </div>
        </FormItem>
        <div v-if="option.options.inputEnabled" class="option-input">
          <Input
            :placeholder="t('survey_creator.question.inputEnabledTip')"
            disabled
          />
        </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,
  Modal,
  Radio,
  RadioGroup,
  Row,
} 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: "single-selection-form",
  components: {
    Form,
    FormItem,
    ButtonGroup,
    Button,
    Input,
    Checkbox,
    Radio,
    RadioGroup,
    Row,
    Col,
    Icon,
    draggable,
    Modal,
    InputNumber,
    RichText,
    Alert,
  },
  mixins: [questionFormMixin],
  data() {
    return {
      choiceLimit: {
        max: 20,
        min: 1,
      },
      layoutOptions: [SurveyLayout.HORIZONTAL, SurveyLayout.VERTICAL],
      enabledInputChoice: false,
      enabledRichText: false,
      enabledSpeciallyQuestions: true,
      enabledEvaluationTag: false,
    };
  },
  created() {
    // @ts-ignore
    this.enabledInputChoice = _.get(
      this.$rootComponent,
      "options.enabledInputChoice",
      false
    );
    // @ts-ignore
    this.enabledRichText = _.get(
      this.$rootComponent,
      "options.enabledPlanSurveyTeacherSetting",
      false
    );
    // @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");
    }

    this.editQuestion.options.richTextEnabled = this.enabledRichText;
  },
  methods: {
    addOption() {
      this.editQuestion.choices.push(
        QuestionFactory.createDefault(this.$rootComponent.primaryLanguage)
      );
    },
    deleteOption(position, choiceId) {
      let jumpIndex = _.findIndex(
        // @ts-ignore
        _.get(this.editQuestion, "jumps", []),
        (jump: any) => jump.choiceId === choiceId
      );
      if (jumpIndex > -1) {
        // @ts-ignore
        Modal.confirm({
          title: this.t("survey_creator.question.jump.delete_option"),
          content: this.t("survey_creator.question.jump.delete_option_desc"),
          onOk: () => {
            this.editQuestion.choices.splice(position, 1);
            this.editQuestion.jumps.splice(jumpIndex, 1);
          },
        });
      } else {
        this.editQuestion.choices.splice(position, 1);
      }
    },
    scoringEnabledChange() {
      if (!this.editQuestion.options.scoringEnabled) {
        _.each(this.editQuestion.choices, (choice) => {
          choice.options.score = null;
        });
      }
    },
    starEnabledChange() {
      if (!this.editQuestion.options.starEnabled) {
        _.each(this.editQuestion.choices, (choice) => {
          choice.options.star = false;
        });
      }
    },
    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;
        });
      }
    },
    starChange(id) {
      _.each(this.editQuestion.choices, (choice) => {
        if (choice.id == id) {
          choice.options.starCount = choice.options.star == true ? 1 : 0;
        }
      });
    },
    validatedStar(rule, value, callback, source, options) {
      if (this.editQuestion.options.starEnabled) {
        let existStar = false;
        _.each(this.editQuestion.choices, (choice) => {
          if (choice.options.star) {
            existStar = true;
          }
        });
        if (existStar) {
          callback();
        }
        callback(new Error(this.t("survey_creator.question.starRequiredTip")));
      }
      callback();
    },
    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>
.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;
  }
}

.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;
  }
}

.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;
    }
  }
}

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

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

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

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