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 + 'colorbar-red.png',
    picUrl + 'colorbar-yellow.png',
    picUrl + 'colorbar-lightgreen.png',
    picUrl + 'colorbar-darkgreen.png',
    picUrl + 'colorbar-blue.png',
    picUrl + 'colorbar-purple.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);
        }
    });
}


preloadimages(preloadImageList, function () {
    $('.home-page').fadeIn(300);
    $('.home-page .candle-block').addClass('animate');
    $('.home-page .btn-next').addClass('animate');
    // showCountDownPage();
    // $('.poster-page').fadeIn(300);


}, function (progress) {

});

const flag = [
    '升职加薪',
    '早日暴富',
    '拿到一个新项目',
    '考过CFA',
    '迎战CPA',
    '读10本金融类书籍',
    '提升工作核心技能',
    '拿下自己的Dream car',
    '买一套小房子',
    '存款超过6位数',
    '回家继承家业',
    '结婚，靠份子钱增收',
    '拥有苹果全家桶',
    '坚持基金定投',
    '坚持记账',
    'get一项理财技能',
    '为孩子做教育基金定投',

    '好好存钱，认真把养老问题提上日程',
    '投资收益超主业，躺着赚钱',
    '靠理财收益，实现水果自由',
    '好好理财，买全李佳琪推荐口红',
    '理财收益多一点，猫粮争取升一级',
    '用理财收益，来场说走就走的旅行',
    '多赚钱，去看一看世界和远方',
];
//色值
const colorList = {
    'red': [
        '#854337',
        '#984534',
        '#b02318',
        '#e5382a',
        '#fa675c',
        '#ffbaaf'
    ],
    'yellow': [
        '#cf9b0d',
        '#e4a701',
        '#ffc411',
        '#f8d35c',
        '#fae28e',
        '#f4d895'
    ],
    'lightgreen': [
        '#6a7c42',
        '#86995c',
        '#9fcd63',
        '#b5d986',
        '#92be71',
        '#bacaa8'
    ],
    'darkgreen': [
        '#3d6743',
        '#368a41',
        '#4eac5b',
        '#6cba77',
        '#8ecc97',
        '#a6c6ab'
    ],
    'blue': [
        '#295a9c',
        '#458baa',
        '#2fa7de',
        '#6fb0da',
        '#88b7db',
        '#b1dce3'
    ],
    'purple': [
        '#543c64',
        '#6d3f82',
        '#986cb2',
        '#856cb9',
        '#9c87c6',
        '#b3a5ce'
    ]
};
//小装饰图片地址
let decorateList = [
    picUrl + 'decorate1.png',
    picUrl + 'decorate2.png',
    picUrl + 'decorate3.png',
    picUrl + 'decorate4.png',
    picUrl + 'decorate5.png',
];

//用户选择的flag列表
let flagStack = [];
//用户选择的小装饰src
let checkedDecorate = "";
//用户署名
let signature = "";
//用户选择的色条index
let colorIndex = 4;
//用户选择的背景色
let bgColor = '#e5382a';
//用户选择的flag数量
let chooseNum = 0;
//用户选择的主色调
let mainColor = 'red';
//切换flag时存储上次的随机结果,以保证不重复
let oldRandFlag = [];
//用于触摸防抖定时器
let timer;
//记录flag调整顺序窗口的开启状态
let checkFlagListStatus = false;
//记录用户是否第一次选择留言，如果是第一次则打开flag调整顺序窗口
let firstChooseFlag = true;
//记录初始状态下色条的left值
let colorbarLeft;
//记录用户是否进入过小装饰设置，如果没有则跳转到小装饰设置页面，不能进入下一页
let clickDecorate = false;
//记录用户是否同意实现flag建议
let agreeSuggestion = false;
//同意按钮闪烁timer
let agreeTimer;

//倒计时canvas
let countDownCanvas;
let countDownCtx;

