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

$('.loading-page .loading-gif-block').append('<img class="loading-gif" src="' + picUrl + 'loading.gif" />');
$('.loading-page').show();
preloadimages(preloadImageList, function () {
    if (browser.versions.weixin) {
        let musicTime = setInterval(function () {
            if ($('#music')[0].currentTime > 0) {
                $('.loading-page').fadeOut();
                $('.home-page').fadeIn(300);
                $('.home-page .btn-next').addClass('animate');
                $('.wrap-inner').prepend($('<div class="font">1</div>'));
                clearInterval(musicTime);
            }
        }, 100);

    } else {
        $('.loading-page').fadeOut();
        $('.home-page').fadeIn(300);
        $('.home-page .candle-block').addClass('animate');
        $('.home-page .btn-next').addClass('animate');
        $('.wrap-inner').prepend($('<div class="font">1</div>'));
    }

    //海报测试逻辑
    // $('.loading-page').fadeOut();
    // $('.wrap-inner').prepend($('<div class="font">1</div>'));
    // showPosterPage();
    // createPoster();

}, function (progress) {});


const flag = [
    '百病不侵',
    '疫情早散去',
    '家人都平安',
    '小赚一个亿',
    '告别单身狗',
    '孩子都健康',
    '家人常相伴',
    '再也不熬夜',
    '存款超六位',
    '实现买房梦',
    '拿下dream car',
    '考试都能过',
    '一定要读书',
    'A股要给力',
    '牛市早日来',
    '闷声发大财',
    '理财收益翻一番',
    '买齐李佳琪推荐口红'
];
//色值
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 = [
    'http://ccb-lantern.dev.izhida.cn/Public/static/image2/decorate1.png',
    'http://ccb-lantern.dev.izhida.cn/Public/static/image2/decorate2.png',
    'http://ccb-lantern.dev.izhida.cn/Public/static/image2/decorate3.png',
    'http://ccb-lantern.dev.izhida.cn/Public/static/image2/decorate4.png',
    'http://ccb-lantern.dev.izhida.cn/Public/static/image2/decorate5.png',
    'http://ccb-lantern.dev.izhida.cn/Public/static/image2/decorate6.png',
    'http://ccb-lantern.dev.izhida.cn/Public/static/image2/decorate7.png',
    'http://ccb-lantern.dev.izhida.cn/Public/static/image2/decorate8.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;

//记录第一次小装饰
let decoratecClick = true;

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

//海报canvas
let posterCanvas;
let posterCtx;

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

let wrapNum = 0;

//记录初始状态下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哦');
$('input[name=customize-flag]').css('color', '#e29e77').val('也能在这里写下您的心愿哦');
//署名的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];




//海报测试变量
// flagStack = flag;
// checkedDecorate = 'http://ccb-lantern.dev.izhida.cn/Public/static/image2/decorate1.png';
// signature = "张三";



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

$(document).ready(function () {
    $("input").on("blur", function () {
        window.scroll(0, 0); //失焦后强制让页面归位
        if ($(this).attr('name') != 'signature') {
            if ($('input[name=customize-flag]').val().match(/^\s*$/)) {
                $('input[name=customize-flag]').css('color', '#e29e77').val('也能在这里写下您的心愿哦');
            }
        }
    });
    // $('.logo').css('top',getTranslateDistance(15));

    $('.gif-block').append('<img class="musicgif" src="' + picUrl + 'music.gif" />');
    // $('.fireworks-gif').append('<img class="fireworksgif" src="' + picUrl + 'fireworks.gif" />');
    $('.btn-music').css('top', 'auto').css('bottom', getTranslateDistance(10, true));
    $('.customize-frame').css('top', 'auto').css('bottom', getTranslateDistance(-40, true));
    $('.logo').css('top', getTranslateDistance(20, true));


    initPage();

    $('.flag-list-content').attr('id', 'flag-list-content');
    colorbarLeft = $('.colorbar').offset().left;

    //调整flag顺序页面初始化排序插件
    createFlagListSort();

    //跳转到page1
    $('.home-page .btn-next').on('click', showPage1);
    //跳转到flag选择页面
    $('.page1 .btn-next,.page1 .red-line-block').on('click', showFlagPage);
    //换一换按钮点击
    $('.flag-page .btn-change').on('click', changeFlag);
    //选择flag
    $('.wrap-inner').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);
    //小装饰点击
    $('.wrap-inner').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
    $('.wrap-inner').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);
    //音乐按钮点击
    $('.btn-music').on('click', toggleMusic);
    //自定义输入框焦点
    $('input[name=customize-flag]').on('focus', setCustomizeVal);


});

function createFlagListSort() {
    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');
        }
    });
}

function setCustomizeVal() {
    if ($('input[name=customize-flag]').val() == '也能在这里写下您的心愿哦' ||
        $('input[name=customize-flag]').val().match(/^\s*$/)) {
        $('input[name=customize-flag]').css('color', "#ffd594").val('');
    }
}

