var spiServer = $("#spiServer").val();
var isPC = ($(window).width()>768);
var globalUserData = '';
var GLOBAL_TOKEN = 'X-Token';
var GLOBAL_USER_ID = 0;
var GLOBAL_USER_IDENTITY = 0;
var GLOBAL_SHOP_ID = 0;
if(localStorage.getItem('userInfo')){
    globalUserData = JSON.parse(localStorage.getItem('userInfo'));
    GLOBAL_TOKEN = globalUserData.token;
    GLOBAL_USER_ID = globalUserData.userId;
    GLOBAL_USER_IDENTITY = globalUserData.identity ? globalUserData.identity : globalUserData.userIdentity;
    GLOBAL_SHOP_ID = globalUserData.shopId;
}
// 头部
var globalHead = new Vue({
    el: '#globalHead',
    data: {
        loginStatus: false,
        userData: {},
        classify: [],
        headCart: {
            cartList: [],
            cartCount: 0,
            productCount: 0,
            priceTotal: 0
        },
        shopId:'',
        userIdentity:'',
        articleType: ''
    },
    methods: {
        // 导航分类数据
        getClassify: 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);
                    }
                }
            });
        },
        // 头部购物车数据
        getHeadCart: function(userId) {
            var _self = this;
            $.getJSON("/header/cart?userId="+userId).done(function (r) {
                if (r.code === 0 && r.data) {
                    _self.headCart.cartList = r.data;
                    _self.headCart.cartCount = r.data.length;
                    r.data.map(function(item){
                        _self.headCart.productCount += item.number;
                        _self.headCart.priceTotal += item.number*item.price;
                    });
                }
            });
        },
        pageLinkSupplier: function(){//预览商品
            window.open('/supplier/index.html?id='+this.shopId);
        },
        // 退出登录
        userLogOut: function(){
            localStorage.removeItem('userInfo');
            this.loginStatus = false;
            window.location.href = "/index.html";
        }
    },
    created: function () {
        // 导航分类数据
        this.getClassify();
        // 判断登录状态
        if (globalUserData.token) {
            this.loginStatus = true;
            this.userData = globalUserData;
            if(this.userData.userId){
                // 获取头部购物车数据
                this.getHeadCart(this.userData.userId);
            }
        }
        // 信息中心
        this.articleType = getUrlParam("type");
    },
    mounted:function(){
        var userData =JSON.parse(window.localStorage.getItem('userInfo'));
        if(userData!=null){
            this.userIdentity = userData.userIdentity;
            this.shopId = userData.shopId;
        }
    }
});
// 初始化效果
$(function(){
    // PC,H5切换时刷新
    $(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 () {
        $.confirm({
            useBootstrap: false,
            boxWidth: (isPC?'338px':'74.6vw'),
            title: false,
            content:'<div class="loginAlert"><span>你还未登录</span><span>请登录后再进行购买</span></div>',
            closeIcon: true,
            animation: 'opacity',
            closeAnimation: 'opacity',
            animateFromElement: false,
            scrollToPreviousElement: false,
            buttons: {
                login: {
                    text: '去登录',
                    btnClass: 'btn-confirm-login',
                    action: function(){
                        localStorage.setItem("loginBeforePath", window.location.href);
                        window.location.href = '/login.html';
                    }
                },
                close: {
                    text: '取消',
                    btnClass: 'btn-cancel-login'
                }
            }
        });
    });
    // 置顶
    $('#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();
        });
        $('body').on("click", '#centerNav .home',function () {
            $('#centerNav').find('.home').toggleClass("on");
            $('#centerNav').find('.centerBox').slideToggle();
            fixedBody();
        }).on("click", '#centerNav .wrap',function (e) {
            e.stopPropagation();
        }).on("click", '#centerNav .centerBox',function () {
             $('#centerNav').find('.home').removeClass("on");
            $('#centerNav').find('.centerBox').slideUp();
            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();
        }
    });
    // 顶部搜索框
    $('#topSearch').on("click", '.searchBtn', function(){
        var type = isPC ? $('#topSearch').find('[data-select]').attr("data-select")*1 : $('#topSearch').find('select').val()*1;
        var keyword = $.trim($('#topSearch').find('.keyword').val());
        if (keyword.length < 2) {
            $.confirm({
                useBootstrap: false,
                boxWidth: (isPC?'300px':'70%'),
                title:'提示',
                content:'请至少输入两个关键字！',
                closeIcon: true,
                animation: 'opacity',
                closeAnimation: 'opacity',
                animateFromElement: false,
                buttons: {
                    close: {
                        text: '确定',
                        btnClass: 'btn-confirm'
                    }
                }
            });
            return false;
        }
        if (type === 0) {
            // 商品
            window.location.href = '/product/list.html?keyword='+encodeURIComponent(keyword);
        } else if(type === 1) {
            // 供应商
            window.location.href = '/supplier/list.html?keyword='+encodeURIComponent(keyword);
        } else if (type === 2) {
            // 项目仪器
            window.location.href = '/equipment/list.html?keyword=' + encodeURIComponent(keyword);
        } else{
            // 文章
            window.location.href = '/info/search.html?keyword=' + encodeURIComponent(keyword);
        }
    }).on('keyup', '.keyword', function(event) {
        // 搜索输入框 按回车键搜索
        var keyCode = event.keyCode || event.which;
        if(keyCode === 13){
            $(this).parents('#topSearch').find('.searchBtn').trigger("click");
        }
    }).on("click", '.hotKey .word', function(){
        // 点击热词 触发搜索
        $(this).parents('#topSearch').find('.keyword').val($(this).text());
        $(this).parents('#topSearch').find('.searchBtn').trigger("click");
    });



});
// 公共方法
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(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 tokenAjax(type, url, params, callback){
    $.ajax({
        type: type,
        url: spiServer + url,
        xhrFields: {
            withCredentials: true
        },
        data: params,
        headers:{
            'Content-Type': type=='post'?'application/x-www-form-urlencoded':'application/json;charset=utf8',
            'X-Token':GLOBAL_TOKEN
        },
        success : function (res) {
            if(res.code === -99){
                localStorage.removeItem('userInfo');
                window.location.href ='/login.html';
            }else{
                callback(res);
            }
        },
        error : function (res) {
           alertInfo("网络连接超时,请重试!")
        }
    });
}

function setSearchProductList(list, userId) {//处理搜索
    var productIdArr = [];
    var resultData = [];
    list.map(function (item) {
        resultData.push({
            id: item.p_id,
            name: item.p_name,
            image: item.p_image,
            unit: item.p_unit,
            brand: item.p_brand_name,
            priceFlag: item.p_price_flag,
            priceGrade: item.p_price_flag,
            actStatus: 0,
            priceLoaded: false
        });
        // 0公开价格 1不公开价格 2仅对会员机构公开
        if (item.p_price_flag !== 1) {
            productIdArr.push(item.p_id)
        }
    });
    if (userId && userId > 0) {
        setProductPrice(resultData, productIdArr.join(","), userId, function () {});
    }else {
    var userId = 0;
     setProductPrice(resultData, productIdArr.join(","), userId, function () {});
    }
    return resultData;
}
function setProductPrice(productList, productIds, userId, callback){
    $.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.id*1 === item.productId){
                        product.userIdentity = item.userIdentity;
                        product.price = item.price;
                        product.priceLoaded = true;
                        product.ladderPriceFlag = item.ladderPriceFlag;
                        product.actStatus =item.actStatus;
                        product.promotions =item.promotions;
                    }
                });
            });
            console.log(productList)
        }
        return callback();
    }).fail(function(){
        return callback();
    })
}
// 登录后返回登录前页面
function toBeforePath(){
    var beforePath = localStorage.getItem("loginBeforePath");
    if (!beforePath) {
        beforePath = '/index.html';
    }
    window.location.href = beforePath;
}
function toLogin() {//去登录
    window.location.href ='/login.html';
}
function  upgrade () { //升级会员
    window.location.href='';
}
/**
 * 至少保留两位小数
 * 10 => "10.00"
 * @param {number} num
 */
