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

let flagStack = [];
let chooseNum = 0;
let oldRandFlag = [];
let first = true;
let startX;
let timer;
let mainColor = 'red';
let colorIndex = 4;
let checkedDecorate;
let checkFlagListStatus = false;
let firstChooseFlag = true;

const fontSize = parseFloat($('html').css('fontSize'));

let flagTemplate = $('.flag-page .flag-frame').find('.flag-block').clone();
$('.flag-frame').html('').addClass('clearfix');
$('input[name=customize-flag]').attr('placeholder', '也能在这里写你的flag哦');

let listTemplate = $('.personal-page .flag-list').find('.flag-item').clone();
$('.personal-page .flag-list').html('');

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');
    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 .btn-choose-color').on('touchstart', chooseColorStart);
    //选择色条拖动
    $('.personal-page .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);
});

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;
    $('.personal-page').css('background', colorList[mainColor][colorIndex - 1]);
    $('.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);
}

function chooseColorStart(e) {
    let touch = e.originalEvent.targetTouches[0];
    startX = touch.pageX / fontSize;
}

function chooseColorMove(e) {
    e.preventDefault();
    if (timer) {
        clearTimeout(timer);
    }
    timer = setTimeout(() => {
        let touch = e.originalEvent.targetTouches[0];
        moveX = touch.pageX / fontSize;


        let left = parseFloat($('.personal-page .btn-choose-color').css('left')) / fontSize;
        left = left + (moveX - startX);

        if (left < 4.2916) {
            left = 4.2916;
        } else if (left > 26.62) {
            left = 26.62;
        }

        if (left < 6.59) {
            colorIndex = 1;
        } else if (left > 6.59 && left < 11) {
            colorIndex = 2;
        } else if (left > 11 && left < 15.46) {
            colorIndex = 3;
        } else if (left > 15.46 && left < 19.91) {
            colorIndex = 4;
        } else if (left > 19.91 && left < 24.38) {
            colorIndex = 5;
        } else if (left > 24.38) {
            colorIndex = 6;
        }

        $('.personal-page').css('background', colorList[mainColor][colorIndex - 1]);

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

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

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