<template><page-meta :root-font-size="fontSize+'px'"></page-meta>
  <home-base :show="false" >
    <view class="div home-marketcard">
      <view class="div marketcard-logo">
        <image mode="aspectFit" class="img" :src="marketcardlogo">
      </view>
      <view class="div scratchcard-bg">
        <view class="div scratchcard" :style="'width:'+cardWidth+'px; height:'+cardHeight+'px'">
          <canvas :style="'width:'+cardWidth+'px;height:'+cardHeight+'px'" @mousedown="touchstart"
            @mousemove="touchmove" @mouseup="touchend" @touchstart="touchstart"
            @touchmove="touchmove" @touchend="touchend" ref="canvas" canvas-id="scratch-card" class="scratchcard-overlay"></canvas>
          <view class="div scratchcard-content">
            <view class="div" v-if="isResult">
              <view class="div result-area" :class="drawResult?'suc':'fail'">
                <view class="div face-area"></view>
                <view class="div result-content-wap">
                  <view class="p result-title">{{drawTitle}}</view>
                  <view class="p result-content">{{drawContent}}</view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
      <view class="div marketcard-info" v-if="marketmanage_info">
        <view class="div title">活动名称：</view>
        <view class="div content">{{marketmanage_info.marketmanage_name}}</view>
        <view class="div title">活动介绍：</view>
        <view class="div content">{{marketmanage_info.marketmanage_detail}}</view>
        <view class="div title">活动有效时间：</view>
        <view class="div content">
          {{marketmanage_info.marketmanage_begintime_text}}至{{marketmanage_info.marketmanage_endtime_text}}</view>
        <view class="div title">活动奖项设置：</view>
        <view class="div content">
          <view class="div" v-for="(marketmanageaward,index) in marketmanageaward_list" :key="index">
            {{marketmanageaward.marketmanageaward_level}}等奖{{marketmanageaward.marketmanageaward_probability}}%：{{marketmanageaward.marketmanageaward_text}}
          </view>
        </view>
      </view>
      <view class="div btn-wrapper">
        <view class="div btn">
          <view class="div common-btn ds-button-large" @click="reset" v-if="canDraw">再刮一次</view>
          <view class="div common-btn ds-button-large" v-else>机会用完了</view>
        </view>
        <view class="div btn">
          <view class="div common-btn ds-button-large" @click="goLog">刮奖记录</view>
        </view>
      </view>
    </view>
  </home-base>
</template>

