<template>
  <div class="sfc-wrapper">
    <table class="sfc-table sfc-table-head">
      <caption class="clearfix">
        <div class="sfc-div sfc-plan" style="position: relative">
          <el-button type="success">选择月份 <i class="el-icon-date"></i></el-button>
          <el-date-picker
            v-model="monthText"
            type="month"
            :editable=false
            style="opacity: 0;position: absolute;left: 0;z-index: 9; cursor: pointer"
            @change="monthChange"
            placeholder="选择月份">
          </el-date-picker>
        </div>
        <div class="sfc-div sfc-flx">
          <div class="form-group">
            <div class="input-group clearflx">
              <button class="btn btn-link sfc-div" @click="changeMonth('prev')">
                <i class="el-icon-caret-left"></i>
              </button>
              <div class="text-center sfc-div">
                <h1>{{ monthText }}</h1>
              </div>
              <button class="btn btn-link sfc-div" @click="changeMonth('next')">
                <i class="el-icon-caret-right"></i>
              </button>
            </div>
          </div>
        </div>
        <div class="sfc-div sfc-plan">
          <button class="btn btn-primary" @click="backClk">
            <i class="fa fa-mail-reply"> 返回当前月</i>
          </button>
        </div>
      </caption>
      <thead>
        <tr>
          <td v-for="weekday in weekdays">{{ weekday }}</td>
        </tr>
      </thead>
    </table>
    <template v-for="week in weekArr">
      <weekline :month-moment="monthMoment" :week="week" :events="tidyEvents" :highlight-time-range="selectedTimeRangeResult" @select="onSelect"></weekline>
    </template>
  </div>
</template>

<script>
import weekline from './components/weekline'
import moment from 'moment'
import { getDurationsDays, getTime } from './util.js'
export default {
  components: {
    weekline
  },
  props: {
    formatter: {
      type: String,
      default: 'YYYY-MM-DD'
    },
    events: {
      type: Array,
      default: []
    }
  },
  data () {
    return {
      monthMoment: null,
      weekdays: ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日'],
      weekArr: [],
      monthText: '',
      selectedTimeRange: {
        start: null,
        between: null,
        end: null
      }
    }
  },
  computed: {
    tidyEvents () {
      let events = this.events.map((eventItem, index) => {
        let s = moment(eventItem.start, this.formatter)
        let e = moment(eventItem.end, this.formatter)
        return Object.assign({}, eventItem, {
          startMoment: s,
          endMoment: e,
          startDate: s.date(),
          startWeekday: s.isoWeekday(),
          durationDays: getDurationsDays(s.format('YYYY-MM-DD'), e.format('YYYY-MM-DD')),
          startTime: getTime(s.format('YYYY-MM-DD'))
        })
      })
      events.sort(function (a, b) {
        return a.startTime - b.startTime
      })
      return events
    },
    selectedTimeRangeResult () {
      let timeRange = this.selectedTimeRange
      let start = timeRange.start
      let end = timeRange.end || timeRange.between
      if (start && end) {
        return start > end ? [end, start] : [start, end]
      } else return []
    }
  },
  beforeMount () {
    this.monthMoment = moment()
    console.log(this.monthMoment)
    this.setMonthInfo()
  },
  methods: {
    monthChange (val) {
      this.monthMoment = moment()
      let str = new Date(val)
      this.monthMoment._d = str
      this.setMonthInfo()
    },
    backClk () {
      this.changeMonth('reset')
    },
    getMonthInfo () {
      // if (!month) return []
      let monthMoment = this.monthMoment
      let dayCount = monthMoment.clone().endOf('month').date()
      var dayArr = []
      for (let i = 0; i < dayCount; i++) {
        let date = i + 1
        let dayMoment = monthMoment.clone().date(date)
        let weekday = dayMoment.isoWeekday()
        dayArr.push({
          month: dayMoment.month(),
          date,
          weekday,
          moment: dayMoment
        })
      }
      // fill date to complete weeks
      let d = dayArr[0].weekday
      while (--d) {
        let dayMoment = monthMoment.clone().startOf('month').isoWeekday(d)
        dayArr.unshift({
          month: dayMoment.month(),
          date: dayMoment.date(),
          weekday: d,
          moment: dayMoment
        })
      }

      d = dayArr[dayArr.length - 1].weekday
      while (++d <= 7) {
        let dayMoment = monthMoment.clone().endOf('month').isoWeekday(d)
        dayArr.push({
          month: dayMoment.month(),
          date: dayMoment.date(),
          weekday: d,
          moment: dayMoment
        })
      }

      // splice into weeks
      let weekArr = []
      while (dayArr.length >= 7) {
        weekArr.push(dayArr.splice(0, 7))
      }

      return weekArr
    },
    changeMonth (direction) {
      switch (direction) {
        case 'prev':
          this.monthMoment.add(-1, 'month')
          break
        case 'next':
          this.monthMoment.add(1, 'month')
          break
        case 'reset':
          this.monthMoment = moment()
          break
        default:
      }
      this.setMonthInfo()
    },
    setMonthInfo () {
      this.weekArr = this.getMonthInfo()
      this.monthText = this.monthMoment.format('YYYY-MM')
    },
    onSelect (point, e) {
      let el = e.target
      let timeRange = this.selectedTimeRange
      switch (point) {
        case 'start':
          timeRange.start = el.getAttribute('data-date')
          timeRange.between = null
          timeRange.end = null
          break
        case 'between':
          if (timeRange.start) {
            timeRange.between = el.getAttribute('data-date')
          }
          break
        case 'end':
          if (timeRange.start) {
            timeRange.end = el.getAttribute('data-date')
            this.addEvent(point === 'end')
          }
          break
        default:
      }
    },
    addEvent (isSelected) {
      if (!isSelected) return
      let [start, end] = this.selectedTimeRangeResult
      this.$emit('timeRangeSelected', {
        start,
        end
      })

      let timeRange = this.selectedTimeRange
      timeRange.start = null
      timeRange.between = null
      timeRange.end = null
    }
  }
}
</script>

<style scoped rel="stylesheet/scss" lang="scss">
  .el-date-editor.el-input {
    width: 100%;
  }
  .el-date-editor.el-input__inner {
    -webkit-appearance: none;
    -moz-appearance: none;
    appearance: none;
    background-color: #fff;
    background-image: none;
    /* border-radius: 4px; */
    border: 1px solid #bfcbd9;
    box-sizing: border-box;
    color: #1f2d3d;
    font-size: inherit;
    height: 36px;
    line-height: 1;
    outline: 0;
    padding: 3px 10px;
    transition: border-color .2s cubic-bezier(.645,.045,.355,1);
  }
  .sfc-wrapper{
    max-width: 1200px;
    width: 100%;
    margin: auto;
    .sfc-table-wrapper {
      position: relative;
      margin-top: -1px;
      .sfc-events-table {
        position: absolute;
        top: 0;
        left: 0;
        pointer-events: none;
      }
    }
    .sfc-table-head{
      width: 100%;
      text-align: center;
      td {
        border: 1px solid #CCC;
        background-color: #FFF;
        height: 40px;
        color: #000;
      }
    }
  }
  .form-group {
    margin: auto;
    width: 30%;
    align-content: center;
  }
  .sfc-div {
    float: left;
  }
  .sfc-flx{
    width: calc(100% - 240px);
  }
  .sfc-plan {
    width: 120px;
  }
</style>
