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 + '/image2/';

var preloadImageList = [
    // picUrl + 'share.png',
    picUrl + 'home-btn-next-active.png',
    picUrl + 'question-btn-next.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);
        }
    });
}

$('.loading-page').show();
preloadimages(preloadImageList, function () {
    $('.loading-page').hide();
    $('.home-page').show();
}, function (progress) {
    $('.loading-page .progress').css('width', (16.6 / 100) * (progress * 100) + 'rem');
});

//当前用户题目索引
let nowQuestionIndex = 1;
//当前题目用户选择答案
let nowAnswer = '';
//答案数组
let answerArr = [];
// 已经进入的题目
let watchedQuestion = [1];
//结果
let resultType = 8;
//提交信息按钮防抖
let submitStatus = true;

//记录初始状态下fontsize
const fontSize = parseFloat($('html').css('fontSize'));

//canvas 位置
let canvasArr = [
    //left top width height headleft headtop color
    [46, 240, 1214, 1814, 36, 42, '#0f5188'],
    [58, 240, 1164, 1748, 34, 30, '#0f5188'],
    [58, 240, 1164, 1748, 34, 30, '#ffffff'],
    [58, 240, 1206, 1808, 34, 30, '#ffffff'],
    [58, 240, 1164, 1740, 34, 30, '#ffffff'],
    [58, 240, 1164, 1808, 34, 30, '#0f5188'],
    [58, 240, 1164, 1812, 34, 30, '#0f5188'],
    [58, 240, 1190, 1812, 34, 30, '#0f5188']
];

//海报canvas
let posterCanvas;
let posterCtx;

$('input[name=tel]').attr('type', 'tel');
$(document).ready(function () {

    $("input").on("blur", function () {
        window.scroll(0, 0); //失焦后强制让页面归位
    });
    $('.index-block').css('top', getTranslateDistance(20));
    $('.question-block').css('top', getTranslateDistance(-36));
    //显示答题页面
    $('.home-page .btn-next').on('click', showQuestion);
    //答案选中
    $('.answer').on('click', chooseAnswer);
    //下一题
    $('.btn-nextquestion').on('click', {
        source: 'btn'
    }, nextQuestion);
    //提交答案
    $('.question-page .btn-submit').on('click', submitAnswer);
    //抽奖
    $('.poster-page .btn-tryprize').on('click', tryprize);
    //提交信息
    $('.prize-page .btn-submit').on('click', submit);



    $(".index-block").on("touchstart", function (e) {
        // 判断默认行为是否可以被禁用
        if (e.cancelable) {
            // 判断默认行为是否已经被禁用
            if (!e.defaultPrevented) {
                e.preventDefault();
            }
        }
        startX = e.originalEvent.changedTouches[0].pageX,
            startY = e.originalEvent.changedTouches[0].pageY;
    });
    $(".index-block").on("touchend", function (e) {
        // 判断默认行为是否可以被禁用
        if (e.cancelable) {
            // 判断默认行为是否已经被禁用
            if (!e.defaultPrevented) {
                e.preventDefault();
            }
        }
        moveEndX = e.originalEvent.changedTouches[0].pageX,
            moveEndY = e.originalEvent.changedTouches[0].pageY,
            X = moveEndX - startX,
            Y = moveEndY - startY;
        //左滑
        if (X > 0) {
            nextQuestion('indexbar');
        }
        //右滑
        else if (X < 0) {
            prevQuestion();
        }
    });
});

function submit() {
    if (submitStatus) {
        submitStatus = false;
        const name = $('input[name=name]').val();
        const tel = $('input[name=tel]').val();

        if (name.match(/^\s*$/)) {
            $('#notification_area').remove();
            my_notify('请填写姓名');
            return false;
        } else if (!tel.match(/^1\d{10}$/)) {
            $('#notification_area').remove();
            my_notify('电话填写有误');
            return false;
        }

        $.ajax({
            url: '/index/commit',
            type: 'POST',
            data: {
                name: name,
                tel: tel
            },
            success: function () {
                $('#notification_area').remove();
                my_notify('提交成功', 1500);
                setTimeout(function () {
                    $('.prize-page').hide();
                    $('.poster-page').show();
                    $('input[name=name]').val('');
                    $('input[name=tel]').val('');
                    submitStatus = true;
                }, 1800);

            }
        })
    }
}

function tryprize() {
    $('.poster-page').hide();
    $('.prize-page').show();
}