//海报canvas
let posterCanvas;
let posterCtx;

//home next
let homeNext = true;
//page1 next
let page1Next = true;

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

//记录flag选择页的flag模版
let flagTemplate = $('.flag-page .flag-frame').find('.flag-block').clone();
$('.flag-frame').html('').addClass('clearfix');


//自定义flag的placeholder
$('input[name=customize-flag]').attr('placeholder', '也能在这里写你的flag哦');
//署名的placeholder
$('input[name=signature]').attr('placeholder', '准备好了，就在此署名吧').attr('disabled', true).attr('id', 'signature');

//倒计时canvas定义
let canvasinfo = initCanvas('.countdown-canvas', 'countDownCanvas', 257, 257, true);
countDownCanvas = canvasinfo[0];
countDownCtx = canvasinfo[1];



//初始化小装饰
initDecorate();

$(document).ready(function () {
    $("input").on("blur", function () {
        window.scroll(0, 0); //失焦后强制让页面归位
    });
    // $('.logo').css('top',getTranslateDistance(15));

    initPage();

    $('.flag-list-content').attr('id', 'flag-list-content');
    colorbarLeft = $('.colorbar').offset().left;
    new Sortable(document.getElementById('flag-list-content'), {
        animation: 150,
        ghostClass: 'flag-sortable-ghost',
        chosenClass: "flag-sortable-active",
        delay: 100,
        direction: 'horizontal',
        onChoose: function (event) {
            const dragEl = $(event.item);
            dragEl.find('.btn-checked-item-delete').css('color', '#fcfcfd');
        },
        onChange: function (event) {
            const dragEl = $(event.item);
            swapArray(flagStack, event.oldIndex, event.newIndex);
            const nodeList = $('.flag-list-content .checked-item:not(.sortable-drag)');
            $('.sortable-drag').find('.checked-flag-no').text(event.newIndex + 1);
            for (let i = 0; i < nodeList.length; i++) {
                $(nodeList[i]).find('.checked-flag-no').text(i + 1);
            }
        },
        onEnd: function (event) {
            const dragEl = $(event.item);
            dragEl.find('.btn-checked-item-delete').css('color', '#c30101');
        }
    });


    //跳转到page1
    $('.home-page .btn-next').on('click', showPage1);
    //跳转到flag选择页面
    $('.page1 .btn-next').on('click', showFlagPage);
    //换一换按钮点击
    $('.flag-page .btn-change').on('click', changeFlag);
    //选择flag
    $(document).on('click', '.flag-page .flag-block', addFlag);
    //自定义flag
    $('.flag-page .btn-submit-flag').on('click', addCustomizeFlag);
    //跳转到个性化页面
    $('.flag-page .btn-next').on('click', showPersonalPage);
    //小装饰按钮点击切换小装饰
    $('.personal-page .btn-tab-decorate').on('click', showDecorate);
    //调整背景色按钮点击切换背景色
    $('.personal-page .btn-tab-bgcolor').on('click', showBgcolor);
    //选择色条触摸开始
    $('.personal-page .colorbar,.btn-choose-color').on('touchstart', chooseColorStart);
    //选择色条拖动
    $('.personal-page .colorbar,.btn-choose-color').on('touchmove', chooseColorMove);
    //红色
    $('.personal-page .btn-red').on('click', {
        color: 'red',
        left: '3.25rem'
    }, changeMainColor);
    //黄色
    $('.personal-page .btn-yellow').on('click', {
        color: 'yellow',
        left: '7.95rem'
    }, changeMainColor);
    //青绿
    $('.personal-page .btn-lightgreen').on('click', {
        color: 'lightgreen',
        left: '12.8rem'
    }, changeMainColor);
    //深绿
    $('.personal-page .btn-darkgreen').on('click', {
        color: 'darkgreen',
        left: '17.64rem'
    }, changeMainColor);
    //蓝色
    $('.personal-page .btn-blue').on('click', {
        color: 'blue',
        left: '22.44rem'
    }, changeMainColor);
    //紫色
    $('.personal-page .btn-purple').on('click', {
        color: 'purple',
        left: '27.26rem'
    }, changeMainColor);
    //小装饰点击
    $(document).on('click', '.personal-page .decorateImg', setDecorate);
    //切换已选flag列表
    $('.flag-page .btn-show-choose').on('click', toggleCheckFlagList);
    //关闭已选flag列表
    $('.flag-page .btn-close-checked').on('click', closeCheckFlagList);
    //删除已选flag
    $(document).on('click', '.btn-checked-item-delete', deleteCheckedFlag);
    //回到flag页
    $('.customize-frame .btn-back').on('click', backToFlag);
    //跳转到建议页
    $('.personal-page .btn-next').on('click', showSuggestPage);
    //署名输入框限制长度事件
    $('.suggest-page input[name=signature]').on('input propertychange', inputLength);
    //署名输入框聚焦判断有没有勾选同意
    $('.suggest-page input[name=signature]').on('touchstart', checkAgree);
    //同意点击
    $('.suggest-page .agree-wrap').on('click', agreeSuggest);
    //完成署名
    $('.suggest-page .btn-next').on('click', showCountDownPage);
});

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

