<template>
  <div :style="styleData.scratchdiv" ref="integralScratch" @click.stop="styleClick('click', 'integralScratch')"
    @mousemove.stop="styleClick('mousemove', 'integralScratch')" @mouseout.stop="styleClick('mouseout')">
    <div style="position:relative;padding-top: 4.1rem;height: 100%;">
      <div id="card" v-if="nowGuaGua && prerentName && isGuaCanvas">{{ prerentName }}</div>
      <canvas id="myCaruse" class="start-btn-container" v-lz-click="'12'" v-if="nowGuaGua && !isWebClick"></canvas>
      <img v-if="!nowGuaGua" :style="styleData.canvasImg" :src="styleData.canvasImg.imageUrl" />
      <img v-if="!nowGuaGua" @click="handlebtn" :style="styleData.startBtn" :src="styleData.startBtn.imageUrl"
        alt="图片加载失败" />
      <div :style="styleData.jfBtn" class="f-tac jf-btn">
        <div :style="styleData.jfBtnIcon"></div>
        <span :style="styleData.jfBtnSpan">{{ pointsPrize }}</span>
        <span> 积分抽奖一次，您当前积分：
          <span style="color:yellow">{{poorScore}}</span>
          分</span>
      </div>
      <div v-if="grantStatus == 3" :style="styleData.jfBtn">
        今日还剩
        <span style="color:yellow">{{drawNum}}</span>
        次抽奖机会
      </div>
      <div v-if="grantStatus == 1" :style="styleData.jfBtn">已达到每天抽奖次数上限，感谢您的参与～</div>
      <div v-if="grantStatus == 2" :style="styleData.jfBtn">已达到活动抽奖次数上限，感谢您的参与～</div>
    </div>
  </div>
</template>
<script>
import bus from '../../../util/bus.js';
import apis1 from '../../../util/apis1.js';
import { Toast } from 'vant';
import { PrizeResultPopComService, NoPrizeResultPopComService,noticePopComService } from '../../../util/hdzxtcomCreate.js';
let { startDraw1, drawPrize, consumePoints,getDrawCountInfoApi,getPoints } = 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: false, //是否抽奖
      isGuaCanvas: false, //是否抽奖后刮画布
      prizeResultData: {
        styleData: {},
        datas: {},
        keyData: {
          prizeUrl: 'showImg',
          prizeName: 'prizeName',
          prizeType: 'prizeType',
          priceInfo: 'priceInfo',
          discountType: 'discountType',
          couponType: 'couponType'
        }
      },
      styleDataOld: {},
      pointsPrize: 0,
      drawNum:0,
      grantStatus:0,
      poorScore:0
    };
  },
  created() {
  },
  mounted() {
    //深拷贝重置需要
    this.styleDataOld = JSON.parse(JSON.stringify(this.styleData));
    this.initData();
  },
  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 {
        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;
      }
      this.prerentName = ''; //奖品名字
      this.nowGuaGua = true; //是否刮奖
      this.isGuaCanvas = false; //是否抽奖后刮画布
      // }
      startDraw1(this.pointsPrize, initDatas => {
        console.log('中奖信息', initDatas);
        if (initDatas.resp_code == 50009) {
          this.$toast('活动已结束');
          this.isStartPlay = false;
          this.nowGuaGua = false
          return;
        }
        if (initDatas.resp_code == 73002 || initDatas.resp_code == 73001) {
          noticePopComService.create(
            initDatas.resp_msg,
              (submit) => {
                noticePopComService.close();
              }
          );
          this.isStartPlay = false;
          this.nowGuaGua = false
          return;
        }

        if (initDatas.resp_code != 0) {
          this.isStartPlay = false;
        }
        if (initDatas.data == '1') {
          this.$toast('积分不足,不可抽奖');
          this.isStartPlay = false;
          this.nowGuaGua = false
          return;
        }
        if (initDatas.data == '2') {
          this.$toast('没有抽奖次数,无法抽奖');
          this.isStartPlay = false;
          this.nowGuaGua = false
          return;
        }

        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(this.scratchList);
              this.pIndex = i;
              console.log('中奖id', this.pIndex);
              this.prize = this.scratchList[this.pIndex].position - 1;
              this.startRoll(initDatas.data.prizeName, this.pIndex); //执行抽奖
              this.winnerDraw = initDatas;
              console.log(this.winnerDraw);
              // 拿到相应的角度调旋转接口

              console.log('奖品id', this.pIndex);
              this.isStartPlay = false;
              noSelect = false;
              break;
            }
          }
          if (noSelect) {

            this.startRoll('未中奖');
            this.winnerDraw = '未中奖';
            this.isStartPlay = false;
          }
        } else {
          this.winnerDraw = '未中奖';
          this.startRoll('未中奖');
        }
        this.canvas(this.winnerDraw);
      });
    },
    async initData() {
      var datasAll = this.templateData;
      if (this.isTemplate == true) {
        if (datasAll) {
          if (datasAll.drawChanceData) {
            this.pointsPrize = datasAll.drawChanceData.integral;
          }
        } else {
          this.pointsPrize = 10;
        }
      } else {
        //请求接口
        await drawPrize(initdatas => {
          console.log(initdatas, 'initdatas');
          let prizeList = initdatas.data.prizeInfo;
          this.restDrawCount = initdatas.data.drawNumber;
          if (prizeList.length != 0) {
            prizeList.forEach(v => {
              this.scratchList.forEach((i, a) => {
                if (v.position == i.id) {
                  this.scratchList[a] = v;
                }
              });
            });
          }
        });
        await consumePoints(datas => {
          this.pointsPrize = datas.data.integral;
        });
        this.getDrawCountInfoFun()
      }
    },
    async getDrawCountInfoFun(){
      await getDrawCountInfoApi(res=>{
          this.drawNum = res.data.drawNum
          this.grantStatus = res.data.grantStatus
        })
       await getPoints(data=>{
        this.poorScore = data.data.poorScore
       })
    },
    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 + 32, y + 30);
        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 - (260 - 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
      );
      var that = this
      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(
                that.styleData,
                submit => {
                  nowVue.publicData.$emit('reShowPrize', true);
                  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;
                  nowVue.isGuaCanvas = false;
                }
              );
              that.getDrawCountInfoFun()
              return;
            } else {
              guagua = false;
              prizeData.datas = winner.data;
              nowVue.publicData.$emit('isNotyFiceWinnerReorrd', true, nowVue.isTemplate);
              PrizeResultPopComService.create(prizeData, winner.data, that.styleData, submit => {
                nowVue.publicData.$emit('reShowPrize', true);
                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;
                nowVue.isGuaCanvas = false;
              });
              that.getDrawCountInfoFun()
              return;
            }
          }
        }
      });
      var a = setTimeout(() => {
        this.isGuaCanvas = true;
        clearTimeout(a);
      }, 500);
    }
  }
};
</script>
<style lang="scss" scoped>
.start-btn-container {
  width: 5.2rem;
  height: 2.3rem;
  position: absolute;
  left: 50%;
  transform: translate(-50%, 0);
  top: 0.5rem;
}
#card {
  font-size: 0.36rem;
  color: #333;
  position: absolute;
  top: 1.16rem;
  left: 50%;
  transform: translate(-50%, 0);
}
</style>
