<template>
  <div class="zzx-calendar">
    <div class="calendar-heander" v-if="type === 2">
      {{ timeStr }}
      <!-- <div class="back-today" @click="goback">
				返回今日
			</div> -->
      <div class="arrow arrowOne" @click="arrowEvent(1)">
        <img src="@/static/image/moreIconTwo.png">
      </div>
      <div class="arrow arrowTwo" @click="arrowEvent(2)">
        <img src="@/static/image/moreIconTwo.png">
      </div>
    </div>
    <div :class="type === 2 ? 'zzx-calendar-box' : ''">
      <div class="calendar-weeks">
        <div class="calendar-week" v-for="(week, index) in weeks" :key="index">
          {{ week }}
        </div>
      </div>
      <div class="calendar-content">
        <swiper
          class="calendar-swiper"
          :style="{
            width: '100%',
            height: sheight,
          }"
          :show-indicators="false"
          :indicator-dots="false"
          :duration="duration"
          :current="current"
          @change="changeSwp"
          :circular="true">
          <swiper-item class="calendar-item" v-for="sitem in swiper" :key="sitem">
            <div class="calendar-days">
              <!-- 当月 -->
              <template v-if="sitem === current">
                <div
                  class="calendar-day"
                  v-for="(item, index) in days"
                  :key="index"
                  :class="{
                    'day-hidden': !item.show,
                  }"
                  @click="clickItem(item)">
                  <div
                    class="date"
                    :class="{
                      [item.info?.status ? item.info.status.split(',').map(s => `dateDot${s}`).join(' ') : '']: item.info && item.info.status,
                      [todayClass]: item.isToday,
                      [checkedClass]: item.fullDate === selectedDate,
                      // 'dateDotSunday': item.time.getDay() === 0
                    }">
                    {{ item.isToday ? '今' : item.time.getDate() }}
                  </div>
                  <div
                    class="dot-show"
                    :class="{
                      [[item.info?.status ? item.info.status.split(',').map(s => `dot-show${s}`).join(' ') : '']]: true,
                      'dot-showSunday': item.time.getDay() === 0
                    }"
                    v-if="item.info && item.info.status" />
                </div>
              </template>
              <template v-else>
                <!-- 上月 -->
                <template v-if="current - sitem === 1 || current - sitem === -2">
                  <div
                    class="calendar-day"
                    v-for="(item, index) in predays"
                    :key="index"
                    :class="{
                      'day-hidden': !item.show,
                    }">
                    <div class="date" :class="[item.isToday ? todayClass : '']">
                      {{ item.isToday ? '今' : item.time.getDate() }}
                    </div>
                  </div>
                </template>
                <!-- 下月 -->
                <template v-else>
                  <div
                    class="calendar-day"
                    v-for="(item, index) in nextdays"
                    :key="index"
                    :class="{
                      'day-hidden': !item.show,
                    }">
                    <div class="date" :class="[item.isToday ? todayClass : '']">
                      {{ item.isToday ? '今' : item.time.getDate() }}
                    </div>
                  </div>
                </template>
              </template>
            </div>
          </swiper-item>
        </swiper>
        <div class="mode-change" @click="changeMode">
          <div class="line"/>
          <div class="modeArrow" :class="weekMode ? 'mode-arrow-bottom' : 'mode-arrow-top'">
            <img class="modeArrow-img" src="../../static/image/modeArrowIcon.png" alt="">
          </div>
          <div class="line"/>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { gegerateDates, dateEqual, formatDate } from './generateDates'