<script>
import {getFontSize} from '@/util/common'
import { env } from '../../../static/config'
  import HomeBase from '../HomeBase'
  import {
    getMarketmanageInfo,
    addMarketmanagelog
  } from '../../../api/homeMarketmanage'
  import {
    mapState
  } from 'vuex'
  let ctx = null;
  export default {
    name: 'Marketcard',
    data() {
      return {
        scrollTop: 0,
        marketmanage_id: 0,
        marketmanage_info: false,
        marketmanageaward_list: false,
        cardWidth: 260,
        cardHeight: 132,
        startX: null,
        startY: null,
        computing: false,
        complete: false,
        isScrape: false,
        ready: false,
        isResult: false,
        drawResult: false,
        drawTitle: '真遗憾，未中奖',
        drawContent: '哎呀，肯定姿势不对！',
        canDraw: false,
		marketcardlogo: env.SITE_URL+'/uploads/home/h5/home/home-marketcard-logo.png'
      }
    },
    components: {
      HomeBase,
    },
    computed:{
      fontSize(){
        return getFontSize()
      },
      ...mapState({
        isOnline: state => state.member.isOnline,
        token: state => state.member.token
      })
    },
    onLoad: function(option) {
      this.marketmanage_id = option.marketmanage_id
      if (!this.marketmanage_id) {
        uni.showToast({
          icon: 'none',
          title: '参数错误'
        })
        return
      }
      getMarketmanageInfo(this.marketmanage_id, this.token).then(res => {
        this.marketmanage_info = res.result.marketmanage_info
        this.marketmanageaward_list = res.result.marketmanageaward_list
        this.canDraw = res.result.can_draw
        this.drawContent = this.marketmanage_info.marketmanage_failed
        if (!this.canDraw) {
          uni.showToast({
            icon: 'none',
            title: res.message
          })
        }
      }).catch(function(error) {
        uni.showToast({
          icon: 'none',
          title: error.message
        })
      })
    },
    onPageScroll: function(e) { //nvue暂不支持滚动监听，可用bindingx代替
      this.scrollTop = e.scrollTop
    },
    methods: {
      goLog() {
        uni.navigateTo({
          url: '/pages/member/marketmanagelog/Marketmanagelog'
        })
      },
      initCanvas() {
        this.computing = false;
        this.complete = false;
        this.isScrape = false;
        this.ready = false;
        ctx.clearRect(0, 0, this.cardWidth, this.cardHeight);
        //绘制画布
        ctx.setFillStyle('#eee');
        ctx.fillRect(0, 0, this.cardWidth, this.cardHeight);
        this.ready = true;
        //绘制文字水印
        this.fillWatermark();
        ctx.draw();
      },
      /**
       * 绘制文字水印
       */
      fillWatermark: function(e) {
        var watermark = '刮一刮'
        var watermarkSize = 14
        var width = watermark.length * watermarkSize;
        ctx.save();
        ctx.rotate(-10 * Math.PI / 180);
        let x = 0;
        let y = 0;
        let i = 0;
        while ((x <= this.cardWidth * 5 || y <= this.cardHeight * 5) && i < 300) {
          ctx.setFillStyle('#999');
          ctx.setFontSize(watermarkSize);
          ctx.fillText(watermark, x, y);
          x += width + width * 1.6;
          if (x > this.cardWidth && y <= this.cardHeight) {
            x = -Math.random() * 100;
            y += watermarkSize * 3;
          }
          i++;
        }
        ctx.restore();
      },

      touchstart: function(e) {
        if (!this.canDraw) {
          return;
        }
        this.startX = e.touches[0].x;
        this.startY = e.touches[0].y;
      },

      touchend: function(e) {
        this.getFilledPercentage();
      },

      touchmove: function(e) {
        if (this.complete || !this.canDraw) {
          return;
        }
        // ctx.globalCompositeOperation = 'destination-out'; 
        ctx.moveTo(this.startX, this.startY);
        // ctx.beginPath();
        // ctx.arc(this.startX, this.startY, 20, 0, Math.PI * 20);
        // ctx.fill();
        ctx.clearRect(this.startX, this.startY, 20, 20);
        ctx.draw(true);
        //记录移动点位
        this.startX = e.touches[0].x;
        this.startY = e.touches[0].y;
      },

      getFilledPercentage: function(e) {
        if (this.computing) {
          return;
        }
        this.computing = true;
        ctx.moveTo(0, 0);
        ctx.clearRect(0, 0, this.cardWidth, this.cardHeight);
        ctx.stroke();
        ctx.draw(true);
        uni.canvasGetImageData({
          canvasId: 'scratch-card',
          x: 0,
          y: 0,
          width: this.cardWidth,
          height: this.cardHeight,
          success: (res) => {
            let pixels = res.data;
            let transPixels = [];
            for (let i = 0; i < pixels.length; i += 4) {
              if (pixels[i + 3] < 128) {
                transPixels.push(pixels[i + 3]);
              }
            }
            var percent = (transPixels.length / (pixels.length / 4) * 100).toFixed(2);
            if (percent >= 10) {
              this.addMarketmanagelog();
            }
            this.computing = false;
            console.log(percent)
          },
          fail: function(e) {
            console.log(e);
          },
        }, this);
      },
      reset() {
        // 重置
        this.isScrape = false
        this.drawResult = false
        this.isFinished = false
        this.isResult = false
        this.initCanvas()
        this.drawImage()
        this.drawTitle = '真遗憾，未中奖'
        this.drawContent = this.marketmanage_info.marketmanage_failed
      },
      addMarketmanagelog() {
        this.complete = true;
        if (this.isScrape) {
          return;
        }
        this.isScrape = true;
        // 消耗刮卡机会
        addMarketmanagelog(this.marketmanage_id).then(res => {
          this.canDraw = res.result.can_draw
          this.isResult = true
          if (res.result.draw_result) { // 中奖
            this.drawResult = true
            this.drawTitle = '恭喜你，获得' + res.result.draw_info.marketmanageaward_level + '等奖'
            this.drawContent = res.result.draw_info.marketmanageaward_text
          }
        }).catch(function(error) {
          uni.showToast({
            icon: 'none',
            title: error.message
          })
        })

      },
    },
    mounted() {
      ctx = uni.createCanvasContext("scratch-card", this);
      this.initCanvas()
    }
  }
