<template>
  <div
    class="styleData"
    :style="styleData"
    v-if="isShow"
    ref="calendar"
    @click="styleClick('click', 'calendar')"
    @mousemove="styleClick('mousemove', 'calendar')"
    @mouseout="styleClick('mouseout')"
  >
    <signPromp
      v-if="comName == 'signPrompt'"
      :hasCumSignDay="hasCumSignDay"
      :needCumSignDay="needCumSignDay"
      :isMostDrawCount="isMostDrawCount"
      :signPlus="signPlus"
      :signPromptStyle="styleData.signPromptStyle"
    ></signPromp>

    <signPromp1 v-if="comName == 'signPrompt1'" :currentData="currentData" :signDays="signDays" :signDateStyle="styleData.signDateStyle" :signPromptStyle="styleData.signPromptStyle"></signPromp1>

    <div :style="styleData.calendarAllStyle" ref="calendarAllStyle">
      <div :style="styleData.mainStyle">
        <div ref="canlendarHeader" :style="styleData.canlendarHeader">
          <div class="xhySty">{{ year }}-{{ month }}-{{ day }}</div>
        </div>
        <div class="canlendar-main" :style="styleData.canlendarMain">
          <ul
            class="main-header"
            :style="styleData.mainHeader"
            ref="mainHeader"
          >
            <li :style="mainStyle.li" v-for="(item, index) in week">
              {{ item }}
            </li>
          </ul>
          <ul class="main" :style="styleData.main" ref="main">
            <li :style="mainStyle.li" v-for="(item, indesx1) in weekDayArr">
              <div
                v-if="preMonthSize - weekDayArr.length + indesx1 + 1 == item"
                class="disabled"
                :style="styleData.isSignDay"
                ref="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="isWebClick">
                <div
                  v-if="item.isSign === true"
                  :style="styleData.isSignDay"
                  ref="isSignDay"
                ></div>
                <div
                  v-else-if="item.isSign === false && item.isCurrentDay == true"
                  :style="styleData.isCurrentDay"
                  ref="isCurrentDay"
                ></div>
                <span v-else class="">{{ item.day }}</span>
              </div>
              <div v-else>
                <div
                  v-if="item.isSign === true"
                  :style="styleData.isSignDay"
                ></div>
                <div
                  v-else-if="item.isSign === false && item.isCurrentDay == true"
                  v-lz-click="'13'"
                  :style="styleData.isCurrentDay"
                  @click.stop="signClick(item)"
                ></div>
                <span v-else class="">{{ item.day }}</span>
              </div>
            </li>

            <li
              :style="mainStyle.li"
              v-for="index in lastWeekDay"
              class="disabled"
            >
              {{ index }}
            </li>
          </ul>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { stringify } from "querystring";
import Vue from "vue";
import signPromp from "../../basisComponent/signPrompt/signPrompt3.vue";
import signPromp1 from "../../basisComponent/signPrompt/signPrompt4.vue";
import dateUtil from "../../../util/dateUtil.js";
import apis1 from "../../../util/apis1.js";
import { Toast, Notify } from "vant";
Vue.use(Toast, Notify);
let { signMainRequest, signDayRequest, getTemplate } = apis1;

