var doc = document

var getId = (id) => {
    return doc.getElementById(id)
}
var getStyle = (ele, pseudoElt) => {
    return window.getComputedStyle(ele, pseudoElt)
}
var getTop = function (e) {
    var offset = e.offsetTop;
    if (e.offsetParent != null) offset += getTop(e.offsetParent);
    return offset;
}
//获取元素的横坐标（相对于窗口）
var getLeft = function (e) {
    var offset = e.offsetLeft;
    if (e.offsetParent != null) offset += getLeft(e.offsetParent);
    return offset;
}

function getParam(name) {
    var getParam2 = function (name, str) {
        //获取参数name的值
        var reg = new RegExp("(^|!|&|\\?)" + name + "=([^&]*)(&|$)");

        //再获取?后面的参数
        r = str.match(reg);
        if (r != null) {
            try {
                return decodeURIComponent(r[2]);
            } catch (e) {
                console.log(e + "r[2]:" + r[2]);
                return null;
            }
        }
        return null;
    }

    //先获取#后面的参数
    var str = document.location.hash.substr(2);
    var value = getParam2(name, str);
    if (value == null) {
        str = document.location.search.substr(1);
        value = getParam2(name, str);
    }

    return value;
};

class pageIndex {
    constructor(id) {
        this.canvas = getId(id)//canvas 
        this.ctx = this.canvas.getContext('2d')//canvas ctx
        this.wrap = this.canvas.parentNode//canvas's wrap
        this.offsetTop = getTop(this.canvas)
        this.offsetLeft = getLeft(this.canvas)
        this.wrapStyle = getStyle(this.wrap)
        this.width = Math.floor(this.wrapStyle.width.slice(0, -2))
        this.height = Math.floor(this.wrapStyle.height.slice(0, -2))
        this.canvasBg = __inline('../../img/canvas-bg.png')
        this.retTpl = __inline('../../tpl/result.tmpl')
        this.init()

        return this
    }

    static formatTime(time) {
        time = time.replace(/-/g, '/');
        var _date = new Date(time),
            year = _date.getFullYear(),
            month = _date.getMonth() + 1,
            date = _date.getDate(),
            hour = _date.getHours(),
            minute = _date.getMinutes()
        return `${[`${month}月`, `${date}日`].join('')} ${hour}：${minute<10?`0${minute}`:minute}`
    }

    static formatCode(str) {
        var len = str.length
        var index = 0
        var newStr = ''
        while (index < len) {
            if (index != 0 && index % 4 == 0) {
                newStr += '-'
            }
            var _str = str.charAt(index)
            newStr += _str
            index++
        }

        return newStr
    }

    init() {
        if (this.checkWx()) {
            this.getData().initWd().initBg().setTouch()
        } else {
            var dialog = getId('dialogTip')
            dialog.classList.add('fadeIn')
            this.initWd().initBg().setTouch()
        }

    }

    checkWx() {
        var ua = window.navigator.userAgent.toLowerCase();
        if (ua.match(/MicroMessenger/i) == 'micromessenger') {
            return true;
        } else {
            return false;
        }
    }

    getData() {
        var id = getParam("id")

        var script = doc.createElement('script')

        script.src = `http://mka.duowan.com/activity/lucky?callback=jQuery1_1&_from=${location.href}&id=${id}`

        doc.getElementsByTagName('head')[0].appendChild(script)

        window.jQuery1_1 = (function (ret) {

            if (ret.code == 0) {
                if (ret.data.is_new == 0) {
                    this.ctx.clearRect(0, 0, this.width, this.height)
                }
                var scratchRet = doc.getElementsByClassName('scratch-ret')[0],
                    appendEle = doc.createElement('div')

                appendEle.innerHTML = this.retTpl({ data: ret.data })
                scratchRet.appendChild(appendEle.children[0])

                getId('startTime').innerHTML = pageIndex.formatTime(ret.data.start_time)
                getId('endTime').innerHTML = pageIndex.formatTime(ret.data.end_time)
                getId('rewardTime').innerHTML = pageIndex.formatTime(ret.data.end_time)
                getId('endRewardTime').innerHTML = pageIndex.formatTime(ret.data.reward_end)
                getId('rewardTips').classList.add('fadeIn')
            } else if (ret.code == -7) {
                //登录跳转
                location.href = ret.url
            } else {
                alert(ret.msg)
            }


        }).bind(this)

        return this
    }

    /**初始化canvas宽高 */
    initWd() {
        this.canvas.width = this.width
        this.canvas.height = this.height

        return this
    }
    initBg() {
        var self = this
        /**背景颜色 */
        this.ctx.fillStyle = "#ebeaee"
        this.ctx.globalCompositeOperation = "destination-over"; //与destination-out实现擦除效果 
        this.ctx.beginPath()
        this.ctx.fillRect(0, 0, this.width, this.height)
        this.ctx.closePath()

        this.ctx.globalCompositeOperation = "source-over"
        /**背景图片 */
        var bg = new Image()
        bg.src = this.canvasBg
        bg.onload = function () {
            self.ctx.drawImage(bg, 0, 0, self.width, self.height)
            /**文本 */
            self.ctx.fillStyle = "#bb8c49"
            self.ctx.font = '30px Microsoft Yahei'
            self.ctx.textAlign = 'center'
            self.ctx.textBaseline = 'middle'
            self.ctx.fillText('刮开您的抽奖码', self.width / 2, self.height / 2)
        }

        setTimeout(function () {
            self.wrap.style.visibility = 'visible'
        }, 1);
        return this
    }
    setTouch() {
        this.wrap.addEventListener('touchmove', this.AfterTouch.bind(this), false)
        this.wrap.addEventListener('touchstart', this.AfterTouch.bind(this), false)
        this.wrap.addEventListener('touchend', this.AfterTouch.bind(this), false)

        return this
    }
    /**清除触摸区域 */
    AfterTouch(e) {
        if (this.finished) return
        var cor = e.changedTouches && e.changedTouches[0]
        if (cor) {
            this.ctx.globalCompositeOperation = "destination-out";
            this.ctx.beginPath();
            this.ctx.arc(cor.pageX - this.offsetLeft, cor.pageY - this.offsetTop, cor.radiusX && cor.radiusX < 10 ? 10 : cor.radiusX || 10, 0, 2 * Math.PI, true);
            this.ctx.fill();
            this.ctx.closePath();
        }
        this.checkArea()
        e.preventDefault()
    }
    /**判断清除区域是否大于60% */
    checkArea() {
        var count = 0
        var data = this.ctx.getImageData(this.width / 6, this.height / 6, this.width / 1.5, this.height / 1.5).data;
        for (var i = 0, len = data.length; i < len; i += 4) {
            if (data[i] && data[i + 1] && data[i + 2] && data[i + 3]) {
                count++;
            }
        }
        if (count <= this.height * this.width * 4 / 9 * 0.2) {
            this.finished = true
            var self = this
            //每隔20ms绘制一个圆形空白区形成清除动画
            var radius = this.width > this.height ? this.width : this.height
            for (var r = 1; r <= radius; r++) {
                setTimeout((function (r) {
                    return function () {
                        self.ctx.arc(self.width / 2, self.height / 2, r, 0, 2 * Math.PI, true);
                        self.ctx.fill()
                    }
                })(r), 20);
            }
        }
        return this
    }
}

document.addEventListener('DOMContentLoaded', function () {
    new pageIndex('cardLayer')
    // new pageIndex('cardLayer2')
}, false)