</script>

<style scoped lang="scss">
  .home-marketcard {
    background-color: #f81213;
    background-image: url(../../../static/image/home/home-marketcard-bg.png);
    background-repeat: repeat-x;
    position: fixed;
    width: 100%;
    height: 100%;
    overflow-y: auto;
  }

  .marketcard-logo {
    text-align: center;

    .img {
      width: 14rem;
	  height: 5.5rem;
      margin-top: 1rem;
    }
  }

  .scratchcard-bg {
    width: 274px;
    height: 132px;
    padding: 7px 0;
    margin: 1rem auto 0;
    position: relative;
    background: url(../../../static/image/home/home-marketcard-wrapper.png) no-repeat;
    background-size: 100%
  }

  .scratchcard {
    position: relative;
    display: block;
    margin-left: 7px;
  }

  .scratchcard>* {

    position: absolute;
    width: 100%;
    height: 100%;
    display: block;
  }

  .scratchcard-overlay {
    z-index: 1;
  }

  .marketcard-info {
    color: #fff;
    padding: 0 1rem;
    margin-top: 1rem;
    font-size: $fontSize;

    .content {
      margin-bottom: 1rem;
    }
  }

  .btn-wrapper {
    display: flex;
    padding: .75rem;

    .btn {
      padding: .25rem;
      flex: 1
    }
  }

  .home-marketcard .result-area {
    background-color: #f1d183;
    position: absolute;
    display: table;
    width: 260px;
    height: 132px;
    line-height: 1.5em;
    color: #e03021;
    text-align: center;
    font-weight: bold;
    top: 0;
  }

  .home-marketcard .result-area .result-content-wap {
    display: table-cell;
    vertical-align: middle;
    word-break: break-all;
    padding: 0 20px
  }

  .home-marketcard .result-area .face-area {
    position: absolute;
    top: 27px;
    left: 8px;
    width: 76px;
    height: 76px;
    background-size: cover
  }

  .home-marketcard .result-area .result-title {
    font-size: $h1
  }

  .home-marketcard .result-area .result-content {
    font-size: 1.1rem;
    margin-top: 5px
  }

  .home-marketcard .result-area.suc .result-content-wap,
  .home-marketcard .result-area.fail .result-content-wap {
    width: 150px;
    text-align: left
  }

  .home-marketcard .result-area.suc .face-area {
    background-image: url("../../../static/image/home/home-marketcard-suc.png")
  }

  .home-marketcard .result-area.suc .result-title {
    font-size: $subFontSize;
    color: #4e3735
  }

  .home-marketcard .result-area.suc .result-content {
    font-size: $h1;
    color: #e03021
  }

  .home-marketcard .result-area.fail .face-area {
    background-image: url("../../../static/image/home/home-marketcard-fail.png")
  }

  .home-marketcard .result-area.fail .result-title {
    font-size: $h2;
    color: #372f2f
  }

  .home-marketcard .result-area.fail .result-content {
    font-size: $subFontSize;
    color: #584c3c
  }
</style>
