<template>
  <Table
    size="small"
    ref="myTable"
    border
    :data="evaluationItems"
    :columns="realColumns"
  >
    <template slot-scope="{ row, column }" slot="levelName">
      <FormItem
        :prop="'evaluationItems[' + row._index + '].text.' + primaryLanguage"
        :rules="{
          required: true,
          message: t('survey_creator.question.commitRequiredTip'),
        }"
      >
        <Input v-model.trim="evaluationItems[row._index].text[primaryLanguage]">
        </Input>
      </FormItem>
    </template>
    <template slot-scope="{ row, column }" slot="level">
      <FormItem
        :prop="'evaluationItems[' + row._index + '].level'"
        :rules="{
          required: true,
          message: t('survey_creator.question.levelRequiredTip'),
        }"
      >
        <span>>=</span>
        <InputNumber
          v-model="evaluationItems[row._index].level"
          :min="1"
          :max="100"
          :active-change="false"
          :precision="0"
          @on-change="calculationItemLevelRange"
        >
        </InputNumber>
      </FormItem>
    </template>
    <template slot-scope="{ row, column }" slot="actions">
      <Button
        @click.native="addItem()"
        v-if="evaluationItems.length"
        icon="md-add"
      ></Button>
      <Button
        @click.native="deleteItem(row._index)"
        v-if="evaluationItems.length > 1"
        icon="md-remove"
      ></Button>
    </template>
  </Table>
</template>
<script lang="ts">
import Vue from "vue";
import {
  FormItem,
  Input,
  InputNumber,
  Select,
  Table,
  Button,
} from "view-design";
import { StarEvaluationItemModel } from "@wg-npm/survey-core";
import questionFormMixin from "../../../../mixins/question-form-mixin";
import draggable from "vuedraggable";
import _ from "lodash";

export default Vue.extend({
  name: "star",
  mixins: [questionFormMixin],
  components: {
    FormItem,
    Input,
    InputNumber,
    draggable,
    Select,
    Table,
    Button,
  },
  props: {
    value: {
      type: Array,
      required: true,
    },
  },
  data() {
    return {
      evaluationItems: this.value,
      realColumns: [],
    };
  },
  created() {
    this.initDefaultChoices();
    this.initColumns();
  },
  methods: {
    initDefaultChoices() {
      const self = this;
      let primaryLanguage = this.$rootComponent.primaryLanguage;
      _.forEach(this.evaluationItems, (item, index) => {
        let i18nText = self.t(
          `survey_creator.question.evaluation.level.${index + 1}`
        );
        if (
          // @ts-ignore
          !_.get(item.text, primaryLanguage) &&
          !i18nText.startsWith("survey_creator.question.evaluation.level")
        ) {
          // @ts-ignore
          _.set(item.text, primaryLanguage, i18nText);
        }
        // @ts-ignore
        if (!_.get(item, "level")) {
          // @ts-ignore
          _.set(item, "level", 1);
        }
      });
      this.calculationItemLevelRange();
    },
    calculationItemLevelRange() {
      let levels = _.chain(this.evaluationItems)
        .map((item) => parseInt(item.level))
        .filter((level) => !isNaN(level))
        .uniq()
        .sortBy()
        // @ts-ignore
        .value();
      _.forEach(this.evaluationItems, (item, index) => {
        // @ts-ignore
        let currentLevelIndex = _.indexOf(levels, _.get(item, "level"));
        if (levels.length == currentLevelIndex + 1) {
          // @ts-ignore
          _.set(item, "range", { max: null, min: levels[currentLevelIndex] });
        } else {
          // @ts-ignore
          _.set(item, "range", {
            max: levels[currentLevelIndex + 1] - 1,
            min: levels[currentLevelIndex],
          });
        }
      });
    },
    initColumns() {
      this.realColumns = [
        {
          title: this.t("survey_creator.question.evaluation.levelNameLabel"),
          key: "levelName",
          slot: "levelName",
        },
        {
          title: `${this.t(
            "survey_creator.question.evaluation.levelNameLabel"
          )}(${this.t(`survey_creator.question.evaluation.type.STAR`)})`,
          key: "level",
          slot: "level",
        },
        {
          title: this.t("survey_creator.common.operation"),
          key: "actions",
          slot: "actions",
        },
      ];
    },
    addItem() {
      let item = new StarEvaluationItemModel(this.primaryLanguage);
      item.level = 1;
      this.evaluationItems.push(item);
      this.initDefaultChoices();
      this.scrollToEnd();
    },
    deleteItem(position) {
      this.evaluationItems.splice(position, 1);
    },
    scrollToEnd() {
      // @ts-ignore
      let id = this.evaluationItems.length - 1;
      this.$nextTick(() => {
        // @ts-ignore
        document.querySelector("tr.ivu-table-row :last-child").scrollIntoView();
      });
    },
  },
});
</script>
