<template>
  <div class="calendar">
    <div class="now-mouth"><i class="el-icon-timer"></i>{{ displayDate }}</div>
    <div class="calendar_sd">
      <div class="calendar-title">
        <div class="calendar-select weeks">
          <div v-for="(week,index) in weekName " :key="index" class="calendar-select-row">
            <input
              :id="'calendarSet_calendar_week_input_'+genID()"
              :ref="'week_'+index"
              class="checkbox"
              type="checkbox"
              :name="week"
              @change="checked('week',index)"
            >
          </div>
          <div class="calendar-select-row"/>
        </div>
        <div class="calendar-select weeks">
          <div v-for="(week, index) in weekName" :key="index" class="calendar-select-row">
            <div class="week"> {{ week }}</div>
          </div>
          <div class="calendar-select-row">
            <input :id="'calendarSet_calendar_week_input_'+genID()" ref="checkAll" class="checkbox" type="checkbox"
                   @change="checkAll">
          </div>
        </div>
      </div>
      <div class="calendar-body">
        <div v-for="(week, weeKIndex) in calendarDay" :key="weeKIndex">
          <div class="calendar-select">
            <div
              v-for="(day, dayIndex) in week"
              :key="dayIndex"
              class="calendar-select-row"
              :class="{isSelected: day.select}"
              @click="selectDay(day)"
            >
              <div v-show="day.day" class="day">
                <span class="t1">{{ day.day }}</span>
                <span class="t2">
                  <template v-if="!!day.lunarDay">
                    {{
                      day.lunarDay.lunarFestival
                        ? day.lunarDay.lunarFestival
                        : day.lunarDay.festival
                          ? day.lunarDay.festival
                          : day.lunarDay.IDayCn == "初一"
                            ? day.lunarDay.IMonthCn
                            : day.lunarDay.IDayCn
                    }}
                  </template>
                </span>
              </div>
            </div>
            <div class="calendar-select-row">
              <input
                v-show="week[0].day || week[6].day"
                :id="'calendarSet_calendar_week_input_'+genID()"
                :ref="'row_'+weeKIndex"
                class="checkbox"
                type="checkbox"
                @change="checked('row',weeKIndex)"
              >
            </div>
          </div>
        </div>
      </div>
    </div>

  </div>
</template>

<script>
/**
 *  Canlendar Module
 * ----------------------
 * Author:zoboy
 * Date: 2019.06.12
 */

import moment from 'moment'
import calendar from "../date";

