<template>
  <Form ref="questionForm" :model="editQuestion" :label-colon="false">
    <!-- Config Row -->
    <div class="config-row">
      <div class="config-item">
        <span class="config-label"
          >{{ t("survey_creator.question.matrixForm.topic") }}:</span
        >
        <Checkbox v-model="editQuestion.options.required">{{
          t("survey_creator.question.matrixForm.required")
        }}</Checkbox>
        <Checkbox v-model="editQuestion.options.titleScoringEnabled">{{
          t("survey_creator.question.matrixForm.scoring")
        }}</Checkbox>
      </div>
      <div class="config-item">
        <span class="config-label"
          >{{ t("survey_creator.question.matrixForm.sub") }}:</span
        >
        <Checkbox v-model="editQuestion.options.subRequired">{{
          t("survey_creator.question.matrixForm.required")
        }}</Checkbox>
        <Checkbox v-model="editQuestion.options.scoringEnabled">{{
          t("survey_creator.question.matrixForm.scoring")
        }}</Checkbox>
      </div>
      <div class="config-item" 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>
      </div>
    </div>

    <!-- Section 1: 主题题目设置 -->
    <div class="section-header">
      <span class="section-title">{{
        t("survey_creator.question.matrixForm.topicSection")
      }}</span>
    </div>
    <div class="section-body">
      <Row type="flex" :gutter="8" align="middle" class="form-row">
        <Col class="row-main">
          <FormItem
            :prop="'header.text.' + primaryLanguage"
            :rules="{
              required: true,
              message: t('survey_creator.question.titleRequiredTip'),
            }"
          >
            <div class="row-input-line">
              <div class="row-label-area">
                <span class="req-star">*</span>
                <span class="row-label"
                  >{{
                    t("survey_creator.question.matrixForm.topicLabel")
                  }}：</span
                >
              </div>
              <Input
                v-model.trim="editQuestion.header.text[primaryLanguage]"
                :placeholder="
                  t('survey_creator.question.matrixForm.topicPlaceholder')
                "
              />
            </div>
          </FormItem>
        </Col>
      </Row>
      <Row
        v-if="editQuestion.options.titleScoringEnabled"
        type="flex"
        :gutter="8"
        align="middle"
        class="form-row"
      >
        <Col class="row-main">
          <FormItem
            prop="options.scoreMin"
            :rules="{
              required: true,
              message: t(
                'survey_creator.question.matrixForm.scoreRangeRequiredTip'
              ),
            }"
          >
            <div class="row-input-line">
              <div class="row-label-area">
                <span class="req-star">*</span>
                <span class="row-label"
                  >{{
                    t("survey_creator.question.matrixForm.scoreRange")
                  }}：</span
                >
              </div>
              <div class="range-inputs">
                <Select
                  v-model="editQuestion.options.scoreMin"
                  style="width: 80px"
                >
                  <Option
                    v-for="item in scoreRange"
                    :value="item"
                    :key="'min-' + item"
                    :disabled="disableScoreMinOption(item)"
                    >{{ item }}</Option
                  >
                </Select>
                <span class="range-sep">-</span>
                <Select
                  v-model="editQuestion.options.scoreMax"
                  style="width: 80px"
                >
                  <Option
                    v-for="item in scoreRange"
                    :value="item"
                    :key="'max-' + item"
                    :disabled="disableScoreMaxOption(item)"
                    >{{ item }}</Option
                  >
                </Select>
              </div>
            </div>
          </FormItem>
        </Col>
      </Row>
    </div>

    <!-- Section 2: 子题题目设置 -->
    <div class="section-header">
      <span class="section-title">{{
        t("survey_creator.question.matrixForm.subSection")
      }}</span>
    </div>
    <div class="section-body">
      <div
        v-for="(subQuestion, index) in editQuestion.subQuestions"
        :id="'subQuestion-' + index"
        :key="subQuestion.id || index"
        class="form-row"
      >
        <Row type="flex" :gutter="8" align="middle">
          <Col class="row-main">
            <FormItem
              :prop="'subQuestions.' + index + '.text.' + primaryLanguage"
              :rules="{
                required: true,
                message: t('survey_creator.question.subQuestionRequiredTip'),
              }"
            >
              <div class="row-input-line">
                <div class="row-label-area">
                  <span class="req-star">*</span>
                  <span class="row-label"
                    >{{
                      t("survey_creator.question.matrixForm.subLabel")
                    }}：</span
                  >
                </div>
                <Input v-model.trim="subQuestion.text[primaryLanguage]" />
              </div>
            </FormItem>
          </Col>
          <Col class="op-col">
            <ButtonGroup>
              <Button icon="md-add" @click.native="addSubQuestion" />
              <Button
                v-if="editQuestion.subQuestions.length > 1"
                icon="md-remove"
                @click.native="deleteSubQuestion(index)"
              />
            </ButtonGroup>
          </Col>
        </Row>
      </div>
    </div>

    <!-- Section 3: 子题选项设置 -->
    <div class="section-header section-header-with-ops">
      <span class="section-title">{{
        t("survey_creator.question.matrixForm.optionSection")
      }}</span>
      <span
        v-if="editQuestion.options.scoringEnabled"
        class="section-score-col"
        >{{ t("survey_creator.question.matrixForm.scoreColumn") }}</span
      >
    </div>
    <div class="section-body">
      <div
        v-for="(choice, index) in editQuestion.choices"
        :key="choice.id"
        class="form-row"
      >
        <Row type="flex" :gutter="8" align="middle">
          <Col class="row-main">
            <FormItem
              :prop="'choices.' + index + '.text.' + primaryLanguage"
              :rules="{
                required: true,
                message: t('survey_creator.question.commitRequiredTip'),
              }"
            >
              <div class="row-input-line">
                <div class="row-label-area">
                  <span class="req-star">*</span>
                  <span class="row-label"
                    >{{
                      t("survey_creator.question.matrixForm.optionLabel")
                    }}：</span
                  >
                </div>
                <Input v-model.trim="choice.text[primaryLanguage]" />
              </div>
            </FormItem>
          </Col>
          <Col v-if="editQuestion.options.scoringEnabled" class="score-col">
            <FormItem
              :prop="'choices.' + index + '.options.score'"
              :rules="{
                required: true,
                message: t('survey_creator.question.scoreRequiredTip'),
              }"
            >
              <InputNumber
                :min="0"
                v-model="choice.options.score"
                class="score-input"
              />
            </FormItem>
          </Col>
          <Col class="op-col">
            <ButtonGroup>
              <Button icon="md-add" @click.native="addChoice" />
              <Button
                v-if="editQuestion.choices.length > 1"
                icon="md-remove"
                @click.native="deleteChoice(index)"
              />
            </ButtonGroup>
          </Col>
        </Row>
      </div>
    </div>
  </Form>
