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', '姓名').attr('id', 'name');;
$('input[name=business]').attr('placeholder', '业务号').attr('type', 'tel').attr('maxlength', 10);
$('.page1 .num').html('已有 <span class="numbig">' + window.num + '</span> 人发起承诺');
//上传canvas定义


let imgInfo = {};
let blackUrl, black;
let uploadCanvas, uploadCtx;
let avatar;
let nowPosterIndex = '';
let posterCanvas, posterCtx;
let idInfo = {
    width: 15,
    height: 16
};
let noInfo = {
    width: 24,
    height: 12
}

preloadimages(preloadImageList, function () {
    blackUrl = $('.black').css('background-image').replace(/^url\((['"]?)(.*)\1\)$/, '$2');
    $('.black').css('background-image', 'none');
    let canvasinfo = initCanvas('.black', 'uploadCanvas', 259, 259);
    uploadCanvas = canvasinfo[0];
    uploadCtx = canvasinfo[1];
}, function (progress) {});

$(document).ready(function () {

    $('.logo').css('top', getTranslateDistance(), true);
    $('.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();
        imgInfo = {};
        img = '';
        bindUpload(this, uploadCtx, uploadCanvas, 1, function (img) {
            avatar = img;
            var mc = new Hammer($('#uploadCanvas').get(0));
            bindMc(mc, uploadCtx, uploadCanvas, img, imgInfo);
        }, imgInfo);
        return false;
    });
    $('.btn-retry').on('click', () => {
        $('input[name=btn-upload]').click()
    });
    //署名输入框限制长度事件
    $('.page1 input[name=name]').on('input propertychange', inputLength);
    //上传头像确认
    $('.page1 .btn-ok').on('click', confirmAvatar);
    //检查用户输入后生成海报
    $('.page1 .btn-go').on('click', checkInfo);
    //返回到首页
    $('.poster-page .btn-backtohome').on('click', backToHome);
    //换一句
    $('.poster-page .btn-change').on('click', changePoster);
});

function changePoster() {
    let name = $('input[name=name]').val();
    let business = $('input[name=business]').val();
    createPoster(name, business);
}

function backToHome() {
    $('.poster-page').hide();
    $('.page1').show();
}

function checkInfo() {
    let name = $('input[name=name]').val();
    let business = $('input[name=business]').val();
    name = '张三三';
    business = '1234567890';
    // if (name.match(/^\s*$/)) {
    //     $('#notification_area').remove();
    //     my_notify('请填写姓名');
    //     return false;
    // }
    // if (!business.match(/^\d{10}$/)) {
    //     $('#notification_area').remove();
    //     my_notify('业务号填写有误');
    //     return false;
    // }
    if ($('input[name=btn-upload]').val() == '') {
        $('#notification_area').remove();
        my_notify('请上传头像');
        return false;
    }
    createPoster(name, business);
}

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

    let oldPosterIndex = nowPosterIndex;
    nowPosterIndex = RandomNumBoth(1, 3, oldPosterIndex);
    console.log('nowPosterIndex：', nowPosterIndex);
    $('.poster-canvas canvas').remove();

    let canvasinfo = initCanvas('.poster-canvas', 'posterCanvas', 425 * 2, 820 * 2);
    posterCanvas = canvasinfo[0];
    posterCtx = canvasinfo[1];


    var posterObj = new Image();
    posterObj.src = '/Public/static/image2/poster' + nowPosterIndex + '.jpg';
    posterObj.onload = function () {
        posterCtx.drawImage(posterObj, 0, 0, posterCanvas.width, posterCanvas.height);
        var headimgObj = new Image();
        headimgObj.src = getManBase64(uploadCanvas);
        headimgObj.onload = function () {
            posterCtx.beginPath();
            posterCtx.arc(214 * 2, 446 * 2, 46 * 2, 0, 2 * Math.PI);
            posterCtx.fillStyle = "#fff"; //填充颜色,默认是黑色
            posterCtx.fill(); //画实心圆
            posterCtx.closePath();
            posterCtx.drawImage(headimgObj, 170 * 2, 402 * 2, 88 * 2, 88 * 2);
            drawUserInfo(name, business, 20, 'bolder');
            setTimeout(function () {
                drawNum();
            }, 200);
            setTimeout(function () {
                $('.poster-canvas .posterimg').remove();
                $('.poster-canvas').append('<img class="posterimg" />');
                $('.posterimg').attr('src', getManBase64(posterCanvas));
                $('.page1').hide();
                $('.poster-page').show();
                $('#notification_area').remove();
            }, 500);

        }
    }
}

function confirmAvatar() {
    $('.regulate-block').hide();
}

function inputLength() {
    checkIt('name', 8);
}

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);
        });
    });
}

function drawImage(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 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 normal';
    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 drawUserInfo(name, business, fontsize, fontweight) {
    fontsize = fontsize * 2;
    posterCtx.font = fontweight + ' ' + fontsize + 'px normal';
    let {
        idX,
        nameX,
        noX,
        businessX
    } = getX(name, business);
    let idObj = new Image();
    idObj.src = '/Public/static/image2/id.png';
    idObj.onload = function () {
        posterCtx.drawImage(idObj, idX, 500 * 2, idInfo.width * 2, idInfo.height * 2);
        txtDraw(posterCtx, name, '#fff', nameX, 515 * 2);
        let noObj = new Image();
        noObj.src = '/Public/static/image2/no.png';
        noObj.onload = function () {
            posterCtx.drawImage(noObj, noX, 502 * 2, noInfo.width * 2, noInfo.height * 2);
            txtDraw(posterCtx, business, '#fff', businessX, 515 * 2);
        };
    };
}

function getX(name, business) {
    let nameWidth = posterCtx.measureText(name).width;
    let businessWidth = posterCtx.measureText(business).width;

    let totalWidth = idInfo.width * 2 + 6 * 2 + nameWidth + 21 * 2 + noInfo.width * 2 + 3 * 2 + businessWidth;

    let idX = 212 * 2 - totalWidth / 2;
    let nameX = idX + (idInfo.width * 2) + 6 * 2;
    let noX = nameX + nameWidth + 21 * 2;
    let businessX = noX + noInfo.width * 2 + 3 * 2;

    return {
        idX,
        nameX,
        noX,
        businessX
    };
}

function txtDraw(ctx, content, color, x, y) {
    ctx.fillStyle = color;
    ctx.fillText(content, x, y);
}

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

function initCanvas(target, id, canvasWidth, canvasHeight, useRem = false) {
    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, exclude = '') {
    var Range = Max - Min;
    var Rand = Math.random();
    var num = Min + Math.round(Rand * Range); //四舍五入
    if (exclude == '') {
        return num;
    } else if (num == exclude) {
        return RandomNumBoth(Min, Max, exclude);
    } else {
        return num;
    }
}

function checkIt(bind, maxNum) {
    var v = document.getElementById(bind).value;
    if (v == "") {
        return [];
    }
    var len = 0; //中英字符长度计数
    //计算
    for (i = 0; i < v.length; i++) {
        var c = v.charCodeAt(i);
        if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) //英文字母状态
        {
            len++;
        } else //中文状态
        {
            len += 2;
        }
        if (len >= maxNum) {
            if (i != v.length - 1) {
                $("#" + bind).val(v.substr(0, i + 1))
                break;
            }
        }
    }
}