<template>
  <div class="month-range-class">
    <Poptip placement="bottom-start" style="width:100%" v-model="visible" @on-popper-show="popperShowEvent" transfer>
      <Input v-model="monthStart" prefix="ios-calendar-outline" readonly placeholder="请选择星期"
             style="width: 200px;" clearable @on-clear="$emit('time', {start:null, end: null})"/>
      <div class="monthPanpel" slot="content">
        <div class="monthPanpel-left">
          <div style="width:100%;display:flex;align-items:center;">
            <span>
              <Icon type="ios-arrow-dropleft" size="20" @click="handleYearBefore('left')" style="cursor:pointer" />
            </span>
            <div style="text-align:center;width: 100%;font-size: 16px;">
              {{ `${yearLast}年` }}{{ `${myMonthTwo}月` }}
            </div>
            <span>
							<Icon type="ios-arrow-dropright" size="20" @click="handleYearBefore('right')"
								style="cursor:pointer" />
						</span>
          </div>
          <div v-for="(item, index) in lastMonthList" class="monthPanpel-left-cell" :key="index"
               @click="handleMonthLeftClick('left', index)"
               :style="{ background: currentBgNum1.indexOf(index) >= 0 ? '#2d8cf0' : '', color: currentBgNum1.indexOf(index) >= 0 ? '#FFF' : '' }">
            <Tooltip :content="item.start + '~' + item.end ">
              <span>{{ item.label }}</span>
            </Tooltip>
          </div>
        </div>
<!--        <div class="monthPanpel-right">-->
<!--          <div style="width:100%;display:flex;align-items:center;">-->
<!--            <div style="text-align:center;width: 100%;font-size: 16px;">-->
<!--              {{ `${yearStart}年` }}{{ `${myMonthOne}月` }}-->
<!--            </div>-->
<!--            <span>-->
<!--              <Icon type="ios-arrow-dropright" size="20" @click="handleYearBefore('right')" style="cursor:pointer" />-->
<!--            </span>-->
<!--          </div>-->
<!--          <div v-for="(item, index) in nowMonthList" class="monthPanpel-right-cell" :key="index"-->
<!--               @click="handleMonthLeftClick('right', index)"-->
<!--               :style="{ background: currentBgNum2.indexOf(index) >= 0 ? '#2d8cf0' : '', color: currentBgNum2.indexOf(index) >= 0 ? '#FFF' : '' }">-->
<!--            <Tooltip :content="item.start + '~' + item.end ">-->
<!--              <span>{{ item.label }}</span>-->
<!--            </Tooltip>-->
<!--          </div>-->
<!--        </div>-->
      </div>
    </Poptip>
  </div>
