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 myCanvas;
var username = '';

preloadimages(preloadImageList, function () {

}, function (progress) {

});

$('input[name=username]').attr('placeholder', '点击输入您的名字');
$('.canvas-block').html('<canvas id="myCanvas" width="' + pxchange(315) + '" height="' + pxchange(316) + '"></canvas><img class="posterimg" />');

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


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

    $('input').on('input', onInput)

    function getLength(str) {
        return str.replace(/[^ -~]/g, 'AA').length;
    }

    function limitMaxLength(str, maxLength) {
        var result = [];
        for (var i = 0; i < maxLength; i++) {
            var char = str[i]
            if (/[^ -~]/.test(char))
                maxLength--;
            result.push(char);
        }
        return result.join('');
    }

    var maxLength = 10; // how many bytes you want

    function onInput() {
        if (getLength(this.value) > maxLength)
            this.value = limitMaxLength(this.value, maxLength);
    }

    window.onInput = onInput;

    $('.btn-create').on('click', function () {
        username = $('input[name=username]').val();
        initCanvas();
        if (username.match(/^\s*$/)) {
            $('#notification_area').remove();
            my_notify('您还没有输入名字');
            return false;
        }

        checkWord(username, function () {

            my_notify('正在生成海报，请稍后', 999999);
            var img = new Image();
            img.src = 'Public/static/image2/poster.png';
            img.onload = function () {
                ctx.drawImage(img, 0, 0, myCanvas.width, myCanvas.height);
                txtDraw(ctx, username, pxchange(158), pxchange(267), pxchange(40), 'normal', '#ffffff');
                $('.posterimg').show();
                $('.posterimg').attr('src', getManBase64());
                $('.username').hide();
                $('.tip').show();
                $('.btn-create').hide();
                $('.btn-retry').show();
                $('#notification_area').remove();
            }
        });
    });

    $('.btn-retry').on('click', function () {
        ctx.clearRect(0, 0, myCanvas.width, myCanvas.height);
        $('.posterimg').hide();
        $('.posterimg').attr('src', '');
        $('input[name=username]').val('');
        $('.username').show();
        $('.tip').hide();
        $('.btn-create').show();
        $('.btn-retry').hide();
    });
});

function checkWord(name, callback) {
    $.ajax({
        url: '/index/checkWord',
        type: 'POST',
        data: {
            name: name
        },
        success: function (resp) {
            if (resp.status == 1) {
                callback();
            } else {
                $('#notification_area').remove();
                my_notify(resp.msg);
            }
        }
    })
}

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

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

    ctx.fillStyle = color;

    ctx.fillText(content, cx, 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() {
    myCanvas = $('#myCanvas')[0];
    ctx = myCanvas.getContext("2d");
    ctx.scale(2, 2);
    myCanvas.width = pxchange(1260);
    myCanvas.height = pxchange(1264);
}

function pxchange(px) {
    var rem = px / 20;
    var fontSize = parseFloat($('html').css('fontSize'));
    return rem * fontSize;
}

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