// import { Swipe, SwipeItem } from 'vant'
export default {
  props: {
    type: {
      type: Number,
      default: 1
    },
    duration: {
      type: Number,
      default: 500
    },
    dotList: {
      type: Array, // / 打点日期列表
      default() {
        return []
      }
    },
    showBack: {
      type: Boolean, // 是否返回今日
      default: false
    },
    todayClass: {
      type: String, // 今日的自定义样式class
      default: 'is-today'
    },
    checkedClass: {
      type: String, // 选中日期的样式class
      default: 'is-checked'
    },
    dotStyle: {
      type: Object, // 打点日期的自定义样式
      default() {
        return {
          background: '#c6c6c6'
        }
      }
    }
  },
  watch: {
    dotList(val) {
      if (!Array.isArray(val)) return
      const days = this.days.slice(0)
      val.forEach((item) => {
        const index = days.findIndex((ditem) => ditem.fullDate === item.days)
        if (index >= 0) {
          days[index].info = item
        }
      })
      this.days = days
    }
  },
  computed: {
    sheight() {
      // 根据年月判断有多少行
      // 判断该月有多少天
      let h = '4rem'
      if (!this.weekMode) {
        const d = new Date(this.currentYear, this.currentMonth, 0)
        const days = d.getDate() // 判断本月有多少天
        let day = new Date(d.setDate(1)).getDay()
        if (day === 0) {
          day = 7
        }
        const pre = 8 - day
        const rows = Math.ceil((days - pre) / 7) + 1
        h = 4.5 * rows + 'rem'
      }
      return h
    },
    timeStr() {
      let str = ''
      const d = new Date(
        this.currentYear,
        this.currentMonth - 1,
        this.currentDate
      )
      const y = d.getFullYear()
      const m =
        d.getMonth() + 1 <= 9 ? `0${d.getMonth() + 1}` : d.getMonth() + 1
      str = `${y}年${m}月`
      return str
    },
    predays() {
      let pres = []
      if (this.weekMode) {
        const d = new Date(
          this.currentYear,
          this.currentMonth - 1,
          this.currentDate
        )
        d.setDate(d.getDate() - 7)
        pres = gegerateDates(d, 'week')
      } else {
        const d = new Date(this.currentYear, this.currentMonth - 2, 1)
        pres = gegerateDates(d, 'month')
      }
      return pres
    },
    nextdays() {
      let nexts = []
      if (this.weekMode) {
        const d = new Date(
          this.currentYear,
          this.currentMonth - 1,
          this.currentDate
        )
        d.setDate(d.getDate() + 7)
        nexts = gegerateDates(d, 'week')
      } else {
        const d = new Date(this.currentYear, this.currentMonth, 1)
        nexts = gegerateDates(d, 'month')
      }
      return nexts
    }
  },
  data() {
    return {
      weeks: ['一', '二', '三', '四', '五', '六', '日'],
      current: 0,
      currentYear: '',
      currentMonth: '',
      currentDate: '',
      days: [],
      weekMode: false,
      swiper: [0, 1, 2],
      // dotList: [], // 打点的日期列表
      today: new Date(),
      selectedDate: formatDate(new Date(), 'yyyy-MM-dd'),
      isShwo: true,
      calendarType: this.type
    }
  },
  methods: {
    arrowEvent(type) {
      if (type === 1) {
        this.daysPre()
      } else if (type === 2) {
        this.daysNext()
      }
    },
    changeSwp(e) {
      const pre = this.current
      const current = e
      /* 根据前一个减去目前的值我们可以判断是下一个月/周还是上一个月/周
       *current - pre === 1, -2时是下一个月/周
       *current -pre === -1, 2时是上一个月或者上一周
       */
      this.current = current
      if (current - pre === 1 || current - pre === -2) {
        this.daysNext()
      } else {
        this.daysPre()
      }
    },
    // 初始化日历的方法
    initDate(cur) {
      let date = ''
      if (cur) {
        date = new Date(cur)
      } else {
        date = new Date()
      }
      this.currentDate = date.getDate() // 今日日期 几号
      this.currentYear = date.getFullYear() // 当前年份
      this.currentMonth = date.getMonth() + 1 // 当前月份
      this.currentWeek = date.getDay() === 0 ? 7 : date.getDay() // 1...6,0   // 星期几
      const nowY = new Date().getFullYear() // 当前年份
      const nowM = new Date().getMonth() + 1
      const nowD = new Date().getDate() // 今日日期 几号
      const nowW = new Date().getDay()
      // this.selectedDate = formatDate(new Date(), 'yyyy-MM-dd')
      this.days = []

      const showList = []
      let days = []
      if (this.weekMode) {
        days = gegerateDates(date, 'week')
        // this.selectedDate = days[0].fullDate
      } else {
        days = gegerateDates(date, 'month')
        // const sel = new Date(this.selectedDate.replace('-', '/').replace('-', '/'))
        // const isMonth = sel.getFullYear() === this.currentYear && (sel.getMonth() + 1) === this.currentMonth
        const isSameMonth = this.today.getFullYear() === this.currentYear && (this.today.getMonth() + 1) === this.currentMonth
        const getDate = isSameMonth ? this.today.getDate() : 1
        this.selectedDate = formatDate(new Date(this.currentYear, this.currentMonth - 1, getDate), 'yyyy-MM-dd')
      }
      days.forEach((day) => {
        const dot = this.dotList.find((item) => {
          return dateEqual(item.days, day.fullDate)
        })
        if (dot) {
          day.info = dot
        }

        if (day.fullDate === this.selectedDate) {
          showList.push(true)
        } else {
          showList.push(false)
        }
      })
      this.days = days
      //  派发事件,时间发生改变
      let obj = {
        start: '',
        end: ''
      }
      if (this.weekMode) {
        obj.start = this.days[0].time
        obj.end = this.days[6].time
      } else {
        const start = new Date(this.currentYear, this.currentMonth - 1, 1)
        const end = new Date(this.currentYear, this.currentMonth, 0)
        obj.start = start
        obj.end = end
      }

      this.$emit('days-change', {
        ...obj,
        day: this.selectedDate,
        isShwo: showList.includes(true)
      })
    },
    //  上一个
    daysPre() {
      if (this.weekMode) {
        const d = new Date(
          this.currentYear,
          this.currentMonth - 1,
          this.currentDate
        )
        d.setDate(d.getDate() - 7)
        this.initDate(d)
      } else {
        const d = new Date(this.currentYear, this.currentMonth - 2, 1)
        this.initDate(d)
      }
    },
    //  下一个
    daysNext() {
      if (this.weekMode) {
        const d = new Date(
          this.currentYear,
          this.currentMonth - 1,
          this.currentDate
        )
        d.setDate(d.getDate() + 7)
        this.initDate(d)
      } else {
        const d = new Date(this.currentYear, this.currentMonth, 1)
        this.initDate(d)
      }
    },
    changeMode() {
      const premode = this.weekMode
      let isweek = false
      if (premode) {
        isweek = !!this.days.find(
          (item) => item.fullDate === this.selectedDate
        )
      }
      this.weekMode = !this.weekMode
      let d = new Date(
        this.currentYear,
        this.currentMonth - 1,
        this.currentDate
      )
      const sel = new Date(
        this.selectedDate.replace('-', '/').replace('-', '/')
      )
      const isMonth =
        sel.getFullYear() === this.currentYear &&
        sel.getMonth() + 1 === this.currentMonth
      if ((this.selectedDate && isMonth) || isweek) {
        d = new Date(this.selectedDate.replace('-', '/').replace('-', '/'))
      }
      this.initDate(d)
    },
    // 点击日期
    clickItem(e) {
      this.selectedDate = e.fullDate
      this.$emit('selected-change', e)
    },
    goback() {
      const d = formatDate(new Date(), 'yyyy-MM-dd')
      if (this.selectedDate === d) return
      this.selectedDate = d
      this.initDate(d)
      this.$emit('selected-change', { fullDate: d })
    }
  },
  created() {
    this.initDate()
    if (this.calendarType === 2) {
      this.changeMode()
    }
  }
}
</script>