</template>
<script>
export default {
  props: {
    init: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      rightYearShow: true,
      visible: false,
      currentBgNum1: [],
      currentBgNum2: [],
      clickNum: 0,
      yearStart: "",
      myMonthOne: "",
      // yearEnd: new Date().getFullYear() + 1,
      myMonthTwo: "",
      yearLast: "",
      monthStart: "",
      startT: [],
      lastMonthList: [],
      nowMonthList: [],
      timer: null,
      nowWeek: '',
      nowDate: '',
      nowTime: ''
    };
  },
  created() {
    // let date = new Date();
    // date = new Date(date.getTime() - 3600 * 1000 * 24 * 30);

    let dateTwo = new Date();
    let lastdate = dateTwo.setTime(dateTwo.getTime() + 3600 * 1000 * 24 * 30);
    this.first(lastdate)
  },
  mounted() {
    if (this.init) {
      this.reset2()
    }
  },
  methods: {
    reset() {
      this.startShow = []
      this.startT = [];
      let weeks = ['一', '二', '三', '四', '五']
      let data = new Date();
      let nowMonthFirstWeek = this.setNowTimes(data)
      let setNowTimes = this.setNowTimes(nowMonthFirstWeek)
      let week = this.getWeek(data)
      if (setNowTimes !== 1) {
        week = week - 2
      }
      if (week - 3 < 0) {
        let num = (this.lastMonthList.length + week - 3)
        this.startT.push({
          start: this.lastMonthList[num].start,
          end: this.lastMonthList[num].end
        });
        this.startShow.push(`${this.yearLast}-${this.myMonthTwo}:${this.lastMonthList[week].label} `)

      } else {
        let num = week - 3
        this.startT.push({
          start: this.nowMonthList[num].start,
          end: this.nowMonthList[num].end
        });
        this.startShow.push(`${this.yearStart}-${this.myMonthOne}:${this.nowMonthList[num].label} `)
      }
      this.startT.push({
        start: this.nowMonthList[week].start,
        end: this.nowMonthList[week].end
      });
      this.startShow.push(`${this.yearStart}-${this.myMonthOne}:${this.nowMonthList[week].label} `)

      // this.startT.push({
      //   start: new Date((this.nowMonthList[week].start).getTime()  - 3600 * 1000 * 24 * 28),
      //   end:  new Date((this.nowMonthList[week].end).getTime()  - 3600 * 1000 * 24 * 28),
      // });
      this.monthStart = this.startShow.join("~");
      this.$emit("time", this.startT)
    },
    reset2() {
      this.startT.push({start: this.getThisMonday(1), end: this.getThisMonday(7)})
      this.monthStart = this.startT[0].start + " ~ " + this.startT[0].end;
      this.$emit("time", this.startT[0])
    },
    getThisMonday(xingQi) {
      let date = new Date(); // 获取当前日期和时间
      let day = date.getDay(); // 获取今天是星期几
      let monday = new Date(date.setDate(date.getDate() - day + xingQi)); // 设置日期为本周一
      return monday.format('yyyy-MM-dd')
    },
    first(val) {
      let date = new Date(val);
      this.yearStart = date.getFullYear()
      this.myMonthOne = date.getMonth() + 1
      let dataa = this.getDate(date)
      let qq = new Date()
      // let last = qq
      let last = new Date(qq.setTime(new Date(this.getDate(date)).getTime() - 3600 * 1000 * 24 * 2));
      this.yearStart = date.getFullYear()
      this.yearLast = last.getFullYear()
      this.myMonthTwo = last.getMonth() + 1
      let dateTwo = new Date();
      let lastdate = dateTwo.setTime(dateTwo.getTime() - 3600 * 1000 * 24 * 30);
      // this.getTime(date);
      this.getLastTime(last);
    },
    getDate(val) {
      let date = new Date(val);
      let new_year = date.getFullYear(); // 取当前的年份
      let month = date.getMonth();
      let new_month = month + 1; // 取当前的月份
      let mon = "";
      let day = "";
      if (month > 12) {
        new_month -= 12; // 月份减
        new_year++; // 年份增
      }
      let firstDay = new Date(new_year, new_month, 1); // 取当年当月中的第一天
      let lastDay = new Date(
        firstDay.getTime() - 1000 * 60 * 60 * 24
      ).getDate(); // 获取当月最后一天日期
      if (firstDay.getMonth() < 10) {
        mon = "0" + firstDay.getMonth();
      } else {
        mon = firstDay.getMonth();
      }
      // if (lastDay < 10) {
      //   day = "0" + lastDay;
      // } else {
      //   day = lastDay;
      // }
      let a = firstDay.getFullYear();
      let b = mon;
      if (mon == '00') {
        a = a - 1;
        mon = 12
      }
      let startDate =
        a +
        "-" +
        mon +
        "-" +
        "0" +
        firstDay.getDate();
      // let endDate = firstDay.getFullYear() + "-" + mon + "-" + day;
      return startDate;
    },
    setNowTimes(val) {
      // let data = new Date(val)
      // let new_year = data.getFullYear(); // 取当前的年份
      // let month = date.getMonth();
      //获取当前时间
      let myDate = new Date(val)
      let wk = myDate.getDay()
      let weeks = ['7', '1', '2', '3', '4', '5', '6']
      let week = weeks[wk];
      return week;
    },
    getDays(val) {
      let date = new Date(val)
      let year = date.getFullYear(); // 取当前的年份
      let month = date.getMonth();
      let days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
      if ((year % 4 === 0) && (year % 100 !== 0 || year % 400 === 0)) {
        days[1] = 29
      }
      return days[month]
    },
    // date.setTime(date.getTime() - 3600 * 1000 * 24);
    getWeek(val) {
      var date = new Date(val);
      var week = date.getDay();
      var day = date.getDate();
      if (week == 0) {
        week = 7;
      }
      let getWeek = Math.ceil((day + 6 - week) / 7)
      return getWeek;
    },
    getTime(val) {
      let weeks = ['一', '二', '三', '四', '五']
      let data = new Date(val);
      let nowMonthFirst = this.getDate(data)
      let nowMonthFirstWeek = this.setNowTimes(nowMonthFirst)
      let nowMonth = this.getWeek(data)
      let nowMonthFirstDate = new Date(nowMonthFirst);
      let haveDay = this.getDays(nowMonthFirst)
      let firstWeekStartTime, firstWeekEndTime, num
      if (nowMonthFirstWeek != 1) {
        firstWeekStartTime = new Date(nowMonthFirstDate.getTime() + 3600 * 1000 * 24 * (7 - nowMonthFirstWeek +
          1))
        firstWeekEndTime = new Date(firstWeekStartTime.getTime() + 3600 * 1000 * 24 * 6)
        num = Math.ceil((haveDay - (7 - nowMonthFirstWeek - 1)) / 7)
      } else {
        firstWeekStartTime = new Date(nowMonthFirstDate.getTime())
        firstWeekEndTime = new Date(firstWeekStartTime.getTime() + 3600 * 1000 * 24 * 6)
        num = Math.ceil(haveDay / 7)
      }
      // let firstWeekStartTime = new Date(nowMonthFirstDate.getTime() + 3600 * 1000 * 24 * (7 - nowMonthFirstWeek +
      //   1))
      // let firstWeekEndTime = new Date(firstWeekStartTime.getTime() + 3600 * 1000 * 24 * 6)
      let n = 0;
      // let num = Math.ceil((haveDay - (7- nowMonthFirstWeek - 1)) / 7)
      this.nowMonthList = []
      for (let i = 0; i < num; i++) {
        const myDate = new Date(firstWeekStartTime.getTime() + 3600 * 1000 * 24 * 7 * (i));
        const year = myDate.getFullYear();
        const month = ("0" + (myDate.getMonth() + 1)).slice(-2);
        const day = ("0" + myDate.getDate()).slice(-2);
        let LastDate = new Date(firstWeekEndTime.getTime() + 3600 * 1000 * 24 * 7 * (i));
        const lastyear = LastDate.getFullYear();
        const lastmonth = ("0" + (LastDate.getMonth() + 1)).slice(-2);
        const lastday = ("0" + LastDate.getDate()).slice(-2);
        let startDate = `${lastyear}-${lastmonth}-${lastday}`;
        let endDate = `${year}-${month}-${day}`;
        this.nowMonthList.push({
          label: '第' + weeks[i] + '周',
          value: "1",
          start: endDate,
          end: startDate
        }, )
      }
    },
    getLastTime(val) {
      let weeks = ['一', '二', '三', '四', '五']
      let data = new Date(val);
      let nowMonthFirst = this.getDate(data)
      //当月1号星期几
      let nowMonthFirstWeek = this.setNowTimes(nowMonthFirst)
      let nowMonth = this.getWeek(data)
      let nowMonthFirstDate = new Date(nowMonthFirst);
      let haveDay = this.getDays(nowMonthFirst)
      let firstWeekStartTime, firstWeekEndTime, num
      if (nowMonthFirstWeek != 1) {
        firstWeekStartTime = new Date(nowMonthFirstDate.getTime() + 3600 * 1000 * 24 * (7 - nowMonthFirstWeek +
          1))
        firstWeekEndTime = new Date(firstWeekStartTime.getTime() + 3600 * 1000 * 24 * 6)
        num = Math.ceil((haveDay - (7 - nowMonthFirstWeek - 1)) / 7)
      } else {
        firstWeekStartTime = new Date(nowMonthFirstDate.getTime())
        firstWeekEndTime = new Date(firstWeekStartTime.getTime() + 3600 * 1000 * 24 * 6)
        num = Math.ceil(haveDay / 7)
      }
      let n = 0;
      // num = Math.ceil((haveDay - (7- nowMonthFirstWeek - 1)) / 7)
      this.lastMonthList = []
      for (let i = 0; i < num; i++) {
        const myDate = new Date(firstWeekStartTime.getTime() + 3600 * 1000 * 24 * 7 * (i));
        const year = myDate.getFullYear();
        const month = ("0" + (myDate.getMonth() + 1)).slice(-2);
        const day = ("0" + myDate.getDate()).slice(-2);
        let LastDate = new Date(firstWeekEndTime.getTime() + 3600 * 1000 * 24 * 7 * (i));
        const lastyear = LastDate.getFullYear();
        const lastmonth = ("0" + (LastDate.getMonth() + 1)).slice(-2);
        const lastday = ("0" + LastDate.getDate()).slice(-2);
        let startDate = `${lastyear}-${lastmonth}-${lastday}`;
        let endDate = `${year}-${month}-${day}`;
        //起始日期超出当月跳出
        if (data.getMonth() + 1 != month) {
          break
        }
        this.lastMonthList.push({
          label: '第' + weeks[i] + '周',
          value: "1",
          start: endDate,
          end: startDate
        })
      }
    },
    popperShowEvent() {
      this.currentBgNum1 = [];
      this.currentBgNum2 = [];
      this.startShow = []
      this.startT = [];
    },
    clear() {
      this.currentBgNum1 = [];
      this.currentBgNum2 = [];
      this.startShow = []
      this.startT = [];
      this.monthStart = "";
    },

    handleMonthLeftClick(type, index) {
      if (type == "left" && this.startT.length < 2) {
        this.currentBgNum1.push(index);
        this.startT.push({
          start: this.lastMonthList[index].start,
          end: this.lastMonthList[index].end
        });
        this.startShow.push(`${this.yearLast}-${this.myMonthTwo}:${this.lastMonthList[index].label} `)

      } else if ((type = "right" && this.startT.length < 2)) {
        this.currentBgNum2.push(index);
        this.startT.push({
          start: this.nowMonthList[index].start,
          end: this.nowMonthList[index].end
        });
        this.startShow.push(`${this.yearStart}-${this.myMonthOne}:${this.nowMonthList[index].label} `)

      }
      if (this.startT.length === 1) {
        // this.monthStart = this.startShow.join("~");
        this.monthStart = this.startT[0].start + " ~ " + this.startT[0].end;

        this.visible = false;
        this.$emit("time", this.startT[0])
      }
      // if (this.startT.length >= 2) {
      //   new Date(this.startT[0].start).getTime() >
      //   new Date(this.startT[1].start).getTime() ?
      //     this.re() :
      //     "";
      //   this.monthStart = this.startShow.join("~");
      //   this.visible = false;
      //   this.$emit("time", this.startT)
      // }
    },
    re() {
      this.startT.length = 2
      this.startT.reverse();
      this.startShow.reverse()
    },
    handleYearBefore(type) {
      if (type == "left") {
        let data = this.yearStart + ':' + this.myMonthOne
        let nowMonthFirst = this.getDate(data)
        let date = new Date(nowMonthFirst)
        nowMonthFirst = new Date(date.getTime() - 3600 * 1000 * 24);
        this.first(nowMonthFirst)
        this.currentBgNum1 = [];
      } else if (type == "right") {
        let data = this.yearStart + ':' + this.myMonthOne
        let days = this.getDays(data)
        let nowMonthFirst = this.getDate(data)
        let date = new Date(nowMonthFirst)
        nowMonthFirst = new Date(date.getTime() + 3600 * 1000 * 24 * (days));
        this.first(nowMonthFirst)
        this.currentBgNum1 = [];
      }
      // this.currentBgNum2 = [Number(acrossM)];
      this.currentBgNum1 = [];
      this.currentBgNum2 = [];
      // if (this.startT.length >= 2) {
      //   let acrossM = this.startT[0].split("-")[1];
      //   let acrossY = this.startT[0].split("-")[0];
      //   if (acrossY == this.yearStart) {
      //     this.currentBgNum1 = [Number(acrossM)];
      //   } else {
      //     this.currentBgNum1 = [];
      //   }
      //   if (acrossY == this.yearEnd) {
      //     this.currentBgNum2 = [Number(acrossM)];
      //   } else {
      //     this.currentBgNum2 = [];
      //   }
      // }
    }
  }
};
</script>
<style lang="less" scoped>
.month-range-class {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}
/deep/.ivu-input{
  height: 30px;
  line-height: 30px;
}
</style>

