var spiServer = $("#spiServer").val();
var isPC = ($(window).width()>768);
var loginState = false;
// 导航分类数据
var mainClassify = new Vue({
    el: '#mainClassify',
    data: {
        classify: []
    },
    methods: {},
    created: function () {
        var _self = this;
        $.getJSON(spiServer+"/product/classify").done(function (r) {
            if (r.code === 0 && r.data) {
                _self.classify = r.data;
                if(isPC){
                    setTimeout(function(){
                        $('#mainClassify').slide({
                            mainCell:".clsCon"
                            ,titCell:".clsTab a"
                            ,trigger: "mouseover"
                        });
                    },500);
                }else{
                    setTimeout(function(){
                        $('#mainClassify').slide({
                            mainCell:".clsCon"
                            ,titCell:".clsTab a"
                            ,trigger: "click"
                        });
                    },500);
                }
            }
        });
    }
});
// 头部购物车数据
var headCart = new Vue({
    el: '#headCart',
    data: {
        cartList: [],
        cartCount: 0,
        productCount: 0,
        priceTotal: 0
    },
    methods: {},
    created: function () {
        var _self = this;
        $.getJSON("/header/cart?userId=1050").done(function (r) {
            if (r.code === 0 && r.data) {
                _self.cartList = r.data;
                _self.cartCount = r.data.length;
                r.data.map(function(item){
                    _self.productCount += item.number;
                    _self.priceTotal += item.number*item.price;
                });
            }
        });
    }
});
// 初始化效果
$(function(){
    $(window).resize(function() {
        var flag = (isPC && $(window).width()<=768) || (!isPC && $(window).width()>768);
        if(flag){
            window.location.reload();
        }
    });
    if(isPC){
        jqClickShow(".baseHeadTop .cTab", ".baseHeadTop .cShow");
        jqSelect(".jqSelect");
        jqHoverShow(".classBtn", "#mainClassify");
    }else{
        jqMultipleShow("click", ".footLink .list", ".tab", ".con");
        $('body').on('click', '.baseHeadCenter .mClassBtn',function () {
            $('#mainClassify').show();
            fixedBody();
        }).on('click', '#mainClassify .close,#mainClassify .mClassBtn',function () {
            $('#mainClassify').hide();
            looseBody();
        }).on('click', '#mainClassify',function (e) {
            e.stopPropagation();
        });
    }
    $('body').on("click", '.toLogin',function () {
        $('.loginAlert').show();
        if(!isPC){fixedBody();}
    }).on("click", '.loginAlert .box',function (e) {
        e.stopPropagation();
    }).on("click", '.loginAlert .close,.loginAlert em.btn,.loginAlert',function () {
        $('.loginAlert').hide();
        if(!isPC){looseBody();}
    });
    // 置顶
    $('#scrollTop').on("click", '.toTop',function () {
        $("html,body").animate({scrollTop:0},500);
    });
    // 热线
    if(!isPC){
        $('#scrollTop').on("click", '.phone',function () {
            $('#scrollTop').find('.phoneHover').show();
            fixedBody();
        }).on("click", '.phoneHover div',function (e) {
            e.stopPropagation();
        }).on("click", '.phoneHover,.phoneHover .close',function () {
            $('#scrollTop').find('.phoneHover').hide();
            looseBody();
        });
    }
    // 侧边栏滚动判断
    $(window).scroll(function () {
        if($('body').attr("style") && $('body').attr("style").indexOf('fixed')>0){
            return false;
        }
        var scoll = Math.max($('html').scrollTop(), $('body').scrollTop());
        if(scoll >200){
            $('#scrollTop').show();
        }else {
            $('#scrollTop').hide();
        }
    });

});
// 公共方法
function jqClickShow(tab, con){
    $("body").on("click", tab, function(e){
        e.stopPropagation();
        if($(tab).hasClass("on")){
            $(tab).removeClass("on");
            $(con).slideUp("fast");
        }else{
            $(tab).addClass("on");
            $(con).slideDown("fast");
        }
    }).on("click", function(){
        $(tab).removeClass("on");
        $(con).slideUp("fast");
    });
}
function jqHoverShow(tab, con){
    $("body").on("mouseover", tab, function(e){
        e.stopPropagation();
        if($(tab).hasClass("on")){
            $(tab).removeClass("on");
            $(con).slideUp("fast");
        }else{
            $(tab).addClass("on");
            $(con).slideDown("fast");
        }
    }).on("mouseover", con, function(e){
        e.stopPropagation();
    }).on("mouseover", function(e){
        $(tab).removeClass("on");
        $(con).slideUp("fast");
    });
}
function jqMultipleShow(event, item, tab, con){
    $("body").on(event, item+' '+tab, function(e){
        e.stopPropagation();
        $(this).parents(item).siblings(item).find(con).slideUp("fast");
        $(this).parents(item).siblings(item).removeClass("on");
        $(this).parents(item).siblings(item).find(tab).removeClass("on");
        if($(this).hasClass("on")){
            $(this).removeClass("on");
            $(this).parents(item).removeClass("on");
            $(this).parents(item).find(con).slideUp("fast");
        }else{
            $(this).addClass("on");
            $(this).parents(item).addClass("on");
            $(this).parents(item).find(con).slideDown("fast");
        }
    }).on(event,  item+' '+con, function(e){
        e.stopPropagation();
    }).on(event, function(){
        $(item+' '+tab).removeClass("on");
        $(item).removeClass("on");
        $(item+' '+con).slideUp("fast");
    });
}
function jqSelect(selectBox){
    $("body").on("click", selectBox, function(e){
        e.stopPropagation();
        var select = $(this).find("select");
        var options = select.find("option");
        var list = "";
        for (var i=0; i<options.length; i++){
            list += '<li data-id="'+$(options[i]).val()+'">'+$(options[i]).text()+'</li>';
            if($(options[i]).val()===select.val()){
                $(this).find("[data-select]").text($(options[i]).text()).attr('data-select',$(options[i]).val());
            }
        }
        $(this).find("ul").html(list);
        $(this).find("ul").slideToggle("fast");
    }).on("click", selectBox + " li", function(e){
        e.stopPropagation();
        $(this).parent().prev().attr('data-select',$(this).attr("data-id")).text($(this).text());
        $(this).parents("pc").next().val($(this).attr("data-id"));
        $(this).parent().slideUp("fast");
    }).on("click", function(){
        $(selectBox).find("ul").slideUp("fast");
    });
}
//解决移动端滚动穿透
function fixedBody(){
    var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
    setTimeout(function(){
        document.body.style.cssText += 'position:fixed;top:-'+scrollTop+'px;';
    },10);
}
function looseBody() {
    var body = document.body;
    body.style.position = '';
    var top = body.style.top;
    document.body.scrollTop = document.documentElement.scrollTop = -parseInt(top);
    body.style.top = '';
}
//url参数
function getUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = decodeURIComponent(unescape(window.location.search)).substr(1).match(reg);
    if (r != null) {
        return (r[2])
    }
    return null;
}
function updateUrlParam(params) {
    var loca = window.location;
    var baseUrl = loca.origin + loca.pathname + "?";
    var query = loca.search.substr(1).toLowerCase();
    var queryArr = query.split("&");
    var keys = Object.keys(params);
    if (keys.length > 0) {
        var obj = {};
        for (var i = 0; i < queryArr.length; i++) {
            queryArr[i] = queryArr[i].split("=");
            obj[queryArr[i][0]] = queryArr[i][1]
        }
        for (var k = 0; k < keys.length; k++) {
            var name = keys[k];
            var value = params[name];
            obj[name.toLowerCase()] = value;
        }
        var url = baseUrl + JSON.stringify(obj).replace(/["\{\}]/g, "").replace(/\:/g, "=").replace(/\,/g, "&");
        return url;
    }
}
function setProductPrice(productList, userId, callback){
    var productIdArr = [];
    productList.map(function(product){
        product.priceLoading = true;
        // 0公开价格 1不公开价格 2仅对会员机构公开
        if (product.priceflag != 1){
             productIdArr.push(product.pid)
        }
    });
    var productIds = productIdArr.join(",");
    $.getJSON(spiServer+"/product/listPrice",{
        userId: userId,
        productIds: productIds
    }).done(function (r) {
        if (r.code === 0 && r.data) {
            var priceList = r.data;
            productList.map(function(product){
                priceList.map(function(item){
                    if(product.pid == item.productId){
                        product.userIdentity = item.userIdentity;
                        product.price = item.price;
                        product.priceLoading = false;
                    }
                });
            });
        }
        return callback();
    }).fail(function(){
        return callback();
    })
}