function toFloat(num) {
  var temp = String(num).split('.');
  if (temp.length === 1 || temp[1].length < 2) {
    return Number(num).toFixed(2);
  }else{
    return Number(num);
  }
}

/** 表单输入框校验 */
function verifyHandle(obj){
    if ($(obj).is(":hidden")) { return false; }
    var v = $.trim($(obj).val()).replace(/\s+/g,"");
    var reg = $(obj).attr("rule");
    var errorTxt = $(obj).siblings('.errTips').attr("tips");
    if ($.trim(v) === '') {
        if ($(obj).attr("placeholder").indexOf("请输入")>=0) {
            errorTxt = $(obj).attr("placeholder").split("请输入")[1]+'不能为空';
        } else {
            errorTxt = '不能为空';
        }
        setErrorTxt(obj, errorTxt);
        return false;
    }else if (typeof reg != "undefined") {
        reg = new RegExp(reg);
        if (!reg.test(v)) {
            setErrorTxt(obj, errorTxt);
            return false;
        }
    }
    clearErrorTxt(obj);
}
function setErrorTxt(obj, txt) {
    $(obj).parent().addClass("error").find('.checked').removeClass("show");
    $(obj).siblings('.errTips').text(txt).addClass("show");
}
function clearErrorTxt(obj) {
    $(obj).siblings('.errTips').removeClass("show");
    $(obj).parent().removeClass("error").find('.checked').addClass("show");
}
// 提交时验证表单
function verifyForm() {
    $("[needverify]:visible").each(function (index, ele) {
        if (!$(ele).siblings('.checked').hasClass("show")) {
            verifyHandle(ele);
        }
    });
    var len = $('.errTips.show:visible').length;
    return (len === 0);
}
// 单个验证表单
function verifyCheack(ele) {
    if (!$(ele).siblings('.checked').hasClass("show")) {
        verifyHandle(ele);
    }
    var len = $(ele).siblings('.errTips.show:visible').length;
    return (len === 0);
}

