<template>
  <div class="styleData" :style="styleData" v-if="isShow">
    <div :style="calendarAllStyle">
      <div class="canlendarPanel" :style="mainStyle">
        <!-- <div :style="mainStyle.canlendarHeader">{{ year }}-{{ month }}-{{ day }}</div> -->
        <div class="canlendar-main" :style="mainStyle.canlendarMain">
          <ul class="main-header" :style="mainStyle.mainHeader">
            <li :style="mainStyle.li" v-for="(item, index) in week">{{ item }}</li>
          </ul>
          <div class="underline"></div>
          <ul class="main" :style="mainStyle.main">
            <li :style="mainStyle.li" v-for="(item, indesx1) in weekDayArr">
              <div v-if="preMonthSize - weekDayArr.length + indesx1 + 1 == item" class="disabled isSignDay"></div>
              <div v-else class="disabled">{{ preMonthSize - weekDayArr.length + indesx1 + 1 }}</div>
            </li>

            <li :style="mainStyle.li" v-for="(item, index) in dayList" :key="index">
              <div v-if="item.isSign === true" class="isSignDay">
                <span class="itemDay">{{ item.day }}</span>
              </div>
              <span v-else>{{ item.day }}</span>
            </li>

            <li :style="mainStyle.li" v-lz-click='"13"' v-for="index in lastWeekDay" class="disabled">{{ index }}</li>
          </ul>
        </div>
      </div>
    </div>
    <div class="singButton" v-lz-click="'13'" @click="signClick" v-if="singButton">点击签到</div>
    <div class="button" v-else>{{ buttonText }}</div>
  </div>
</template>