function toggleMusic() {
    if ($('#music')[0].paused) {
        $('#music')[0].play();
        $('.music.stop').hide();
        $('.music.play').show();
        musicStatus = true;
    } else {
        $('#music')[0].pause();
        $('.music.play').hide();
        $('.music.stop').show();
        musicStatus = false;
    }
}

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) {
        $('.home-page').fadeOut(300);
        $('.page1').show();
        homeNext = false;
        // $('.home-hide').fadeOut(500);
        // $('.home-scale').addClass('animate');
        // $('.home-page .btn-next').removeClass('animate');
        // $('.fireworks-gif').fadeIn(200);
        // setTimeout(function () {
        //     $('.home-page .candle').css('opacity', 1);

        //     setTimeout(function () {
        //         $('.home-page').fadeOut(300);
        //         $('.page1').show();
        //     }, 2500);
        // }, 1500);
    }

}

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 posterLeft = pxToRem(45 * 2);
    let posterTop = pxToRem(107 * 2);
    let flagListTop = pxToRem((350 + 107) * 2);


    //初始化海报canvas
    let canvasinfo = initCanvas('.poster-canvas-block', 'posterCanvas', 640 * 2, 1238 * 2, true);
    posterCanvas = canvasinfo[0];
    posterCtx = canvasinfo[1];
    //计算每行文字数量
    wrapNum = calculationWrap();
    $('.poster-list-page').show();
    $('.poster-page .poster-canvas-block').append($('<img class="posterImg" src="" />'));
    $('.poster-page .poster-canvas-block').append($('<img class="posterImg-true" 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 + 20;
    let topHalfHeight = 390;
    let bottomHalfHeight = 207;
    let posterCanvasHeight = 0;
    flagListHeight = flagListHeight + 60;

    //计算海报总高度
    if (flagListHeight < 400) {
        posterCanvasHeight = topHalfHeight + 400 + bottomHalfHeight;
        flagListHeight = 400;
    } else {
        posterCanvasHeight = topHalfHeight + flagListHeight + bottomHalfHeight;
    }

    posterCanvasHeight += 214;

    //创建海报canvas
    $('#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 = "/Public/static/image2/poster-tophalf.png";
    topHalf.onload = function () {
        //画海报中部背景
        posterCtx.fillStyle = '#ffffff';
        posterCtx.fillRect(posterLeft, flagListTop - 5, pxToRem(550 * 2), pxToRem(flagListHeight * 2) + 10);
        posterCtx.save();
        posterCtx.restore();

        //画海报上半部分
        posterCtx.drawImage(topHalf, posterLeft, posterTop, pxToRem(550 * 2), pxToRem(350 * 2));
        posterCtx.save();
        posterCtx.restore();

        //画海报底部
        let bottomHalf = new Image();
        bottomHalf.src = "/Public/static/image2/poster-bottomhalf.png";
        bottomHalf.onload = function () {
            bottomHalfTop = pxToRem(457) + pxToRem(flagListHeight);
            $('.poster-tip').css('top', bottomHalfTop + pxToRem(133));
            posterCtx.drawImage(bottomHalf, posterLeft, bottomHalfTop * 2, pxToRem(550 * 2), pxToRem(207 * 2));
            drawFlagItem(pxToRem(489 + 20));
            let decorate = new Image();
            decorate.src = checkedDecorate;
            decorate.onload = function () {
                posterCtx.drawImage(decorate, pxToRem(169 * 2), pxToRem(285 * 2), pxToRem(300 * 2), pxToRem(150 * 2));
                flagTextDraw(posterCtx, signature, pxToRem(40 * 2), '#222222', pxToRem(233 * 2), (bottomHalfTop + pxToRem(76)) * 2, 'font');


                setTimeout(function () {
                    $('.posterImg').attr('src', getManBase64(posterCanvas)).css('height', pxToRem(posterCanvasHeight));
                    //绘制tip
                    let tip = new Image();
                    tip.src = "/Public/static/image2/poster-tip.png";
                    tip.onload = function () {
                        posterCtx.drawImage(tip, pxToRem(111 * 2), (bottomHalfTop + pxToRem(133)) * 2, pxToRem(70 * 2), pxToRem(32 * 2));
                        setTimeout(function () {
                            $('.posterImg-true').attr('src', getManBase64(posterCanvas)).css('height', pxToRem(posterCanvasHeight));
                        }, 300);
                    }
                }, 1000);

            }
        }
    }

}

function drawFlagItem(initialPosition) {
    initialPosition = initialPosition - 20;
    let noBg = new Image();
    noBg.src = '/Public/static/image2/flag-no.png';
    noBg.onload = function () {
        let redline = new Image();
        redline.src = '/Public/static/image2/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, 11 * 2, '#ffffff', pxToRem(127 * 2), (top + pxToRem(26)) * 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(375 * 2), pxToRem(9 * 2));
                }
            }
        }

    }
}