<style lang="less" scoped>
.zzx-calendar {
  position: relative;
  margin: auto;
  width: 100%;
  height: auto;

  .zzx-calendar-box {
    padding: 60rpx 0 40rpx 0;
    border-radius: 80rpx;
    background: rgba(255, 255, 255, 1);
  }

  .calendar-heander {
    text-align: center;
    padding: 64rpx 0 56rpx 0;
    height: 96rpx;
    line-height: 96rpx;
    position: relative;
    font-size: 56rpx;
    font-weight: 500;
    color: rgba(0, 0, 0, 1);

    .arrowOne {
      left: 24rpx;
    }

    .arrowTwo {
      right: 24rpx;
    }

    .back-today {
      position: absolute;
      right: 0;
      width: 200rpx;
      height: 60rpx;
      line-height: 60rpx;
      font-size: 40rpx;
      top: 30rpx;
      border-radius: 30rpx 0 0 30rpx;
      color: #ffffff;
      background-color: #ff6633;
    }
  }

  .calendar-weeks {
    margin-bottom: 40rpx;
    width: 100%;
    display: flex;
    flex-flow: row nowrap;
    height: 20rpx;
    line-height: 20rpx;
    justify-content: center;
    align-items: center;
    font-size: 20rpx;
    color: rgba(37, 37, 37, 0.65);

    .calendar-week {
      width: calc(100% / 7);
      height: 100%;
      text-align: center;
    }
  }

  swiper {
    width: 100%;
    height: 120rpx;
  }

  .calendar-content {
    // min-height: 22.2rem;
  }

  .calendar-swiper {
    // min-height: 22.2rem;
    transition: height ease-out 0.3s;
  }

  .calendar-item {
    margin: 0;
    padding: 0;
    height: 100%;
  }

  .calendar-days {
    display: flex;
    flex-flow: row wrap;
    width: 100%;
    height: 100%;
    overflow: hidden;
    font-size: 24rpx;

    .calendar-day {
      width: calc(100% / 7);
      height: 90rpx;
      text-align: center;
      display: flex;
      flex-flow: column nowrap;
      justify-content: flex-start;
      align-items: center;
    }
  }

  .day-hidden {
    visibility: hidden;
  }

  .mode-change {
    margin-bottom: 32rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .line{
      width: 45%;
      height: 2rpx;
      background: rgba(151, 151, 151, .1);
    }
    .modeArrow{
      position: relative;
      width: 22.44rpx;
      height: 14.22rpx;
      .modeArrow-img{
        position: absolute;
        top: 0;
        left: 0;
        width: 22.44rpx;
        height: 14.22rpx;
      }
    }
  }

  .is-today {
    color: #fff !important;
    border-radius: 50%;
    background: rgba(79, 129, 240, 1) !important;
  }

  .is-checked {
    color: #fff !important;
    background: rgba(79, 129, 240, 1) !important;
    box-shadow: 4rpx 6rpx 26rpx 2rpx rgba(79, 129, 240, 0.35);
  }

  .date {
    width: 48rpx;
    height: 48rpx;
    line-height: 48rpx;
    margin: 0 auto;
    border-radius: 48rpx;
  }

  .dot-show {
    margin-top: 8rpx;
    width: 6rpx;
    height: 6rpx;
    border-radius: 50%;
  }

  .dateDot2,
  .dateDot3,
  .dateDot4,
  .dateDot5,
  .dateDot6,
  .dateDot7,
  .dateDot8,
  .dateDot9,
  .dateDot10,
  .dateDot11,
  .dateDot12,
  .dateDot13,
  .dateDot14,
  .dateDot15,
  .dateDot16,
  .dateDot17,
  .dateDot18,
  .dateDot19,
  .dateDotSunday
   {
    color: #fff;
  }

  .dot-show6,
  .dot-showSunday {
    background: #00b342;
  }

  .dot-show7 {
    background: #ffff00;
  }

  .dot-show5,
  .dot-show19 {
    background: #ffc9a8;
  }
  .dot-show8 {
    background: #c88d00;
  }

  .dot-show8,
  .dot-show9,
  .dot-show10,
  .dot-show11,
  .dot-show12,
  .dot-show13,
  .dot-show14,
  .dot-show15,
  .dot-show16,
  .dot-show17,
  .dot-show18 {
    background: #00b3f6;
  }
  .dot-show2,
  .dot-show3,
  .dot-show4 {
    background: #ff0000;
  }

  .dateDot6,
  .dateDotSunday {
    background: #00b342;
  }

  .dateDot1 {
    color: inherit;
    background: transparent;
  }
  .dateDot7 {
    background: #ffff00;
  }

  .dateDot5,
  .dateDot19 {
    background: #ffc9a8;
  }

  .dateDot8,
  .dateDot9,
  .dateDot10,
  .dateDot11,
  .dateDot12,
  .dateDot13,
  .dateDot14,
  .dateDot15,
  .dateDot16,
  .dateDot17,
  .dateDot18 {
    background: #00b3f6;
  }
  .dateDot2,
  .dateDot3,
  .dateDot4 {
    background: #ff0000;
  }
}
</style>