</template>

<script lang="ts">
import Vue from "vue";
import _ from "lodash";
import {
  Button,
  ButtonGroup,
  Checkbox,
  Col,
  Form,
  FormItem,
  Input,
  InputNumber,
  Option,
  Radio,
  RadioGroup,
  Row,
  Select,
} from "view-design";
import { ChoiceModel, SubQuestionModel } from "@wg-npm/survey-core";
import questionFormMixin from "../../../mixins/question-form-mixin";

export default Vue.extend({
  name: "matrix-form",
  components: {
    Form,
    FormItem,
    ButtonGroup,
    Button,
    Input,
    Checkbox,
    Radio,
    RadioGroup,
    InputNumber,
    Row,
    Col,
    Select,
    Option,
  },
  mixins: [questionFormMixin],
  data() {
    return {
      enabledEvaluationTag: false,
      scoreRange: [] as number[],
    };
  },
  created() {
    // @ts-ignore
    this.enabledEvaluationTag = _.get(
      this.$rootComponent,
      "options.enabledEvaluationTag",
      false
    );
    if (this.enabledEvaluationTag && !this.editQuestion.options.evaluationTag) {
      this.$set(this.editQuestion.options, "evaluationTag", "COURSE");
    }
    // @ts-ignore
    this.scoreRange = _.get(
      this.$rootComponent,
      "options.scoreRange",
      [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    );
  },
  mounted() {
    this.initData();
  },
  methods: {
    initData() {
      // Ensure new fields exist
      if (this.editQuestion.options.titleScoringEnabled === undefined) {
        this.$set(this.editQuestion.options, "titleScoringEnabled", false);
      }
      if (this.editQuestion.options.subRequired === undefined) {
        this.$set(this.editQuestion.options, "subRequired", false);
      }
      if (
        this.editQuestion.options.scoreMin === undefined ||
        this.editQuestion.options.scoreMin === null
      ) {
        this.$set(this.editQuestion.options, "scoreMin", 1);
      }
      if (
        this.editQuestion.options.scoreMax === undefined ||
        this.editQuestion.options.scoreMax === null
      ) {
        this.$set(
          this.editQuestion.options,
          "scoreMax",
          _.last(this.scoreRange)
        );
      }
      // Ensure subQuestions array exists
      this.editQuestion.subQuestions ||
        // @ts-ignore
        _.set(this.editQuestion, "subQuestions", []);
      // Initialize default choice texts and scores
      this.initDefaultItems(this.editQuestion);
    },

    disableScoreMinOption(value) {
      return value >= this.editQuestion.options.scoreMax;
    },

    disableScoreMaxOption(value) {
      return value <= this.editQuestion.options.scoreMin;
    },

    initDefaultItems(question) {
      const primaryLanguage = this.primaryLanguage;
      const t = this.t;
      _.forEach(question.choices, (choice, index) => {
        // @ts-ignore
        if (!_.get(choice.text, primaryLanguage)) {
          // @ts-ignore
          _.set(
            choice.text,
            primaryLanguage,
            t(`survey_creator.question.matrixLevel${index + 2}`) || ""
          );
        }
        if (
          choice.options.score === null ||
          choice.options.score === undefined
        ) {
          choice.options.score = index + 1;
        }
      });
      return question;
    },

    addSubQuestion() {
      this.editQuestion.subQuestions.push(
        new SubQuestionModel(this.primaryLanguage)
      );
      this.scrollToEnd();
    },

    deleteSubQuestion(position) {
      this.editQuestion.subQuestions.splice(position, 1);
    },

    addChoice() {
      const choice = new ChoiceModel(this.primaryLanguage);
      // @ts-ignore
      choice.options.score = this.editQuestion.choices.length + 1;
      this.editQuestion.choices.push(choice);
    },

    deleteChoice(position) {
      if (this.editQuestion.choices.length > 1) {
        this.editQuestion.choices.splice(position, 1);
      }
    },

    scrollToEnd() {
      // @ts-ignore
      let id = this.editQuestion.subQuestions.length - 1;
      this.$nextTick(() => {
        // @ts-ignore
        document.getElementById("subQuestion-" + id).scrollIntoView();
      });
    },
  },
  watch: {
    editQuestion: function (value) {
      this.initData();
    },
  },
});
</script>

<style scoped lang="less">
/deep/ .ivu-form-item {
  width: 100%;
  margin-bottom: 0;
}
/deep/ .ivu-form-item-content {
  line-height: normal;
}
/deep/ .ivu-form-item-error-tip {
  padding-top: 2px;
}

.config-row {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 20px;
  padding: 12px 8px 16px;
  border-bottom: 1px solid #e8eaec;
  margin-bottom: 16px;

  .config-item {
    flex: auto;
    display: flex;
    align-items: center;
    gap: 12px;

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

.section-header {
  display: flex;
  align-items: center;
  background: #f5f5f7;
  height: 34px;
  border-radius: 4px;
  padding: 0 16px;
  margin-bottom: 16px;

  .section-title {
    flex: 1;
    font-size: 14px;
    color: #70748c;
  }

  .section-score-col {
    width: 80px;
    font-size: 14px;
    color: #70748c;
    text-align: center;
  }
}

.section-body {
  padding-left: 16px;
  margin-bottom: 24px;

  .form-row {
    margin-bottom: 16px;

    &:last-child {
      margin-bottom: 0;
    }
  }
}

.row-main {
  flex: 1;
  min-width: 0;
}

.score-col {
  width: 80px;
  flex-shrink: 0;
  display: flex;
  align-items: center;
}

.op-col {
  width: 76px;
  flex-shrink: 0;
  display: flex;
  align-items: center;
  margin-left: 8px;
}

.section-header-with-ops {
  padding-right: 80px;
}

.score-input {
  width: 80px;
}

.row-input-line {
  display: flex;
  align-items: center;

  .row-label-area {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    width: 90px;
    flex-shrink: 0;
    gap: 4px;

    .req-star {
      color: #ed4014;
      font-size: 12px;
    }

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

  .ivu-input-wrapper {
    flex: 1;
  }
}

.range-inputs {
  display: flex;
  align-items: center;
  gap: 8px;

  .range-sep {
    color: #525566;
    font-size: 14px;
  }
}
</style>
