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].src = obj[i];
        // console.log(obj[i]);
        images[i].onload = load;
        images[i].setAttribute('crossOrigin', 'anonymous');
        images[i].onerror = load;
        images[i].onabort = load;
    }
    if (obj.length == 0) {
        complete_cb(images);
    }

    function load() {
        ++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);
            }
        });
    }



var uploadCanvas;
var headimgCanvas;
var posterCanvas;

var uploadctx;
var headimgctx;
var posterctx;

var imgInfo = {};
var nowTemplate = 1;

preloadimages(preloadImageList, function () {

}, function (progress) {

});

$('input[name=customize]').attr('placeholder','输入自定义文字（仅限四个字）').attr('maxlength','4');
$('.canvas-block').html('<canvas id="uploadCanvas" width="'+ 330 +'" height="'+ 330 +'"></canvas>');
$('.headimg-canvas-block').html('<canvas id="headimgCanvas" width="'+ 330 +'" height="'+ 330 +'"></canvas><img id="headimg" />');
$('.poster-canvas-block').html('<canvas id="posterCanvas" width="'+ 525 +'" height="'+ 849 +'"></canvas><img id="poster" />');

$('.page1').show();


$(document).ready(function () {
    $("input").on("blur",function(){
        window.scroll(0,0);//失焦后强制让页面归位
    });

    $('.logo-top').css('top',getTranslateDistance(30)); 
    $('.logo-bottom').css('top',parseInt(getTranslateDistance($('.wrap').height())) - 50 + 'px'); 

    $('.btn-go').on('click',homeBtnGoHandleClick);

    $('.btn-slideleft').on('click',slidePrevTemplate);
    $('.btn-slideright').on('click',slideNextTemplate);

    $('.btn-toheadimg').on('click',createHeadimg);

    $('.headimg-page .btn-back').on('click',backToUpload);

    $('.btn-toposter').on('click',creatPoster);

    $('.btn-share').on('click',showShare);
    $('.share-block').on('click',hideShare);

    $('.upload-page .btn-back').on('click',backToReupload);

    $('.poster-page .btn-back').on('click',backToUpload)

    $('[name=btn-tocreate]').change(function() {
        var canvasinfo = initCanvas('#uploadCanvas',660,660);
        uploadCanvas = canvasinfo[0];
        uploadctx = canvasinfo[1];
        imgInfo.rotation = 0;
        imgInfo.x = 0;
        imgInfo.y = 0;
        imgInfo.scale = 1;
        event.preventDefault();
        var imgData = this.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() {
                    $('.btn_test').hide();
                    $('.btn_holder').show();
                    $('.page_test .picture').css({
                        'opacity': 0,
                        '-webkit-animation': 'none',
                        'animation': 'none',
                        'z-index': 9
                    });
                    drawImage();
                    $('.copywriting2,.btn-tocreate').fadeOut(300);
                    $('.upload-page').delay(0).fadeIn(300);
                    initGame();
                    results = null;
                    imgData = null;
                };
                img.src = results.base64;
            });
        });
        return false;
    });

    var mc = new Hammer($('.hammer-block').get(0));
    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) {
        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();
        }
    });
    var oldScale = 1;
    mc.on('pinchstart pinchmove pinchend', function(event) {
        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();
        }
    });
    var oldRotation = 0;
    mc.on('rotatestart rotatemove rotateend', function(event) {
        if (!img) {
            return;
        }
        if (event.type == 'rotatestart' || event.type == 'rotateend') {
            oldRotation = 0;
        } else {
            nowRotation = event.rotation - oldRotation;
            oldRotation = event.rotation;
            imgInfo.rotation += nowRotation;
            drawImage();
        }
    });
});

function backToReupload() {
    $('[name=btn-tocreate]').val('');
    $('.upload-page').fadeOut(300);
    $('.btn-tocreate,.copywriting2').fadeIn(300);
}

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

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

