<template>
  <table class="mm-year-table">
    <tbody @click="handleClick">
      <tr
        v-for="(row, rowIndex) of years"
        :key="rowIndex">
        <td
          v-for="(cell, cellIndex) of row"
          :key="cellIndex"
          :class="{
            'selected': cell === pickedYear,
            'disabled': isDisabled(rowIndex, cellIndex),
            'today': isToday(cell),
          }">
          <span class="mm-year">
            {{ cell }}
          </span>
        </td>
      </tr>
    </tbody>
  </table>
</template>

<script>
import chunk from "lodash/chunk"
import { getClassName } from "../../../utils/helper"
import { today, getCellDateDisabled } from "../../../utils/date"
const COLUMNS = 3

export default {
  name: "mm-year-table",
  props: {
    today: {
      type: Date,
      default() {
        return today()
      },
    },
    month: {
      type: Number,
      validator(value) {
        return value >= 0 && value <= 11
      },
    },
    year: Number,
    onPickYear: Function,
    pickedDate: [Date, String],
    disabledDate: Function,
  },
  computed: {
    years() {
      const startYear = Math.floor(this.year / 10) * 10
      return chunk(Array.from({ length: 10 }).map((_, index) => startYear + index), COLUMNS)
    },
    pickedYear() {
      return this.pickedDate ? this.pickedDate.getFullYear() : 0
    },
  },
  methods: {
    isDisabled(row, cell) {
      const year = this.years[row][cell]
      return getCellDateDisabled({
        mode: "year",
        cellDate: new Date(year, 0, 1),
        disabledDate: this.disabledDate,
      })
    },
    isToday(year) {
      return year === this.today.getFullYear()
    },
    handleClick(e) {
      let { target } = e
      if (target.tagName === "SPAN") {
        target = target.parentNode
      }
      if (target.tagName !== "TD") {
        return
      }
      if (getClassName(target).indexOf("disabled") > -1) {
        return
      }

      const { cellIndex } = target
      const { rowIndex } = target.parentNode
      const year = this.years[rowIndex][cellIndex]

      this.onPickYear && this.onPickYear(year)
    },
  },
}
</script>