export default {
  name: 'Canlendar',
  components: {},
  props: {
    mouth: {
      type: String,
      required: true
    },
    calendarOptiondDay: {
      type: Array,
      required: true
    }
  },
  data() {
    return {
      displayDate: '',
      nowDay: '',
      calendarDay: [],
      checkedDay: [],
      uncheckedDay: [],
      weekName: ['日', '一', '二', '三', '四', '五', '六']
    }
  },
  computed: {},
  watch: {
    mouth(newMouth) {
      this.createCalendar(newMouth)
    },
    calendarOptiondDay(val) {
      if (val) {
        this.createCalendar(this.mouth)
      }
    },
    calendarDay: {
      handler(canlendar) {
        this.checkedDay = []
        this.uncheckedDay = []
        let row = new Set()
        let column = new Set()
        canlendar.forEach(week => {
          week.forEach(day => {
            if (day && day.day) {
              if (day.select) {
                this.checkedDay.push(day)
              } else {
                this.uncheckedDay.push(day)
                row.add(day.week)
                column.add(day.row)
              }
            }
          })
        })
        let week = [0, 1, 2, 3, 4, 5, 6]
        week.forEach(r => {
          let weekRef = 'week_' + r
          let rowRef = 'row_' + r
          if (this.$refs[weekRef])
            if (row.has(r)) this.$refs[weekRef][0].checked = false
            else this.$refs[weekRef][0].checked = true
          if (this.$refs[rowRef])
            if (column.has(r)) this.$refs[rowRef][0].checked = false
            else this.$refs[rowRef][0].checked = true
        })
        // console.log(row,column)
        if (row && row.size > 0 && column && column.size > 0) {
          this.$refs.checkAll.checked = false
          this.$emit('checkedAll', {'mouth': this.mouth, 'checkedAll': false})
        } else {
          this.$refs.checkAll.checked = true
          this.$emit('checkedAll', {'mouth': this.mouth, 'checkedAll': true})
        }
        this.$emit('checkedDate', {
          'mouth': this.mouth,
          'checkedDay': this.checkedDay,
          'uncheckedDay': this.uncheckedDay
        })
        // console.log(this.checkedDay)
      },
      deep: true
    }
  },
  created() {
    this.createCalendar(this.mouth)
  },
  methods: {
    selectDay(day) {
      if (day && day.day) this.$emit('selectDay', day)
    },
    checked(target, index) {
      const checkRef = target + '_' + index
      const check = this.$refs[checkRef][0].checked
      this.calendarDay.forEach(week => {
        week.forEach(day => {
          if (day && day.day && day[target] === index) day.select = check
        })
      })
    },
    checkWork(isOnWork, select) {
      this.calendarDay.forEach(week => {
        week.forEach(day => {
          if (day && day.day) {
            if (isOnWork && (day.week > 0 && day.week < 6)) {
              day.select = select
            } else if (!isOnWork && (day.week === 0 || day.week === 6)) {
              day.select = select
            }
          }
        })
      })
    },
    checkWeekend(flag, select) {
      this.calendarDay.forEach(week => {
        week.forEach(day => {
          if (day && day.day) {
            if (flag == 1) {
              //奇数日周六
              if (day.day % 2 !== 0 && day.week == 6) {
                day.select = select
              }
            } else if (flag == 2) {
              //偶数日周六
              if (day.day % 2 === 0 && day.week == 6) {
                day.select = select
              }
            } else if (flag == 3) {
              //周日
              if (day.week == 0) {
                day.select = select
              }
            }
          }
        })
      })
    },


    checkAll() {
      const check = this.$refs.checkAll.checked
      this.calendarDay.forEach(week => {
        week.forEach(day => {
          if (day && day.day) day.select = check
        })
      })
    },
    createCalendar(mouth) {
      if (mouth) this.nowDay = moment(mouth).format('YYYY-MM')
      else this.nowDay = moment().format('YYYY-MM')
      this.displayDate = moment(this.nowDay).format('YYYY年MM月')
      this.calendarDay = this.getCurrMonthDays(this.nowDay)
    },
    getCurrMonthDays(theDay) {
      // 获取当前月的第一天
      const start = moment(theDay).add('month', 0).format('YYYY-MM') + '-01'
      // 获取上一个月的总天数
      const lastMonthDays = moment(this.date).subtract(1, 'month').daysInMonth()
      // 构造日历的42个格子
      const daysArr = [[], [], [], [], [], []]
      // 获取当前月的第一天是星期几
      const currentWeekday = moment(start).format('E')
      // 获取当前月的总天数
      const nowMouthDays = moment(theDay).daysInMonth()
      for (let i = 0; i < 7; i++) { // 每一周
        // 虚拟天数
        let virtualDay
        if (currentWeekday - 7 === 0) virtualDay = (lastMonthDays - currentWeekday) + i + 8
        else virtualDay = (lastMonthDays - currentWeekday) + i + 1
        for (let j = 0; j < daysArr.length; j++) { // 每一天
          daysArr[j][i] = this.getDay(i, j, start, virtualDay + (j * 7), lastMonthDays, nowMouthDays) // 每一行*7
        }
      }
      return daysArr
    },
    getDay(week, row, start, day, lastMonthDays, nowMouthDays, index) {
      let dayObj = {}
      if (day <= lastMonthDays) { // 上一月
        // return day
        dayObj = {'day': ''}
      } else if (day <= (lastMonthDays + nowMouthDays)) {


        const dayNum = day - lastMonthDays
        let dateObj = moment(start).add(dayNum - 1, 'days');
        const date = dateObj.format('YYYY-MM-DD')
        let date2 = dateObj.toDate();
        let lunarDay = calendar.solar2lunar(date2.getFullYear(), (date2.getMonth() + 1), date2.getDate());
        dayObj = {
          day: dayNum,
          date: date,
          week: week,
          row: row,
          lunarDay: lunarDay,
          isToday: new Date(date).getTime() === new Date(moment().format('YYYY-MM-DD')).getTime(),
          select: !!this.calendarOptiondDay.find((day) => day.date === date)
        }
      } else { // 下一月
        // return day - (lastMonthDays + nowMouthDays)
        dayObj = {'day': ''}
      }
      return dayObj
    },
    genID() {
      return Number(Math.random().toString().substr(3, 4) + Date.now()).toString(36)
    }
  }
}
</script>

<style lang="scss" scoped>
.calendar {
  margin: 10px 17px;
  //width: 264px;
  // height: 224px;
  display: flex;
  flex-direction: column;
  margin-bottom: 15px;
  margin-right: 15px;

  .calendar_sd {
    //width: 264px;
    // border-top: 1px solid #ddd;
    // border-left: 1px solid #ddd;
  }

  .now-mouth {
    margin-bottom: 4px;
    font-weight: 549;

    > i {
      margin-right: 4px;
    }
  }

  .calendar-title {
    .calendar-week {
      min-width: 35px;
    }
  }

  .calendar-select {
    display: flex;
    flex-direction: row;

    &.weeks {
      .calendar-select-row {
        min-height: 36px;
        line-height: 28px;
      }
    }

    .calendar-select-row {
      min-width: 46px;
      min-height: 48px;
      border: 1px solid #ddd;
      margin-left: -1px;
      margin-top: -1px;
      position: relative;
      text-align: center;
      line-height: 40px;
      // &:last-child {
      //   border-right: none;
      // }
      .checkbox {
        line-height: 34px;
        text-align: center;
        background-color: #ddd;
        display: inline-block;
      }

      .week {
        line-height: 34px;
        text-align: center;
        background-color: #f3f3f3;
      }

    }
  }

  .calendar-body {
    .day {
      line-height: 17px;
      text-align: center;
      cursor: pointer;
      padding: 8px 0px 5px;

      span {
        display: block;

        &.t2 {
          font-size: 12px;
          zoom: 0.8;
          opacity: 0.6;
        }
      }
    }

    .isSelected {
      background-color: #22507617;
      color: #225076;

      &:before {
        content: "休";
        display: inline-block;
        position: absolute;
        right: -1px;
        top: 0;
        font-size: 12px;
        zoom: 0.85;
        background: #DB835D;
        padding: 0 2px 0 3px;
        color: #FFF;
        border-radius: 0 0 0 12px;
        line-height: 17px;
      }
    }
  }
}
</style>