function creatPoster() {
    if(nowTemplate == 5)
    {
        if($('[name=customize]').val() == '')
        {
            $('#notification_area').remove();
            my_notify('请填写自定义文字');
            return false;
        }
        else 
        {
            checkWord($('[name=customize]').val(),function(status){
                if(status == 0 || status == -1)
                {
                    $('#notification_area').remove();
                    my_notify('您提交的姓名包含敏感词');
                    return false;
                }
                else 
                {
                    var canvasinfo = initCanvas('#posterCanvas',1050,1698);
                    posterCanvas = canvasinfo[0];
                    posterctx = canvasinfo[1];

                    var posterObj = new Image();
                    posterObj.src = '/Public/static/image2/poster.png';

                    posterObj.onload = function() {
                        posterctx.drawImage(posterObj,0,0,posterCanvas.width,posterCanvas.height);
                        var headimgObj = new Image();
                        headimgObj.src = getManBase64(uploadCanvas);

                        headimgObj.onload = function() {
                            posterctx.drawImage(headimgObj,51*2,184*2,387*2,387*2);

                            var frameimg = new Image();
                            frameimg.src = '/Public/static/image2/canvas-frame5.png';

                            frameimg.onload = function() {
                                posterctx.drawImage(frameimg,51*2,184*2,387*2,387*2);

                                txtDraw(posterctx, $('[name=customize]').val(), 50, 'normal', '#fff', 90,231);

                                $('#poster').attr('src',getManBase64(posterCanvas));

                                $('.upload-page').fadeOut(300);
                                $('.poster-page').fadeIn(300);
                            }
                        }
                    }
                }
            });
        }
    }
    else 
    {
        var canvasinfo = initCanvas('#posterCanvas',1050,1698);
        posterCanvas = canvasinfo[0];
        posterctx = canvasinfo[1];

        var posterObj = new Image();
        posterObj.src = '/Public/static/image2/poster.png';

        posterObj.onload = function() {
            posterctx.drawImage(posterObj,0,0,posterCanvas.width,posterCanvas.height);
            var headimgObj = new Image();
            headimgObj.src = getManBase64(uploadCanvas);

            headimgObj.onload = function() {
                posterctx.drawImage(headimgObj,51*2,184*2,387*2,387*2);

                var frameimg = new Image();
                frameimg.src = '/Public/static/image2/frame' + nowTemplate + '.png';

                frameimg.onload = function() {
                    posterctx.drawImage(frameimg,51*2,184*2,387*2,387*2);

                    $('#poster').attr('src',getManBase64(posterCanvas));

                    $('.upload-page').fadeOut(300);
                    $('.poster-page').fadeIn(300);
                }
            }
        }
    }
}

function backToUpload() {
    $('.headimg-page,.poster-page').fadeOut(300);
    $('.upload-page').delay(0).fadeIn(300);
}

function createHeadimg() {

    if(nowTemplate == 5)
    {
        if($('[name=customize]').val() == '')
        {
            my_notify('请填写自定义文字');
            return false;
        }
        else 
        {
            checkWord($('[name=customize]').val(),function(status){
                if(status == 0 || status == -1)
                {
                    $('#notification_area').remove();
                    my_notify('您提交的姓名包含敏感词');
                    return false;
                }
                else 
                {
                    var headimgObj = new Image();
                    headimgObj.src = getManBase64(uploadCanvas);

                    var canvasinfo = initCanvas('#headimgCanvas',660,660);
                    headimgCanvas = canvasinfo[0];
                    headimgctx = canvasinfo[1];

                    headimgObj.onload = function() {
                        headimgctx.drawImage(headimgObj,5,3,headimgCanvas.width-10,headimgCanvas.height-10);

                        var frameimg = new Image();
                        frameimg.src = '/Public/static/image2/canvas-frame5.png';

                        frameimg.onload = function() {
                            headimgctx.save();
                            headimgctx.drawImage(frameimg,0,0,headimgCanvas.width,headimgCanvas.height);
                            headimgctx.restore();

                            headimgctx.save();
                            // 236, 259,
                            txtDraw(headimgctx, $('[name=customize]').val(), 41, 'normal', '#fff');
                            headimgctx.restore();

                            $('#headimg').attr('src',getManBase64(headimgCanvas));

                            $('.upload-page').fadeOut(300);
                            $('.headimg-page').delay(0).fadeIn(300);
                        }
                    }
                }
            });
        }
    }
    else 
    {
        var headimgObj = new Image();
        headimgObj.src = getManBase64(uploadCanvas);

        var canvasinfo = initCanvas('#headimgCanvas',660,660);
        headimgCanvas = canvasinfo[0];
        headimgctx = canvasinfo[1];

        headimgObj.onload = function() {
            headimgctx.drawImage(headimgObj,5,3,headimgCanvas.width-10,headimgCanvas.height-10);

            var frameimg = new Image();
            frameimg.src = '/Public/static/image2/frame' + nowTemplate + '.png';

            frameimg.onload = function() {
                headimgctx.drawImage(frameimg,0,0,headimgCanvas.width,headimgCanvas.height);

                $('#headimg').attr('src',getManBase64(headimgCanvas));

                $('.upload-page').fadeOut(300);
                $('.headimg-page').delay(0).fadeIn(300);
            }
        }
    }
    
}