function createPoster(callback) {

    $('.poster-bg').hide();
    $('.poster-bg-' + resultType).show();
    $('.poster-canvas-block').css({
        'width': pxToRem(canvasArr[resultType - 1][2]) / 2 + 'rem',
        'height': pxToRem(canvasArr[resultType - 1][3]) / 2 + 'rem',
        'left': pxToRem(canvasArr[resultType - 1][0]) / 2 + 'rem',
    }).css('top', '6rem');
    if (resultType <= 5) {
        $('.tip1').show();
        $('.tip6').hide();
    } else {
        $('.tip1').hide();
        $('.tip6').show();
    }

    //海报canvas定义
    let canvasinfo = initCanvas('.poster-canvas-block', 'posterCanvas', designPxToRealPx(canvasArr[resultType - 1][2]), designPxToRealPx(canvasArr[resultType - 1][3]));
    posterCanvas = canvasinfo[0];
    posterCtx = canvasinfo[1];
    $('.poster-canvas-block').append($('<img class="posterImg" src="" />'));

    $('#posterCanvas').css({
        'width': pxToRem(canvasArr[resultType - 1][2]) / 2 + 'rem',
        'height': pxToRem(canvasArr[resultType - 1][3]) / 2 + 'rem',
    });
    let posterImg = new Image();
    posterImg.src = 'http://maf.dev.izhida.cn/Public/static/image2/poster' + resultType + '.png';
    posterImg.onload = function () {
        posterCtx.drawImage(posterImg, 0, 0, posterCanvas.width, posterCanvas.height);
        let headimg = new Image();
        headimg.src = window.getImageUrl + '?url=' + encodeURI(user_header_url);
        headimg.onload = function () {
            // posterCtx.drawImage(headimg, designPxToRealPx(canvasArr[resultType - 1][5]), designPxToRealPx(canvasArr[resultType - 1][4]), designPxToRealPx(52), designPxToRealPx(52));
            drawRoundedRect(posterCtx, designPxToRealPx(canvasArr[resultType - 1][5] - 6), designPxToRealPx(canvasArr[resultType - 1][4] - 6), designPxToRealPx(52) * 2, designPxToRealPx(52) * 2, designPxToRealPx(5) * 2,
                true, canvasArr[resultType - 1][6]);
            drawRoundRectImg(posterCtx, designPxToRealPx(5) * 2, designPxToRealPx(canvasArr[resultType - 1][5]), designPxToRealPx(canvasArr[resultType - 1][4]), designPxToRealPx(46) * 2, designPxToRealPx(46) * 2, headimg);
            txtDraw(posterCtx, '@' + window.nickname, designPxToRealPx(canvasArr[resultType - 1][5] + 128), designPxToRealPx(canvasArr[resultType - 1][4] + 84), designPxToRealPx(20), 'normal', canvasArr[resultType - 1][6]);
            $('.posterImg').attr('src', getManBase64(posterCanvas));
            callback();
        }
    }
}

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

function drawRoundedRect(ctx, x, y, width, height, r, fill, color) {
    ctx.save();
    ctx.fillStyle = color;
    ctx.beginPath(); // draw top and top right corner 
    ctx.moveTo(x + r, y);
    ctx.arcTo(x + width, y, x + width, y + r, r); // draw right side and bottom right corner 
    ctx.arcTo(x + width, y + height, x + width - r, y + height, r); // draw bottom and bottom left corner 
    ctx.arcTo(x, y + height, x, y + height - r, r); // draw left and top left corner 
    ctx.arcTo(x, y, x + r, y, r);
    if (fill) {
        ctx.fill();
    }
    ctx.restore();
}

function drawRoundRectImg(ctx, r, x, y, w, h, img) {
    ctx.save()
    if (w < 2 * r) r = w / 2
    if (h < 2 * r) r = h / 2
    ctx.beginPath()
    ctx.moveTo(x + r, y)
    ctx.arcTo(x + w, y, x + w, y + h, r)
    ctx.arcTo(x + w, y + h, x, y + h, r)
    ctx.arcTo(x, y + h, x, y, r)
    ctx.arcTo(x, y, x + w, y, r)
    ctx.closePath();
    ctx.clip()
    ctx.drawImage(img, x, y, w, h)
    ctx.restore() // 返回上一状态
}

