<template>
  <a-modal
    :cancel-text="labels.cancel"
    :title="labels.setLadder"
    :ok-text="labels.confirm"
    width="50%"
    :maskClosable="false"
    :visible.sync="fieldDialogVisible"
    @cancel="confirmCancel"
    @ok="handleOk"
  >
    <avue-form
      ref="ladderForm"
      v-model="ladderFormOption.form"
      :option="ladderFormOption.option"
      @submit="submitLadderForm"
    ></avue-form>
    <avue-crud :data="ladderOption.data" :option="ladderOption.option" @row-del="delLadderUpdate">
    </avue-crud>
  </a-modal>
</template>

<script>
import { ft } from '../../../lib/utils.js';
import ladderFormOption from './const/ladderForm';
import ladderOption from './const/ladder';

const LABELS = {
  cancel: ft('i18n_common_cancel', '取消'),
  close: ft('i18n_common_close', '关闭'),
  confirm: ft('i18n_common_confirm', '确认'),
  numberOfPreviousSteps: ft('i18n_common_the_number_of_previous_steps', '上一阶梯数量'),
  numberOfSteps: ft('i18n_common_the_number_of_steps', '阶梯数量'),
  ladderIsNotSaved: ft('i18n_common_ladder_data_is_not_saved', '阶梯数据未保存'),
  pleaseAdd: ft('i18n_common_please_add', '请添加 '),
  pleaseSelect: ft('i18n_common_please_select', '请选择'),
  setLadder: ft('i18n_common_set_ladder', '设置阶梯'),
  shouldBeGreaterThen: ft('i18n_common_should_be_greater', '应当大于 ?'),
  sureWantToCloseDialog: ft('i18n_common_are_you_sure_want_to_close_the_dialog', '确定关闭对话框')
};

// 采购方设置阶梯报价信息
export default {
  name: 'LadderJsonDialog',
  components: {},
  created: function () {},
  props: {
    fieldDialogType: String,
    fieldDialogVisible: {
      type: Boolean,
      default: false
    },
    field: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  data() {
    return {
      labels: LABELS,
      ladderFormOption: ladderFormOption,
      ladderOption: ladderOption,
      ladderPriceJsonString: ''
    };
  },
  watch: {
    field(newVal) {
      const jsonString = newVal.ladderPriceJson || '';
      // this.ladderOption.data = this.recoveryData(jsonString);
      this.ladderOption.data = jsonString ? JSON.parse(jsonString) : [];
      this.ladderPriceJsonString = jsonString;
    }
  },
  methods: {
    cancel() {
      // recovery data
      this.ladderOption.data = this.ladderPriceJsonString
        ? JSON.parse(this.ladderPriceJsonString)
        : [];

      this.closeDialog();
    },

    closeDialog() {
      this.$emit('cancel-field-dialog');
    },

    confirmCancel() {
      const data = this.ladderOption.data;

      const currentString =
        data.length > 0
          ? data
              .map((item) => {
                return item.ladderQuantity;
              })
              .join('_')
          : '';

      const originalString = this.ladderPriceJsonString
        ? JSON.parse(this.ladderPriceJsonString)
            .map((item) => {
              return item.ladderQuantity;
            })
            .join('_')
        : '';

      if (currentString !== originalString) {
        const _this = this;

        this.$confirm({
          title: `${LABELS.ladderIsNotSaved}, ${LABELS.sureWantToCloseDialog.toLowerCase()}`,
          okText: LABELS.close,
          cancelText: LABELS.cancel,
          type: 'warning',
          onOk() {
            _this.cancel();
          }
        });
      } else {
        this.closeDialog();
      }
    },

    delLadderUpdate(row, index) {
      this.ladderOption.data.splice(index, 1);
      this.updateLadder();
    },

    handleOk() {
      if (this.ladderOption.data.length < 1) {
        this.$message.error(`${LABELS.pleaseAdd}${LABELS.numberOfSteps.toLowerCase()}`);
        return;
      }

      const jsonString = JSON.stringify(
        this.ladderOption.data.map((item) => {
          return {
            ladderQuantity: item.ladderQuantity,
            ladderGrade: item.ladderGrade
          };
        })
      );

      this.ladderPriceJsonString = jsonString;

      this.$emit('on-save-ladder-json', jsonString);
    },

    submitLadderForm(form, done) {
      const length = this.ladderOption.data.length;
      const current = Number(form.ladderQuantity);

      const last =
        this.ladderOption.data.length >= 1
          ? Number(this.ladderOption.data[length - 1].ladderQuantity)
          : 0;

      if (current <= last) {
        this.$message.error(
          `${LABELS.numberOfSteps}: ${LABELS.shouldBeGreaterThen.replace(
            '?',
            `${LABELS.numberOfPreviousSteps}`
          )}`
        );
        done();
        return;
      }

      this.ladderOption.data.push(form);
      this.updateLadder();
      this.ladderFormOption.form.ladderQuantity = '';

      done();
    },

    updateLadder() {
      const length = this.ladderOption.data.length;
      this.ladderOption.data = this.ladderOption.data.map((item, index) => {
        if (index === length - 1) {
          return {
            ...item,
            ladderGrade: `${item.ladderQuantity} <= x`
          };
        } else {
          return {
            ...item,
            ladderGrade: `${item.ladderQuantity} <= x < ${
              this.ladderOption.data[index + 1].ladderQuantity
            }`
          };
        }
      });
    }
  }
};
</script>
