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].url = obj[i];
        images[i].src = 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);
        }
    }
}
preloadImageList = []
for (var i = 1; i <= 2; i++) {
    preloadImageList.push('/Public/static/image2/cover/' + i + '.png');
}
preloadImageList.push('/Public/static/image2/cover/3.png');
preloadimages(preloadImageList, function () {
    init();
}, function (progress) {});

var canvas = false,
    ctx = false,
    imgInfo = false,
    oldpoz = false,
    inited = false,
    firstSwiper, images = [],
    custom = false,
    uploadedImg = false;
$(document).ready(function () {
    if ($('.page').height() < document.documentElement.clientHeight) {
        var scale = document.documentElement.clientHeight / $('.page').height();
        $('.page').css({
            'transform': 'translate(0%,-50%) scale(1,' + scale + ')'
        });
    }
    $('.container').css('height', document.documentElement.clientHeight + 'px');
    var fixHeight = Math.abs($('.page').height() - document.documentElement.clientHeight) / 2;
    $('.logo').css('top', fixHeight + 30 + 'px');
    $("input").on("blur", function () {
        window.scroll(0, 0); //失焦后强制让页面归位
    });
    $('input[type=text]').on('focus', function () {
        $('.inputTip').hide();
        //  $('.start').hide();
    })
    $('input[type=text]').on('blur', function () {
        window.scrollTo(0, 0);
        if ($.trim($(this).val()) === '') {
            $('.inputTip').show();
            // $('.start').hide();
        } else {
            $('.inputTip').hide();
            // $('.start').show();
        }
    })
    $('.again').on('click', function () {
        $('.swiperBox,.make,.username,.upload').show();
        $('.again,.saveTip').hide();
        $('.inputTip').show();
        $('.page').hide().filter('.page0').show();
        ctx.save();
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.fillStyle = "#ffffff";
        ctx.fillRect(0, 0, canvas.width, canvas.height);
    })
    $('.make').on('click', function () {
        if (!inited) {
            return;
        }
        $('.usertips').hide();
        var text = $.trim($('.page:visible').find('input[type=text]').val());
        if (text === '') {
            showTip('您还没有输入名字');
            return;
        }
        if (custom) {
            if (!uploadedImg) {
                showTip('您还没有上传头像');
                return;
            }
        }
        if (text.length === 2) {
            var last = text[1];
            text = text[0] + ' ' + last;
        }
        $.getJSON('https://service-gsevjgkv-1259141669.ap-beijing.apigateway.myqcloud.com/release/nlp?callback=?', 'text=' + text, function (res) {
            text = res.text;
            $('.swiperBox,.L-arrow,.R-arrow,.make,.username,.upload').hide();
            $('.again,.saveTip').show();
            var img, canvas2, ctx2;
            if (custom) {
                img = loadedImages['/Public/static/image2/cover/1.png'];
                canvas2 = canvas;
                ctx2 = ctx;
            } else {
                var id = images.length - 1 - firstSwiper.realIndex;
                img = images[id];

                canvas2 = document.createElement('CANVAS'),
                    ctx2 = canvas2.getContext('2d');
                ctx2.scale(2, 2);
                canvas2.height = img.height;
                canvas2.width = img.width;
                ctx2.drawImage(img, 0, 0);
            }


            var top = 0;
            if (custom) {
                top = 550;
                ctx2.fillStyle = '#FFFFFF';
                ctx2.font = 'bolder 80px fzlt';
            } else if (firstSwiper.realIndex === 0) {
                top = 460;
                ctx2.fillStyle = '#000000';
                ctx2.font = 'bolder 130px fzlt';
            } else {
                top = 50;
                ctx2.fillStyle = '#000000';
                ctx2.font = 'bolder 130px fzlt';
            }

            ctx2.textAlign = 'left';
            ctx2.textBaseline = 'top';
            var left = (img.width - ctx2.measureText(text).width) / 2;
            alert(1);
            ctx2.shadowBlur = 0;
            ctx2.fillText(text, left, top * 2);
            $('.page:visible').find('.showBox').show().html('<img src="' + canvas2.toDataURL('image/png') + '">');
        });
    })
    $('input[type=text]').on('input', onInput);
    $('.L-arrow').on('click', function () {
        if (firstSwiper) {
            firstSwiper.slideNext();
        }
    })
    $('.R-arrow').on('click', function () {
        if (firstSwiper) {
            firstSwiper.slidePrev();
        }
    })
    $('.choose1').on('click', function () {
        showPage1();
    })
    $('.choose2').on('click', function () {
        $('.upload').show();
        $('.imgTip').find('canvas').hide();
        showPage2();
    })
    $('input[type=file]').on('change', function () {
        $('.imgTip').find('canvas').show();
        $('.usertips').show();
        imgInfo = {
            x: 0,
            y: 0,
            scale: 1,
            rotation: 0
        }, oldpoz = {
            x: 0,
            y: 0,
            scale: 1,
            rotation: 0
        }
        var imgData = this.files[0];
        var rotation;
        this.value = '';
        EXIF.getData(imgData, function () {
            // if(navigator.userAgent.indexOf('iPhone') > -1){
            //     rotation = 0;
            // }else{

            // }
            var orientation = EXIF.getTag(this, "Orientation");
            switch (orientation) {
                case 3:
                    rotation = 180;
                    break;
                case 6:
                    rotation = 90;
                    break;
                case 8:
                    rotation = 270;
                    break;
                default:
                    rotation = 0;
            }
            var objectImg = new Image();
            objectImg.crossOrigin = "Anonymous";
            objectImg.setAttribute('crossOrigin', 'anonymous');
            objectImg.onload = function () {
                var scale = 1.3,
                    width = objectImg.width * 2,
                    height = objectImg.height * 2;
                if (rotation === 90 || rotation === 270) {
                    width = objectImg.height;
                    height = objectImg.width;
                }
                uploadedImg = document.createElement('CANVAS');
                var uploadctx = uploadedImg.getContext('2d');
                var scale = 1.3;
                if (width < height) {
                    scale = 1000 / width;
                } else {
                    scale = 1000 / height;
                }
                uploadctx.scale(scale, scale);
                uploadedImg.width = width;
                uploadedImg.height = height;
                uploadctx.translate(uploadedImg.width / 2, uploadedImg.height / 2);
                uploadctx.scale(scale, scale);
                uploadctx.rotate(Math.PI / 180 * rotation);
                uploadctx.drawImage(objectImg, -objectImg.width / 2, -objectImg.height / 2);
                // $('.canvas').html(  '<img src="'+base64Img+'">');
                drawImage();

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

var showTip = function (msg, delay) {
    $('#notification_area').remove();
    return my_notify(msg, delay);
}
var init = function () {
    inited = true;
    $('.imgTip').html('<canvas></canvas>');
    canvas = $('canvas').get(0);
    ctx = canvas.getContext('2d');
    ctx.scale(2, 2);
    var img = loadedImages['/Public/static/image2/cover/3.png'];
    canvas.width = img.width;
    canvas.height = img.height;
}
var drawImage = function () {
    if (uploadedImg) {
        ctx.save();
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.fillStyle = "#ffffff";
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        ctx.translate(canvas.width / 2, canvas.height / 2);
        ctx.translate(imgInfo.x, imgInfo.y);
        ctx.rotate(Math.PI / 180 * imgInfo.rotation);
        ctx.scale(imgInfo.scale, imgInfo.scale);
        ctx.drawImage(uploadedImg, -uploadedImg.width / 2, -uploadedImg.height / 2);
        ctx.restore();
    }
    var img = loadedImages['/Public/static/image2/cover/3.png'];
    ctx.drawImage(img, 0, 0);
}
var showPage1 = function () {
    custom = false;
    $('.page').hide().filter('.page1').show();
    if (!firstSwiper) {
        var swiperHtml = $('<div class="swiper-container"><div class="swiper-wrapper"></div></div>');
        swiperHtml.attr('id', 'firstSwiper').css({
            width: $('.swiperBox').css('width'),
            height: $('.swiperBox').css('height')
        });
        swiperHtml.appendTo('.swiperBox');
        for (var i = 1; i < 3; i++) {
            var img = '/Public/static/image2/cover/' + (3 - i) + '.png';
            images.push(loadedImages[img]);
            var item = $('<div class="img"><img src="' + img + '" /></div>');
            item.wrap('<div class="swiper-slide"></div>').parent().prependTo($('#firstSwiper').find('.swiper-wrapper'));
        }
        $('.img').css({
            width: $('.showBox').css('width'),
            height: $('.showBox').css('height')
        });
        firstSwiper = new Swiper('#firstSwiper', {
            'allowSlideNext': true,
            // direction: 'vertical'
        });
        firstSwiper.detachEvents()
    } else {
        $('.swiperBox,.make,.username').show();
        $('.again,.saveTip,.showBox').hide();
        $('input').val('');
        $('.inputTip').show();
    }
}
var showPage2 = function () {
    custom = true;
    uploadedImg = false;
    $('.again,.saveTip,.showBox').hide();
    $('.page').find('.imgTip,.make,.username').show();
    $('input').val('');
    $('.inputTip').show();
    $('.page').hide().filter('.page2').show();
}
var onInput = function () {
    var maxLength = 10;
    if (getLength(this.value) > maxLength)
        this.value = limitMaxLength(this.value, maxLength);
}
var getLength = function (str) {
    return str.replace(/[^ -~]/g, 'AA').length;
}
var limitMaxLength = function (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 mc = new Hammer($('.imgTip').get(0));
mc.get('pan').set({
    direction: Hammer.DIRECTION_ALL
});
mc.get('pinch').set({
    enable: true
});
mc.get('rotate').set({
    enable: true
});
mc.on('panstart panmove panend', function (event) {
    if (!uploadedImg) {
        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 * 4;
        imgInfo.y += movedY * 4;
        drawImage();
    }
    //苹果手机自动调整图片 不需要旋转
    if (navigator.userAgent.indexOf('iPhone') > -1) {
        imgInfo.rotation = 0;
    }
    return false;
});
mc.on('pinchstart pinchmove pinchend', function (event) {
    if (!uploadedImg) {
        return;
    }
    if (event.type == 'pinchstart' || event.type == 'pinchend') {
        oldpoz.scale = imgInfo.scale;
    } else {
        var nowScale = event.scale * oldpoz.scale;
        //oldpoz.scale = event.scale;
        imgInfo.scale = nowScale;
        drawImage();
    }
    return false;
});
mc.on('rotatestart rotatemove rotateend', function (event) {
    if (!uploadedImg) {
        return;
    }
    if (event.type == 'rotatestart' || event.type == 'rotateend') {
        oldpoz.rotation = 0;
    } else {
        var nowRotation = (event.rotation - oldpoz.rotation);
        oldpoz.rotation = event.rotation;
        imgInfo.rotation += nowRotation;
        drawImage();
    }
    return false;
});