function showPage1() {
    if (homeNext) {
        homeNext = false;
        $('.home-page .candle').css('opacity', 1);
        $('.home-page .btn-next').removeClass('animate');
        setTimeout(function () {
            $('.home-page').fadeOut(300);
            $('.page1').show();
        }, 3000);
    }

}

function calculationWrap() {
    let redLineWidth = pxToRem(367 * 2);
    let content = '啊啊啊啊啊啊啊啊';
    posterCtx.font = 1.4 * fontSize * 2 + 'px normal';
    for (let i = 8; i < 20; i++) {
        let textWidth = posterCtx.measureText(content).width;
        if (textWidth > redLineWidth) {
            return i - 2;
        } else {
            content += '啊';
        }
    }
}

function createPoster() {
    let canvasinfo = initCanvas('.poster-canvas-block', 'posterCanvas', 640 * 2, 1238 * 2, true);
    posterCanvas = canvasinfo[0];
    posterCtx = canvasinfo[1];
    let wrapNum = calculationWrap();
    $('.poster-list-page').show();
    $('.poster-page .poster-canvas-block').append($('<img class="posterImg" src="" />'));
    // 创建海报页面的flag列表
    for (let i = 0; i < flagStack.length; i++) {
        createList('.poster-list-page .poster-list', flagStack[i], i + 1, wrapNum);
    }

    let flagListHeight = $('.poster-list-page .poster-list').height();
    flagListHeight = (flagListHeight / fontSize) * 20;
    flagListHeight = flagListHeight + 40;
    let topHalfHeight = 489;
    let bottomHalfHeight = 368;
    let posterCanvasHeight = 0;
    flagListHeight = flagListHeight + 60;

    if (flagListHeight < 383) {
        posterCanvasHeight = topHalfHeight + 383 + bottomHalfHeight;
        flagListHeight = 383;
    } else {
        posterCanvasHeight = topHalfHeight + flagListHeight + bottomHalfHeight;
    }


    $('#posterCanvas').remove();
    canvasinfo = initCanvas('.poster-canvas-block', 'posterCanvas', 640 * 2, posterCanvasHeight * 2, true);
    posterCanvas = canvasinfo[0];
    posterCtx = canvasinfo[1];

    $('#posterCanvas').css('height', pxToRem(posterCanvasHeight));

    posterCtx.fillStyle = bgColor;
    posterCtx.fillRect(0, 0, posterCanvas.width, posterCanvas.height);
    //45 107
    let topHalf = new Image();
    topHalf.src = picUrl + "poster-tophalf.png";
    topHalf.onload = function () {
        //画海报上半部分
        posterCtx.drawImage(topHalf, pxToRem(45 * 2), pxToRem(107 * 2), pxToRem(550 * 2), pxToRem(382 * 2));
        posterCtx.save();
        posterCtx.restore();
        //画海报中部背景
        posterCtx.fillStyle = '#f4f4f4';
        posterCtx.fillRect(pxToRem(45 * 2), pxToRem(489 * 2), pxToRem(550 * 2), pxToRem(flagListHeight * 2));
        posterCtx.save();
        posterCtx.restore();
        //画海报底部
        let bottomHalf = new Image();
        bottomHalf.src = picUrl + "poster-bottomhalf.png";
        bottomHalf.onload = function () {
            bottomHalfTop = pxToRem(487) + pxToRem(flagListHeight);
            $('.poster-tip').css('top', bottomHalfTop + pxToRem(181));
            posterCtx.drawImage(bottomHalf, pxToRem(45 * 2), bottomHalfTop * 2, pxToRem(550 * 2), pxToRem(238 * 2));
            drawFlagItem(pxToRem(489 + 20));
            let decorate = new Image();
            decorate.src = checkedDecorate;
            decorate.onload = function () {
                posterCtx.drawImage(decorate, pxToRem(170 * 2), pxToRem(305 * 2), pxToRem(300 * 2), pxToRem(150 * 2));
                // flagTextDraw(posterCtx, signature, pxToRem(40 * 2), '#222222', pxToRem(230 * 2), (bottomHalfTop + pxToRem(103)) * 2, 'font');
                // flagTextDraw(posterCtx, getTime(), pxToRem(20 * 2), '#222222', pxToRem(230 * 2), (bottomHalfTop + pxToRem(136)) * 2);
                setTimeout(function () {
                    $('.posterImg').attr('src', getManBase64(posterCanvas)).css('height', pxToRem(posterCanvasHeight));
                }, 1000);

            }
        }
    }

}

