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].src = obj[i];
        images[i].url = 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);
        }
    }
}
var picUrl = window.base_resource_url + '/images/';
var preloadImageList = [
    // picUrl + 'share.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);
        }
    });
}


$('.page1').show();
$('input[name=name]').attr('placeholder', '姓名');
$('input[name=business]').attr('placeholder', '业务号');
$('.page1 .num').html('已有 <span class="numbig">' + window.num + '</span> 人发起承诺');
//上传canvas定义
let canvasinfo = initCanvas('.block', 'uploadCanvas', 257, 257),
    uploadCanvas = canvasinfo[0],
    uploadCtx = canvasinfo[1];

let imgInfo = {};
var blackUrl, black;


blackUrl = $('.block').css('background-image').replace(/^url\((['"]?)(.*)\1\)$/, '$2');
preloadimages(preloadImageList, function () {}, function (progress) {});

$(document).ready(function () {
    $('.logo').css('top', getTranslateDistance(20));
    $('.music').click(function () {
        if ($('#music')[0].paused) {
            $('#music')[0].play();
            $('.music.stop').hide();
            $('.music.play').show();
            musicStatus = true;
        } else {
            $('#music')[0].pause();
            $('.music.play').hide();
            $('.music.stop').show();
            musicStatus = false;
        }
    });
    $('input[name=btn-upload]').change(function () {
        $('.regulate-block').show();
        bindUpload(this, uploadCtx, uploadCanvas, 1, function (img) {
            var mc = new Hammer($('#uploadCanvas').get(0));
            bindMc(mc, uploadCtx, uploadCanvas, img, imgInfo);
        }, imgInfo);
        return false;
    });

});

function bindMc(mc, ctx, myCanvas, img, imgInfo) {
    mc.get('pan').set({
        direction: Hammer.DIRECTION_ALL
    });
    mc.get('pinch').set({
        enable: true
    });
    mc.get('rotate').set({
        enable: true
    });
    var oldpoz = {};
    mc.on('panstart panmove panend', function (event) {
        event.preventDefault();
        if (!img) {
            return;
        }
        if (event.type == 'panstart' || event.type == 'panend') {
            oldpoz.x = 0;
            oldpoz.y = 0;
        } else {
            var movedX = (event.deltaX - oldpoz.x);
            var movedY = (event.deltaY - oldpoz.y);
            oldpoz.x = event.deltaX;
            oldpoz.y = event.deltaY;
            //console.log("movedX:" + movedX + ' movedY:' + movedY + 'event.deltaX:' + event.deltaX + ' event.deltaY:' + event.deltaY + "\r\n");
            imgInfo.x += movedX;
            imgInfo.y += movedY;
            drawImage(ctx, myCanvas, img, imgInfo);
        }
    });
    var oldScale = 1;
    mc.on('pinchstart pinchmove pinchend', function (event) {
        event.preventDefault();
        if (!img) {
            return;
        }
        if (event.type == 'pinchstart' || event.type == 'pinchend') {
            oldScale = 1;
        } else {
            var nowScale = event.scale / oldScale;
            oldScale = event.scale;
            imgInfo.scale *= nowScale;
            drawImage(ctx, myCanvas, img, imgInfo);
        }
    });
    var oldRotation = 0;
    mc.on('rotatestart rotatemove rotateend', function (event) {
        event.preventDefault();
        if (!img) {
            return;
        }
        if (event.type == 'rotatestart' || event.type == 'rotateend') {
            oldRotation = 0;
        } else {
            nowRotation = event.rotation - oldRotation;
            oldRotation = event.rotation;
            imgInfo.rotation += nowRotation;
            drawImage(ctx, myCanvas, img, imgInfo);
        }
    });
}

function bindUpload(that, ctx, myCanvas, index, callback, imgInfo) {
    imgInfo.rotation = 0;
    imgInfo.x = 0;
    imgInfo.y = 0;
    imgInfo.scale = 1;
    event.preventDefault();
    var imgData = that.files[0];
    EXIF.getData(imgData, function () {
        //获取旋转信息
        var orientation = EXIF.getTag(this, "Orientation");
        switch (orientation) {
            case 3:
                imgInfo.rotation = 180;
                break;
            case 6:
                imgInfo.rotation = 90;
                break;
            case 8:
                imgInfo.rotation = 270;
                break;
            default:
                imgInfo.rotation = 0;
        }
        if (navigator.userAgent.indexOf('iPhone') > -1) {
            imgInfo.rotation = 0;
        }
        lrz(imgData, {
            width: 640
        }, function (results) {
            img = new Image();
            img.onload = function () {
                drawImage(ctx, myCanvas, img, imgInfo);
                results = null;
                imgData = null;
            };
            img.src = results.base64;
            console.log(img.src);
            // headimg[index] = img;
            callback(img);
        });
    });
}


var drawImage = function (ctx, myCanvas, img, imgInfo) {
    ctx.save();
    ctx.clearRect(0, 0, myCanvas.width, myCanvas.height);
    ctx.drawImage(black, 0, 0);
    ctx.globalCompositeOperation = 'source-in';
    ctx.translate(myCanvas.width / 2, myCanvas.height / 2);
    ctx.translate(imgInfo.x, imgInfo.y);
    ctx.rotate(Math.PI / 180 * imgInfo.rotation);
    ctx.scale(imgInfo.scale, imgInfo.scale);
    ctx.drawImage(img, -img.width / 2, -img.height / 2);
    ctx.restore();
}

function initCanvas(target, id, canvasWidth, canvasHeight, useRem = false) {
    console.log(1);
    if (useRem) {
        canvasWidth = pxToRem(canvasWidth);
        canvasHeight = pxToRem(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 getTranslateDistance(cardinal = 0, abs = false) {
    var wrapInnerTransform = $('.wrap-inner').css('transform');
    var wrapInnertop = parseFloat($('.wrap-inner').css('top'));
    wrapInnerTransform = wrapInnerTransform.match(/^matrix\(1,\s0,\s0,\s1,\s0,\s\-?(\d+)/);
    wrapInnerTransform = parseFloat(wrapInnerTransform[1]);
    if (abs) {
        var wrapInnerjl = Math.abs(wrapInnertop - wrapInnerTransform);
    } else {
        var wrapInnerjl = wrapInnertop - wrapInnerTransform;
    }

    return wrapInnerjl + cardinal + 'px';
}

//获取随机数方法
//min 最小值
//max 最大值
function RandomNumBoth(Min, Max) {
    var Range = Max - Min;
    var Rand = Math.random();
    var num = Min + Math.round(Rand * Range); //四舍五入
    return num;
}