<template>
  <div class="time-selector">
    <el-select
      class="quantity mr10"
      :size="size"
      :value="value.quantity"
      @change="handleChange('quantity', $event)"
      placeholder="请选择"
      no-data-text="选择单位后载入数据"
      :clearable="isClearable"
    >
      <el-option v-if="hasZero && value.unit === periodUnitMap.day" key="0" label="0" :value="0" />
      <el-option
        v-for="quantity in quantities"
        :key="quantity"
        :label="quantity.toString()"
        :value="quantity"
      />
    </el-select>

    <el-select
      class="unit"
      :size="size"
      :value="value.unit"
      @change="handleChange('unit', $event)"
      placeholder="请选择"
      :clearable="isClearable"
      style="width: 120px"
    >
      <el-option
        :label="item.label"
        :value="item.value"
        v-for="item in periodUnitEnum.options"
        :key="item.value"
      />
    </el-select>
  </div>
</template>

<script>
import { periodUnitMap } from "@/constant";
export default {
  enums: ["periodUnitMap", "periodUnitEnum"],
  data() {
    return {
      quantities: [],
    };
  },
  props: {
    size: String,
    value: {
      type: Object,
      defualt: {},
    },
    hasZero: {
      type: Boolean,
      default: false,
    },
    clearable: {
      type: Boolean,
      default: false,
    },
    defaultUnit: {
      type: [Number, String],
      default: periodUnitMap.day,
    },
  },
  created() {
    if (!this.value.unit && this.defaultUnit) {
      this.handleChange("unit", this.defaultUnit);
    }
    this.init();
  },
  computed: {
    isClearable() {
      return this.clearable || this.clearable === "";
    },
  },
  watch: {
    "value.unit"() {
      this.init();
    },
  },
  methods: {
    init() {
      const { unit, quantity } = this.value;
      if (unit === this.periodUnitMap.day) {
        this.quantities = Array.from({ length: 30 }, (_, i) => i + 1);
        if (quantity > 30) {
          this.handleChange("quantity", 30);
        }
      } else if (unit === this.periodUnitMap.month) {
        this.quantities = Array.from({ length: 12 }, (_, i) => i + 1);
        if (quantity > 12) {
          this.handleChange("quantity", 12);
        }
      } else if (unit === this.periodUnitMap.year) {
        this.quantities = Array.from({ length: 10 }, (_, i) => i + 1);
        if (quantity > 10) {
          this.handleChange("quantity", 10);
        }
      } else {
        this.quantities = [];
        this.handleChange("quantity", "");
      }
    },
    handleChange(field, value) {
      this.$emit("change", {
        unit: this.value.unit,
        quantity: this.value.quantity,
        [field]: value,
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.time-selector {
  display: flex;
  align-items: center;
  .unit {
    width: 80px;
  }
}
</style>