function drawFlagItem(initialPosition) {
    // initialPosition = initialPosition + parseFloat(getTranslateDistance());
    let noBg = new Image();
    noBg.src = picUrl + 'flag-no.png';
    noBg.onload = function () {
        let redline = new Image();
        redline.src = picUrl + 'flag-redline.png';
        redline.onload = function () {
            let nodeList = $('.poster-list-page .poster-list .flag-item');
            for (let i = 0; i < flagStack.length; i++) {
                let top = initialPosition + $(nodeList[i]).position().top;
                let textTop = top + 17;
                posterCtx.drawImage(noBg, pxToRem(105 * 2), top * 2, pxToRem(44 * 2), pxToRem(39 * 2));
                flagNoDraw(posterCtx, i + 1, 14 * 2, '#222222', pxToRem(129 * 2), (top + pxToRem(28)) * 2);
                let lineTop = flagTextDraw(posterCtx, flagStack[i], 1.4 * fontSize * 2, '#222222', pxToRem(167 * 2), textTop * 2);
                if (lineTop != 0) {
                    posterCtx.drawImage(redline, pxToRem(161 * 2), lineTop, pxToRem(367 * 2), pxToRem(20 * 2));
                }
            }
        }

    }
}

function showPosterPage() {
    $('.effect-page').fadeOut(300);
    $('.poster-page').show();
}

function showCountDownPage() {
    // $('.suggest-page input[name=signature]').val('张三');
    let val = $('.suggest-page input[name=signature]').val();
    if (val.match(/^\s*$/)) {
        $('#notification_area').remove();
        my_notify('请填写名字');
        return false;
    }
    $('.countdown-page').css('background', bgColor);
    createPoster();

    $('.countdown-page').show();
    $('.suggest-page .suggest-wrap').addClass('animate');
    signature = val;

    setTimeout(function () {
        $('.suggest-page').fadeOut(300);
        countDown(function () {
            $('.countdown-page').fadeOut(300);
            $('.effect-page').css('background', bgColor).show();
            setTimeout(function () {
                showPosterPage();
            }, 3000);
        });
    }, 999);
}

