<template>
  <div class="dv-data-calendar-wrap">
    <div class="dv-data-calendar-index-column">
      <div class="dv-data-calendar-index-column-label">月</div>
      <div class="dv-data-calendar-index-column-label" v-for="(row, index) in rows" :key="index">{{row|labelFormat}}</div>
    </div>
    <div class="dv-data-calendar-body">
      <dv-loading v-if="loading"></dv-loading>
      <div class="dv-data-calendar-header">
        <div class="dv-data-calendar-header-cells">
          <div class="dv-data-calendar-header-cell" v-for="day in 31" :key="day">{{ day }}</div>
        </div>
      </div>
      <div class="dv-data-calendar-rows">
        <div class="dv-data-calendar-row" v-for="(row, index) in rows" :key="index">
          <div class="dv-data-calendar-row-cells">
            <div :class="[getCellClass(row, day)]"
                 class="dv-data-calendar-row-cell"
                 @mouseenter="handleCellMouseEnter($event, row, day)"
                 @mouseleave="handleCellMouseLeave($event, row, day)"
                 @click="onClick($event, row, day)"
                 v-for="day in 31"
                 :key="day">
              <slot v-if="isCellValid(row, day)"
                    :value="getCellValue(row, day)"
                    :time="getTime(row, day)">{{getCellValue(row, day)}}</slot>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import dayjs from "dayjs";
import SubDayCalendar from "./SubDayCalendar";

export default {
  name: "DayDataCalendar",
  mixins: [SubDayCalendar],
  filters: {
    labelFormat(value) {
      return dayjs(value).format('MM');
    }
  },
  props: {
    startTime: {
      type: String,
      default: '2020-01'
    },
    endTime: {
      type: String,
      default: '2020-12'
    }
  },
  computed: {
    rows() {
      const rows = [];
      let date = dayjs(this.startTime);
      const endTime = dayjs(this.endTime);

      while (!date.isAfter(endTime)) {
        rows.push(date.format('YYYY-MM-01 00:00:00'));
        date = date.add(1, 'month');
      }
      return rows;
    }
  },
  methods: {
    isCellValid (date, day) {
      const time = dayjs(date).date(day);
      return time.date() === day && !time.isAfter(dayjs());
    },
    getTime(date, day) {
      return dayjs(date).date(day).format('YYYY-MM-DD 00:00:00');
    },
    getCellClass (date, day) {
      const time = this.getTime(date, day);
      const month = dayjs(date).month();
      const thisMonth = dayjs(time).month();
      const valid = month === thisMonth;
      const cellClass = this.cellClass(time);
      return [cellClass, {
        'invalid': !valid
      }];
    }
  }
}
</script>
