<template>
  <div class="fl time">
    <el-date-picker
      v-model="value"
      type="month"
      :size="size"
      placeholder="选择月"
      value-format="yyyy-MM"
      @change="timeChange"
      :editable="false"
      :clearable="true"
      :disabled="isEdit"
      :picker-options="pickerOptions"
    >
    </el-date-picker>
  </div>
</template>

<script>
// 选择时间段(只有日期)组件
// timeReturned 返回值{startTime: Number,endTime: Number}
export default {
  name: "PeriodDatePicker",
  props: ["month", "disabled", "size", "width", "type", "placeholder", "newTime"],
  data() {
    return {
      value: this.month,
      isEdit: this.disabled,
      pickerOptions: {
        disabledDate: (time) => {
          return time.getTime() > new Date().valueOf();
        },
      },
    };
  },
  watch: {
    disabled: function (val) {
      this.isEdit = val;
    },
    month: function (val) {
      this.value = val;
    },
    newTime: function (val) {
      this.timeChange();
    },
  },
  mounted() {},
  methods: {
    timeChange() {
      if (this.value === null) {
        this.value = "";
        let model = {
          startTime: "",
          endTime: "",
          value: this.value,
        };
        this.$emit("timeReturned", model);
      } else {
        let end = "";
        let time = new Date(this.value);
        let y = time.getFullYear();
        let M = time.getMonth() + 1;
        let timeTemplate = y + "-" + (M < 10 ? "0" + M : M) + "-";
        if (M + "" === "12") {
          end = timeTemplate + "31";
        } else {
          let M2 = parseInt(M) + 1;
          let ti2 = y + "-" + (M < 10 ? "0" + M2 : M2) + "-01";
          let timestamp = new Date(ti2).valueOf() - 1000 * 60 * 60 * 24;
          let time2 = new Date(timestamp);
          let D = time2.getDate();
          end = timeTemplate + (D < 10 ? "0" + D : D);
        }
        let model = {
          startTime: `${this.value}-01`,
          endTime: end,
          value: this.value,
        };
        this.$emit("timeReturned", model);
      }
      console.log(this.value);
    },
  },
};
</script>
<style lang="scss">
.date-picker.el-input {
  // width: 150px !important;
}
</style>