function countDown(callback) {
    let angle = 0;
    let countdown = 3;
    let timer;

    countDownCtx.fillStyle = bgColor;
    timer = setInterval(function () {
        $('.countdown-num').text(countdown).addClass('animate');
        angle = ((angle * 10) + 36) / 10;
        if (angle >= 360) {
            countdown--;
            if (countdown == 0) {
                clearInterval(timer);
                callback();
            } else {
                angle = 0;
                let numNode = $('.countdown-num').clone();
                $('.countdown-num').remove();
                numNode.text(countdown);
                console.log(countdown);

                numNode.appendTo('.countdown-page');
            }
        }
        countDownCtx.clearRect(0, 0, countDownCanvas.width, countDownCanvas.height);

        countDownCtx.sector(countDownCanvas.width / 2, countDownCanvas.height / 2, countDownCanvas.width / 2, 0, angle).fill();

    }, 10);
}

function agreeSuggest() {
    $('input[name=signature]').attr('disabled', false);
    $('.suggest-page .agree').hide();
    $('.suggest-page .agree-active').show();
    $('.agree-wrap').removeClass('animate');
    agreeSuggestion = true;
}

function checkAgree() {
    if (!agreeSuggestion) {
        $('.agree-wrap').addClass('animate');
        clearTimeout(agreeTimer);
        agreeTimer = setTimeout(function () {
            $('.agree-wrap').removeClass('animate');
        }, 3000);
    }
}

function inputLength() {
    checkIt('signature', 12);
}

function showSuggestPage() {
    if (!clickDecorate) {
        $('.personal-page .btn-tab-decorate').click();
        return false;
    }
    $('.flag-page').hide();
    $('.suggest-page').css('background', bgColor);
    $('.personal-page .personal-wrap').addClass('animate');
    $('.suggest-page').show();
    setTimeout(function () {
        $('.personal-page').fadeOut(500);
    }, 300);
}

function backToFlag() {
    // $('.personal-page').fadeOut(3000, function () {
    //     setTimeout(function () {
    //         // 
    //     }, 1000)

    // });

    $('.personal-page').animate({
        opacity: 0
    }, 300, function () {
        setTimeout(function () {
            $('.personal-page').css('opacity', 1).hide();
            $('.flag-page').css('zIndex', '6');
        }, 300)

    });
    $('.flag-page').css('opacity', 1);
}

function deleteCheckedFlag(event) {
    const target = $(event.target);
    const text = target.parent().find('.checked-flag-text').text();
    const index = flagStack.indexOf(text);
    flagStack.splice(index, 1);
    target.parent().remove();
    const nodeList = $('.flag-list-content .checked-item');
    for (let i = 0; i < nodeList.length; i++) {
        $(nodeList[i]).find('.checked-flag-no').text(i + 1);
    }


}

function toggleCheckFlagList() {
    if (checkFlagListStatus) {
        $('.checked-flag-list').css('transform', 'scale(0)');
        checkFlagListStatus = false;
    } else {
        $('.checked-flag-list').css('transform', 'scale(1)');
        checkFlagListStatus = true;
    }
}

function closeCheckFlagList() {
    if (checkFlagListStatus) {
        $('.checked-flag-list').css('transform', 'scale(0)');
        checkFlagListStatus = false;
    }
}

function setDecorate(event) {
    let src = event.target.src;
    checkedDecorate = src;
    $('.personal-page .checked-decorate-img').css('background', 'url(' + src + ') left top no-repeat')
        .css('backgroundSize', '100%');

}

function changeMainColor(event) {
    mainColor = event.data.color;
    bgColor = colorList[mainColor][colorIndex - 1];
    $('.personal-page').css('background', bgColor);
    $('.personal-page .colorbar').css('background', 'url(/Public/static/image2/colorbar-' + mainColor + '.png) left top no-repeat')
        .css('backgroundSize', '100%');
    $('.personal-page .maincolor-active').css('left', event.data.left);
    $('.btn-choose-color').removeClass('animate');
}