import {
  SignPromptComService,
  SignPromptComService1,
} from "../../../util/comCreate.js";
import store from "../../../store/store";
export default {
  props: [
    "isTemplate",
    "datas",
    "styleData",
    "keyData",
    "modifyContent",
    "templateData",
    "mdeldata",
    "isWebClick",
  ],
  components: {
    signPromp,
    signPromp1
  },
  data() {
    return {
      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: false, //默认不显示日历组件
      hasCumSignDay: 0,
      needCumSignDay: 0,
      isMostDrawCount: false,
      signPlus: 1,
      styleDataOld: {},
    };
  },
  watch: {
    styleData: {
      handler(val) {
        this.styleData = val;
      },
      deep: true,
    },
  },
  created() {
     //深拷贝重置需要
    this.styleDataOld = JSON.parse(JSON.stringify(this.styleData));
    console.log(123321, sessionStorage.getItem("templateCode"));
    this.publicData.$on("upDataCalendar", () => {
      this.initData();
    });
    // console.log(4444, this.styleData);
    // //如果父组件传递过来的样式数据则使用样式数据否则使用默认数据
    // if (this.styleData && JSON.stringify(this.styleData) != "{}") {
    //   console.log(333);
    //   this.styleData = this.styleData; //父组件传递过来的样式数据
    // } else {
    //   this.styleData = styleJson; //默认数据
    // }

    this.isShowCalendar = this.datas.isAlwaysShowCalendar; //日历组件是否一直显示
    this.isShow = this.datas.isAlwaysShowCalendar; //如果是一直显示的，直接复制true,否则先复制false,达到条件之后复制true
    this.comName = this.datas.comname;

      console.log(this.comName,7788)

    this.closeSignPrompt();
  },
  mounted() {
    this.initData();
    console.log(this.comName, "this.comName");
  },

  methods: {
    //点击可修改位置的方法
    styleClick(type, refName) {
      if (this.isWebClick) {
        //传值给B端
        let byValue = {
          modifyContent: this.modifyContent,
          refName: refName,
          styleData: this.styleData,
          styleDataOld: this.styleDataOld,
          c_this: this,
        };
        this.$emit("opertaionCom", type, byValue);
      }
    },
    //每次先关闭，防止叠加
    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;

        // await getTemplate((data) => {
        //   // console.log("data11111111", JSON.parse(data.basicJson));
        //   // this.styleJson = data.data;
        // });
        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
              };
              if (!this.isShowCalendar) {
                this.isShow = true;
                this.publicData.$emit("showMyPrize", false);
              }
            } else if (tabValue == "2") {
              //领奖期
              this.nowDate = new Date().getTime(); //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
              };
              if (!this.isShowCalendar) {
                this.publicData.$emit(
                  "showPrizePreview",
                  this.templateData,
                  true
                );
                this.isShow = false;
              }
            } 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(
                "isNotyFiceWinnerReorrd",
                true,
                this.isTemplate
              );
              if (!this.isShowCalendar) {
                this.isShow = false;
                this.publicData.$emit("showMyPrize", true);
              }
            }
          } else {
            this.nowDate = 1613721651000;
            var mainDatasAll = {
              signStartTime: 1611208276000, //initDataAll.startTime ? initDataAll.startTime : null,
              signEndTime: 1613887436000, //initDataAll.endTime ? initDataAll.endTime : null
              activityEndTime: 1616379869000,
            };
            if (!this.isShowCalendar) {
              this.isShow = true;
            }
          }
        } else {
          this.nowDate = 1613721651000;
          var mainDatasAll = {
            signStartTime: 1611208276000,
            signEndTime: 1613887436000,
            activityEndTime: 1616379869000,
          };
          if (!this.isShowCalendar) {
            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; //已达上限
          }
        }

        if (!this.isShowCalendar) {
        } else {
          //抽奖活动一直显示我的奖品
          this.isShow = true;
          this.publicData.$emit("showMyPrize", true);
        }
      } else {
        this.nowDate = new Date().getTime();
        let actStatus = sessionStorage.getItem("actStatus");
        //签到有礼类的活动活动结束不显示签到组件,签到抽奖类的活动一直显示日历组件
        if (!this.isShowCalendar) {
          if (actStatus == 2) {
            this.isShow = false;
            return;
          }
        }

        await signMainRequest((mainDatas) => {
          //签到时间判断
          let mainDatasAll = mainDatas.data;
          this.signStartTime = mainDatasAll.signStartTime;
          this.signEndTime = mainDatasAll.signEndTime; //1609736010000 1614418856000;
          this.signDays = mainDatasAll.signNum;
          this.activityEndTime = mainDatasAll.activityEndTime; //活动结束时间
          var timeDiff = parseInt(this.signEndTime - new Date().getTime()) + "";

          if (timeDiff.length < 9 && timeDiff > 0) {
            //定时刷新判断签到时间是否结束
            var a = setInterval(() => {
              this.initData();
              clearInterval(a);
              // 2676401580
            }, parseInt(timeDiff));
          }

          if (!this.isShowCalendar) {
            //有礼活动签到期不显示我的奖品
            console.log('aaaaaaaaaaaaaaaaa')
            this.publicData.$emit("showMyPrize", false);
          } else {
            //抽奖活动一直显示我的奖品
            this.isShow = true;
            this.publicData.$emit("showMyPrize", true);
          }

          if (!this.isShowCalendar) {
            if (this.nowDate > this.activityEndTime) {
              //活动已结束
              console.log('aaaaaaaaaaaaaaaaa11111111111')
              this.isShow = false;
              this.publicData.$emit("showMyPrize", true);
              return;
            }

            if (
              this.nowDate >= this.signStartTime &&
              this.nowDate <= this.signEndTime
            ) {
              //处于签到时间
              this.isShow = true;
            } else if (this.nowDate > this.signEndTime) {
              //签到日期结束 显示领奖状态
              console.log("签到日期结束 显示领奖状态");
              this.publicData.$emit("showPrizePreview", null, true);
              this.isShow = false;
            } else {
              //活动未开始
              console.log("活动未开始");
              this.isShow = true;
            }
          }

          // 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++) {
          this.basicData.signDayArr2[i] = dateUtil.dateChangeYYYY(
            this.basicData.signDayArr2[i],
            3
          );
        }
      }
      this.initDate();
    },

    //呼起提示组件
    createSignPrompt() {
      console.log(this.comName, "this.comName");
      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;
              }
            } 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(itemData) {
      console.log(itemData);
      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: itemData.year,
          month: itemData.month,
          day: itemData.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) => {
          Toast("签到成功");
          var a = setTimeout(() => {
            if (this.isNotifyRotary) {
              this.publicData.$emit("notifyCallBack", "updata");
            }
            this.initData();
            this.initDate();
          }, 1000);
        });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
body,
ul {
  /*组合选择器*/
  list-style: none; /*清除列表默认样式*/
  padding: 0; /*清除padding*/
  margin: 0;
}
li {
  float: left;
}
.clickBorderDiv {
  border: 2px solid #00ff00;
  position: absolute;
  pointer-events: none;
  box-sizing: border-box;
}
.canlendar-main {
  .main-header {
    li {
      text-align: center;
      flex: 1;
    }
  }
  ul.main {
    li {
      position: relative;
      width: 14.2%;
      line-height: "0.25rem";
      cursor: pointer;
      text-align: center;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .disabled {
      color: #d7d7d7;
      cursor: default;
    }
    .isSignDay {
      background: url(//img10.360buyimg.com/imgzone/jfs/t1/140686/40/18482/2213/5fd714f4E0b949c57/c0def3c77853e79c.png)
        no-repeat;
      background-size: 100% 100%;
      width: 0.23rem;
      height: 0.29rem;
    }
    .isCurrentDay {
      background: url(//img10.360buyimg.com/imgzone/jfs/t1/135582/17/19832/3615/5fd718a8E58a83014/40754803ebf4fc52.png)
        no-repeat;
      background-size: 100% 100%;
      width: 0.58rem;
      height: 0.58rem;
    }
  }
}
.styleData {
  // position: relative;
}
</style>