function showPosterPage() {
    $('.effect-page').fadeOut(300);
    // $('.wrap-inner').css('top', '0').css('transform', 'translate(0,0)');
    $('.poster-page').show();
}

function showCountDownPage() {
    if (suggestNext) {

        let val = $('.suggest-page input[name=signature]').val();
        if (val.match(/^\s*$/)) {
            $('#notification_area').remove();
            my_notify('请填写名字');
            return false;
        }

        suggestNext = 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();
                    $('#notification_area').remove();
                    my_notify('晒出您的心愿吧!<br>长按可以保存图片哦!', 3000);
                }, 2000);
            });
        }, 200);
    }
}

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,.wrap').css('background', bgColor);
    $('.personal-page .personal-wrap').addClass('animate');
    $('.suggest-page').show();
    setTimeout(function () {
        $('.personal-page').fadeOut(500);
    }, 300);
}

function backToFlag() {
    $('.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();
    $('.flag-page .choose-num').text((chooseNum--) - 1);
    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;
    // checkedDecorate = 'http://ccb-lantern.dev.izhida.cn/Public/static/image2/' + src.replace("https://static3.izhida.cn/cdn1/chinaamc-2020flag/v1.1.7/image2/", "");
    $('.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) {
    console.log(e);

    const touch = e.originalEvent.targetTouches[0];
    const startX = (touch.pageX - colorbarLeft) / fontSize;
    console.log(startX);

    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() {
    let arr = [8, 7, 6, 5, 4, 3, 2, 1, 8, 7, 6, 5, 4, 3, 2, 1];
    for (let i = 0; i < decorateList.length * 2; i++) {
        let img = $('<img src="' + picUrl + 'decorate' + arr[i] + '.png" 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();
    if (decoratecClick) {
        decoratecClick = false;
        let left = (81.25 * fontSize) - (8.125 * fontSize);
        $('.decorate-content').scrollLeft(left);
    }
}


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) {
    console.log(wrapNum);

    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 = '';
        let wn = wrapNum * 2;
        let nowLen = 0;
        for (let i = 0; i < flag.length; i++) {
            const tLen = calculateStringLength(flag[i]);
            if (nowLen + tLen <= wn) {
                res += flag[i];
                nowLen += tLen;
            } else {
                res = res + '<br/>' + flag[i];
                nowLen = 0;
            }
        }
        flag = res;
    }
    item.find('.flag-text').html(flag);
    $(target).append(item);
}

function addCustomizeFlag() {
    let text = $('input[name=customize-flag]').val();
    if (text.match(/^\s*$/) || $('input[name=customize-flag]').val() == '也能在这里写下您的心愿哦') {
        $('#notification_area').remove();
        my_notify('请填写你的心愿');
        return false;
    }

    $('.flagadd').show().addClass('animate');
    setTimeout(function () {
        $('.flagadd').removeClass('animate');
    }, 2000);
    if (firstChooseFlag) {
        $('.flag-page .choose-block').addClass('animate');
        firstChooseFlag = false;
    }
    flagStack.push(text);
    addFlagToList(text);
    $('.flag-page .choose-num').text((chooseNum++) + 1);
    $('input[name=customize-flag]').css('color', '#e29e77').val('也能在这里写下您的心愿哦');
    //mark
}

function addFlag(e) {
    let text = $(this).find('.flag-text').text();
    if (flagStack.indexOf(text) != -1) {
        $('#notification_area').remove();
        my_notify('这个心愿已经许过啦!');
        return false;
    }
    if (firstChooseFlag) {
        $('.flag-page .choose-block').addClass('animate');
        firstChooseFlag = false;
    }
    $('#flagMusic')[0].currentTime = 0;
    $('#flagMusic')[0].play();
    $(e.currentTarget).find('.star1,.star2').addClass('animate');
    setTimeout(function () {
        $(e.currentTarget).find('.star1,.star2').removeClass('animate');
    }, 2500);

    $('.flag-choose-tip').removeClass('active');

    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,.red-line2').addClass('animate');
        setTimeout(function () {
            $('.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));
            }
        }, 700);

        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, abs = false) {
    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]);
    if (abs) {
        var wrapInnerjl = Math.abs(wrapInnertop - wrapInnerTransform);
    } else {
        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 + 10;
    } else {
        let lineArr = [];
        let lineNo = 0;

        let res = '';
        let wn = wrapNum * 2;
        let nowLen = 0;
        for (let i = 0; i < content.length; i++) {
            const tLen = calculateStringLength(content[i]);
            if (nowLen + tLen <= wn) {
                res += content[i];
                nowLen += tLen;
                if (i == content.length - 1) {
                    lineArr.push(res);
                }
            } else {
                lineArr.push(res);
                res = content[i];
                if (i == content.length - 1) {
                    lineArr.push(res);
                }
                nowLen = 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;
            ctx.fillText(lineArr[i], x, y + (lineNo * (fontsize + 10)));
            if (i == lineArr.length - 1) {
                lineTop = y + (lineNo * (fontsize + 10)) + 10;
            }
            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');
}