function chooseColorStart(e) {
    const touch = e.originalEvent.targetTouches[0];
    const startX = (touch.pageX - colorbarLeft) / fontSize;
    setBgColor(startX);
    $('.btn-choose-color').removeClass('animate');
}

function chooseColorMove(e) {
    e.preventDefault();
    if (timer) {
        clearTimeout(timer);
    }
    timer = setTimeout(() => {
        const touch = e.originalEvent.targetTouches[0];
        const moveX = (touch.pageX - colorbarLeft) / fontSize;
        setBgColor(moveX);
    }, 5);
}

function setBgColor(moveX) {
    if (moveX < 4.2916) {
        moveX = 4.2916;
    } else if (moveX > 26.62) {
        moveX = 26.62;
    }

    if (moveX < 6.59) {
        colorIndex = 1;
    } else if (moveX > 6.59 && moveX < 11) {
        colorIndex = 2;
    } else if (moveX > 11 && moveX < 15.46) {
        colorIndex = 3;
    } else if (moveX > 15.46 && moveX < 19.91) {
        colorIndex = 4;
    } else if (moveX > 19.91 && moveX < 24.38) {
        colorIndex = 5;
    } else if (moveX > 24.38) {
        colorIndex = 6;
    }
    bgColor = colorList[mainColor][colorIndex - 1];
    $('.personal-page').css('background', bgColor);

    $('.personal-page .btn-choose-color').css('left', moveX + 'rem');
}

function initDecorate() {
    for (let i = 0; i < decorateList.length; i++) {
        let img = $('<img src="' + decorateList[i] + '" class="decorateImg" />');
        img.appendTo($('.personal-page .decorate-content'));
    }
}

function showBgcolor() {
    $('.personal-page .tab-bgcolor,.personal-page .tab-decorate-active,.decorate-content').hide();
    $('.personal-page .tab-bgcolor-active,.personal-page .tab-decorate,.bgcolor-content').show();
}

function showDecorate() {
    clickDecorate = true;
    $('.personal-page .tab-bgcolor,.personal-page .tab-decorate-active,.decorate-content').show();
    $('.personal-page .tab-bgcolor-active,.personal-page .tab-decorate,.bgcolor-content').hide();
}

function showPersonalPage() {
    if (!checkedDecorate) {
        checkedDecorate = decorateList[0];
        $('.personal-page .checked-decorate-img').css('background', 'url(' + decorateList[0] + ') left top no-repeat')
            .css('backgroundSize', '100%');
    }
    $('.flag-page').animate({
        'opacity': 0
    }, 300, '', function () {
        $('.flag-page').css('z-index', '4');
    });
    $('.personal-page').fadeIn(300);
    // 创建个性化页面的flag列表
    for (let i = 0; i < flagStack.length; i++) {
        createList('.personal-page .flag-list', flagStack[i], i + 1);
    }
}

function createList(target, flag, no, wrapNum = 0) {
    let item = $('<div class="flag-item"></div>');
    item.append($('<div class="flag-no"></div>'));
    item.append($('<div class="flag-text"></div>'));
    item.find('.flag-no').text(no);
    if (wrapNum != 0) {
        let res = '';
        for (let i = 0; i < flag.length; i += wrapNum) {
            res += flag.slice(i, wrapNum) + '<br />';
            if (i + wrapNum >= flag.length) {
                res += flag.slice(i * wrapNum, flag.length);
            }
        }
        flag = res;
    }
    item.find('.flag-text').html(flag);
    $(target).append(item);
}

