<template>
  <div
    :style="styleData.scratchdiv"
    ref="scratch"
    @click.stop="styleClick('click', 'scratch')"
    @mousemove.stop="styleClick('mousemove', 'scratch')"
    @mouseout.stop="styleClick('mouseout')"
  >
    <div id="card" v-if="prerentName != ''">{{ prerentName }}</div>
    <canvas
      id="myCaruse"
      class="start-btn-container"
      v-lz-click="'12'"
      v-if="nowGuaGua && !this.isWebClick"
    ></canvas>
    <img
      v-if="this.isWebClick"
      :style="styleData.canvasImg"
      :src="styleData.canvasImg.imageUrl"
    />
    <img
      v-if="prerentName == ''"
      @click="handlebtn"
      :style="styleData.startBtn"
      :src="styleData.startBtn.imageUrl"
      alt="图片加载失败"
    />
  </div>
</template>
<script>
import bus from "../../../util/bus.js";
import apis1 from "../../../util/apis1.js";
import { Toast } from "vant";
import {
  AddressPopComService,
  PrizeResultPopComService,
  NoPrizeResultPopComService,
} from "../../../util/comCreate.js";
let { startDraw } = apis1;
export default {
  props: [
    "isTemplate",
    "datas",
    "styleData",
    "keyData",
    "templateData",
    "modifyContent",
    "isWebClick",
  ],
  data() {
    return {
      scratchList: [
        {
          id: 1,
          showImg: "",
          angle: 0,
          prizeName: "谢谢参与",
        },
        {
          id: 2,
          showImg: "",
          angle: 0,
          prizeName: "谢谢参与",
        },
        {
          id: 3,
          showImg: "",
          angle: 0,
          prizeName: "谢谢参与",
        },
        {
          id: 4,
          showImg: "",
          angle: 0,
          prizeName: "谢谢参与",
        },
        {
          id: 5,
          showImg: "",
          angle: 0,
          prizeName: "谢谢参与",
        },
        {
          id: 6,
          showImg: "",
          angle: 0,
          prizeName: "谢谢参与",
        },
        {
          id: 7,
          showImg: "",
          angle: 0,
          prizeName: "谢谢参与",
        },
        {
          id: 8,
          showImg: "",
          angle: 0,
          prizeName: "谢谢参与",
        },
      ],
      restDrawCount: 0,
      prerentName: "",
      lastClick: null,
      winnerDraw: null,
      nowGuaGua: true,
      dataListLength: 0,
      prizeResultData: {
        styleData: {},
        datas: {},
        keyData: {
          prizeUrl: "showImg",
          prizeName: "prizeName",
          prizeType: "prizeType",
          priceInfo: "priceInfo",
          discountType: "discountType",
          couponType: "couponType",
        },
      },
      styleDataOld: {},
    };
  },
  created() {},
  mounted() {
    //深拷贝重置需要
    this.styleDataOld = JSON.parse(JSON.stringify(this.styleData));
    this.initDatas();
  },
  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);
      }
    },
    handlebtn(vw) {
      var ms = 2000;
      if (Date.now() - this.lastClick >= ms) {
        this.lastClick = Date.now();
      } else {
        console.log(1233);
        return;
      }
      if (this.isTemplate) {
        this.$toast("活动预览，仅供查看");
        return;
      }
      let actStatus = sessionStorage.getItem("actStatus");
      if (actStatus == 2) {
        Toast("活动已结束");
        return;
      }
      if (actStatus == 1) {
        Toast("活动尚未开始");
        return;
      }
      if (this.prerentName != "") {
        return;
      }
      if (this.restDrawCount <= 0) {
        if (this.dataListLength > 0) {
          this.$toast("您没有抽奖机会了，点击“更多机会”获取机会吧~");
        } else {
          this.$toast("您没有抽奖机会了");
        }
        return;
      } else {
        this.restDrawCount--;
        bus.$emit("restDrawCount", this.restDrawCount);
        this.nowGuaGua = true;
      }
      startDraw((initDatas) => {
        console.log("中奖信息", initDatas);
        if (initDatas.resp_code == 50009) {
          this.$toast("活动已结束");
          this.isStartPlay = false;
          return;
        }

        if (initDatas.resp_code != 0) {
          this.isStartPlay = false;
        }

        const self = this;

        console.log("initDatas.data", initDatas.data);
        if (initDatas.data) {
          // 奖品id没有匹配上的时候
          var noSelect = true;
          for (var i = 0; i < this.scratchList.length; i++) {
            if (this.scratchList[i].id == initDatas.data.prizeInfoId) {
              console.log(self.scratchList);
              self.pIndex = i;
              console.log("中奖id", self.pIndex);
              this.prize = self.scratchList[self.pIndex].position - 1;
              this.startRoll(initDatas.data.prizeName, self.pIndex); //执行抽奖
              this.winnerDraw = initDatas;
              console.log(this.winnerDraw);
              // 拿到相应的角度调旋转接口

              console.log("奖品id", self.pIndex);
              this.isStartPlay = false;
              noSelect = false;
              break;
            }
          }
          if (noSelect) {
            for (var i = 0; i < self.prizeListData.length; i++) {
              if (!self.machineContent[i].text) {
                this.prize = self.prizeListData[i].position - 1;
              }
            }
            this.startRoll("未中奖");
            this.winnerDraw = "未中奖";
            this.isStartPlay = false;
          }
        } else {
          for (var i = 0; i < self.machineContent; i++) {
            if (!self.machineContent[i].text) {
              this.prize = self.machineContent[i].position - 1;
            }
          }
          this.winnerDraw = "未中奖";
          this.startRoll("未中奖");
        }
        this.canvas(this.winnerDraw);
      });
    },
    initDatas() {
      if (this.isTemplate == true) {
        var datasAll = this.templateData;
      } else {
        var ms = 2000;
        this.lastClick = Date.now() - ms;
        bus.$on("restDrawCount", (content) => {
          this.restDrawCount = content;
        });
        bus.$on("ourprizeList", (content) => {
          let prizelist = content;
          if (prizelist.length != 0) {
            prizelist.forEach((v) => {
              this.scratchList.forEach((i, a) => {
                if (v.position == i.id) {
                  this.scratchList[a] = v;
                }
              });
            });
          }
        });
        bus.$on("data", (content) => {
          this.dataListLength = content.taskList.length;
        });
      }
    },
    startRoll(hope, tope) {
      console.log(hope, tope);
      if (hope == "未中奖") {
        this.prerentName = "谢谢参与";
      } else {
        this.prerentName = hope;
      }
    },
    bodyScroll(event) {
      event.preventDefault();
    },
    endScroll(event) {
      document.body.removeEventListener("touchmove", this.bodyScroll, {
        passive: false,
      });
    },
    canvas(winner) {
      var guagua = true;
      var nowVue = this;
      var prizeData = this.prizeResultData;
      var myCaruse = document.getElementById("myCaruse");
      document.body.addEventListener("touchmove", this.bodyScroll, {
        passive: false,
      });
      document.body.addEventListener("touchend", this.endScroll, {
        passive: false,
      });
      console.log(myCaruse);
      var can = myCaruse.getContext("2d");
      var x = myCaruse.offsetWidth;
      var y = myCaruse.offsetHeight;
      var l = myCaruse.getBoundingClientRect().left;
      var t = myCaruse.getBoundingClientRect().top;
      var nowNum = 0;
      myCaruse.style.display = "block";
      console.log(x, y, "sukabulie");
      var myImg = new Image();
      myImg.src = this.styleData.canvasImg.imageUrl;
      myImg.onload = function () {
        can.beginPath();
        can.drawImage(myImg, 0, 0, x + 40, y + 40);
        can.closePath();
      };
      can.save();
      var userAgentInfo = navigator.userAgent;
      var mobileAgents = [
        "Android",
        "iPhone",
        "SymbianOS",
        "Windows Phone",
        "iPad",
        "iPod",
      ];
      var mobile = false;
      for (var v = 0; v < mobileAgents.length; v++) {
        if (userAgentInfo.indexOf(mobileAgents[v]) > 0) {
          mobile = true;
          break;
        }
      }
      var startMove = mobile ? "touchstart" : "mousedown";
      var onTheMove = mobile ? "touchmove" : "mousemove";
      var endMove = mobile ? "touchend" : "mouseup";
      function nowMove(ev) {
        document.body.parentNode.style.overflow = "hidden";
        var ex = mobile ? ev.touches[0].clientX : ev.clientX;
        var ey = mobile ? ev.touches[0].clientY : ev.clientY;
        ex = ex - 50;
        ey = ey - (392.5 - window.scrollY);
        // console.log(window.scrollY);
        can.beginPath();
        can.globalCompositeOperation = "destination-out";
        can.arc(ex, ey, 20, 0, 2 * Math.PI, false);
        nowNum += 20 * 2;
        can.fill();
        can.closePath();
        ev.preventDefault();
      }
      myCaruse.addEventListener(
        startMove,
        function () {
          if (guagua != true) {
            return;
          } else {
            myCaruse.addEventListener(onTheMove, nowMove, false);
          }
        },
        false
      );
      myCaruse.addEventListener(
        endMove,
        function () {
          if (guagua != true) {
            return;
          } else {
            myCaruse.addEventListener(onTheMove, nowMove, false);
          }
        },
        false
      );
      myCaruse.addEventListener(endMove, function () {
        if (guagua != true) {
          return;
        } else {
          document.body.removeEventListener("touchmove", nowVue.bodyScroll, {
            passive: false,
          });
          document.body.parentNode.style.overflow = "auto";
          var allpx = myCaruse.offsetWidth * myCaruse.offsetHeight;
          console.log(nowNum, allpx);
          if (nowNum >= allpx / 8) {
            can.restore();
            console.log(winner);
            if (winner == "未中奖") {
              guagua = false;
              NoPrizeResultPopComService.create(
                "非常遗憾，您与大奖擦肩而过~",
                "//img10.360buyimg.com/imgzone/jfs/t1/136745/32/20121/48059/5fd996feE56314a28/b952f0e6f3fe811f.png",
                (submit) => {
                  NoPrizeResultPopComService.close();
                  nowVue.prerentName = "";
                  window.removeEventListener(startMove, function () {
                    console.log("1111"), false;
                  });
                  window.removeEventListener(onTheMove, function () {
                    console.log("1111"), false;
                  });
                  window.removeEventListener(endMove, function () {
                    console.log("1111"), false;
                  });
                  nowVue.nowGuaGua = false;
                }
              );
              return;
            } else {
              guagua = false;
              prizeData.datas = winner.data;
              nowVue.publicData.$emit(
                "isNotyFiceWinnerReorrd",
                true,
                nowVue.isTemplate
              );
              PrizeResultPopComService.create(
                prizeData,
                winner.data,
                (submit) => {
                  PrizeResultPopComService.close();
                  nowVue.prerentName = "";
                  window.removeEventListener(startMove, function () {
                    console.log("1111"), false;
                  });
                  window.removeEventListener(onTheMove, function () {
                    console.log("1111"), false;
                  });
                  window.removeEventListener(endMove, function () {
                    console.log("1111"), false;
                  });
                  myCaruse.style.display = "none";
                  nowVue.nowGuaGua = false;
                }
              );
              return;
            }
          }
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.start-btn-container {
  width: 5.07rem;
  height: 2.23rem;
  position: absolute;
  left: 50%;
  transform: translate(-50%, 0);
}
.startBtn {
  width: 3.05rem;
  height: 1.08rem;
  position: absolute;
  left: 1rem;
  top: 0.55rem;
  z-index: 100;
}
#card {
  font-size: 0.36rem;
  color: #333;
  position: absolute;
  top: 3.8rem;
  left: 50%;
  transform: translate(-50%, 0);
}
</style>