// 公共信息提示弹框
function alertInfo(txt,callback) {
    $.confirm({
        useBootstrap: false,
        boxWidth: (isPC?'300px':'70%'),
        title:'提示',
        content: txt,
        closeIcon: true,
        animation: 'opacity',
        closeAnimation: 'opacity',
        animateFromElement: false,
        buttons: {
            close: {
                text: '确定',
                btnClass: 'btn-confirm',
                action: function () {
                    callback()
                }
            }
        }
    });
}
//公共吐司
function dialog(txt,callback) {
    $.confirm({
        title: false,
        content: txt,
        boxWidth: (isPC?'300px':'70%'),
        autoClose: 'close|2000',
        useBootstrap:false,
        buttons: {
            close:{
                isHidden: true,
                action: function () {
                    callback()
                }
            }
        }
    });
}

// 加入购物车
function addShoppingCart(userId, productId, count, callback){
    tokenAjax("post", "/shoppingCart/addCart", {
        userID: userId,
        productID: productId,
        productCount: count
    },function (res) {
        if(res && res.code*1 === 0){
            globalHead.getHeadCart(userId);
            $.confirm({
                useBootstrap: false,
                boxWidth: (isPC?'338px':'74.6vw'),
                title: false,
                content:'<div class="cartAlert"><h6>商品已成功加入购物车！</h6><p>当前购物车共<em>'+res.data+'</em>种商品</p></div>',
                closeIcon: true,
                animation: 'opacity',
                closeAnimation: 'opacity',
                animateFromElement: false,
                scrollToPreviousElement: false,
                buttons: {
                    login: {
                        text: '去结算',
                        btnClass: 'btn-to-cart',
                        action: function(){
                            window.location.href = '/shopping/cart.html';
                        }
                    },
                    close: {
                        text: '继续购物',
                        btnClass: 'btn-to-goon',
                        action: callback?callback():function(){}
                    }
                }
            });
        } else {
            dialog("加入购物车失败！");
        }
    });
}