function addCustomizeFlag() {
    let text = $('input[name=customize-flag]').val();
    if (text.match(/^\s*$/)) {
        $('#notification_area').remove();
        my_notify('请填写flag');
        return false;
    }
    if (firstChooseFlag) {
        $('.checked-flag-list').css('transform', 'scale(1)');
        checkFlagListStatus = true;
        firstChooseFlag = false;
    }
    flagStack.push(text);
    addFlagToList(text);
    $('.flag-page .choose-num').text((chooseNum++) + 1);
    $('input[name=customize-flag]').val('');
}

function addFlag() {
    if (firstChooseFlag) {
        $('.checked-flag-list').css('transform', 'scale(1)');
        checkFlagListStatus = true;
        firstChooseFlag = false;
    }
    $('.flag-choose-tip').removeClass('active');
    let text = $(this).find('.flag-text').text();
    flagStack.push(text);
    addFlagToList(text);
    $('.flag-page .choose-num').text((chooseNum++) + 1);
}

function addFlagToList(text) {
    let item = $('<div class="checked-item"></div>');
    let flagNo = $('<div class="checked-flag-no">' + flagStack.length + '</div>');
    let flagText = $('<div class="checked-flag-text">' + text + '</div>');
    let flagDelete = $('<div class="btn-checked-item-delete">删除</div>');
    item.append(flagNo);
    item.append(flagText);
    item.append(flagDelete);
    $('.flag-page .flag-list-content').append(item);
}

function showFlagPage() {
    if (page1Next) {
        page1Next = false;
        $('.red-line').addClass('animate');
        setTimeout(function () {
            // $('.red-line').removeClass('animate');
            $('.page1').fadeOut(500);
            $('.flag-page').show();
            $('.flag-page .choose-num').text(chooseNum);
            let flagArr = randomFlag();
            for (let i = 0; i < flagArr.length; i++) {
                fadeInTextUp(flag[flagArr[i]], 2000, '.flag' + (i + 1));
            }
        }, 300);

        setTimeout(function () {
            $('.flag-choose-tip').addClass('active');
        }, 2500);
    }
}

function changeFlag() {
    $('.flag-text span').fadeOut(100);
    $('.flag-line,.flag-no,.text-bottom').css('animation', 'none 0 ease 0 1 normal')
    setTimeout(function () {
        let flagArr = randomFlagArr(6);
        for (let i = 0; i < 6; i++) {
            $('.flag' + (i + 1) + ' span').text(flag[flagArr[i]]);
        }
        $('.flag-text span').fadeIn(100);
    }, 100);
}

function randomFlag() {
    $('.flag-frame').html('');
    let flagArr = randomFlagArr(6);
    for (let i = 0; i < flagArr.length; i++) {
        createItem(flag[flagArr[i]], i + 1);
    }
    return flagArr;
}

function randomFlagArr(length) {
    let arr = Array(length);
    for (let i = 0; i < arr.length; i++) {
        arr[i] = getRand(arr);
        oldRandFlag.push(arr[i]);
    }
    arr.sort(function (a, b) {
        return a - b;
    });
    console.log(arr);
    console.log('oldRandFlag:' + oldRandFlag);


    return arr;
}

function getRand(arr) {
    let i = RandomNumBoth(0, flag.length - 1);
    if (oldRandFlag.length == flag.length) {
        oldRandFlag = [];
    }
    if (arr.indexOf(i) == -1 && oldRandFlag.indexOf(i) == -1) {
        return i;
    } else {
        return getRand(arr);
    }
}

function createItem(flag, no) {
    let item = flagTemplate.clone();
    item.find('.flag-no').text(no);
    item.find('.flag-text').append('<span>' + flag + '</span>').addClass('flag' + no);
    $('.flag-page .flag-frame').append(item);
}

