<template>
  <Card dis-hover>
    <Row type="flex" :gutter="6" slot="title">
      <Col>
        <div class="text">
          {{ t("survey_creator.question.evaluation.condition.if") }}
        </div>
      </Col>
      <Col>
        <Button type="primary" icon="md-add" @click="onAdd">
          {{
            t("survey_creator.question.evaluation.condition.add_if_template")
          }}
        </Button>
      </Col>
    </Row>
    <a href="#" slot="extra" @click.prevent="onDelete" v-show="deletable">
      {{ t("survey_creator.common.delete") }}
    </a>
    <Row type="flex" justify="start" align="middle">
      <Col :span="22">
        <Row type="flex" justify="start" align="middle">
          <Col class="label">
            <Icon type="ios-arrow-forward" color="#2d8cf0" />
            {{ t("survey_creator.question.evaluation.condition.requirements") }}
          </Col>
          <Col :span="16">
            <Select v-model="exprConditionType">
              <Option
                v-for="type in exprConditionTypes"
                :value="type"
                :key="type"
              >
                {{
                  t(`survey_creator.question.evaluation.condition.type.${type}`)
                }}
              </Option>
            </Select>
          </Col>
        </Row>
      </Col>
      <Col :span="2">
        <Button
          icon="md-add"
          :disabled="disableAddConditionBtn"
          class="action"
          @click="addCondition"
        ></Button>
      </Col>
    </Row>
    <Row
      type="flex"
      justify="space-between"
      align="middle"
      v-for="(condition, index) in evaluationItems[position].conditions"
      :key="index"
      class="mt-base"
    >
      <Col :span="22">
        <condition
          :key="index"
          :index="index"
          :type="condition.type"
          v-model="condition.payload"
          @expr="expr"
          :question="question"
          :evaluation-items="evaluationItems"
          :item-index="position"
        />
      </Col>
      <Col :span="2">
        <Button
          icon="md-remove"
          class="action"
          style="margin-bottom: 24px"
          @click="removeCondition(index)"
        ></Button>
      </Col>
    </Row>
    <Row type="flex" justify="end" align="middle" class="mt-base">
      <Col>
        <FormItem
          :prop="'evaluationItems[' + position + '].text.' + primaryLanguage"
          :rules="{
            required: true,
            message: t(
              'survey_creator.question.evaluation.condition.evaluation_require_tip'
            ),
          }"
          >{{
            t("survey_creator.question.evaluation.condition.evaluation_label")
          }}
          <Input
            class="input"
            v-model.trim="evaluationItems[position].text[primaryLanguage]"
          />
        </FormItem>
      </Col>
    </Row>
  </Card>
</template>
<script lang="ts">
import Vue from "vue";
import QuestionFormMixin from "../../../../../mixins/question-form-mixin";
import {
  ExprConditionType,
  ExprEvaluationItemType,
} from "@wg-npm/survey-core/src/models";
import {
  Card,
  Row,
  Col,
  Button,
  Select,
  Option,
  Icon,
  FormItem,
  Input,
} from "view-design";
import Condition from "./condition.vue";
import _ from "lodash";

export default Vue.extend({
  name: "if",
  mixins: [QuestionFormMixin],
  components: {
    Card,
    Row,
    Col,
    Select,
    Option,
    Button,
    Icon,
    Condition,
    FormItem,
    Input,
  },
  props: {
    value: {
      type: Array,
      required: true,
    },
    position: {
      type: Number,
      required: true,
    },
  },
  data() {
    return {
      evaluationItems: this.value,
      exprConditionType: ExprConditionType.AUTO,
      exprConditionTypes: [
        ExprConditionType.AUTO,
        ExprConditionType.ASSIGN,
        ExprConditionType.SCORE,
      ],
    };
  },
  computed: {
    totalScore() {
      return this.$rootComponent.currentSurvey.statistics.maxScore;
    },
    deletable() {
      return (
        _.size(
          _.filter(
            this.evaluationItems,
            (item) => item.type == ExprEvaluationItemType.IF
          )
        ) > 1
      );
    },
    disableAddConditionBtn() {
      let conditions = this.evaluationItems[this.position].conditions;
      let scoreConditions = _.size(
        _.filter(conditions, (item) => item.type == ExprConditionType.SCORE)
      );
      return (
        this.exprConditionType == ExprConditionType.SCORE && scoreConditions > 0
      );
    },
  },
  methods: {
    onAdd() {
      this.evaluationItems.splice(this.position + 1, 0, {
        id: `Evaluation-Item-${_.now()}-${_.random(0, 9999999)}`,
        type: ExprEvaluationItemType.IF,
        text: {
          "zh-CN": "",
        },
        conditions: [],
      });
    },
    onDelete() {
      this.evaluationItems.splice(this.position, 1);
    },
    addCondition() {
      this.evaluationItems[this.position].conditions ||
        this.$set(this.evaluationItems[this.position], "conditions", []);
      this.evaluationItems[this.position].conditions.push({
        type: this.exprConditionType,
        payload: this.buildPayloadByType(this.exprConditionType),
      });
    },
    buildPayloadByType(type) {
      if (type == ExprConditionType.SCORE) {
        return {
          minScore: null,
          leftOperator: "<",
          rightOperator: "<",
          maxScore: null,
        };
      }
      return {
        scope: [],
        operator: "=",
        values: [],
        size: 0,
      };
    },
    removeCondition(index) {
      this.evaluationItems[this.position].conditions.splice(index, 1);
    },
    expr(index, value) {
      // @ts-ignore
      _.set(
        this.evaluationItems[this.position].conditions[index],
        "expr",
        value
      );
    },
  },
});
</script>
<style scoped lang="less">
.mt-base {
  margin-top: 12px;
}

.action {
  float: right;
}

.input {
  width: 100px;
}

.label {
  text-align: right;
  padding-right: 4px;
}

.text {
  background-color: #ebf7ff;
  height: 32px;
  padding: 8px 18px;
  font-weight: 500;
  color: #515a6e;
}

/deep/ .ivu-card .ivu-form-item {
  margin-bottom: 4px;
  margin-top: 0;
}

/deep/ .ivu-card .ivu-form-item-error {
  margin-bottom: 24px;
  margin-top: 0;
}
</style>
