<template>
  <div class="year-month-select">
    <div class="year-warp" style="width: 95px">
      <el-date-picker
        v-model="year"
        type="year"
        :clearable="false"
        placeholder="选择年"
        size="small"
        value-format="yyyy"
      >
      </el-date-picker>
    </div>
    <div class="month-wrap">
      <div class="month-list">
        <div
          :class="[{ active: month == item.value }, 'month-list-item']"
          v-for="item of monthList"
          :key="item.value"
          @click="handleMonthClick(item)"
        >
          {{ item.name }}
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "YearMonthSelect",
  props: {
    value: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      monthList: [],
      year: "",
      month: "",
    };
  },
  watch: {
    value: {
      handler(newVal) {
        if (newVal) {
          let dateArr = newVal.split("-");
          this.year = dateArr[0];
          this.month = dateArr[1] || "00";
        }
      },
      immediate: true,
    },
    year(newVal) {
      this.$emit("input", this.formatYearMonth(newVal, this.month));
    },
  },
  created() {
    this.initMonth();
  },
  methods: {
    initMonth() {
      let list = [];
      for (let i = 0; i < 12; i++) {
        let month = i + 1;
        list.push({
          name: month + "月",
          value: month > 9 ? month.toString() : "0" + month,
        });
      }
      list.push({ name: "全年", value: "00" });
      this.monthList = list;
    },
    formatYearMonth(year, month) {
      if (month == "00") {
        return year;
      }
      return year + "-" + month;
    },
    handleMonthClick(data) {
      this.month = data.value;
      this.$emit("input", this.formatYearMonth(this.year, this.month));
    },
  },
};
</script>

<style lang="scss">
.year-month-select {
  display: flex;
  align-items: center;
  margin: 12px 0;
}
.month-list {
  display: flex;
  margin-left: 12px;
  &-item {
    width: 40px;
    height: 30px;
    line-height: 30px;
    text-align: center;
    background-color: #fff;
    color: #409eff;
    border-radius: 4px;
    margin-right: 8px;
    border: 1px solid #409eff;
    cursor: pointer;
    font-size: 12px;
    &.active {
      background-color: #409eff;
      color: #fff;
    }
    // &.primary {
    //   background-color: #409EFF;
    //   border: 1px solid #409EFF;
    // }
    // &.success {
    //   background-color: #67c23a;
    //   border-color: #67c23a;
    // }
  }
}
</style>
