<template>
  <table class="mm-month-table">
    <tbody @click="handleClick">
      <tr
        v-for="(row, rowIndex) of months"
        :key="rowIndex">
        <td
          v-for="(cell, cellIndex) of row"
          :key="cellIndex"
          :class="{
            'selected': isCurrent && (rowIndex * 3 + cellIndex) === pickedMonth,
            'disabled': isDisabled(rowIndex, cellIndex),
            'today': isToday(rowIndex, cellIndex),
          }">
          <span class="mm-month">
            {{ cell }}
          </span>
        </td>
      </tr>
    </tbody>
  </table>
</template>

<script>
import locale from "../../../mixins/locale"
import chunk from "lodash/chunk"
import { getClassName } from "../../../utils/helper"
import { today, getCellDateDisabled } from "../../../utils/date"

const COLUMNS = 3

export default {
  name: "mm-month-table",
  mixins: [locale],
  props: {
    today: {
      type: Date,
      default() {
        return today()
      },
    },
    year: Number,
    onPickMonth: Function,
    pickedDate: [Date, String],
    disabledDate: Function,
  },
  data() {
    return {
      months: chunk(
        Array.from({ length: 12 }).map((m, index) => this.t(`ui.datepicker.months[${[index]}]`)),
        COLUMNS
      ),
    }
  },
  computed: {
    isCurrent() {
      return this.pickedDate && this.pickedDate.getFullYear() === this.year
    },
    pickedMonth() {
      return this.pickedDate ? this.pickedDate.getMonth() : -1
    },
  },
  methods: {
    isDisabled(row, cell) {
      const month = row * COLUMNS + cell
      return getCellDateDisabled({
        mode: "month",
        cellDate: new Date(this.year, month, 1),
        disabledDate: this.disabledDate,
      })
    },
    isToday(row, cell) {
      const month = row * COLUMNS + cell
      return this.year === this.today.getFullYear() && month === this.today.getMonth()
    },
    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 month = rowIndex * COLUMNS + cellIndex

      this.onPickMonth && this.onPickMonth(month)
    },
  },
}
</script>
