<template>
  <div class="exam-backup-edit inline-block">
    <el-select
      v-model="type"
      :disabled="disabled"
      class="mr-1"
      size="small"
      @change="typeChange"
    >
      <el-option value="count" label="按固定份数设置"></el-option>
      <el-option value="percent" label="按比例设置"></el-option>
    </el-select>
    <el-input-number
      v-model="backupCount"
      size="small"
      :min="1"
      :max="type === 'count' ? 200 : 99"
      :step="1"
      step-strictly
      :controls="false"
      style="width: 60px"
      :disabled="disabled"
      @change="emitChange"
    ></el-input-number>
    <span class="ml-1">{{ type === "count" ? "份" : "%" }}</span>
  </div>
</template>

<script>
export default {
  name: "exam-backup-edit",
  props: {
    value: {
      type: Number,
      default: 1,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  watch: {
    value: {
      immediate: true,
      handler(val) {
        if (!val) {
          this.backupCount = 1;
        } else {
          this.type = val >= 0 && val < 1 ? "percent" : "count";
          this.backupCount = val;
          if (this.type === "percent") {
            this.backupCount = val * 100;
          }
        }
      },
    },
  },
  data() {
    return {
      type: "count",
      backupCount: 1,
    };
  },
  methods: {
    typeChange() {
      if (this.type === "percent") {
        this.backupCount = Math.min(this.backupCount, 99);
      }
      this.emitChange();
    },
    emitChange() {
      let val = this.backupCount;
      if (this.type === "percent") {
        val = val / 100;
      }
      this.$emit("input", val);
      this.$emit("change", val);
    },
  },
};
</script>
