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();
    $('.poster-page').show();
    createPoster();
}, 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 = 1;

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

//canvas 位置
let canvasArr = [
    [46, 240, 1214, 1814, 36, 42],
    [58, 240, 1164, 1748],
    [58, 240, 1164, 1748],
    [58, 240, 1206, 1008],
    [58, 240, 1164, 1740],
    [58, 240, 1164, 1008],
    [58, 240, 1164, 1008],
    [58, 240, 1190, 1812]
];

//海报canvas
let posterCanvas;
let posterCtx;

$(document).ready(function () {

    $("input").on("blur", function () {
        window.scroll(0, 0); //失焦后强制让页面归位
    });
    $('.index-block').css('top', getTranslateDistance(20));
    //显示答题页面
    $('.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);



    $(".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 createPoster() {
    $('.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];
    $('#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);
            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] + 168), designPxToRealPx(canvasArr[resultType - 1][4] + 104), designPxToRealPx(20), 'normal', '#0f5188')
        }
    }
}

function drawRoundedRect(ctx, x, y, width, height, r, fill, stroke) {
    ctx.save();
    ctx.fillStyle = "#0f5188";
    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();
    }
    if (stroke) {
        ctx.stroke();
    }
    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();
            $('.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) {
    x = x * 2;
    y = y * 2;
    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;
}