function submitAnswer() {
    if (nowAnswer !== '') {
        if (answerArr[0] == 0) {
            resultType = 4;
        } else if (answerArr[1] == 0) {
            resultType = 1;
        } else if (answerArr[1] == 2) {
            resultType = 3;
        } else if (answerArr[2] == 1) {
            resultType = 1;
        } else if (answerArr[2] == 2) {
            resultType = 6;
        } else if (answerArr[3] == 2) {
            resultType = 7;
        } else if (answerArr[4] == 0) {
            resultType = 8;
        } else if (answerArr[4] == 1) {
            resultType = 2;
        } else if (answerArr[4] == 2) {
            resultType = 5;
        }

        $('.question' + nowQuestionIndex + '-block').addClass('fadeoutleft');
        setTimeout(function () {
            $('.question' + nowQuestionIndex + '-block').removeClass('fadeoutleft').hide();
            $('#notification_area').remove();
            my_notify('海报生成中,请稍候');
            createPoster(function () {
                $('#notification_area').remove();
                $('.question-page').hide();
                $('.poster-page').show();
            });
        }, 1000);
    }
}

function prevQuestion() {
    if (nowQuestionIndex != 1) {
        let nowIndex = nowQuestionIndex;
        $('.question' + nowQuestionIndex + '-block').addClass('fadeoutleft');
        setTimeout(function () {
            $('.question' + nowIndex + '-block').removeClass('fadeoutleft').hide();
        }, 1000);
        $('.btn-submit').hide();
        $('.btn-nextquestion').show();
        nowQuestionIndex--;
        nowAnswer = answerArr[nowQuestionIndex - 1];
        $('.question-page .point').animate({
            'left': '' + 5.5 * (nowQuestionIndex - 1) + 'rem'
        }, 500);
        setTimeout(function () {
            $('.question' + nowQuestionIndex + '-block').show();
        }, 900);
    }
}

function nextQuestion(e) {
    if ((e == 'indexbar' && (watchedQuestion.indexOf(nowQuestionIndex + 1) != -1)) || e != 'indexbar') {
        if (nowQuestionIndex != 5) {
            if (nowAnswer !== '') {
                let nowIndex = nowQuestionIndex;
                answerArr[nowQuestionIndex - 1] = nowAnswer;
                if (answerArr[nowQuestionIndex] !== undefined) {
                    nowAnswer = answerArr[nowQuestionIndex]
                } else {
                    nowAnswer = '';
                }

                $('.question' + nowQuestionIndex + '-block').addClass('fadeoutleft');
                setTimeout(function () {
                    $('.question' + nowIndex + '-block').removeClass('fadeoutleft').hide();
                }, 1000);
                nowQuestionIndex++;
                watchedQuestion.push(nowQuestionIndex);
                $('.question-page .point').animate({
                    'left': '' + 5.5 * (nowQuestionIndex - 1) + 'rem'
                }, 500);
                if (nowQuestionIndex == 5) {
                    $('.btn-submit').show();
                    $('.btn-nextquestion').hide();
                }
                setTimeout(function () {
                    $('.question' + nowQuestionIndex + '-block').show();
                }, 900);
            } else {
                if (e != 'indexbar') {
                    $('#notification_area').remove();
                    my_notify('请选择答案');
                    return false;
                }
            }
        }
    }

}

function chooseAnswer(e) {
    let node = $(e.target);
    $('.question' + nowQuestionIndex + '-block .answer-active').hide();
    if (node.attr('class').indexOf('active') != -1) {
        nowAnswer = '';
    } else {
        nowAnswer = $('.question' + nowQuestionIndex + '-block .answer').index(node);
        answerArr[nowQuestionIndex - 1] = nowAnswer;
        node.find('div[class$=-active]').show();
    }

}

function showQuestion() {
    initQuestion();
    $('.home-page').hide();
    $('.question-page').show();
}

function initQuestion() {
    $('.answer-active').hide();
    $('.question-block').hide();
    $('.question1-block').show();
    $('.btn-submit').hide();
    $('.btn-nextquestion').show();
    nowQuestionIndex = 1;
    answerArr = [];
    nowAnswer = '';
    watchedQuestion = [1];
}


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

function txtDraw(ctx, content, x, y, fontsize, fontweight, color) {
    fontsize = fontsize * 2;
    ctx.font = fontweight + ' ' + fontsize + 'px arial';

    ctx.fillStyle = color;
    ctx.fillText(content, x, y);

}

function pxToRem(px) {
    return px / 20;
}

function designPxToRealPx(px) {
    return px / 20 * fontSize;
}