<template>
  <table
    cellspacing="0"
    cellpadding="0"
    class="el-date-table"
    @click="handleClick"
    @mousemove="handleMouseMove">
    <tbody>
    <tr>
      <th v-for="(week, key) in WEEKS" :key="key">{{ t('el.datepicker.weeks.' + week) }}</th>
    </tr>
    <tr
      class="el-date-table__row"
      v-for="(row, key) in rows"
      :key="key">
      <td
        v-for="(cell, index) in row"
        :class="getCellClasses(cell)"
        :key="index">
        <div>
          <span>
            {{ cell.text }}
          </span>
        </div>
        <div class="custom-event">
          <slot name="dateCell" v-bind="getSlotData(cell)"></slot>
          <template v-if="!elCalendar.$scopedSlots.dateCell && eventDay(cell)">
            <el-tooltip>
              <div v-html="getToolTipContent(cell.events)" slot="content"></div>
              <div class="event-wrap">
                <div v-for="(event, i) in cell.eventsList" :key="i + event" class="eventTooltip"></div>
              </div>
            </el-tooltip>
          </template>
        </div>
      </td>
    </tr>
    </tbody>
  </table>
</template>

<script>
  import ElTooltip from 'modesign-ui/packages/tooltip';
  import { getFirstDayOfMonth, formatDate, getDayCountOfMonth, getStartDateOfMonth, nextDate, isDate, clearTime as _clearTime} from 'modesign-ui/src/utils/date-util';
  import Locale from 'modesign-ui/src/mixins/locale';

  const WEEKS = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];
  const getDateTimestamp = function(time) {
    if (typeof time === 'number' || typeof time === 'string') {
      return _clearTime(new Date(time)).getTime();
    } else if (time instanceof Date) {
      return _clearTime(time).getTime();
    } else {
      return NaN;
    }
  };

  export default {
    mixins: [Locale],

    inject: ['elCalendar'],
    
    components: { ElTooltip },

    props: {
      firstDayOfWeek: {
        default: 7,
        type: Number,
        validator: val => val >= 1 && val <= 7
      },

      value: {},

      defaultValue: {
        validator(val) {
          // either: null, valid Date object, Array of valid Date objects
          return val === null || isDate(val) || (Array.isArray(val) && val.every(isDate));
        }
      },

      date: {},

      disabledDate: {},
  
      cellClassName: {},

      minDate: {},

      maxDate: {},

      rangeState: {
        default() {
          return {
            endDate: null,
            selecting: false
          };
        }
      },

      events: {
        type: Array,
        default: () => {
          return []
        }
      }
    },

    computed: {
      offsetDay() {
        const week = this.firstDayOfWeek;
        // 周日为界限，左右偏移的天数，3217654 例如周一就是 -1，目的是调整前两行日期的位置
        return week > 3 ? 7 - week : -week;
      },

      WEEKS() {
        const week = this.firstDayOfWeek;
        return WEEKS.concat(WEEKS).slice(week, week + 7);
      },

      year() {
        return this.date.getFullYear();
      },

      month() {
        return this.date.getMonth();
      },

      startDate() {
        return getStartDateOfMonth(this.year, this.month);
      },

      rows() {
        // TODO: refactory rows / getCellClasses
        const date = new Date(this.year, this.month, 1);
        let day = getFirstDayOfMonth(date); // day of first day
        const dateCountOfMonth = getDayCountOfMonth(date.getFullYear(), date.getMonth());
        const dateCountOfLastMonth = getDayCountOfMonth(date.getFullYear(), (date.getMonth() === 0 ? 11 : date.getMonth() - 1));

        day = (day === 0 ? 7 : day);

        const offset = this.offsetDay;
        const rows = this.tableRows;
        let count = 1;

        const startDate = this.startDate;
        const disabledDate = this.disabledDate;
        const cellClassName = this.cellClassName;
        const now = getDateTimestamp(new Date());

        for (let i = 0; i < 6; i++) {
          const row = rows[i];

          for (let j = 0; j < 7; j++) {
            let cell = row[j];
            if (!cell) {
              cell = { row: i, column: j, type: 'normal', inRange: false, start: false, end: false };
            }

            cell.type = 'normal';

            const index = i * 7 + j;
            const time = nextDate(startDate, index - offset).getTime();
            cell.inRange = time >= getDateTimestamp(this.minDate) && time <= getDateTimestamp(this.maxDate);
            cell.start = this.minDate && time === getDateTimestamp(this.minDate);
            cell.end = this.maxDate && time === getDateTimestamp(this.maxDate);
            const isToday = time === now;

            if (isToday) {
              cell.type = 'today';
            }

            if (i >= 0 && i <= 1) {
              const numberOfDaysFromPreviousMonth = day + offset < 0 ? 7 + day + offset : day + offset;

              if (j + i * 7 >= numberOfDaysFromPreviousMonth) {
                cell.text = count++;
              } else {
                cell.text = dateCountOfLastMonth - (numberOfDaysFromPreviousMonth - j % 7) + 1 + i * 7;
                cell.type = 'prev-month';
              }
            } else {
              if (count <= dateCountOfMonth) {
                cell.text = count++;
              } else {
                cell.text = count++ - dateCountOfMonth;
                cell.type = 'next-month';
              }
            }

            let cellDate = new Date(time);
            cell.disabled = typeof disabledDate === 'function' && disabledDate(cellDate);
            cell.customClass = typeof cellClassName === 'function' && cellClassName(cellDate);
            this.$set(row, j, cell);
          }
        }
        return rows;
      }
    },

    watch: {
      'rangeState.endDate'(newVal) {
        this.markRange(this.minDate, newVal);
      },

      minDate(newVal, oldVal) {
        if (getDateTimestamp(newVal) !== getDateTimestamp(oldVal)) {
          this.markRange(this.minDate, this.maxDate);
        }
      },

      maxDate(newVal, oldVal) {
        if (getDateTimestamp(newVal) !== getDateTimestamp(oldVal)) {
          this.markRange(this.minDate, this.maxDate);
        }
      }
    },

    data() {
      return {
        tableRows: [ [], [], [], [], [], [] ],
        lastRow: null,
        lastColumn: null,
        formatDate
      };
    },

    methods: {
      getToolTipContent(events) {
        return events.join('<br/>');
      },

      getSlotData(cell) {
        const date = this.getDateOfCell(cell.row, cell.column);
        const data = {
          isSelected: this.cellMatchesDate(cell, this.value),
          type: cell.type,
          day: formatDate(date)
        }
        return {
          date, data
        }
      },

      eventDay(cell) {
        let result = null;
        const date = this.getDateOfCell(cell.row, cell.column);
        if (this.events && this.events.length > 0) {
          result = this.events.find(x => x.date === formatDate(date))
          if (result) {
            cell.events = result.content;
            if (result.content.length > 3) {
              cell.eventsList = result.content.slice(0, 2);
              cell.eventsList.push(`剩余${result.content.length - 2}个日程`);
            } else {
              cell.eventsList = result.content;
            }
          }
        }
        return result;
      },
      cellMatchesDate(cell, date) {
        const value = new Date(date);
        return this.year === value.getFullYear() &&
          this.month === value.getMonth() &&
          Number(cell.text) === value.getDate();
      },

      getCellClasses(cell) {
        const defaultValue = this.defaultValue ? Array.isArray(this.defaultValue) ? this.defaultValue : [this.defaultValue] : [];

        let classes = [];
        if ((cell.type === 'normal' || cell.type === 'today') && !cell.disabled) {
          classes.push('available');
          if (cell.type === 'today') {
            classes.push('today');
          }
        } else {
          classes.push(cell.type);
        }

        if (cell.type === 'normal' && defaultValue.some(date => this.cellMatchesDate(cell, date))) {
          classes.push('default');
        }

        if ((cell.type === 'normal' || cell.type === 'today') && this.cellMatchesDate(cell, this.value)) {
          classes.push('current');
        }

        if (cell.inRange && (cell.type === 'normal' || cell.type === 'today')) {
          classes.push('in-range');

          if (cell.start) {
            classes.push('start-date');
          }

          if (cell.end) {
            classes.push('end-date');
          }
        }

        if (cell.disabled) {
          classes.push('disabled');
        }

        if (cell.customClass) {
          classes.push(cell.customClass);
        }

        return classes.join(' ');
      },

      getDateOfCell(row, column) {
        const offsetFromStart = row * 7 + column - this.offsetDay;
        return nextDate(this.startDate, offsetFromStart);
      },

      markRange(minDate, maxDate) {
        minDate = getDateTimestamp(minDate);
        maxDate = getDateTimestamp(maxDate) || minDate;
        [minDate, maxDate] = [Math.min(minDate, maxDate), Math.max(minDate, maxDate)];

        const startDate = this.startDate;
        const rows = this.rows;
        for (let i = 0, k = rows.length; i < k; i++) {
          const row = rows[i];
          for (let j = 0, l = row.length; j < l; j++) {
            const cell = row[j];
            const index = i * 7 + j;
            const time = nextDate(startDate, index - this.offsetDay).getTime();

            cell.inRange = minDate && time >= minDate && time <= maxDate;
            cell.start = minDate && time === minDate;
            cell.end = maxDate && time === maxDate;
          }
        }
      },

      handleMouseMove(event) {
        if (!this.rangeState.selecting) return;

        let target = event.target;
        if (target.tagName === 'SPAN') {
          target = target.parentNode.parentNode;
        }
        if (target.tagName === 'DIV') {
          target = target.parentNode;
        }
        if (target.tagName !== 'TD') return;

        const row = target.parentNode.rowIndex - 1;
        const column = target.cellIndex;

        // can not select disabled date
        if (this.rows[row][column].disabled) return;

        // only update rangeState when mouse moves to a new cell
        // this avoids frequent Date object creation and improves performance
        if (row !== this.lastRow || column !== this.lastColumn) {
          this.lastRow = row;
          this.lastColumn = column;
        }
      },

      handleClick(event) {
        let target = event.target;
        if (target.tagName === 'SPAN') {
          target = target.parentNode.parentNode;
        }
        if (target.tagName === 'DIV') {
          target = target.parentNode;
        }

        if (target.tagName !== 'TD') return;

        const row = target.parentNode.rowIndex - 1;
        const column = target.cellIndex;
        const cell = this.rows[row][column];

        if (cell.disabled || cell.type === 'week') return;

        const newDate = this.getDateOfCell(row, column);
        this.$emit('pick', newDate);
      }
    }
  };
</script>
