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',
    picUrl + 'poster8.png',
    picUrl + 'rule-active.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 posterStatus = false;

let myScroll;

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

//canvas 位置
let canvasArr = [
    //left top width height headleft headtop color 统计id
    [46, 240, 1214, 1814, 36, 42, '#0f5188', '19'],
    [58, 240, 1164, 1800, 34, 30, '#0f5188', '20'],
    [58, 240, 1164, 1748, 34, 30, '#ffffff', '21'],
    [58, 240, 1206, 1808, 34, 30, '#ffffff', '22'],
    [58, 240, 1164, 1740, 34, 30, '#ffffff', '23'],
    [58, 240, 1164, 1808, 34, 30, '#0f5188', '24'],
    [58, 240, 1164, 1812, 34, 30, '#0f5188', '25'],
    [58, 240, 1190, 1812, 34, 30, '#0f5188', '26']
];

//海报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();

    $('.index-block').css('top', getTranslateDistance(20));
    $('.question-block').css('top', getTranslateDistance(-36));
    $('.rule-page .rule-content').css('top', getTranslateDistance(-40));

    //显示答题页面
    $('.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);
    //关闭抽奖
    $('.prize-page .btn-close').on('click', closePrize);
    //解决移动端:active伪类失效
    document.body.addEventListener('touchstart', function () {}, false);


    $(".question-page").on("touchstart", function (e) {

        // 判断默认行为是否可以被禁用
        if (e.cancelable) {
            // 判断默认行为是否已经被禁用
            if (!e.defaultPrevented) {
                e.preventDefault();
            }
        }
        startX = e.originalEvent.changedTouches[0].pageX,
            startY = e.originalEvent.changedTouches[0].pageY;
    });
    $(".question-page").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');
        } else if (X == 0) {
            if ($(e.target).attr('class').indexOf('index-scroll') == -1) {
                $(e.target).click();
            }
        }
    });
});

function closePrize() {
    $('.prize-page').hide();
}

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');
        let g = (height - 61.9) / 2;
        $('.frame').css('top', g + 'rem');
        // $('.btn-back').css('top',)
    }
}

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();
    $('.btn-rule').addClass('active');
}

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

function retry() {
    if (posterStatus) {
        try {
            MtaH5.clickStat("28");
        } catch (error) {
            console.log(error);
        }
        initQuestion();
        $('.poster-page').hide();
        $('.question-page').show();
        posterStatus = false;
    }

}

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(/^\s*$/)) {
            $('#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() {
    if (posterStatus) {
        try {
            MtaH5.clickStat("27");
        } catch (error) {
            console.log(error);

        }
        $('.prize-page').show();
    }
}

function createPoster(callback) {
    try {
        MtaH5.clickStat(canvasArr[resultType - 1][7]);
    } catch (error) {
        console.log(error);

    }



    $('.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();
    }
    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;
    }
    $('.poster-canvas-block').append($('<img class="posterImg" src="" />'));
    $('.posterImg').attr('src', 'http://maf.dev.izhida.cn/Public/static/image2/poster' + resultType + '.png');
    if (!browser.versions.weixin) {
        // if (0) {
        $('.dialog').hide();
        posterStatus = true;
        callback();
        return false;
    }

    //海报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',
    });
    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));
                posterStatus = true;
                $('.dialog').hide();
                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 !== '') {
        try {
            MtaH5.clickStat("18");
        } catch (error) {
            console.log(error);
        }
        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;
        }

        //进行答题统计
        try {
            MtaH5.clickStat(answerArr[0] + 1);
            MtaH5.clickStat(answerArr[1] + 5);
            MtaH5.clickStat(answerArr[2] + 8);
            MtaH5.clickStat(answerArr[3] + 11);
            MtaH5.clickStat(answerArr[4] + 14);
        } catch (error) {
            console.log(error);
        }

        $('.question' + nowQuestionIndex + '-block').addClass('fadeoutleft');
        setTimeout(function () {
            $('.dialog').show();
            $('.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) {
        if (nowQuestionIndex == 2) {
            $('.index-scroll').css('height', '27.5rem');
        } else {
            $('.index-scroll').css('height', '30.5rem');
        }
        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) {
            $('.index-scroll').css('height', '30.5rem');
            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) {
    e.stopPropagation();
    let node = $(e.delegateTarget);
    $('.question' + nowQuestionIndex + '-block .answer-active').hide();
    nowAnswer = $('.question' + nowQuestionIndex + '-block .answer').index(node);
    answerArr[nowQuestionIndex - 1] = nowAnswer;
    node.find('div[class$=-active]').show();

}

function showQuestion() {
    if (checkedRule) {
        try {
            MtaH5.clickStat("17");
        } catch (error) {
            console.log(error);

        }
        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('');
    $('.index-scroll').css('height', '27.5rem');
    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;
}