function fadeInTextUp(text, fadeTime, divName) {
    //清空div
    $(divName + ' span').remove();
    //分割待处理的数组
    let textArr = text.split('');
    for (let i = 0; i < textArr.length; i++) {
        //遍历数组添加到目标div中
        $(divName).append($('<div class="fly' + i + '">' + textArr[i] + '</div>'));
        //为每个文字设置初始位置并将opacity设置为0，执行fadeTime制定的fadein
        let time = RandomNumBoth(10, 100) / 100;
        $(divName + ' .fly' + i).css('transform', 'translateY(' + RandomNumBoth(2000, 2500) / 100 + 'rem)')
            .css('animationDelay', time / 4 + 's')
            .fadeOut(0)
            .fadeIn(time * 3000);
    }
    setTimeout(function () {
        //待动画执行完毕后删除动画div，将文字合并
        $(divName + ' div[class^=fly]').remove();
        $(divName).append('<span>' + text + '</span>');
    }, 2400);
}

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

CanvasRenderingContext2D.prototype.sector = function (x, y, r, angle1, angle2) {
    this.save();
    this.beginPath();
    this.moveTo(x, y);
    this.arc(x, y, r, angle1 * Math.PI / 180, angle2 * Math.PI / 180, true);
    this.closePath();
    this.restore();
    return this;
}

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 = 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;
}
/**
 * 数组元素交换位置
 * @param {array} arr 数组
 * @param {number} index1 添加项目的位置
 * @param {number} index2 删除项目的位置
 * index1和index2分别是两个数组的索引值，即是两个要交换元素位置的索引值，如1，5就是数组中下标为1和5的两个元素交换位置
 */
function swapArray(arr, index1, index2) {
    arr[index1] = arr.splice(index2, 1, arr[index1])[0];
    return arr;
}

function checkIt(bind, maxNum) {
    if (agreeSuggestion) {
        var v = document.getElementById(bind).value;

        if (v == "") {
            return [];
        }

        var len = 0; //中英字符长度计数
        //计算
        for (i = 0; i < v.length; i++) {
            var c = v.charCodeAt(i);
            if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) //英文字母状态
            {
                len++;
            } else //中文状态
            {
                len += 2;
            }
            if (len >= maxNum) {
                if (i != v.length - 1) {
                    $("#" + bind).val(v.substr(0, i + 1))
                    break;
                }
            }
        }
    } else {
        $("#" + bind).val('');
    }
}

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

function flagNoDraw(ctx, content, fontsize, color, x, y) {
    ctx.font = fontsize + 'px normal';
    console.log(fontsize);

    var width = ctx.measureText(content).width;
    var cx = x - width / 2;
    ctx.fillStyle = color;
    ctx.fillText(content, cx, y);
}

function flagTextDraw(ctx, content, fontsize, color, x, y, font = "normal") {
    let length = calculateStringLength(content);

    let lineTop = 0;
    if (length <= wrapNum * 2) {
        ctx.font = fontsize + 'px ' + font;
        ctx.fillStyle = color;
        ctx.fillText(content, x, y);
        lineTop = y - 8;
    } else {
        let lineArr = [];
        let lineNo = 0;
        for (let i = 0; i < content.length; i += 12) {
            lineArr.push(content.substr(i, 12));
        }
        for (let i = 0; i < lineArr.length; i++) {
            ctx.font = fontsize + 'px normal';
            ctx.fillStyle = color;
            alert(ctx.measureText(content).width);
            ctx.fillText(lineArr[i], x, y + (lineNo * (fontsize + 10)));
            if (i == lineArr.length - 1) {
                lineTop = y + (lineNo * (fontsize + 10)) - 8;
            }
            lineNo++;
        }
    }
    return lineTop;
}

function calculateStringLength(str) {
    var len = 0; //中英字符长度计数
    //计算
    for (i = 0; i < str.length; i++) {
        var c = str.charCodeAt(i);
        if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) //英文字母状态
        {
            len++;
        } else //中文状态
        {
            len += 2;
        }
    }
    return len;
}

function getTime() {
    let date = new Date();
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let day = date.getDate();
    let hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
    let minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();

    return '立于' + year + '/' + month + '/' + day + ' ' + hour + ':' + minute;
}

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