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-submit-active.png',
    picUrl + 'question-btn-next-active.png',
    picUrl + 'btn-back-active.png',
    picUrl + 'btn-back.png',
    picUrl + 'btn-retry-active.png',
    picUrl + 'btn-submit-active.png',
    picUrl + 'btn-tryprize-active.png',
    picUrl + 'poster1.png',
    picUrl + 'poster2.png',
    picUrl + 'poster3.png',
    picUrl + 'poster4.png',
    picUrl + 'poster5.png',
    picUrl + 'poster6.png',
    picUrl + 'poster7.png',
    picUrl + 'poster8.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 = 0;
//提交信息按钮防抖
let submitStatus = true;
//是否已经看过规则
let checkedRule = false;
//滚动防抖定时器
let timer;

let myScroll;

//记录初始状态下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, 1800, 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 () {
    // $('.page').on('touchmove', function (e) {
    //     e.preventDefault();
    // });
    $("input").on("blur", function () {
        window.scroll(0, 0); //失焦后强制让页面归位
    });
    initPage();

    $('.rule-block').attr('id', 'rule-block');
    loaded();

    $('.index-block').css('top', getTranslateDistance(20));
    $('.question-block').css('top', getTranslateDistance(-36));
    $('.rule-page').css('top', getTranslateDistance(-40));
    // $('.rule-title').css('top', getTranslateDistance(30));
    // $('.rule-block').css('top', parseFloat(getTranslateDistance(30)) + (4.5 * fontSize));
    $('.btn-back').css('top', 'auto').css('bottom', getTranslateDistance(10));
    // let trans = parseFloat(getTranslateDistance());
    // let transRem = trans / fontSize;
    // $('.rule-block').css('height', (61.9 * fontSize) - (parseFloat(getTranslateDistance()) * 2) - (parseFloat(getTranslateDistance(30)) + (4.5 * fontSize)) + 'px');
    //显示答题页面
    $('.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);
    //再来一次
    $('.poster-page .btn-retry').on('click', retry);
    //活动规则
    $('.home-page .btn-rule').on('click', showRule);
    //返回首页
    $('.rule-page .btn-back').on('click', hideRule);
    //滚动条
    $('.rule-block').on('scroll', ruleScroll);
    //解决移动端:active伪类失效
    document.body.addEventListener('touchstart', function () {}, false);


    $(".index-scroll").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-scroll").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) {
            prevQuestion();
        }
        //右滑
        else if (X < 0) {
            nextQuestion('indexbar');
        }
    });
});


function changeBtnBg(event) {
    const pic = event.data.pic;
    $(event.target).css({
        'background': pic,
        'backgroundSize': '100%'
    })

}

function initPage() {
    let displacement = parseInt(getTranslateDistance());
    if (displacement > 0) {
        let height = 61.9 + ((displacement + 10) / fontSize);
        $('.wrap-inner,.page,.bg,.poster-bg').css('height', height + 'rem');
    }
}

function ruleScroll() {
    //7.9-46.9
    if (timer) {
        clearTimeout(timer);
    }
    timer = setTimeout(() => {
        let blockHeight = $('.rule-block').height() / fontSize; //rem
        let wrapHeight = 149.7; //rem
        let scrollHeight = wrapHeight - blockHeight; //rem
        let step = (39 * fontSize) / (scrollHeight * fontSize);

        let scrollTop = $('.rule-block').scrollTop();


        if (scrollTop < 0) {
            scrollTop = 0;
        } else if (scrollTop > (scrollHeight * fontSize)) {
            scrollTop = scrollHeight * fontSize;
        }
        let top = (7.9 * fontSize) + scrollTop * step;
        $('.scroll-bar').css('top', top + 'px');
    }, 5);

}

function loaded() {
    myScroll = new IScroll('#rule-block');
}

function hideRule() {
    $('.rule-page').hide();
}

function showRule() {
    checkedRule = true;
    $('.home-page .tips').removeClass('animate').hide();
    $('.rule-block').scrollTop(0);
    $('.rule-page').show();
}

function retry() {
    initQuestion();
    $('.poster-page').hide();
    $('.question-page').show();
}

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('请填写姓名');
            submitStatus = true;
            return false;
        } else if (!tel.match(/^1\d{10}$/)) {
            $('#notification_area').remove();
            my_notify('电话填写有误');
            submitStatus = true;
            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();
                    $('input[name=name]').val('');
                    $('input[name=tel]').val('');
                    submitStatus = true;
                }, 1800);

            }
        })
    }
}

function tryprize() {
    $('.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',
    });
    $('.posterImg').attr('src', 'http://maf.dev.izhida.cn/Public/static/image2/poster' + resultType + '.png');

    switch (resultType) {
        case 1:
            $('.tip1,.tip6').css('top', '51.8rem');
            break;
        case 2:
            $('.tip1,.tip6').css('top', '51.6rem');
            break;
        case 3:
            $('.tip1,.tip6').css('top', '51rem');
            break;
        case 4:
            $('.tip1,.tip6').css('top', '51.7rem');
            break;
        case 5:
            $('.tip1,.tip6').css('top', '50.9rem');
            break;
        case 6:
            $('.tip1,.tip6').css('top', '51.7rem');
            break;
        case 7:
            $('.tip1,.tip6').css('top', '51.8rem');
            break;
        case 8:
            $('.tip1,.tip6').css('top', '51.75rem');
            break;
    }
    setTimeout(function () {
        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();
            }
        }
    }, 2000);
}

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('海报生成中,请稍候', 9999999);
            $('.question-page').hide();
            $('.poster-page').show();

            createPoster(function () {
                $('#notification_area').remove();
            });
        }, 300);
    }
}

function prevQuestion() {
    if (nowQuestionIndex != 1) {
        let nowIndex1 = nowQuestionIndex;
        console.log('nowIndex:' + nowIndex1);
        $('.question' + nowQuestionIndex + '-block').addClass('fadeoutright');
        setTimeout(function () {
            $('.question' + nowIndex1 + '-block').removeClass('fadeoutright').hide();
        }, 500);
        $('.btn-submit').hide();
        $('.btn-nextquestion').show();
        nowQuestionIndex--;
        let nowIndex2 = nowQuestionIndex;
        nowAnswer = answerArr[nowQuestionIndex - 1];
        $('.question-page .point').animate({
            'left': '' + 5.5 * (nowQuestionIndex - 1) + 'rem'
        }, 500);
        setTimeout(function () {
            $('.question' + nowQuestionIndex + '-block').addClass('fadeinleft').css('opacity', 1);
            setTimeout(function () {
                console.log('nowIndex:' + nowIndex2);

                $('.question' + nowIndex2 + '-block').removeClass('fadeinleft').css('opacity', 1);
            }, 500);
        }, 300);
    }
}

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').css('opacity', 0);
                }, 500);
                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();
                }, 300);
            } 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() {
    if (checkedRule) {
        initQuestion();
        $('.home-page').hide();
        $('.question-page').show();
    } else {
        $('.home-page .tips').text('请阅读并同意活动规则及隐私条款进入答题').addClass('animate');
    }

}

function initQuestion() {
    $('.answer-active').hide();
    $('.question-block').hide().css('opacity', 1);
    $('.question1-block').show();
    $('.btn-submit').hide();
    $('.btn-nextquestion').show();
    $('.point').css('left', 0);
    $('.poster-canvas-block').html('');
    nowQuestionIndex = 1;
    answerArr = [];
    nowAnswer = '';
    watchedQuestion = [1];
    resultType = 0;
}


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