function homeBtnGoHandleClick() 
{
    $('.subtitle,.copywriting1,.btn-go').fadeOut(300);
    $('.btn-tocreate,.copywriting2').delay(200).fadeIn(300);
}

function slidePrevTemplate() {
    if(nowTemplate - 1 <= 0)
    {
        nowTemplate = 6;
    }
    nowTemplate -= 1;
    $('.template').hide();
    $('.template' + nowTemplate).show();
    if(nowTemplate == 5) $('.customize').show();
    else $('.customize').hide();
}

function slideNextTemplate() {
    if(nowTemplate + 1 >= 6)
    {
        nowTemplate = 0;
    }
    nowTemplate += 1;
    $('.template').hide();
    $('.template' + nowTemplate).show();
    if(nowTemplate == 5) $('.customize').show();
    else $('.customize').hide();
}

function drawImage() {
    uploadctx.save();
    uploadctx.clearRect(0, 0, uploadCanvas.width, uploadCanvas.height);
    uploadctx.translate(uploadCanvas.width / 2, uploadCanvas.height / 2);
    uploadctx.translate(imgInfo.x, imgInfo.y);
    uploadctx.rotate(Math.PI / 180 * imgInfo.rotation);
    uploadctx.scale(imgInfo.scale, imgInfo.scale);
    uploadctx.drawImage(img, -img.width / 2, -img.height / 2);
    uploadctx.restore();
}

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

function initGame() {
    $('.template').hide();
    $('.template' + nowTemplate).show();
    $('.customize').hide();
}

function txtDraw(ctx, content, fontsize, fontweight, color, cx=0, cy=0) {
    var contentArr = content.split('');
    if(contentArr.length == 1)
    {
        x = (255+cx) * 2;
        y = (276+cy) * 2;
        fontsize = fontsize * 2;
        ctx.font = fontweight + ' '+fontsize+'px zkkh';

        ctx.fillStyle = color;

        ctx.fillText(content, x, y);
    }
    else if(contentArr.length == 2)
    {
        x = 236+cx;
        y = 276+cy;
        x = x * 2;
        y = y * 2;
        fontsize = fontsize * 2;
        ctx.font = fontweight + ' '+fontsize+'px zkkh';

        ctx.fillStyle = color;

        ctx.fillText(content, x, y);
    }
    else if(contentArr.length == 3)
    {
        x = 236+cx;
        y = 255+cy;
        x = x * 2;
        y = y * 2;
        fontsize = fontsize * 2;
        ctx.font = fontweight + ' '+fontsize+'px zkkh';

        ctx.fillStyle = color;

        ctx.fillText(contentArr[0] + contentArr[1], x, y);
        x = 255+cx;
        y = 295+cy;
        x = x * 2;
        y = y * 2;
        ctx.fillText(contentArr[2], x, y);
    }
    else if(contentArr.length == 4)
    {
        x = 236+cx;
        y = 255+cy;
        x = x * 2;
        y = y * 2;
        fontsize = fontsize * 2;
        ctx.font = fontweight + ' '+fontsize+'px zkkh';

        ctx.fillStyle = color;

        ctx.fillText(contentArr[0] + contentArr[1], x, y);
        x = 236+cx;
        y = 295+cy;
        x = x * 2;
        y = y * 2;
        ctx.fillText(contentArr[2] + contentArr[3], x, y);
    }
    

    // var contentArr = content.split('');

    // var width = ctx.measureText(content).width;
    // var cx = x - width / 2 - ((pxchange(0) * (contentArr.length - 1)) / 2);
    // var onewidth = ctx.measureText(contentArr[0]).width;
    // ctx.fillStyle = color;

    // for(var i = 0; i < contentArr.length;i++)
    // {
    //     ctx.fillText(contentArr[i], cx, y);
    //     cx = cx + pxchange(0) + onewidth;
    // }
}

function initCanvas(id,canvasWidth,canvasHeight) {
    canvas = $(id)[0];
    ctx = canvas.getContext("2d");
    ctx.scale(2,2);
    canvas.width = canvasWidth;
    canvas.height = canvasHeight;
    return [canvas, ctx];
}

function checkWord(name,callback) {
    $.ajax({
        url: '/index/checkWord',
        type: 'POST',
        data:{
            name:name
        },
        success: function(resp){
            callback(resp.status);
        }
    })
}

function getTranslateDistance(cardinal = 0) {
    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]);
    var wrapInnerjl = Math.abs(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;
}