var loadedImages = {};

function preloadimages(obj, complete_cb, progress_cb) {
    var loaded = 0;
    var toload = 0;
    var images = obj instanceof Array ? [] : {};
    toload = obj.length;
    for (var i = 0; i < obj.length; i++) {
        images[i] = new Image();
        images[i].crossOrigin = "Anonymous";
        images[i].setAttribute('crossOrigin', 'anonymous');
        images[i].url = obj[i];
        images[i].src = obj[i];

        //console.log( images[i].src );
        images[i].onload = load;
        images[i].onerror = load;
        images[i].onabort = load;
    }
    if (obj.length == 0) {
        complete_cb(images);
    }

    function load() {
        loadedImages[this.url] = this;
        ++loaded;
        if (progress_cb) {
            progress_cb(loaded / toload);
        }
        if (loaded >= toload) {
            complete_cb(images);
        }
    }
}
preloadImageList = [
    window.base_resource_url + '/image2/result11.png',
    window.base_resource_url + '/image2/result-1.png',
    window.base_resource_url + '/image2/result-2.png',
    window.base_resource_url + '/image2/result-3.png',
    window.base_resource_url + '/image2/result-4.png',
    window.base_resource_url + '/image2/result-5.png',
    window.base_resource_url + '/image2/result-6.png',
    window.base_resource_url + '/image2/result-7.png',
    window.base_resource_url + '/image2/result-8.png',
    window.base_resource_url + '/image2/result-9.png',
    window.base_resource_url + '/image2/result-10.png',
]
if ($('div').length > 0) {
    $.each($('div'), function (index, val) {
        var img = $(val).css('background-image').replace(/^url\((['"]?)(.*)\1\)$/, '$2');
        img = $.trim(img);
        if (img && img.match(/[^/]+(jpg|png|gif)$/)) {
            preloadImageList.push(img);
        }
    });
}
preloadimages(preloadImageList, function () {
    init();
}, function (progress) {});

window.requestAnimationFrame =
    window.requestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    window.oRequestAnimationFrame ||
    window.msRequestAnimationFrame ||
    function (callback) {
        window.setTimeout(callback, 1000 / 60);
    };

var fireworkCanvas, fireworkCtx, w, h, particles = [],
    probability = 0.04,
    xPoint, yPoint;

var fireworkLock = false;

let posterCanvas, posterCtx;

let scrollTimer,
    showItemStatus = false,
    nowShowIndex = 1,
    createPosterLock = false;

let fixHeight = document.documentElement.clientHeight > 1238 ? document.documentElement.clientHeight : 1238;
let introScrolltop = 0;

let submitLock = false;

const guardian = [
    '事事顺意守',
    '健康祈愿守',
    '金运上升守',
    '心愿成就守',
    '事业向上守',
    '厄运消散守',
    '元气满满守',
    '友谊万岁守',
    '美貌一番守',
    '恋爱成就守'
]

$(document).ready(function () {
    $('.rule-page').on('touchmove', function () {
        return false;
    });
    audioAutoPlay('music')
    $('.bg').css({
        'height': fixHeight + 'px'
    });
    $("input").on("blur", function () {
        window.scroll(0, 0); //失焦后强制让页面归位
    });

    $('.wrap-inner').on('scroll', showItem)

    $('.page1 .btn-next').on('click', toPage2);
    $('.page2 .btn-next').on('click', toPage3);

    $('.scene-1').on('click', {
        scene: 1
    }, toscene)

    $('.scene-2').on('click', {
        scene: 2
    }, toscene)

    $('.scene-3').on('click', {
        scene: 3
    }, toscene)

    $('.result').on('click', showResult)
    $('.btn-retry').on('click', retry)
    $('.page1 .btn-rule').on('click', showRule)
    $('.page1 .btn-intro').on('click', showIntro)
    $('.rule-page .btn-close-rule').on('click', hideRule)
    $('.intro-page .btn-close-intro').on('click', hideIntro)
    $('.page7 .btn-close-second').on('click', hideSecond)
    $('.page7 .btn-share').on('click', showShare)
    $('.share-block').on('click', hideShare)
    $('.btn-close-first').on('click', hideFirst)
    $('.btn-submit').on('click', submitInfo)
    $('.btn-back').on('click', backToMap)
});

function backToMap() {
    $('.page').hide();
    $('.page3').show();
}

function submitInfo() {
    if (!submitLock) {
        submitLock = true;
        const name = $('input[name=name]').val()
        const tel = $('input[name=tel]').val()
        const address = $('input[name=address]').val()

        if (name.match(/^\s*$/)) {
            $('#notification_area').remove();
            my_notify('请输入姓名')
            submitLock = false
            return false;
        }
        if (tel.match(/^\s*$/)) {
            $('#notification_area').remove();
            my_notify('请输入电话')
            submitLock = false
            return false;
        }
        if (!tel.match(/^1\d{10}$/)) {
            $('#notification_area').remove();
            my_notify('电话号码输入有误')
            submitLock = false
            return false;
        }
        if (address.match(/^\s*$/)) {
            $('#notification_area').remove();
            my_notify('请输入地址')
            submitLock = false
            return false;
        }

        $.ajax({
            url: '/index/submitInfo',
            type: 'POST',
            data: {
                name: name,
                tel: tel,
                address: address
            },
            success: function (resp) {
                if (resp.status == 1) {
                    $('#notification_area').remove();
                    my_notify('信息已成功提交', 2000);
                    setTimeout(function () {
                        $('.first-block').hide();
                        $('#notification_area').remove();
                        my_notify('请长按页面保存海报');
                        submitLock = false;
                    }, 2000)

                } else {
                    submitLock = false
                    $('#notification_area').remove();
                    my_notify('网络错误，请重试');
                }
            }
        })
    }
}

function hideFirst() {
    if (!submitLock) {
        $('.first-block').hide();
        $('#notification_area').remove();
        my_notify('请长按页面保存海报');
    }
}

function hideShare() {
    $('.share-block').hide();
}

function showShare() {
    $('.share-block').show();
}

function hideSecond() {
    $('.second-block').hide();
    $('#notification_area').remove();
    my_notify('请长按页面保存海报');
}

function hideIntro() {
    $('.intro-page').hide();

    $('.page1').show();
    $('.wrap-inner').scrollTop($('.wrap-inner')[0].scrollHeight)
    // introScrolltop = 0;
    $('.wrap-inner').css({
        height: '100%',
        overflowY: 'scroll',
        marginTop: '0px',
        top: 0
    })
}

function hideRule() {
    // $('.wrap-inner').scrollTop(introScrolltop);
    // introScrolltop = 0;
    $('.page1').show();
    $('.wrap-inner').scrollTop($('.wrap-inner')[0].scrollHeight)
    $('.rule-page').hide();
    $('.wrap-inner').css({
        height: '100%',
        overflowY: 'scroll',
        overflowX: 'hidden',
        marginTop: '0px',
        top: 0,
    })
}

function showRule() {
    // introScrolltop = $('.wrap-inner').scrollTop();
    $('.wrap-inner').scrollTop(0)
    $('.page1').hide();
    $('.rule-page').show();
    $('.wrap-inner').css({
        height: fixHeight + 'px',
        overflow: 'hidden',
        marginTop: '-619px',
        top: '50%'
    })
}

function showIntro() {
    // introScrolltop = $('.wrap-inner').scrollTop();
    $('.wrap-inner').scrollTop(0);
    $('.page1').hide();
    $('.intro-page').css('height', '100%').show();
    $('.wrap-inner').css({
        height: '100%',
        overflow: 'hidden',
        marginTop: '0px',
        top: 0
    })
}

function audioAutoPlay(id) {
    var audio = document.getElementById(id);
    if (window.WeixinJSBridge) {

        WeixinJSBridge.invoke('getNetworkType', {}, function (e) {
            audio.play();
        }, false);
    } else {

        document.addEventListener("WeixinJSBridgeReady", function () {
            WeixinJSBridge.invoke('getNetworkType', {}, function (e) {
                // alert(4)
                audio.play();
            });
        }, false);
    }
    audio.play();

    return false;
}

function showItem() {
    if (showItemStatus) {
        return false;
    }
    if (scrollTimer !== null) {
        clearTimeout(scrollTimer)
    }
    scrollTimer = setTimeout(() => {
        const scrollTop = $('.wrap-inner').scrollTop();
        const scrollLeft = $('.wrap-inner').scrollLeft();
        if (nowShowIndex == 1 && scrollTop > 700) {
            $('.title,.page1 .cloud').show();
            nowShowIndex++
        } else if (nowShowIndex == 2 && scrollLeft > 380) {
            $('.toast1').show();
            nowShowIndex++
        } else if (nowShowIndex == 3 && scrollLeft > 930) {
            $('.toast2').show();
            showItemStatus = true
        }
    }, 1)
}


function toscene(event) {
    const scene = event.data.scene;
    $('.page').hide()
    $(`.page${scene+3}`).show();
}

function toPage2() {

    $('.wrap-inner').css({
        height: fixHeight + 'px',
        overflowX: 'scroll',
        overflowY: 'hidden',
        marginTop: '-619px',
        top: '50%'
    });

    $('.maruko').css('top', 837 - parseInt(getTranslateDistance()) + 'px')

    $('.page1').hide();
    $('.page2').show();
    fireworkLock = true;
    $('.logo').css({
        top: 'inherit',
        bottom: getTranslateDistance(20)
    })
}

function toPage3() {
    $('.page2').hide();
    $('.page3').show();
}

function showResult(event) {
    window.joinNum++;
    console.log(window.pt)
    if (!createPosterLock) {
        let resultFlag = /-(\d)\s/g.exec($(event.target).attr('class'))[1]
        if (window.pt === '0') {
            $.ajax({
                url: '/index/tryprize',
                type: 'POST',
                success: function (resp) {
                    if (resp.status == 1) {
                        resultFlag = 10
                        dialogFlag = 'first'
                        createPosterLock = true;
                        window.pt = '1'
                    } else {
                        dialogFlag = 'second'
                        createPosterLock = true;
                        window.pt = '2'
                    }
                    createPoster(resultFlag, dialogFlag)
                }
            })
        } else if (window.pt === '2') {
            createPosterLock = true;
            window.pt = '2'
            dialogFlag = 'second'
            createPoster(resultFlag, dialogFlag)

        } else {
            createPoster(resultFlag)
            createPosterLock = true;
        }
    }

}

function retry() {
    $('.wrap-inner').css({
        height: '100%',
        overflowX: 'hidden',
        overflowY: 'scroll',
        marginTop: '0px',
        top: 0,
    })
    $('.page').hide();
    $('.page1').show();
    fireworkLock = false
    updateWorld()
    showItemStatus = false
    nowShowIndex = 1
    $('.title,.toast1,.toast2').hide();
    $('.poster-canvas').html('')
}

function createPoster(resultFlag, dialogFlag = false) {
    $('#notification_area').remove();
    my_notify('正在生成海报，请稍候', 60000);

    let canvasinfo = initCanvas('.poster-canvas', 'posterCanvas', 640 * 2, 1238 * 2);
    posterCanvas = canvasinfo[0];
    posterCtx = canvasinfo[1];
    var posterObj = new Image();
    posterObj.src = '/Public/static/image2/result11.png';
    posterObj.onload = function () {
        posterCtx.drawImage(posterObj, 0, 0, posterCanvas.width, posterCanvas.height);

        var guardObj = new Image();
        guardObj.src = `/Public/static/image2/result-${resultFlag}.png`;
        guardObj.onload = function () {
            posterCtx.drawImage(guardObj, 184 * 2, 350 * 2, 276 * 2, 484 * 2);
            setTimeout(function () {
                drawNum(resultFlag);
            }, 100);
            setTimeout(function () {
                $('.page7 .text').html(`成为樱桃小丸子的第${window.joinNum}个的<br/>祈福伙伴，并获得「${guardian[resultFlag-1]}」`)
                $('.guard').css({
                    background: `url("/Public/static/image2/result-${resultFlag}.png") left top no-repeat`,
                    backgroundSize: '100% 100%'
                })
                $('.poster-canvas').append('<img class="posterimg" />');
                $('.posterimg').attr('src', getManBase64(posterCanvas));
                $('.page').hide();
                $('.page7').show();
                $('#notification_area').remove();
                if (dialogFlag) {
                    setTimeout(function () {
                        $(`.page7 .${dialogFlag}-block`).show();
                        createPosterLock = false;
                    }, 1500);
                } else {
                    createPosterLock = false;
                    my_notify('请长按页面保存海报');
                }
                $('#posterCanvas').css({
                    height: fixHeight + 'px'
                });

            }, 200);
        }
    }
}

function drawNum(resultFlag) {
    // const text1 = `成为樱桃小丸子的第100个的`;
    const text1 = `成为樱桃小丸子的第${window.joinNum}个的`;
    const text2 = `祈福伙伴，并获得「${guardian[resultFlag-1]}」`
    txtDraw(posterCtx, text1, 320, 302, 24, 'bolder', '#748b6c');
    txtDraw(posterCtx, text2, 320, 337, 24, 'bolder', '#748b6c');
}

function txtDraw(ctx, content, x, y, fontsize, fontweight, color) {
    x = x * 2;
    y = y * 2;
    fontsize = fontsize * 2;
    ctx.font = fontweight + ' ' + fontsize + 'px arial';
    var width = ctx.measureText(content).width;
    var cx = x - width / 2;
    ctx.fillStyle = color;
    ctx.fillText(content, cx, y);
}

function getManBase64(canvas) {
    return canvas.toDataURL('image/png');
}

function initCanvas(target, id, canvasWidth, canvasHeight) {
    $(target).append($('<canvas id="' + id + '" width="' + canvasWidth + '" height="' + canvasHeight + '"></canvas>'));
    canvas = $('#' + id)[0];
    ctx = canvas.getContext("2d");
    ctx.scale(2, 2);
    canvas.width = canvasWidth;
    canvas.height = canvasHeight;
    return [canvas, ctx];
}

function deepClone(obj) {

    var objClone = new Particle

    if (obj && typeof obj === 'object') {

        for (key in obj) {
            if (key !== 'children') {
                objClone[key] = obj[key]
            }
        }
    }
    return objClone

}

function getTranslateDistance(cardinal = 0, abs = false) {
    let wrapHeight = parseFloat($('.wrap').css('height'));
    let wrapInnerHeight = parseFloat($('.wrap-inner').css('height'));
    return (wrapInnerHeight - wrapHeight) / 2 + cardinal + 'px';
}

function init() {
    inited = true;
    $('input[name=name]').attr('maxLength', 10)
    $('input[name=tel]').attr('maxLength', 11).attr('type', 'number')
    $('.page6').append('<div class="leaves leaves-1"></div><div class="leaves leaves-2"></div><div class="leaves leaves-3"></div>');
    $('.page1').show();
    resizeCanvas();
    onLoad();
    window.addEventListener("resize", resizeCanvas, false);
}

function onLoad() {
    $('.canvas-block').html('<canvas id="fireworkCanvas"></canvas>');
    fireworkCanvas = document.getElementById("fireworkCanvas");
    fireworkCtx = fireworkCanvas.getContext("2d");
    resizeCanvas();

    window.requestAnimationFrame(updateWorld);
}

function resizeCanvas() {
    if (!!fireworkCanvas) {
        w = fireworkCanvas.width = 640;
        h = fireworkCanvas.height = 1400;
    }
}

function updateWorld() {
    fireworkCanvas.width = 641;
    fireworkCanvas.width = 640;
    update();
    paint();
    if (!fireworkLock) {
        window.requestAnimationFrame(updateWorld);
    }
}

function update() {
    if (particles.length < 100) {
        createFirework();
    }
    var alive = [];
    for (var i = 0; i < particles.length; i++) {
        oldParticle = deepClone(particles[i])
        if (particles[i].move()) {
            alive.push(particles[i]);
            particles[i].children.push(oldParticle)
            if (particles[i].children.length > 5) {
                particles[i].children.splice(0, 1)
            }
        }
    }
    particles = alive;
}

function paint() {
    fireworkCtx.globalCompositeOperation = 'lighter';
    for (var i = 0; i < particles.length; i++) {
        particles[i].draw(fireworkCtx);
        for (k in particles[i].children) {
            particles[i].children[k].w -= 0.205
            particles[i].children[k].draw(fireworkCtx)
        }
    }
}

function createFirework() {
    xPoint = Math.random() * (w - 200) + 100;
    yPoint = Math.random() * (h - 500) + 100;
    var nFire = Math.random() * 50 + 30;
    // var nFire = 1;
    var c = "rgb(" + (~~(Math.random() * 200 + 55)) + "," +
        (~~(Math.random() * 200 + 55)) + "," + (~~(Math.random() * 200 + 55)) + ")";
    for (var i = 0; i < nFire; i++) {
        var particle = new Particle();
        particle.color = c;
        var vy = Math.sqrt(25 - particle.vx * particle.vx);
        if (Math.abs(particle.vy) > vy) {
            particle.vy = particle.vy > 0 ? vy : -vy;
        }
        particles.push(particle);
    }
}

function Particle() {
    this.w = this.h = 1.5;

    this.x = xPoint - this.w / 2;
    this.y = yPoint - this.h / 2;

    this.vx = (Math.random() - 0.5) * 10;
    this.vy = (Math.random() - 0.5) * 10;

    this.alpha = Math.random() * .5 + .5;

    this.color;
    this.children = [];
}

Particle.prototype = {
    gravity: 0.05,
    move: function () {
        this.x += this.vx;
        this.vy += this.gravity;
        this.y += this.vy;
        this.alpha -= 0.01;
        if (this.x <= -this.w || this.x >= fireworkCanvas.width ||
            this.y >= fireworkCanvas.height ||
            this.alpha <= 0) {
            this.alpha = 0
            return false;
        }
        return true;
    },
    draw: function (c) {
        c.save();
        c.beginPath();
        this.w = this.w >= 0 ? this.w : 0.09
        c.translate(this.x + this.w / 2, this.y + this.h / 2);
        c.arc(0, 0, this.w, 0, Math.PI * 2);
        c.fillStyle = this.color;
        c.globalAlpha = this.alpha;

        c.closePath();
        c.fill();
        c.restore();
    }
}