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



//上传canvas定义


imgInfo = {};
let blackUrl, black;
let uploadCanvas, uploadCtx;
let avatar;
let nowPosterIndex = '';
let posterCanvas, posterCtx;
let canvasHeight = 0;


let createPosterLock = false;


// 会长 2 卓越主管 3 卓越十强 4 三项奖 5 卓越银奖 6 卓越铜奖 7 副会长
let level = 0;
let username = '';
let company = '';



preloadimages(preloadImageList, function () {
    initPage();
    $('.page1').show();

    $('input[name=name]').attr('placeholder', '请输入姓名').attr('id', 'name');
    $('input[name=job-number]').attr('placeholder', '请输入工号').attr('type', 'tel');
    let canvasinfo = initCanvas('.upload-canvas-block', 'uploadCanvas', 640 * 2, canvasHeight * 2);
    uploadCanvas = canvasinfo[0];
    uploadCtx = canvasinfo[1];

}, function (progress) {});


$(document).ready(function () {

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

    //提交信息
    $('.page1 .btn-next').on('click', checkInfo);

    $('input[name=btn-upload]').change(function () {
        $('.hide-block').hide();
        $('.show-block').show();

        bindUpload(this, uploadCtx, uploadCanvas, 1, function (img, imgInfo) {
            $('.btn-upload-block').css('left', '53px');
            $('.btn-createposter').show();
            $('.upload-before').hide();
            $('.upload-after').show();
            var mc = new Hammer($('#uploadCanvas').get(0));
            bindMc(mc, uploadCtx, uploadCanvas, img, imgInfo);
        }, imgInfo);
        return false;
    });

    $('.btn-createposter').on('click', createPoster);
});

function showIcon() {
    if (level == 1) {
        $('.exce-1').show();
        $('.exce-2').hide();
        $('.exce-3').hide();
        $('.exce-4').hide();
        $('.exce-5').hide();
        $('.exce-6').hide();
        $('.exce-7').hide();
    } else if (level == 2) {
        $('.exce-1').hide();
        $('.exce-2').show();
        $('.exce-3').hide();
        $('.exce-4').hide();
        $('.exce-5').hide();
        $('.exce-6').hide();
        $('.exce-7').hide();
    } else if (level == 3) {
        $('.exce-1').hide();
        $('.exce-2').hide();
        $('.exce-3').show();
        $('.exce-4').hide();
        $('.exce-5').hide();
        $('.exce-6').hide();
        $('.exce-7').hide();
    } else if (level == 4) {
        $('.exce-1').hide();
        $('.exce-2').hide();
        $('.exce-3').hide();
        $('.exce-4').show();
        $('.exce-5').hide();
        $('.exce-6').hide();
        $('.exce-7').hide();
    } else if (level == 5) {
        $('.exce-1').hide();
        $('.exce-2').hide();
        $('.exce-3').hide();
        $('.exce-4').hide();
        $('.exce-5').show();
        $('.exce-6').hide();
        $('.exce-7').hide();
    } else if (level == 6) {
        $('.exce-1').hide();
        $('.exce-2').hide();
        $('.exce-3').hide();
        $('.exce-4').hide();
        $('.exce-5').hide();
        $('.exce-6').show();
        $('.exce-7').hide();
    } else if (level == 7) {
        $('.exce-1').hide();
        $('.exce-2').hide();
        $('.exce-3').hide();
        $('.exce-4').hide();
        $('.exce-5').hide();
        $('.exce-6').hide();
        $('.exce-7').show();
    }
}

function toUploadPage() {
    $('.page1').hide();
    $('.upload-page').show();
    $('.cat').hide();
    $('.cat' + level).show();
    $('.btn-createposter').hide();
    $('.btn-upload-block').css('left', 200);
}

function checkInfo() {
    let name = $('input[name=name]').val();
    let code = $('input[name=job-number]').val();
    if (name.match(/^\s*$/)) {
        $('#notification_area').remove();
        my_notify('请填写姓名');
        return false;
    } else if (code.match(/^\s*$/)) {
        $('#notification_area').remove();
        my_notify('请填写工号');
        return false;
    }
    $.ajax({
        url: '/index/getInfo',
        type: 'POST',
        data: {
            name: name,
            code: code
        },
        success: function (resp) {
            if (resp.status == 1) {
                level = resp.poster;
                username = name;
                company = resp.branch;
                toUploadPage();
                showIcon();
                $('.username').text(username);
                $('.company').html('中信保诚人寿<br/>' + company);
                // $('.company').html('中信保诚人寿<br/>' + company + '分公司');

            } else {
                $('#notification_area').remove();
                my_notify(resp.msg);
                return false;
            }
        }
    })
}

