<template>
  <div class="el-picker-panel el-date-picker">
    <el-card size="senior" v-show="showDateHeader" shadow="never" :headerBorder="headerBorder">
      <div class="el-calendar-picker-header" slot="header">
        <span class="title">日程</span>
        <span class="today" @click="toNow">今天</span>
      </div>
    </el-card>
    <div class="el-picker-panel__body">
      <div class="el-date-picker__header el-date-picker__header--bordered">
        <button type="button" @click="prevYear" :aria-label="t(`el.datepicker.prevYear`)"
          class="el-picker-panel__icon-btn el-date-picker__prev-btn el-icon-d-arrow-left">
        </button>
        <button type="button" @click="prevMonth" :aria-label="t(`el.datepicker.prevMonth`)"
          class="el-picker-panel__icon-btn el-date-picker__prev-btn el-icon-arrow-left">
        </button>
        <span role="button" class="el-date-picker__header-label">
          {{ yearLabel }} {{ t(`el.datepicker.month${month + 1}`) }}
        </span>
        <button type="button" @click="nextYear" :aria-label="t(`el.datepicker.nextYear`)"
          class="el-picker-panel__icon-btn el-date-picker__next-btn el-icon-d-arrow-right">
        </button>
        <button type="button" @click="nextMonth" :aria-label="t(`el.datepicker.nextMonth`)"
          class="el-picker-panel__icon-btn el-date-picker__next-btn el-icon-arrow-right">
        </button>
      </div>

      <div class="el-picker-panel__content">
        <date-table @pick="handleDatePick" :selection-mode="selectionMode" :first-day-of-week="firstDayOfWeek"
          :events="events" ref="dateTable" :value="value" :default-value="defaultValue ? new Date(defaultValue) : null"
          :date="date">
          <template v-slot:dateCell="{date, data}">
            <slot name="dateCell" v-bind="{date, data}"></slot>
          </template>
        </date-table>
      </div>
    </div>
  </div>
</template>

<script type="text/babel">
import {
  isDate,
  prevYear,
  nextYear,
  prevMonth,
  nextMonth,
  timeWithinRange
} from 'modesign-ui/src/utils/date-util';
import fecha from 'modesign-ui/src/utils/date';
import Locale from 'modesign-ui/src/mixins/locale';
import ElCard from 'modesign-ui/packages/card';
import DateTable from './simple-date-table';

export default {
  mixins: [Locale],

  watch: {
    value(val) {
      if (this.value) return;
      if (isDate(val)) {
        this.date = new Date(val);
      } else {
        this.date = this.getDefaultValue();
      }
    },

    defaultValue(val) {
      if (!isDate(this.value)) {
        this.date = val ? new Date(val) : new Date();
      }
    }
  },

  methods: {
    toNow() {
      this.date = new Date();
      this.value = new Date();
      this.$emit('changeToday', this.date);
    },

    prevMonth() {
      this.date = prevMonth(this.date);
      this.$nextTick(() => {
        this.emitDate();
      });
    },

    nextMonth() {
      this.date = nextMonth(this.date);
      this.$nextTick(() => {
        this.emitDate();
      });
    },

    prevYear() {
      if (this.currentView === 'year') {
        this.date = prevYear(this.date, 10);
      } else {
        this.date = prevYear(this.date);
      }
      this.$nextTick(() => {
        this.emitDate();
      });
    },

    nextYear() {
      if (this.currentView === 'year') {
        this.date = nextYear(this.date, 10);
      } else {
        this.date = nextYear(this.date);
      }
      this.$nextTick(() => {
        this.emitDate();
      });
    },

    emitDate() {
      const rows = this.$refs.dateTable.rows;
      const startDate = rows[0][0].type === 'prev-month' ? new Date(this.date.getFullYear(), this.date.getMonth() - 1, rows[0][0].text) : new Date(this.date.getFullYear(), this.date.getMonth(), 1)
      const endDate = rows[5][6].type === 'next-month' ? new Date(this.date.getFullYear(), this.date.getMonth() + 1, rows[5][6].text) : new Date(this.date.getFullYear(), this.date.getMonth(), rows[5][6].text);
      this.$emit('changeSimpleDate', {
        date: fecha.format(this.date, 'yyyy-MM-dd'),
        year: this.date.getFullYear(),
        month: this.date.getMonth() + 1,
        startDate: fecha.format(startDate, 'yyyy-MM-dd'),
        endDate: fecha.format(endDate, 'yyyy-MM-dd')
      })
    },

    handleDatePick(value) {
      this.value = value;
      this.$emit('changeValue', value);
    },
    getDefaultValue() {
      // if default-value is set, return it
      // otherwise, return now (the moment this method gets called)
      return this.defaultValue ? new Date(this.defaultValue) : new Date();
    },

    checkDateWithinRange(date) {
      return this.selectableRange.length > 0
        ? timeWithinRange(date, this.selectableRange, 'HH:mm:ss')
        : true;
    }
  },

  components: {
    DateTable, ElCard
  },

  data() {
    return {
      date: new Date(),
      value: null,
      defaultValue: null, // use getDefaultValue() for time computation
      selectionMode: 'day',
      currentView: 'date',
      selectableRange: [],
      firstDayOfWeek: 7,
      headerBorder: false
    };
  },

  props: {
    events: Array,
    defaultDate: {},
    defaultPropValue: {},
    showDateHeader: {
      type: Boolean,
      default: false
    }
  },

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

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

    yearLabel() {
      const yearTranslation = this.t('el.datepicker.year');
      if (this.currentView === 'year') {
        const startYear = Math.floor(this.year / 10) * 10;
        if (yearTranslation) {
          return startYear + ' ' + yearTranslation + ' - ' + (startYear + 10) + ' ' + yearTranslation;
        }
        return startYear + ' - ' + (startYear + 10);
      }
      return this.year + ' ' + yearTranslation;
    },

    dateFormat() {
      return 'yyyy-MM-dd';
    }
  },

  created() {
    if (this.defaultDate) {
      if (typeof this.defaultDate) {
        this.date = new Date(this.defaultDate);
      } else {
        this.date = this.defaultDate;
      }
    }
    if (this.defaultPropValue) {
      this.value = this.defaultPropValue;
    }
  },
  mounted() {
    this.emitDate();
  },
};
</script>
