(function (){
    init();

    function init(){
        countDown();
        initCombo();
        initBandwidth();
        initDurationSelect();
        initHuaweiApply();
    }

    // 活动时间处理
    function countDown() {
        let oActivityText = document.getElementById('activityText');

        
        let timer = null;
        const startTime = new Date('2024-08-01 00:00:00');
        const endTime = new Date('2024-08-31 23:59:59');

        const nowTime = new Date();

        const beginDiff = parseInt((startTime.getTime() - nowTime.getTime()) / 1000);
        const endDiff = parseInt((endTime.getTime() - nowTime.getTime()) / 1000);
        // 剩余时间
        const leftTime = beginDiff > 0 ? beginDiff : endDiff;
        let day = parseInt(leftTime / (24 * 60 * 60));
        let hour = parseInt(leftTime / (60 * 60) % 24);
        let minute = parseInt(leftTime / 60 % 60 );
        let second = parseInt(leftTime % 60);
        day = addZero(day);
        hour = addZero(hour);
        minute = addZero(minute);
        second = addZero(second);
        
        if(beginDiff > 0) {
            oActivityText.innerText = `距离活动开始`;
            $('.J_time_day').text(day);
            $('.J_time_hour').text(hour);
            $('.J_time_minute').text(minute);
            $('.J_time_second').text(second);
            timer = setTimeout(countDown, 1000);
        }else if(leftTime <= 0){
            oActivityText.innerText = `活动已结束！更多优惠请在线咨询`;
            $('.J_time_day').text('0');
            $('.J_time_hour').text('00');
            $('.J_time_minute').text('00');
            $('.J_time_second').text('00');
            clearTimeout(timer);
        }else{
            oActivityText.innerText = `距离活动结束还剩`;
            $('.J_time_day').text(day);
            $('.J_time_hour').text(hour);
            $('.J_time_minute').text(minute);
            $('.J_time_second').text(second);
            timer = setTimeout(countDown, 1000);
        }

    }

    function addZero(i){
        return i < 10 ? "0" + i : i;
    }

    // 活动套餐 初始化
    function initCombo() {
        for(let tableKey in idcPrice){
            if(!$('.J_combo[data-table="' + tableKey + '"]')){
                continue;
            }
            let priceTable = idcPrice[tableKey];
            $('.J_combo[data-table="' + tableKey + '"] .J_list').empty();

            let listHtml = "";
            for(let i=0; i<priceTable.comboList.length; i++) {
                let item = priceTable.comboList[i];
                // 处理带宽选择
                let bandItemHtml = "";
                for(var bandKey in item.bandwidth){
                    if(bandKey == 0){
                        bandItemHtml += `<div class="select-value active" data-value="${item.bandwidth[bandKey].value}">${item.bandwidth[bandKey].label}</div>`;
                    }else{
                        bandItemHtml += `<div class="select-value" data-value="${item.bandwidth[bandKey].value}">${item.bandwidth[bandKey].label}</div>`;
                    }
                }
                // 处理周期选择
                let durationItemHtml = "";
                for(var durationKey in item.duration) {
                    durationItemHtml += `<option value="${item.duration[durationKey].value}">${item.duration[durationKey].name}</option>`;
                }
                // 设置默认套餐价格
                let price = (parseFloat(item.duration[0]?.price) + parseFloat(item.bandwidth[0]?.value) * parseFloat(item.bandwidthDuration[0]?.unitPrice)).toFixed(0);
                let oldPrice = (price / 0.7).toFixed(0) ;
                

                listHtml += `
                    <div class="activity-item J_item" data-id="${item.id}">
                        <div class="item-left">
                            <p class="item-name">${item.name}</p>
                            <p class="item-desc">${item.desc}</p>
                        </div>
                        <div class="item-middle">
                            <div class="option">
                                <div class="option-value">${item.stand}</div>
                                <div class="option-name">${priceTable.standName}</div>
                            </div>
                            <div class="option">
                                <div class="option-value">${item.power}</div>
                                <div class="option-name">机柜功率</div>
                            </div>
                            <div class="option-2">
                                <div class="option-select J_bandwidth_select">
                                    ${bandItemHtml}
                                </div>
                                <div class="option-name">独享带宽</div>
                            </div>
                        </div>
                        <div class="item-right">
                            <div class="item-price">
                                <div class="price">
                                    <div class="price-num J_price">${price}</div>
                                    <div class="price-text">
                                        <div class="tips">续费同价</div>
                                        <div class="old-price J_oldPrice">原价 ¥ <span class="J_old_price">${oldPrice}</span></div>
                                    </div>
                                </div>
                                <div class="duration">
                                    <select class="J_duration_select">
                                        ${durationItemHtml}
                                    </select>
                                </div>
                            </div>
                            <div class="item-btn J_buy_alert_btn">
                                <span>立即抢购</span>
                                <div class="discount-tag">${item.discountTag}</div>
                            </div>
                        </div>
                    </div>
                `;
            }

            $('.J_combo[data-table="' + tableKey + '"] .J_list').html(listHtml);
        }
        
    }

    // 活动套餐 带宽点击事件
    function initBandwidth() {
        $('.J_item .J_bandwidth_select .select-value').click(function (e){
            if($(this).hasClass('active')) {
                return;
            }
            let oItem = $(this).parents(".J_item");
            let id = oItem.data('id');
            let tableKey = $(this).parents(".J_combo").data("table");
            let bandwidthValue = $(this).data('value');
            let durationValue = oItem.find(".J_duration_select").val();
            

            calcPrice(tableKey, id, bandwidthValue, durationValue, oItem);
            $(this).siblings(".active").removeClass("active");
            $(this).addClass("active");
        })
    }

    // 活动套餐 周期点击事件
    function initDurationSelect() {
        $('.J_item .J_duration_select').change(function (){
            let oItem = $(this).parents(".J_item");
            let id = oItem.data("id");
            let tableKey = $(this).parents(".J_combo").data("table");
            let bandwidthValue = oItem.find(".J_bandwidth_select .select-value.active").data("value");
            let durationValue = oItem.find(".J_duration_select").val();

            calcPrice(tableKey, id, bandwidthValue, durationValue, oItem);
        });
    }

    // 计算价格
    function calcPrice(tableKey, id, bandwidthValue, durationValue, oItem) {
        let table = idcPrice[tableKey];
        let item = table.comboList.find(i => {
            return i.id == id;
        });
        if(!item) {
            return;
        }
        
        let bandwidthPrice = item.bandwidthDuration.find(a => {
            return a.value == durationValue;
        });

        let standPrice = item.duration.find(b => {
            return b.value == durationValue;
        });
        


        let price = (parseFloat(standPrice?.price) + parseFloat(bandwidthValue) * parseFloat(bandwidthPrice?.unitPrice)).toFixed(0);
        let oldPrice = (price / 0.7).toFixed(0);

        oItem.find('.J_price').text(price);
        oItem.find('.J_old_price').text(oldPrice);
    }

    function initHuaweiApply (){
        var codeOpen = false,
            sending = false,
            phoneReg = /^[1][0-9]{10}$/,
            name = "", // 姓名
            phone = ""; // 手机号
        
        $('.J_huawei_form input[type=submit]').click(function (e){
            var e = e || window.event;
            e.preventDefault();
            if(codeOpen){
                return false;
            }
            
            name = $.trim($('.J_huawei_form input[name=consultName]').val());
            phone = $.trim($('.J_huawei_form input[name=consultPhone]').val());
            if(!name) {
                layer.msg('请输入您的姓名', { icon: 0 });
                return false;
            }
            if(!phoneReg.test(phone)) {
                layer.msg('请输入正确的联系方式', { icon: 0});
                return false;
            }
            
            openHuaweiCode(name, phone);
        });
        
        $('.J_huawei_sale_code .J_huawei_sale_code_form .cancel-btn').on('click', function (e){
            closeHuaweiCode();
        });
        
        $('.J_huawei_sale_code .J_huawei_sale_code_form').on('submit', function (e){
            var e = e || window.event;
            e.preventDefault();
            
            if(sending){
                return false;
            }
            
            sending = true;
            var that = this, form = $(this), loading = layer.msg('加载中', {
                icon: 16,
                shade: 0.01
            });
            
            $.ajax({
                url: form.prop('action'),
                type: form.prop('method') || 'POST',
                data: form.serialize(),
                dataType: 'json',
                success: function (res){
                    layer.close(loading);
                    
                    if(res.code == 0) {
                        layer.msg(res.msg, { icon: 0 });
                    } else {
                        closeHuaweiCode();
                        $('.J_huawei_form input[name=consultName]').val('');
                        $('.J_huawei_form input[name=consultPhone]').val('');
                        layer.msg('提交成功，稍后商务经理会与您联系', { icon: 1 });
                        that.reset();
                    }
                },
                error: function (){
                    layer.msg('系统错误', { icon: 0 });
                },
                complete: function (){
                    form.find('.code-img img').trigger('click');
                    sending = false;
                }
            });
            
            return false;
        });
        
        function openHuaweiCode(name, phone) {
            if(codeOpen) {
                return;
            }
            
            $('.J_huawei_sale_code .J_huawei_sale_code_form .phone').val(phone);
            $('.J_huawei_sale_code .J_huawei_sale_code_form .name').val(name);
            
            $('.J_huawei_sale_code').addClass('show');
            codeOpen = true;
        }
        
        function closeHuaweiCode(){
            $('.J_huawei_sale_code .J_huawei_sale_code_form .phone').val('');
            $('.J_huawei_sale_code .J_huawei_sale_code_form .name').val('');
            
            $('.J_huawei_sale_code').removeClass('show');
            codeOpen = false;
        }
    }



})()