<template>
  <table @click="handleQuarterTableClick" class="el-quarter-table">
    <tbody>
      <tr>
        <td class="available" :class="getCellStyle(1)">
          <a class="cell">Q1</a>
        </td>
        <td class="available" :class="getCellStyle(2)">
          <a class="cell">Q2</a>
        </td>
        <td class="available" :class="getCellStyle(3)">
          <a class="cell">Q3</a>
        </td>
        <td class="available" :class="getCellStyle(4)">
          <a class="cell">Q4</a>
        </td>
      </tr>
    </tbody>
  </table>
</template>

<script type="text/babel">
  import { hasClass } from 'modesign-ui/src/utils/dom';
  import { isDate, range, nextDate, getDayCountOfQuarter } from 'modesign-ui/src/utils/date-util';
  import { arrayFindIndex, coerceTruthyValueToArray } from 'modesign-ui/src/utils/util';

  const datesInQuarter = (year, quarter) => {
    const numOfDays = getDayCountOfQuarter(year, quarter);
    const firstDay = new Date(year, 0, 1);
    return range(numOfDays).map(n => nextDate(firstDay, n));
  };

  export default {
    props: {
      disabledDate: {},
      value: {},
      defaultValue: {
        validator(val) {
          // null or valid Date Object
          return val === null || (val instanceof Date && isDate(val));
        }
      },
      date: {}
    },

    computed: {
      startYear() {
        return Math.floor(this.date.getFullYear() / 10) * 10;
      }
    },

    methods: {
      getCellStyle(quarter) {
        const style = {};
        const year = this.date.getFullYear();

        style.disabled = typeof this.disabledDate === 'function'
          ? datesInQuarter(year, quarter).every(this.disabledDate)
          : false;
        style.current = arrayFindIndex(coerceTruthyValueToArray(this.value), date => this.getQuarter(date) === quarter) >= 0;
        style.today = this.getQuarter(new Date()) === quarter;
        style.default = this.defaultValue && this.getQuarter(this.defaultValue) === quarter;
        return style;
      },

      // 判断是第几季度
      getQuarter(date) {
        return Math.floor((date.getMonth() + 1) / 3) + 1
      },

      handleQuarterTableClick(event) {
        const target = event.target;
        if (target.tagName === 'A') {
          if (hasClass(target.parentNode, 'disabled')) return;
          const quarter = target.textContent || target.innerText;
          this.$emit('pick', String(quarter));
        }
      }
    }
  };
</script>