<script>
import Vue from 'vue';
import dataJson from '../../../../src/data.json';
import dateUtil from '../../../util/dateUtil.js';
import apis1 from '../../../util/apis1.js';
import { Toast, Notify } from 'vant';
Vue.use(Toast, Notify);
import store from '../../../store/store';
let { signMainRequest, signDayRequest } = apis1;
import { SignPromptComService, SignPromptComService1 } from '../../../util/comCreate.js';
export default {
  name: 'calendar1',
  props: ['isTemplate', 'datas', 'styleData', 'keyData', 'templateData'],
  components: {},
  data() {
    return {
      singButton: true, //签到按钮
      buttonText: '',

      year: 0,
      month: 0,
      day: 0,
      week: ['日', '一', '二', '三', '四', '五', '六'],
      monthList: [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
      weekDayArr: [],
      lastWeekDay: 1,
      preMonthSize: 30,
      basicData: {
        signDayArr2: []
      },
      restDrawCount1: 0,

      dayList: [],
      calendarAllStyle: '', //背景样式
      mainStyle: '', //整体样式

      comName: '', //日历组件需要的提示组件
      isNotifyRotary: true, //是否通知抽奖组件刷新页面
      isShow: true //是否显示日历组件
    };
  },
  created() {
    this.publicData.$on('upDataCalendar', () => {
      this.initData();
    });

    this.activityType = sessionStorage.getItem('activityType');

    this.closeSignPrompt();
    this.comName = this.datas.comname;

    this.calendarAllStyle = {
      background: 'url(//img10.360buyimg.com/imgzone/jfs/t1/155394/33/21118/4774/60407af4E08a5ba60/ebae6acddf1a7a52.png)',
      'background-size': '100% 100%',
      width: '6.18rem',
      height: '5.15rem',
      'margin-top': '1.14rem',
      'padding-top': '0.56rem',
      margin: '1.14rem auto'
    };

    this.mainStyle = dataJson.calendarStyle1;
    this.initData();
  },

  methods: {
    //每次先关闭，防止叠加
    closeSignPrompt() {
      SignPromptComService.close();
      SignPromptComService1.close();
    },
    async initData() {
      this.closeSignPrompt();

      this.getCurrentDate();
      this.initDate();
      // 上一个月有多少天
      this.preMonthSize = this.month - 1 === 0 ? 31 : this.monthList[this.month - 2];

      if (this.isTemplate == true) {
        var datasAll = this.templateData;
        console.log(datasAll, 'datasAll');
        if (datasAll) {
          var initDataAll = datasAll.sign;
          var tabValue = store.state.tabValue; //模板预览时期

          if (tabValue) {
            if (tabValue == '1') {
              //签到期
              this.nowDate = new Date().getTime(); //1613721651000;//2021-02-19 16:00:51
              var mainDatasAll = {
                signStartTime: datasAll.sign.startTime, // 1611208276000, //2021-01-21 13:51:16 initDataAll.startTime ? initDataAll.startTime : null,
                signEndTime: datasAll.sign.endTime, //1613887436000, //2021-02-21 14:03:56 initDataAll.endTime ? initDataAll.endTime : null
                activityEndTime: datasAll.activity.endTime //1616379869000
              };
              this.isShow = true;
            } else if (tabValue == '2') {
              //领奖期
              this.nowDate = new Date().getTime(); //1613721651000;//2021-02-19 16:00:51
              var mainDatasAll = {
                signStartTime: datasAll.sign.startTime, // 1611208276000, //2021-01-21 13:51:16 initDataAll.startTime ? initDataAll.startTime : null,
                signEndTime: datasAll.sign.endTime, //1613887436000, //2021-02-21 14:03:56 initDataAll.endTime ? initDataAll.endTime : null
                activityEndTime: datasAll.activity.endTime //1616379869000
              };
              this.singButton = false;
              this.buttonText = '签到结束';
              this.publicData.$emit('showPrizePreview', this.templateData, true);
              this.isShow = true;
            } else if (tabValue == '3') {
              //公告期（活动结束）
              this.nowDate = 1613721651000; //2021-02-19 16:00:51
              var mainDatasAll = {
                signStartTime: 1611208276000, //2021-01-21 13:51:16 initDataAll.startTime ? initDataAll.startTime : null,
                signEndTime: 1613960669000, //2021-02-21 14:03:56 initDataAll.endTime ? initDataAll.endTime : null
                activityEndTime: 1613615069000
              };
              this.publicData.$emit('showCarouselimg', false);
              this.singButton = false;
              this.buttonText = '活动结束';
            }
          } else {
            this.nowDate = 1613721651000;
            var mainDatasAll = {
              signStartTime: 1611208276000, //initDataAll.startTime ? initDataAll.startTime : null,
              signEndTime: 1613887436000, //initDataAll.endTime ? initDataAll.endTime : null
              activityEndTime: 1616379869000
            };
            this.isShow = true;
          }
        } else {
          this.nowDate = 1613721651000;
          var mainDatasAll = {
            signStartTime: 1611208276000,
            signEndTime: 1613887436000
          };
          this.isShow = true;
        }

        //模板预览
        this.restDrawCount1 = 0;
        this.signDays = 0;
        this.basicData.signDayArr2 = [];
        this.signPlus = 1;
        this.hasCumSignDay = 0;
        this.needCumSignDay = this.signPlus - (this.hasCumSignDay % this.signPlus);
        this.status = 0;
        this.signStartTime = mainDatasAll.signStartTime;
        this.signEndTime = mainDatasAll.signEndTime;
        this.activityEndTime = mainDatasAll.activityEndTime; //活动结束时间

        if (this.status == 0) {
          this.isMostDrawCount = false; //未达上限
        } else {
          //1.先判断是否完成任务-  以签到天数/signplus  完成几次任务>= max
          //2再判断抽奖次数是否是0，都满足
          this.isMostDrawCount = false; //未达上限
          if (this.hasCumSignDay / this.signPlus >= this.maxNumber) {
            this.signButton = true;
            this.isMostDrawCount = true; //已达上限
          }
        }


      } else {
        this.nowDate = new Date().getTime();
        let actStatus = sessionStorage.getItem('actStatus');

        await signMainRequest(mainDatas => {
          console.log('mainDatas', mainDatas);
          //签到时间判断
          let mainDatasAll = mainDatas.data;
          this.signStartTime = mainDatasAll.signStartTime;
          this.signEndTime = mainDatasAll.signEndTime; //1609736010000 1614418856000;
          this.signDays = mainDatasAll.signNum;
          this.activityEndTime = mainDatasAll.activityEndTime; //活动结束时间

          if (this.nowDate >= this.signStartTime && this.nowDate <= this.signEndTime) {
            console.log('处于签到时间');
            //处于签到时间
            this.singButton = true;
            this.publicData.$emit('showCarouselimg', true);
          } else if (this.nowDate > this.signEndTime) {
            //签到日期结束
            console.log('签到日期结束');
            this.singButton = false;
            this.buttonText = '签到结束';
            this.publicData.$emit('showCarouselimg', true);
          } else {
            //活动未开始
            console.log('活动未开始');
            this.singButton = false;
            this.buttonText = '活动未开始';
            this.publicData.$emit('showCarouselimg', true);
          }

          if (this.nowDate > this.activityEndTime) {
            //活动已结束
            this.publicData.$emit('showCarouselimg', false);
            this.singButton = false;
            this.buttonText = '活动结束';
          }

          // maxNumber 可以签到几天
          // signNum 已累计签到几天
          // signPlus 签到几天获取抽奖次数
          this.restDrawCount1 = mainDatasAll.drawNumber;
          this.basicData.signDayArr2 = mainDatasAll.signTime;

          this.signPlus = mainDatasAll.signPlus;
          this.hasCumSignDay = mainDatasAll.signNum;
          this.needCumSignDay = mainDatasAll.leftNum; //this.signPlus - (this.hasCumSignDay % this.signPlus);
          this.status = mainDatasAll.status;
          this.maxNumber = mainDatasAll.maxNumber;

          if (this.status == 0) {
            this.isMostDrawCount = false; //已达上限
            this.signButton = false;
          } else {
            //1.先判断是否完成任务-
            //2再判断抽奖次数是否是0，都满足
            this.isMostDrawCount = false; //未达上限
            // 2 / 1  2
            // console.log(this.hasCumSignDay/this.signPlus,'asdsd')
            if (this.hasCumSignDay / this.signPlus >= this.maxNumber) {
              //成任务无法签到
              this.signButton = true;
              // if (this.restDrawCount1 == 0) {
              this.isMostDrawCount = true; //已达上限
              // }
            }
          }
        });
      }
      this.createSignPrompt();
      //签到日期
      if (this.basicData.signDayArr2.length > 0) {
        for (var i = 0; i < this.basicData.signDayArr2.length; i++) {
          console.log(dateUtil.dateChangeYYYY(this.basicData.signDayArr2[i], 3),'asssssssssssss')
          this.basicData.signDayArr2[i] = dateUtil.dateChangeYYYY(this.basicData.signDayArr2[i], 3);
        }
      }
      this.initDate();
    },

    //呼起提示组件
    createSignPrompt() {
      if (this.comName == 'signPrompt') {
        // console.log(this.hasCumSignDay)
        SignPromptComService.create(this.isMostDrawCount, this.hasCumSignDay, this.needCumSignDay, this.restDrawCount1, this.signPlus, submit => {
          SignPromptComService.close();
        });
      } else if (this.comName == 'signPrompt1') {
        SignPromptComService1.create(this.signDays, this.currentData, submit => {
          SignPromptComConstructor1.close();
        });
      }
    },

    // 获得今天的日期
    getCurrentDate() {
      const date = new Date();
      this.year = date.getFullYear();
      this.month = date.getMonth() + 1;
      this.day = date.getDate();
      this.currentData = this.year + '年' + this.month + '月' + this.day + '号';
    },
    // 根据年月日获得为星期几
    getWeekDay(year, month, day) {
      return new Date(`${year}/${month}/${day}`).getDay();
    },
    //初始化时间
    initDate() {
      console.log(this.basicData.signDayArr2, '初始化时间');
      this.dayList = [];
      if ((this.year % 4 === 0 && this.year % 100 !== 0) || this.year % 400 === 0) {
        this.monthList[1] = 29;
      } else {
        this.monthList[1] = 28;
      }
      // 获得指定年月的1号是星期几
      const firstDay = this.getWeekDay(this.year, this.month, 1);

      // 在1号前面填充多少个上个月的日期
      this.weekDay = firstDay === 7 ? 0 : firstDay;

      // 获得最后一天是星期几，往后填充多少个
      var remineDay = this.getWeekDay(this.year, this.month, this.monthList[this.month - 1]);
      // console.log(remineDay, '获得最后一天是星期几，往后填充多少个');
      this.lastWeekDay = remineDay === 7 ? 6 : 6 - remineDay;

      var days = this.monthList[this.month - 1];

      //补充上个月的日期
      this.weekDayArr = [];
      for (var i = 0; i < this.weekDay; i++) {
        var obj1 = {
          year: this.year,
          month: this.month,
          day: days - i,
          isSign: false, //是否签到
          isCurrentDay: false //是否是今天
        };
        this.weekDayArr = this.weekDayArr.concat(obj1);
      }

      for (var i = 0; i < days; i++) {
        var obj = {
          year: this.year,
          month: this.month,
          day: i + 1,
          isSign: false, //是否签到
          isCurrentDay: false //是否是今天
        };
        this.dayList = this.dayList.concat(obj);
        if (this.day == obj.day) {
          this.dayList[i].isCurrentDay = true;
        }
        //已经签到的日期
        for (var j = 0; j < this.basicData.signDayArr2.length; j++) {
          const date = this.basicData.signDayArr2[j];
          if (date.year == this.year) {
            if (date.month == this.month) {

              if (date.day == i + 1) {
               this.dayList[i].isSign = true;
               this.dayList[i].year = date.year;
               this.dayList[i].month = date.month;

                if (date.day == this.day) {
                  this.singButton = false;
                  this.buttonText = '已签到';
                }
              }
            } else {
              if (date.month == this.month - 1) {
                for (var k = 0; k < this.weekDay; k++) {
                  if (date.day == this.preMonthSize - this.weekDay + k + 1) {
                    this.weekDayArr[k] = date.day;
                  }
                }
              }
            }
          }
        }
      }
    },
    signClick() {
      if (this.isTemplate) {
        this.$toast('活动预览，仅供查看');
        return;
      }
      let actStatus = sessionStorage.getItem('actStatus');
      if (actStatus == 2) {
        Toast('活动已结束');
        return;
      }
      if (actStatus == 1) {
        Toast('活动尚未开始');
        return;
      }
      //请求签到接口

      if (this.signButton == true) {
        Toast('签到次数已达上限，无法签到');
        return;
      }

      if (this.isTemplate == true) {
        var obj = {
          year: this.year,
          month: this.month,
          day: this.day
        };
        this.basicData.signDayArr2.push(obj);
        this.initDate();
        this.signDays = 1; //连续累计签到1天
        this.hasCumSignDay = this.hasCumSignDay + 1;
        this.needCumSignDay = this.needCumSignDay - 1;
        SignPromptComService.close();
        SignPromptComService1.close();
        this.createSignPrompt();
        Toast('签到成功');
        var a = setTimeout(() => {
          if (this.isNotifyRotary) {
            this.publicData.$emit('notifyCallBack', 'updata');
          }
          clearTimeout(a);
        }, 1000);
      } else {
        //请求接口
        signDayRequest(signDatas => {
          console.log(signDatas);
          Toast('签到成功');
          this.singButton = false;
          this.buttonText = '已签到';
          this.initData();
          this.initDate();
        });
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.singButton {
  width: 3.1rem;
  height: 0.8rem;
  line-height: 0.8rem;
  background-color: #ddba71;
  border-radius: 0.5rem;
  margin: auto;
  margin-top: -1rem;
  font-size: 0.5rem;
  color: #7f5935;
}
.button {
  width: 3.1rem;
  height: 0.8rem;
  line-height: 0.8rem;
  background-color: #cbcbcb;
  border-radius: 0.5rem;
  margin: auto;
  margin-top: -1rem;
  font-size: 0.5rem;
  color: #7f7f7f;
}
.underline {
  background-color: #0e822f;
  width: 5.3rem;
  height: 2px;
  margin-top: 5px;
}
.canlendarPanel {
  .canlendar-main {
    .main-header {
      li {
        text-align: center;
        flex: 1;
      }
    }
    ul.main {
      li {
        position: relative;
        width: 14%;
        line-height: 25px;
        cursor: pointer;
        text-align: center;
        display: flex;
        justify-content: center;
        align-items: center;
      }
      .disabled {
        color: #d7d7d7;
        cursor: default;
      }

      .itemDay {
        width: 0.47rem;
        height: 0.47rem;
        border-radius: 50%;
      }
      .isSignDay {
        background-color: #0e822f;
        width: 0.47rem;
        height: 0.47rem;
        border-radius: 50%;
        color: #fff;
      }
    }
  }
}
</style>
