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 () {
    $('.page1').fadeIn(300);
}, function (progress) {

});

// $('input[name=tel]').attr('type','tel');
// $('input[name=tel]').attr('maxlength',11);

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

//用户选择的flag列表
let flagStack = [];
//用户选择的小装饰src
let checkedDecorate;
//用户选择的主色调
let mainColor = 'red';
//用户选择的flag数量
let chooseNum = 0;
//用户选择的色条index
let colorIndex = 4;
//用户选择的背景色
let bgColor = '#e5382a';
//切换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;

//记录初始状态下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('id', 'signature');

//倒计时canvas定义

let canvasinfo = initCanvas('.countdown-canvas', 'countDownCanvas', 254, 254, true);
countDownCanvas = canvasinfo[0];
countDownCtx = canvasinfo[1];

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

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

    $('.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 .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').on('touchstart', chooseColorStart);
    //选择色条拖动
    $('.personal-page .colorbar').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').on('click', agreeSuggest);
    //完成署名
    $('.suggest-page .btn-next').on('click', showCountDownPage);
});

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


    $('.countdown-page').show();
    $('.suggest-page .suggest-wrap').addClass('animate');
    setTimeout(function () {
        $('.suggest-page').fadeOut(300);
        countDown(function () {
            $('.countdown-page').fadeOut(300);
        });
    }, 500);
}

function countDown(callback) {
    let angle = -360;
    let countdown = 3;
    let timer;
    $('.countdown-num').text(countdown).addClass('animate');
    countDownCtx.fillStyle = bgColor;
    timer = setInterval(function () {
        angle = ((angle * 10) + 36) / 10;
        countDownCtx.clearRect(0, 0, countDownCanvas.width, countDownCanvas.height);
        countDownCtx.sector(countDownCanvas.width / 2, countDownCanvas.height / 2, countDownCanvas.width / 2, 0, angle).fill();
        if (angle >= 0) {
            countdown--;
            if (countdown == 0) {
                clearInterval(timer);
                // $('.countdown-num').removeClass('animate');
                callback();

            } else {
                angle = -360;
                $('.countdown-num').text(countdown);
            }
        }
    }, 10);
}

function agreeSuggest() {
    $('.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(300);
    $('.flag-page').animate({
        'opacity': 1
    }, 300, '', function () {
        $('.flag-page').css('z-index', '4');
    });
}

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', '2');
    });
    $('.personal-page').fadeIn(300);
    // 创建个性化页面的flag列表
    for (let i = 0; i < flagStack.length; i++) {
        createList(flagStack[i], i + 1);
    }
}

function createList(flag, no) {
    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);
    item.find('.flag-text').text(flag);
    $('.personal-page .flag-list').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() {
    $('.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]], 1000, '.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);
    }
    arr.sort(function (a, b) {
        return a - b;
    });
    oldRandFlag = arr;
    console.log(arr);

    return arr;
}

function getRand(arr) {
    let i = RandomNumBoth(0, flag.length - 1);
    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
        $(divName + ' .fly' + i).css('transform', 'translateY(' + RandomNumBoth(22, 25) + 'rem)').fadeOut(0).fadeIn(fadeTime);
    }
    setTimeout(function () {
        //待动画执行完毕后删除动画div，将文字合并
        $(divName + ' div[class^=fly]').remove();
        $(divName).append('<span>' + text + '</span>');
    }, 3000);
}

function initCanvas(target, id, canvasWidth, canvasHeight, useRem = false) {
    if (useRem) {
        canvasWidth = (canvasWidth / 20) * fontSize;
        canvasHeight = (canvasHeight / 20) * fontSize;
    }
    $(target).html('<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, false);
    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 = 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;
}
/**
 * 数组元素交换位置
 * @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('');
    }
}