function initPage() {
    const displacement = parseFloat(getTranslateDistance());
    const wrapHeight = parseFloat($('.wrap').css('height'));
    canvasHeight = wrapHeight - displacement;
    $('.upload-canvas-block,.poster-img,.show-img,.poster-canvas').css('height', wrapHeight + 'px').css('top', displacement < 0 ? -displacement : 0 + 'px');
    if (-displacement + 179 > 243) {

        $('.upload-page .logo').css('top', -displacement + 183 + 'px');
    }
    if (displacement > 0) {
        const scale = document.documentElement.clientHeight / $('.page').height();
        $('.wrap-inner').css({
            'transform': 'translate(0%,-50%) scale(1,' + scale + ')'
        });
        $('.top').css('top', '0px');
        $('.bottom').css({
            top: 'auto',
            bottom: '0px'
        });
    } else {
        $('.top').css('top', -displacement - 5 + 'px');
        $('.bottom').css({
            top: 'auto',
            bottom: -displacement - 5 + 'px'
        });
    }
}

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 createPoster() {
    $('#notification_area').remove();
    my_notify('正在生成海报，请稍候', 60000);

    $('.poster-canvas canvas').remove();

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

    posterCtx.fillStyle = "#ffffff";
    posterCtx.beginPath();
    posterCtx.fillRect(0, 0, posterCanvas.width, posterCanvas.height);
    posterCtx.closePath();

    showIcon();

    var photo = new Image();
    photo.src = getManBase64(uploadCanvas);

    photo.onload = function () {
        posterCtx.drawImage(photo, 0, 0, posterCanvas.width, posterCanvas.height);

        var logoObj = new Image();
        logoObj.src = '/Public/static/image2/logo.png';
        logoObj.onload = function () {
            txtDraw(posterCtx, username, '#ffffff', 515 * 2, 300 * 2, 45 * 2, 'bolder');
            txtDraw(posterCtx, '中信保诚人寿', '#ffffff', 515 * 2, 340 * 2, 20 * 2);
            txtDraw(posterCtx, company, '#ffffff', 515 * 2, 370 * 2, 20 * 2);
            // txtDraw(posterCtx, company + '分公司', '#464646', 520 * 2, 365 * 2, 20 * 2);
            var titleObj = new Image();
            var jobTitle = level
            if (jobTitle) {
                titleObj.src = '/Public/static/image2/exce-' + jobTitle + '.png';
                titleObj.onload = function () {
                    posterCtx.drawImage(titleObj, 425 * 2, 43 * 2, 183 * 2, 175 * 2);
                }
            }

            setTimeout(function () {
                posterCtx.drawImage(logoObj, 49 * 2, 42 * 2, 262 * 2, 72 * 2);
                var posterBottomObj = new Image();
                posterBottomObj.src = '/Public/static/image2/poster-bottom.png';
                posterBottomObj.onload = function () {
                    posterCtx.drawImage(posterBottomObj, 0, (canvasHeight - 325) * 2, posterCanvas.width, 325 * 2);
                    $('#notification_area').remove();
                    my_notify('请长按页面保存海报')
                    $('.upload-page').hide();
                    $('.poster-page').show();

                    $('.show-img').append('<img class="showimg" />');
                    $('.showimg').attr('src', getManBase64(uploadCanvas));

                    $('.poster-img').append('<img class="posterimg" />');
                    $('.posterimg').attr('src', getManBase64(posterCanvas));
                }
            }, 500);
        }
    }
}

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

function inputLength() {}

function bindMc(mc, ctx, myCanvas, img, imgInfo) {
    console.log(imgInfo.x, imgInfo.y)
    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 * 2;
            imgInfo.y += movedY * 2;

            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 = {
        x: 0,
        y: 0,
        scale: 0.5,
        rotation: 0
    }, oldpoz = {
        x: 0,
        y: 0,
        scale: 0.5,
        rotation: 0
    }
    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;
        }
        img = new Image();
        img.crossOrigin = "Anonymous";
        img.setAttribute('crossOrigin', 'anonymous');
        img.onload = function () {
            if (imgInfo.rotation === 90 || imgInfo.rotation === 270) {
                width = img.height;
                height = img.width;
            }
            drawImage(ctx, myCanvas, img, imgInfo);
            callback(img, imgInfo);

        }
        img.src = URL.createObjectURL(imgData);

    });
}

function drawImage(ctx, myCanvas, img, imgInfo) {
    ctx.save();
    ctx.clearRect(0, 0, myCanvas.width, myCanvas.height);
    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, -img.height, 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 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 drawUserInfo(name, business, fontsize, fontweight) {
    fontsize = fontsize * 2;
    posterCtx.font = fontweight + ' ' + fontsize + 'px text';
    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, fontsize, fontWeight = 'normal') {
    ctx.font = fontWeight + ' ' + fontsize + 'px zkkh';
    var width = ctx.measureText(content).width;
    var cx = x - width / 2;
    ctx.fillStyle = color;
    ctx.fillText(content, cx, 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);
    }
    $(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) {
    let wrapHeight = parseFloat($('.wrap').css('height'));
    let wrapInnerHeight = parseFloat($('.wrap-inner').css('height'));
    return (wrapHeight - wrapInnerHeight) / 2 + 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) {
            return false;
        }
    }
    return true;
}

function timest() {
    var tmp = Date.parse(new Date()).toString();
    tmp = tmp.substr(0, 10);
    return tmp;
}