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 = []
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 canvas, ctx, w, h, particles = [],
    probability = 0.04,
    xPoint, yPoint;

var fireworkLock = false;

let posterCanvas, posterCtx;

$(document).ready(function () {
    if ($('.page').height() < document.documentElement.clientHeight) {
        var scale = document.documentElement.clientHeight / $('.page').height();
        $('.bg').css({
            'transform': 'scale(1,' + scale + ')'
        });
    }
    $('.container').css('height', document.documentElement.clientHeight + 'px');
    var fixHeight = Math.abs($('.page').height() - document.documentElement.clientHeight) / 2;
    $('.logo').css('top', fixHeight + 30 + 'px');
    $("input").on("blur", function () {
        window.scroll(0, 0); //失焦后强制让页面归位
    });

    $('.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', {
        resultFlag: this.attr('class').replace(/[^0-9]/ig, "")
    }, showResult)
});


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

function toPage2() {
    $('.container').css('overflow-x', 'scroll').css('overflow-y', 'hidden');
    $('.page1').hide();
    $('.page2').show();
    fireworkLock = true;
}

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

function showResult(event) {
    const resultFlag = event.data.resultFlag
    console.log(resultFlag)
}

function createPoster(resultFlag) {
    $('#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/result-' + resultFlag + '.jpg';
    posterObj.onload = function () {
        posterCtx.drawImage(posterObj, 0, 0, posterCanvas.width, posterCanvas.height);
        setTimeout(function () {
            drawNum();
        }, 200);
        setTimeout(function () {
            $('.poster-canvas').append('<img class="posterimg" />');
            $('.posterimg').attr('src', getManBase64(posterCanvas));
            $('.page').hide();
            $('.page7').show();
            $('#notification_area').remove();
            createPosterLock = false;
        }, 500);
    }
}

function drawNum() {
    posterCtx.font = 'normal ' + '48px normal';
    let text1 = '已有';
    let text2 = '人发起承诺';
    let text1Width = posterCtx.measureText(text1).width;
    let text2Width = posterCtx.measureText(text2).width;
    posterCtx.font = 'normal ' + '80px num';
    let numWidth = posterCtx.measureText(window.num).width;
    let totalWidth = text1Width + 10 * 2 + numWidth + 6 * 2 + text2Width;
    let text1X = 212 * 2 - totalWidth / 2;
    let numX = text1X + text1Width + 10 * 2;
    let text2X = numX + numWidth + 6 * 2;
    txtDraw(posterCtx, window.num, '#fff', numX, 557 * 2);
    posterCtx.font = 'normal ' + '48px normal';
    txtDraw(posterCtx, text1, '#fff', text1X, 557 * 2);
    txtDraw(posterCtx, text2, '#fff', text2X, 557 * 2);
}

function txtDraw(ctx, content, x, y, fontsize, fontweight, color, textAlign = 'left', rightReserved = 0, stroke = false) {
    x = x * 2;
    y = y * 2;
    fontsize = fontsize * 2;
    ctx.font = fontweight + ' ' + fontsize + 'px arial';
    if (stroke) {
        //设置描边颜色
        ctx.strokeStyle = "#494949";
        //设置描边宽度
        ctx.lineWidth = 7;
    }
    if (textAlign == 'center') {
        var width = ctx.measureText(content).width;
        var cx = x - width / 2;
        ctx.fillStyle = color;
        ctx.fillText(content, cx, y);
    } else if (textAlign == 'right') {
        var width = ctx.measureText(content).width;
        var cx = x - width;
        if (rightReserved) {
            cx = x - width - rightReserved;
        }
        ctx.fillStyle = color;
        ctx.fillText(content, cx, y);
        return width;
    } else {
        ctx.fillStyle = color;
        if (stroke) {
            ctx.strokeText(content, x, y);
        }
        ctx.fillText(content, x, y);
    }

}

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

function initCanvas(target, id, canvasWidth, canvasHeight) {
    black = loadedImages[blackUrl];
    $(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 init() {
    inited = true;
    $('.page1').show();
    window.addEventListener("resize", resizeCanvas, false);
    window.addEventListener("DOMContentLoaded", onLoad, false);
}

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

    window.requestAnimationFrame(updateWorld);
}

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

function updateWorld() {
    canvas.width = 641;
    canvas.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() {
    ctx.globalCompositeOperation = 'lighter';
    for (var i = 0; i < particles.length; i++) {
        particles[i].draw(ctx);
        for (k in particles[i].children) {
            particles[i].children[k].w -= 0.205
            particles[i].children[k].draw(ctx)
        }
    }
}

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 >= canvas.width ||
            this.y >= canvas.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();
    }
}