"use strict";

/*by zhang chi */
!function (a) {
    a.fn.slide = function (b) {
        var c = a.extend({
            autoPlay: 1,
            delayTime: 4000,
            interTime: 600,
            trigger: 0,
            triggerEvent: 1,
            defaultIndex: 0,
            panle: ".panel ul",
            prev: ".prev",
            next: ".next",
            startSlide: null,
            endSlide: null
        }, b || {});
        return this.each(function () {
            function r() {
                o && clearInterval(o), o = setInterval(function () {
                    m = d, m++, t(m);
                }, c.delayTime);
            }

            function s() {
                o && clearInterval(o);
            }

            function t(a) {
                n = 0;
                var b = a;
                a == l && (b = 0), -1 == a && (b = l - 1), 0 != c.trigger && e.children().eq(b).addClass("active").siblings().removeClass("active"), f.children().eq(b + 1).addClass("active").siblings().removeClass("active"), "function" == typeof c.startSlide && c.startSlide(f, a), f.stop(!0, !1).animate({
                    left: -a * k
                }, c.interTime, function () {
                    a == l && (f.css({
                        left: 0
                    }), a = 0), -1 == a && (f.css({
                        left: -1 * (l - 1) * k
                    }), a = l - 1), n = 1, d = a, "function" == typeof c.endSlide && c.endSlide(f, a);
                });
            }

            var e,
                m,
                o,
                p,
                q,
                b = a(this),
                d = c.defaultIndex,
                f = b.find(c.panle),
                g = f.children(),
                h = b.find(c.prev),
                i = b.find(c.next),
                k = (f.parent().height(), f.parent().width()),
                l = f.children().length,
                n = 1;
            1 == c.trigger ? (q = '<div class="trigger">', f.children().each(function (a) {
                q += d == a ? '<span class="active">' + (a + 1) + "</span>" : "<span>" + (a + 1) + "</span>";
            }), q += "</div>", f.parent().after(q), e = b.find(".trigger")) : null != c.trigger && 0 != c.trigger && (e = a(c.trigger, b)), f.prepend(g.eq(l - 1).clone().css("marginLeft", -k)), f.append(g.eq(0).clone()), f.css({
                width: k * (l + 2),
                left: -d * k
            }), g.eq(d).addClass("active"), c.autoPlay && r(), 0 != c.trigger && e.children().bind("mouseenter", function () {
                if (s(), 1 == c.triggerEvent) {
                    var b = a(this).index();
                    p = setTimeout(function () {
                        t(b);
                    }, 200);
                }
            }).bind("mouseleave", function () {
                c.autoPlay && r(), p && clearTimeout(p);
            }).bind("click", function () {
                2 == c.triggerEvent && t(a(this).index());
            }), h.click(function () {
                return n ? (m = d, m--, t(m), void 0) : !1;
            }), i.click(function () {
                return n ? (m = d, m++, t(m), void 0) : !1;
            }), f.bind("mouseenter", function () {
                s();
            }).bind("mouseleave", function () {
                c.autoPlay && r();
            }), h.bind("mouseenter", function () {
                s();
            }).bind("mouseleave", function () {
                c.autoPlay && r();
            }), i.bind("mouseenter", function () {
                s();
            }).bind("mouseleave", function () {
                c.autoPlay && r();
            });
        });
    };
}(jQuery);
$.fn.extend({
    scrollUp: function scrollUp(o) {
        o = $.extend({
            delayTime: 2000,
            interTime: 1000,
            size: 5
        }, o);
        var el = $(this);

        if (el.children().length <= o.size) {
            return false;
        }

        var h = el.children().eq(0).height();

        function play() {
            var a = el.children().eq(0);
            a.animate({
                "margin-top": -h
            }, o.interTime, function () {
                a.css("margin-top", 0).appendTo(el);
            });
        }

        var timer = setInterval(play, o.delayTime);
        el.hover(function () {
            clearInterval(timer);
        }, function () {
            timer = setInterval(play, o.delayTime);
        });
    },
    scrollLeft: function scrollLeft(o) {
        o = $.extend({
            interTime: 1500,
            size: 4
        }, o);
        var el = $(this); // if (el.children().length <= o.size) {
        //     return false;
        // }

        var w = el.children().eq(0).width();
        var len = el.children().length;
        var size = len >= 8 ? 4 : (len - 4) % 4;
        el.css({
            width: w * len + w * 15
        });
        var prev = el.parent().siblings('.pn').find('.prev');
        var next = el.parent().siblings('.pn').find('.next');

        if (len < 5) {
            return el.parent().siblings('.pn').remove();
        }

        el.parent().siblings('.pn').append('<div class="mask hide"></div>');
        var mask = el.parent().siblings('.pn').find('.mask');
        next.click(function (event) {
            event.stopPropagation();
            mask.removeClass('hide');
            el.prepend('<div class="next-wrap clearfix"></div>');
            var nextWrap = el.find('.next-wrap');
            el.children().each(function (index) {
                if (index <= size) {
                    $(this).appendTo(nextWrap);
                }
            });
            nextWrap.animate({
                "margin-left": -w * size - 15 * size
            }, o.interTime, function () {
                nextWrap.children().each(function () {
                    $(this).appendTo(el);
                    mask.addClass('hide');
                });
                nextWrap.remove();
            });
        });
        prev.click(function (event) {
            event.stopPropagation();
            mask.removeClass('hide');
            el.css({
                left: -w * size - 15 * size,
                width: w * el.children().length + w * 15 + 956
            });
            el.children().each(function (index) {
                if (index >= len - size) {
                    $(this).prependTo(el);
                }
            });
            el.animate({
                left: 0
            }, o.interTime, function () {
                mask.addClass('hide');
            });
        });
    }
}); //获取最大值

function getMax(arr) {
    var _this = this;

    var num = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
    var MaxArr = arr.map(function (item) {

        var data = item.data.map(function (max) {
            return max == "-" ? 0 : max;
        });
        return Math.max.apply(_this, data);
    });
    return Math.max.apply(this, MaxArr) + num;
}

; //获取最小值

function getMin(arr) {
    var _this2 = this;

    var num = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
    var MaxArr = arr.map(function (item) {
        var data = item.data.map(function (min) {
            return min == "-" ? 0 : min;
        });
        return Math.min.apply(_this2, data);
    });
    return Math.min.apply(this, MaxArr);
}

;

function focusPicture(el) {
    var len = el.find('.panel li').length;

    if (len < 2) {
        return false;
    }

    var w = "20%";

    if (len > 3) {
        w = Math.round(80 / len, 1) + "%";
    }

    el.slide({
        trigger: 1,
        startSlide: function startSlide(ele, index) {
            var a = el.find(".trigger span");

            if (index == -1) {
                index = len - 1;
            } else if (index == len) {
                index = 0;
            }

            cover.stop(true, false).animate({
                left: a.eq(index).position().left + 6
            }, 500);
        }
    });
    el.find('.panel img').each(function (index, el) {
        $(this).attr('src', $(this).attr('data-original'));
    });
    el.find(".trigger span").html("<i></i>");
    el.find(".trigger span").each(function (index) {
        $(this).find('i').text(index + 1);
    });
    var cover = el.children('.cover');
    cover.css({
        width: w,
        left: el.find(".trigger span").eq(0).position().left + 6,
        display: 'block'
    });
} // $('.main-slider .panel li:first img').animate({opacity: 1},300);


function slidePicture(el) {
    var len = el.find('.panel li').length;
    el.append('<div class="trigger"></div>');

    for (var i = 0; i < len; i++) {
        el.find('.trigger').append('<span>');
    }

    if (len < 2) {
        return false;
    }

    var w = "20%";

    if (len > 3) {
        w = Math.round(80 / len, 1) + "%";
    }

    var i_mun = 0;
    var timer_banner = null;
    el.find('.panel li:first').css('z-index', 1);
    el.find('.panel li:gt(0)').hide(); //页面加载隐藏所有的li 除了第一个

    el.find('.trigger span:first').addClass('active'); //自动播放函数

    function bannerMoveks() {
        timer_banner = setInterval(function () {
            move_banner();
        }, 6400);
    }

    bannerMoveks(); //开始自动播放
    //鼠标移动到banner上时停止播放

    el.find('.panel').mouseover(function () {
        clearInterval(timer_banner);
    }); //鼠标离开 banner 开启定时播放

    el.find('.panel').mouseout(function () {
        bannerMoveks();
    });

    function move_banner() {
        if (i_mun == len - 1) {
            i_mun = -1;
        } //大图切换


        el.find('.panel li').eq(i_mun + 1).fadeIn(600).siblings('li').fadeOut('slow');
        el.find('.trigger span').eq(i_mun + 1).addClass('active').siblings().removeClass('active');
        i_mun++;
    } //底下小图标点击切换


    el.find('.trigger span').hover(function () {
        $(this).addClass('active').siblings('span').removeClass('active');
        var i_mun1 = el.find('.trigger span').index(this);
        el.find('.panel li').eq(i_mun1).fadeIn(600).siblings('li').fadeOut('slow');
        clearInterval(timer_banner);
        i_mun = i_mun1;
    }, function () {
        bannerMoveks();
    });
    el.find('.panel img').each(function (index, el) {
        $(this).attr('src', $(this).attr('data-original'));
    });
    el.find(".trigger span").html("<i></i>");
    var tWidth = 0 - el.find(".trigger").outerWidth();
    el.find(".trigger").css('margin-left', tWidth);
} //scroll handle


function scrollHandler() {
    //panel  Animation
    $(window).unbind('scroll,resize').on('scroll resize', function () {
        var scrollTop = $(this).scrollTop();
        var panelAnimationTop = $(".panel-about").offset().top;

        if (scrollTop >= panelAnimationTop - 300) {
            $('.panel-parallelogram .item-1').css({
                display: 'block',
                animation: 'parallelogram-slide-1 2s ease'
            });
            $('.panel-parallelogram .item-2').css({
                display: 'block',
                animation: 'parallelogram-slide-2 2s ease'
            });
            $('.panel-parallelogram .item-3').css({
                display: 'block',
                animation: 'parallelogram-slide-3 2s ease'
            });
            $('.panel-parallelogram .item-4').css({
                display: 'block',
                animation: 'parallelogram-slide-4 2s ease'
            });
            $('.panel-bubble').css({
                display: 'block',
                animation: 'bubble-show 3.5s ease'
            });
            setTimeout(function () {
                $(".panel-content .panel-mask").css({
                    display: "none"
                });
            }, 3000);
        }
        /*var panelPurchaseTop = $('.panel-purchase').offset().top;
         if(scrollTop >= panelPurchaseTop- 300){
         $('.panel-purchase .img-1 .img-bg').css({
         display: 'block',
         animation: 'bg 2s ease'
         });
         $('.panel-purchase .img-1 .word-1').css({
         display: 'block',
         animation: 'img-1-word-1 1.2s ease'
         });
         $('.panel-purchase .img-1 .word-2').css({
         display: 'block',
         animation: 'img-1-word-2 1.2s ease'
         });
         $('.panel-purchase .img-1 .word-3').css({
         display: 'block',
         animation: 'img-1-word-3 1.2s ease'
         });
         $('.panel-purchase .img-1 .pic-1').css({
         display: 'block',
         animation: 'img-1-right-1 1.2s ease'
         });
         $('.panel-purchase .img-1 .pic-2').css({
         display: 'block',
         animation: 'img-1-right-2 1.2s ease-out'
         });
         }*/

        /*右侧 欢迎咨询滚动才显示*/


        if (scrollTop >= 320) {
            $('.right-weiget').stop(false, false).animate({
                right: 0,
                opacity: 1
            }, 200);
        } else {
            $('.right-weiget').stop(false, false).animate({
                right: -36
            }, 200);
        }
    });
}

; //click event handle

function eventHandle() {
    //panel-nav 菜单切换，异步加载panel-content的内容
    var obj = $('.panel-trend .panel-nav li,.panel-product .panel-nav li');
    obj.on('mouseover', function () {
        var content = $(this).parents(".mnue_nr.main-panel").find('.panel-content.clearfix');
        $(this).addClass('active').siblings().removeClass('active');
        var id = $(this).attr('data-id');
        var index = $(this).attr('data-index');
        $(this).parents('.mnue_nr.main-panel').find('.panel-content .content-wrap[data-index=' + index + ']').removeClass('hide').siblings('.content-wrap').addClass('hide');
        var url = $(this).parent().attr('data-url');
        if (typeof url == 'undefined') return LCGT.msg({
            content: '参数错误'
        });
    });
}

function inquiry() {
    //panel-product event

    /*click inquiry price*/
    $('.panel-product .cell-right button').click(function (event) {
        event.stopPropagation();
        var url = $(this).attr('data-url');
        var id = $(this).attr('data-id');
        var obj = $(this);
        $.ajax({
            url: url,
            dataType: 'json',
            type: 'post',
            data: {
                goods_id: id,
                num: 1
            },
            success: function success(res) {
                if (res.code == 1) {
                    LCGT.msg({
                        content: '询价成功！'
                    });
                    obj.addClass('hide');
                    obj.after('<span class="send-text">询价已发送</span>');
                } else if (res.code == -1) {
                    //未登录
                    loginTips(event);
                } else {
                    //失败提示
                    LCGT.tips({
                        el: obj,
                        text: res.msg
                    });
                }
            }
        });
    });
}

function loginTips(a) {
    var el = $(".login-tips");

    if (!el.length) {
        el = $('<div class="login-tips">');
        el.html('<div class="bd clearfix"><i class="ico"></i><span class="words">提示：登录后方可进行此操作</span><a class="btn">登录</a></div><div class="close"></div>');
        $("body").append(el);
        el.find('.close').on('click', function (event) {
            el.css('display', 'none');
        });
        el.find('.btn').on('click', function (event) {
            el.remove();
            LCGT.loginWidget();
        });
    }

    if (el.css('display') == 'none') {
        var pos = getMousePos(a);
        el.css({
            display: 'block',
            left: pos.x - 282,
            top: pos.y
        });
    }
}

function getMousePos(event) {
    var e = event || window.event;
    var scrollX = document.documentElement.scrollLeft || document.body.scrollLeft;
    var scrollY = document.documentElement.scrollTop || document.body.scrollTop;
    var x = e.pageX || e.clientX + scrollX;
    var y = e.pageY || e.clientY + scrollY;
    return {
        'x': x,
        'y': y
    };
} //news title width handle


function newsTitleWidthHandler() {
    $('.panel-news .panel-center .news-link p').each(function () {
        var firstTitleWidth = $(this).find('.first-link').outerWidth();
        var totleWidth = $(this).outerWidth();
        $(this).find('.last-link').css({
            width: totleWidth - firstTitleWidth - 25
        });
    });
} //purchase 采购管家 提交订单


function purchaseEventHandler() {
    var phone = $(".J-phone");
    var code = $('.J-code');
    var text = $('.purchase-demand');
    var contact = $('.J-people');

    var reg = function reg(a, b) {
        var c = new RegExp(b);
        return c.test(a);
    }; //purchase-img handler


    $('.panel-purchase .trigger span').hover(function (event) {
        event.stopPropagation();
        $(this).addClass('active').siblings().removeClass('active');
        var dataIndex = parseInt($(this).attr('data-index'));
        $('.panel-purchase .panel-img li').eq(dataIndex).addClass('active').siblings().removeClass('active');
    });
    var index = 0;

    function purchasePlay() {
        $('.panel-purchase .trigger span').eq(index).trigger('mouseenter');
        index++;

        if (index === 3) {
            index = 0;
        }
    }

    var timer = setInterval(purchasePlay, 3800);
    /*send-code*/

    $('.panel-steward .send-code').click(function (event) {
        event.stopPropagation();

        if ($(this).hasClass("a-disabled")) {
            return false;
        }

        var phoneVal = $.trim(phone.val());

        if (phoneVal == '') {
            LCGT.tips({
                el: phone,
                text: "手机号码不能为空！"
            });
            phone.val('').focus();
            return false;
        }

        if (!reg(phoneVal, "^(13|15|18|14|17|19)[0-9]{9}$")) {
            LCGT.tips({
                el: phone,
                text: "手机号码不正确！"
            });
            phone.focus();
            return false;
        }

        $(this).addClass('a-disabled').html("正在发送...");
        $.ajax({
            url: "/index/ajaxSend",
            type: "POST",
            data: {
                phone: phoneVal
            },
            dataType: "json",
            cache: false,
            success: function success(data) {
                if (data.code == 200) {
                    wait = 120;
                    getSetTime();
                    LCGT.tips({
                        // el: $(".su_ipt2"),
                        el: $(".J-code"),
                        text: data.msg
                    });
                } else {
                    LCGT.tips({
                        el: $(".su_ipt2"),
                        text: data.msg
                    });
                }
            }
        });
    }); // wait send code time

    var wait = 0;

    function getSetTime() {
        if (wait == 0) {
            code.find("a").removeClass("a-disabled");
            $(".send-code").removeClass("a-disabled");
            $(".send-code").html("重新发送");
        } else {
            $(".send-code").addClass("a-disabled");
            $(".send-code").html("重新发送(" + wait + ")");
            wait--;
            $(".send-code").data('timer', setTimeout(function () {
                getSetTime();
            }, 1000));
        }
    }

    var isSend = 0;
    var el = $('.upload');
    var fileUrl = $('#file_name');
    /*submit purchase order*/

    $('.J-submit').click(function (event) {
        var that = $(this);

        if (that.hasClass('disabled')) {
            return false;
        }

        var textVal = $.trim(text.val());
        var phoneVal = $.trim(phone.val());
        var codeVal = $.trim(code.val());
        var fileVal = $.trim(fileUrl.val());
        var contactVal = $.trim(contact.val());

        if (textVal == '' && !isSend) {
            LCGT.tips({
                el: text,
                text: "请填写采购需求信息或上传采购单！",
                skin: 'bounceIn-grey',
                duration: 2000
            });
            text.focus();
            return false;
        }

        if (phoneVal == '') {
            LCGT.tips({
                el: phone,
                text: "手机号码不能为空！"
            });
            phone.val('').focus();
            return false;
        }

        if (contactVal == '') {
            LCGT.tips({
                el: contact,
                text: "请输入联系人姓名"
            });
            return false;
        }

        if (!reg(phoneVal, "^(13|15|18|14|17|19)[0-9]{9}$")) {
            LCGT.tips({
                el: phone,
                text: "手机号码不正确！"
            });
            phone.focus();
            return false;
        }

        if (codeVal == '') {
            LCGT.tips({
                el: code,
                text: "手机验证码不能为空！"
            });
            code.val('').focus();
            return false;
        }

        that.addClass('disabled').html('正在提交...'); //ajax

        $.ajax({
            url: '/index/ajaxsubmit',
            type: 'post',
            dataType: 'json',
            data: {
                contact: contactVal,
                phone: phoneVal,
                valid_code: codeVal,
                ph_info: textVal,
                file_name: fileVal,
                is_file: 1,
                url: get_page_url(),
                purchaseToken: $('#purchase_token').val()
            },
            success: function success(res) {
                if (res.code == 200) {
                    $('.panel-purchase .send-code').removeClass('a-disabled').html('发送验证码');
                    LCGT.purchase_submit(res);
                } else {
                    LCGT.msg({
                        content: res.msg
                    });
                }
            }
        });
    });
}

var data = [{
    xData: ['11月8日', '11月9日', '11月10日', '11月11日', '11月12日'],
    yData: [3733, 3753, 3778, 3751, 3761]
}, {
    xData: ['15周', '16周', '17周', '18周', '本周'],
    yData: [10, 18, 20, 30, 20]
}, {
    xData: ['7月', '8月', '9月', '10月', '11月'],
    yData: [3753, 3718, 3611, 3651, 3721]
}];
var colors = ['#ff4a4a', '#61aaff', '#58c00c', 'rgba(255,74,74,0.1)', 'rgba(72,156,255,0.1)', 'rgba(85,184,15,0.1)'];

/**
 * @param {object} datas - {xData:['11月8日','11月9日','11月10日','11月11日','11月12日'],
 *   yData:[3733, 3753, 3778, 3751, 3761]}
 * @param {object} ele - '.section-hot .center .index-tab-content .day'
 * @param {boolean} isWeigh
 * */

function spotPriceChart(ele, datas, isWeigh) {
    var seriesName = typeof isWeigh == 'undefined' ? '价格指数' : '地磅指数';
    var color = '';
    var areaColor = '';

    if (datas.yData[datas.yData.length - 1] > datas.yData[datas.yData.length - 2]) {
        color = colors[0];
        areaColor = colors[3];
    } else if (datas.yData[datas.yData.length - 1] < datas.yData[datas.yData.length - 2]) {
        color = colors[2];
        areaColor = colors[5];
    } else {
        color = colors[1];
        areaColor = colors[4];
    }

    var option = {
        tooltip: {
            trigger: 'axis'
        },
        grid: {
            left: '0',
            right: '0',
            bottom: '0',
            top: '5%',
            containLabel: true,
            show: true,
            borderColor: 'rgba(182,187,206,.8)',
            borderWidth: 1
        },
        xAxis: [{
            type: 'category',
            boundaryGap: true,
            data: datas.xData,
            splitLine: {
                lineStyle: {
                    color: 'rgba(182,187,206,.8)'
                }
            },
            axisLine: {
                lineStyle: {
                    color: 'rgba(182,187,206,.8)'
                }
            },
            axisTick: {
                show: true,
                alignWithLabel: true
            }
            /*axisLabel:{
             interval:0
             }*/

        }],
        yAxis: [{
            type: 'value',
            axisLine: {
                lineStyle: {
                    color: '#96a2b4'
                }
            },
            splitLine: {
                lineStyle: {
                    color: 'rgba(182,187,206,.8)'
                }
            },
            // min: 50*Math.floor(Math.min.apply(null,datas.yData)/50),
            // max: 50*Math.ceil(Math.max.apply(null,datas.yData)/50),
            min: Math.min.apply(null, datas.yData) - 20 > 0 ? Math.min.apply(null, datas.yData) - 20 : 0,
            max: 100 * Math.ceil(Math.max.apply(null, datas.yData) / 100)
        }],
        series: [{
            color: [color],
            name: seriesName,
            type: 'line',
            lineStyle: {
                normal: {
                    color: color
                }
            },
            // showAllSymbol: true,
            // smooth: true,
            areaStyle: {
                normal: {
                    color: areaColor
                }
            },
            data: datas.yData
        }]
    };
    var chart = echarts.init(ele);
    chart.setOption(option);
}

var filterZero = function filterZero(arr) {
    return arr.map(function (item) {
        if (item == 0) {
            return "-";
        } else {
            return item;
        }
    });
};

var toggloEchartsModal =  function (e, index, code, parentDom) {


    let dom = e.parents(".MaskBox").find(".EchartsMask");

    let timeArr = ["近1月", "近3月", "近6月", "近1年",'近7天'];


    let time = '时间范围为<span style="color: #007cdf;">' + timeArr[index] + "</span>的数据";


    let text = code == 5 ? '仅供<span style="color: #007cdf;">钢铁世界会员</span>查看' : code == 6 ? '仅供<span class="lvip">行情VIP</span>查看' : '仅供行情<span style="color: #007cdf;">高级VIP</span>查看';

    dom.find(".echartsTime").html(time);
    dom.find(".echartsTips").html(text);
    code == 1 ? dom.hide() : dom.show();
    if (code == 5) {
        parentDom.find(".echartsLogin").show();
        parentDom.find(".echartsHandle").hide();
    } else {
        parentDom.find(".echartsLogin").hide();
        parentDom.find(".echartsHandle").attr("level",code-4); //code: 2、VIP，3、高级VIP
        let level = code - 4

        parentDom.find(".echartsHandle").show();
    }
};

function getGoodsEchartData(event, ele, date_id,flag) {
    $.post('/index/getComprehensiveData', {
        time: date_id
    }, function (res) {
       let e = event.length ? $(event.target) : $(".selectBtn").eq(0);
        console.log("e", e, $(event.target)," $(event.target)");
        toggloEchartsModal(e, date_id - 1, res.code,$(".EchartIndex"))


				
				if(flag != 1){
					
					var dataInOut = '<span>时间：</span>'
					for (let i = 0; i < res.data.times.length; i++) {
						const element = res.data.times[i];
						if(element.value!=""){
							// dataInOut+=`<button onclick="doGetInOut(${element.value},this)" class="chartDateNew1" dateId="${element.value}">${element.show_name}</button>`
							dataInOut+=`<button class="selectBtn" dateId="${element.value}">${element.show_name}</button>`
						}
					}
					$('.MaskBoxTimeZongHe').html(dataInOut)
					$('.selectBtn').eq(0).addClass('active')
				}
				// else{
				// 	for (let index = 0; index < $('.selectBtn').length; index++) {
				// 		const element = $('.selectBtn')[index];
				// 		if($(element).attr('dateId')==times){
				// 			$(element).addClass('active')
				// 		}
				// 	}
				// }

        if (res.code === 1) {
            var Ydata = res.data.data.arr.map(function (item) {
                return {
                    type: 'line',
                    name: item.name,
                    data: filterZero(item.yData)
                };
            });
            var nameArr = res.data.data.arr.map(function (item) {
                return item.name;
            });
            var MAXNUM = getMax(Ydata);
            var MINNUM = getMin(Ydata);
            var options = {
                tooltip: {
                    trigger: 'axis'
                },
                grid: {
                    top: "8%",
                    left: '1%',
                    right: '4%',
                    bottom: '15%',
                    containLabel: true
                },
                legend: {
                    data: nameArr,
                    icon: "circle",
                    itemWidth: 12,
					itemHeight: 12,
					bottom:'2%',
                    itemGap: 10,
                    textStyle: {
                        fontSize: 13,
                        color: "#333"
                    }
                },
                xAxis: [{
                    type: 'category',
                    data: res.data.data.t,
                    axisPointer: {
                        type: 'shadow'
                    }
                }],
                yAxis: [{
                    type: 'value',
                    // min: 3200,
                    // max: getMax(Ydata)<4800?4800:getMax(Ydata,200),
                    // interval: 200,
                    max: 100 * Math.ceil(MAXNUM / 100) + 200,
                    min: 100 * Math.floor(MINNUM / 100) - 100,
                    splitNumber: 5
                }],
                series: Ydata
            };
            var chart = echarts.init(ele);
            chart.setOption(options);
        } else if (res.code == 5) {
            // loginTips(event);
            console.log("event", event)
        }
    }, 'json');
}

function weightChart(event, date_id) {
    if ($('.chart').length > 0) {
		//地磅指数
		// getChartsData
        $.post('/index/getChartsData', {
            type: 'weight',
            time: date_id
        }, function (res) {
			console.log(res,'llkj')
            let e = event.length ? $(event.target) : $(".chartDate").eq(0);

            toggloEchartsModal(e, date_id - 1, res.code, $(".EchartsWeight"))

            if (res.code === 1) {
                var dataArr = res.data;
                spotPriceChart($('.chart')[0], {
                    xData: dataArr.xData,
                    yData: dataArr.yData
                }, true);
            } else if (res.code == 5) {
                // loginTips(event);
            }
        }, 'json');
    }

    ;
}

$().ready(function () {
    /*图表登录按钮事件*/
    $(".echartsLogin").click(function(event){
        LCGT.loginWidget();
    })

    /*图表开通按钮事件*/
    $(".echartsHandle").click(function(event){
		 $.ajax({
			url: "/login/getSaveInfo",
			async:false,
			type: "get",
			data: {},
			dataType: "jsonp",
			success:function(res){
				if(res.data){
					LCGT.openMarket();
				}else{
					LCGT.loginWidget();
				}
	
			}
		});


        // if ($("input[name='isLogin']").val()) {
        //     LCGT.openMarket();
        // } else {
        //     LCGT.loginWidget();
        // }
    });


    scrollHandler();
    $(window).trigger('scroll');
    eventHandle();
    purchaseEventHandler();
    $('.record-slider').scrollUp({
        size: 1
    });
    $('.product-card-wrap .panel ul').each(function () {
        $(this).scrollLeft({
            size: 4
        });
    });
    slidePicture($('.main-slider'));
    focusPicture($(".slide-img"));
    inquiry();
    $(".chartDate").click(function (event) {
        //切换选中样式
        $(this).addClass("active").siblings().removeClass("active");
        var date_id = $(this).attr("dateId");
        // weightChart(event, date_id);
    });
    $(document).on('click','.selectBtn',function (event) {
        //切换选中样式
        $(this).addClass("active").siblings().removeClass("active");
        getGoodsEchartData(event, $("#goodsEcharts")[0], $(this).attr("dateId"),1);
    }); //初始化图表数据

    // weightChart(1, 1);
    getGoodsEchartData(1, $("#goodsEcharts")[0], '');
    var timer, index, scrollData; //优质报价商家滚动事件

    function scrollPrice(Arr, i) {
        var dom, appendDom;
        dom = $("#quotingTrader");
        timer = setInterval(function () {
            appendDom = "";
            appendDom += '<div class="h_list" style="display: none;">\n' + '<a href="' + Arr[i].url + '" target="_blank">' + '<div>\n' + '        <div class="h_company">\n' + '                <span>\n' + Arr[i].short_name + '                </span>\n' + '            <div>\n';

            if (Arr[i].open_panorama == 1) {
                appendDom += '  <img src="/assets/images/index/360.png" title="该商家已开通360°全景" alt="">';
            }

            appendDom += '  <img src="/assets/images/index/indexUp.png" alt="" title="价格指数特约采集单位">' + '  </div>\n' + '        </div>\n' + '        <div class="goodsNumber" title="报价' + Arr[i].trade_product_str + '等' + Arr[i].count + '个产品">\n' + '            报价' + Arr[i].trade_product_str + '等' + Arr[i].count + '个产品\n' + '        </div>\n' + '        </div>\n' + '        </a>\n' + '    </div></a>';
            i = i === Arr.length - 1 ? 0 : i + 1;
            index = i;
            dom.prepend(appendDom);
            dom.children(".h_list:last-child").slideUp();
            dom.children(".h_list:first-child").slideDown();
            setTimeout(function () {
                dom.children(".h_list:last-child").remove();
            }, 1000);
        }, 3000);
    }

    $.ajax({
        url: 'index/getSpotPriceIndex',
        type: 'post',
        dataType: 'json',
        data: {},
        success: function success(res) {
			scrollData = res.data.res;
            scrollPrice(scrollData, 6);
        }
    }); //鼠标移入后停止滚动。

    $("#quotingTrader").hover(function () {
        clearInterval(timer);
    }); //鼠标移除后恢复滚动事件；

    $("#quotingTrader").mouseleave(function () {
        index = index ? index : 6;
        scrollPrice(scrollData, index);
    });
    $('.panel-steward .panel-content .mid li a, .panel-quote .panel-float a').click(function (e) {
        var url = $(this).attr('data-url')
        console.log(url,'hhhhhhh')
        var type = $(this).data('type');
        var that = $(this);
        e.preventDefault();
        $.post('/index/islogin', {}, function (res) {
			var NewUrl = res.data.user_type 
			if(NewUrl == 1){
				//买家
				url = $('#myJia').val()
			}else{
				url = $('#maiJia').val()
			}
            if (res.code === 1) {
				if(that.attr('data-my') == 1){
					// 今日报价新需求 
					$.get('/index/getisauthbaojia', {}, function (res) {
						// res.data.code = 0
						if(res.data.code == 1){
							// 可以报价 就跳转
							// window.open(url);
							window.location.href = url
						}
						if(res.data.code == 2){
							// 审核中
							LCGT.msg({content: "今日报价申请审核中，如有疑问请联系客服"});
						}
						if(res.data.code == 3){
							// 审核不通过
							LCGT.msg({content: "请联系客服开通今日报价"});
						}
						if(res.data.code == 0 ){
							// 没开通
							console.log(res,'123123123')
							$('.phoneInput_l').val(res.data.info.mobile)
							$('.gongsiInput_l').val(res.data.info.suppliers_name)
                            $('.tellInput_l').val(res.data.info.real_name)
                            console.log($('.l_qcode').find('img'),'llll')
                            console.log($('.l_qcode').find('img').attr('src'),'llll')
                            console.log(res.data.qrcode,'llll')
							$('.l_qcode').find('img').attr('src',res.data.qrcode)

							// alert(海哥)

							that.attr('href','javascript:void(0)')
							$('.l_show').hide()
							$('.l_bgBlack').show()
						}

					});
				}else{
                    var data = res.data;

                if (data.user_type === 1) {
                    var el = $('.popup-quote');

                    if (type !== 1) {
                        el.css('width', '400px');
                        el.find('.com-popup-content p.main').text('求购信息现只对钢铁世界园区商户开放！');
                    }

                    el.removeClass('hide');
                    LCGT.popup({
                        el: el,
                        mask: {
                            opacity: .1
                        }
                    });
                } else {
                    // window.open(url);
                }
                }
                
            } else {
                var tipsType = type === 1 ? 1 : 2;
                LCGT.loginWidget('', tipsType,1);
            }
        });
	});
	// 提交申请 
	$('.l_leftBoxSub_btn').click(function(){
		var mobile = $('.phoneInput_l').val()
		var suppliers_name=	$('.gongsiInput_l').val()
		var name = $('.tellInput_l').val()
		$.post('/index/postbaojiaInfo', {
			mobile,
			suppliers_name,
			name
		},  function(res) {
			if(res.data.code == 1){
				LCGT.msg({content: "提交成功"});
				$('.l_show').show()
			}else{
				LCGT.msg({content: res.msg});
			}

		});
	})
	// 关闭弹框
	$('.l_bgBlack').click(function(){
		$(this).hide()
		window.location.reload()
	})
	$('.l_close').click(function(){
		$('.l_bgBlack').hide()
		window.location.reload()
	})
	$(".l_bgBlackSon").click(function(event){
		event.stopPropagation();
	})

    var footerleftP = $('.popup-quote'); //关闭弹窗DIV的Class

    footerleftP.find('.com-popup-close').click(function (event) {
        //关闭弹出
        $('.ui-mask').remove();
        footerleftP.stop().animate({
            left: "-100%",
            display: "none"
        }, 600);
    });
    // var rollwidth = 0;
    // var wrawidth = 0;
    // var hintWrap = $(".hint-wrap");
    // var hintWrapUl = $(".hint-wrap ul");
    // var iCountA = setInterval(function () {
    //     hintrolls();
    // }, 25);
    // $(".hint-wrap ul li").each(function () {
    //     wrawidth = wrawidth + $(this).outerWidth(true) - 50;
    // });

    // function hintrolls() {
    //     var hwid = wrawidth - rollwidth;

    //     if (rollwidth > hwid) {
    //         rollwidth = 0;
    //     } else {
    //         rollwidth = rollwidth + 1;
    //     }

    //     hintWrapUl.stop(false, false).animate({
    //         "margin-left": -rollwidth
    //     }, 1);
    // };
    // hintWrap.mouseenter(function () {
    //     clearInterval(iCountA);
    // });
    // hintWrap.mouseleave(function () {
    //     iCountA = setInterval(function () {
    //         hintrolls();
    //     }, 25);
    // });
    var rollsHbox = $(".panel-content .right .list ul");
    var rollsHt = rollsHbox.find("li").outerHeight(true);
    console.log(rollsHt,'rollsHt')
    var iCountB = setInterval(function () {
        rollsH();
    }, 2000);

    function rollsH() {
        rollsHbox.stop(false, true).animate({
            "margin-top": -rollsHt
        }, 1500, function () {
            rollsHbox.append(rollsHbox.find("li:first"));
            rollsHbox.css({
                "margin-top": "0px"
            });
        });
    }

    ;
    rollsHbox.mouseenter(function () {
        clearInterval(iCountB);
    });
    rollsHbox.mouseleave(function () {
        iCountB = setInterval(function () {
            rollsH();
        }, 2000);
    });
    $('.right-weiget').css({
        "opacity": "0"
    });

    var Loop1 = null, Loop2 = null
    getTodayOfferLists()
    Loop1 = setInterval(function () {
		// 每2分钟更新一次今日报价数据
		clearInterval(iCountA);
		getTodayOfferLists()
    }, 60000);
    getRecommendList()
    getCollegeList()
    Loop2 = setInterval(function () {
        // 每3分钟更新一次实力商家数据
        // 每3分钟更新一次焦点推荐数据
        getRecommendList()
        getCollegeList()
    }, 120000);
    // 实力商家数据
    function getCollegeList() {
        $.ajax({
            url: 'index/getCollegeList',
            type: 'get',
            data: {},
            dataType: 'json',
            success: function (res) {
              if(res.code==0){
                var collegeData = res.data
                var collegeHtml = ''
                collegeData.forEach(function(item,index){
                    collegeHtml += '<div class="tab-item">'
                                    + (item.suppliers_logo?'<a href="'+ item.url +'" target="_blank"><img src="'+item.suppliers_logo+'" alt="'+item.short_name+'" width="67px" height="50px"></a>':'<img src="../assets/images/no_pur.jpg" alt="暂无图片" width="67px" height="50px">')
                                    + '<div class="right">'
                                    +   '<a href="'+item.url+'" target="_blank">'
                                    +       '<h2 title="'+item.short_name+'">'+item.short_name+'</h2>'
                                    +   '</a>'
                                    +   '<span class="descri"  title="主营:'+item.trade_product+'"><span class="main">主营：</span>'+item.trade_product+'</span>'
                                    +   '<div class="brand">'
                                    + (item.is_cat_ad_pay&&item.is_cat_ad_pay==1?'<img src="../assets/images/company/is_cat_ad_pay.png" alt="" title="钢铁世界网建议您优先选择类目商家">':'')
                                    + (item.is_category_ad_pay&&item.is_category_ad_pay==1?'<img src="../assets/images/identification/Category.png" alt="" title="钢铁世界网建议您优先选择类目商家">':'')
                                    + (item.is_index_advert&&item.is_index_advert==1?'<img src="../assets/images/identification/Hpas.png" alt="" title="钢铁世界网特约推广商家">':'')
                                    + (item.sem&&item.sem==1?'<img src="../assets/images/diamonds.png" alt="" title="该商家已列入为优选商家">':'')
                                    + (item.open_panorama&&item.open_panorama==1&&item.panorama_url?('<a href="'+item.panorama_url+'" target="_blank"><img src="../assets/images/360.png" alt="" title="该公司已开通360°全景"></a>'):'')
                                    + (item.category_status==1?('<img src="../assets/images/identification/expert.png" alt="" title="'+item.category_val+'">'):'')
                                    + (item.pr_status==1?'<img src="../assets/images/company/trend.png" alt="" title="钢铁世界网特约报价商家">':'')
                                    + (item.area_status==1?('<div class="area-number">'+item.area_val+'<img src="../assets/images/mi.png" alt="" title="该商家经营面积'+item.area_val+'㎡以上"></div>'):'')
                                    + (item.time_status==1?'<div class="year-number">'+item.time_val+'<img src="../assets/images/nian.png" alt="" title="该商家经营时间为'+item.time_val+'年"></div>':'')
                                    +   '</div>'
                                    + '</div>'
                                    + '<div class="text">'+item.short_desc+'</div>'
                                    + '</div>'
                    $('#college_list').html(collegeHtml);
                })
              }
            }
        })
    }
    // 焦点推荐数据
    function getRecommendList() {
        $.ajax({
            url: 'index/getRecommendList',
            type: 'get',
            data: {},
            dataType: 'json',
            success: function (res) {
              if(res.code==0){
                var recommendData = res.data
                var recommendHtml = ''
                recommendData.forEach(function(item,index){
                    recommendHtml += '<div class="company-wrap" data-logo="'+ (item.suppliers_logo?item.suppliers_logo:'../assets/images/index3.0/service-1.jpg')+'}" data-photo="'+(item.photo?item.photo:'')+'">'
                                    +   '<a href="'+item.url+'" target="_blank">'
                                    +       '<div class="img" style="text-align: center;">'
                                    +           '<img style="max-width: 100%;width: auto;" src="'+(item.suppliers_logo?item.suppliers_logo:'../assets/images/index3.0/service-1.jpg')+'">'
                                    +       '</div>'
                                    +       '<div class="name">'+item.suppliers_name+'</div>'
                                    +       '<div class="text">'+item.short_desc+'</div>'
                                    +   '</a>'
                                    + '</div>'
                    $('#recommend_list').html(recommendHtml);
                })
              }
            }
        })
    }

    let chunk = function (array, size) {
        let [start, end, result] = [null, null, []];
        for (let i = 0; i < Math.ceil(array.length / size); i++) {
            start = i * size;
            end = start + size;
            result.push(array.slice(start, end));
        }
        return result;
    };


    // 今日报价数据
    function getTodayOfferLists() {
        $.ajax({
            url: 'index/getTodayOfferLists',
            type: 'get',
            data: {},
            dataType: 'json',
            success: function (res) {
                console.log(res,'uuuyytrr')
              if(res.code==0){
				
				// 轮播start
				var hintData = res.data.log;

				var htmlHint = ''
				hintData.forEach((item,idx)=>{
					
					htmlHint += '<li>'
							 +       '<a class="licon-main" href="'+item.current_url+'" target="_blank">'+item.user_type+'<i>'+item.user_name+'</i>查看了'+item.salesName+'的<span>报价表</span></a><span class="time">'+item.add_time+'</span>'
							+  '</li>'
								
					
				})
				$('.hintWrapBox').html(htmlHint);
				var rollwidth = 0;
				var wrawidth = 0;
				var hintWrap = $(".hint-wrap");
				var hintWrapUl = $(".hint-wrap ul");
				var iCountA = setInterval(function () {
					hintrolls();
				}, 25);
				$(".hint-wrap ul li").each(function () {
					wrawidth = wrawidth + $(this).outerWidth(true) - 50;
					
				});
				
				function hintrolls() {
					var hwid = wrawidth;

					if (rollwidth > hwid) {
						rollwidth = 0;
					} else {
						rollwidth = rollwidth + 1;
					}

					hintWrapUl.stop(false, false).animate({
						"margin-left": -rollwidth
					}, 1);
				};
				hintWrap.mouseenter(function () {
					clearInterval(iCountA);
				});
				hintWrap.mouseleave(function () {
					iCountA = setInterval(function () {
						hintrolls();
					}, 25);
				});
				//轮播end
                var supplierCount = res.data.count.supplier
                var productCount = res.data.count.product
                $('#supplierCount').html(supplierCount);
                $('#productCount').html(productCount);
                let todayOfferDataList = chunk(res.data.lists,8)
                if(todayOfferDataList.length <= 1){
                    $('.swiper-button-prev-1').hide()
                    $('.swiper-button-next-1').hide()
                }
				// var todayOfferData = res.data.lists.slice(-12,8)
                var todayOfferHtmlList = ''
                todayOfferDataList.forEach(element => {
                    var todayOfferHtml = ''
                    element.forEach(function(item,index){
                        let htmlprame = ''
                        if(item.suppliers_id > 0 ){
                            htmlprame =				' '+item.short_name
                            +              (item.is_cat_ad_pay&&item.is_cat_ad_pay==1?'<img src="../assets/images/company/is_cat_ad_pay.png" alt="" title="钢铁世界网建议您优先选择类目商家">':'')
                            +              (item.is_category_ad_pay&&item.is_category_ad_pay==1?'<img src="../assets/images/identification/Category.png" alt="" title="钢铁世界网建议您优先选择类目商家">':'')
                            +              (item.is_index_advert&&item.is_index_advert==1?'<img src="../assets/images/identification/Hpas.png" alt="" title="钢铁世界网特约推广商家">':'')
                            +              (item.sem&&item.sem==1?'<img src="../assets/images/diamonds.png" alt="" title="该商家已列入为优选商家">':'')
                            +              (item.open_panorama&&item.open_panorama==1&&item.panorama_url?('<img VrAttr="'+item.panorama_url+'" class="vrImg" src="../assets/images/360.png" alt="" title="该公司已开通360°全景">'):'')
                            +              (item.is_quote_suppliers&&item.is_quote_suppliers==1?'<img src="../assets/images/company/trend.png" alt="" title="钢铁世界网特约报价商家">':'')
                        }else{
                            + '123123123123123123123123'
                        }
                        
                        todayOfferHtml += '<li>'
                                          +  '<a href="'+item.url+'" target="_blank">'
                                          +      '<div >'
                                          +          '<span class="left"><b>'+item.trade_product+'</b></span>'
                                          +          '<span class="right">'+item.update_time+'</span>'
                                          +      '</div>'
                                          +      '<div class="baojiabiao">'
                                          +          '<p class="left" style="width: auto;margin-right: 6px;">'+item.name  
                                          + htmlprame
                                          +          '</p>'
                                          +          '<span class="right" style="cursor:pointer">'
                                          +              '<b onclick="javascript:window.open("'+item.url+'")">'
                                          +              (item.is_qi==1?('<span style="font-family: MicrosoftYaHei;font-size: 14px;font-stretch: normal;line-height: 24px;color:#999999;">'+item.is_qi_price+'</span><span style="font-family: MicrosoftYaHei;font-size: 14px;font-weight: normal;color: #999999;padding-right: 10px;">元起</span>'):'')
                                          +              '报价表'
                                          +              '</b>'
                                          +          '</span>'
                                          +      '</div>'
                                          +      '<div class="clicklook" style="text-align: center;font-size: 14px;color: #027CDF;height: 24px;line-height: 24px;box-shadow: 0 0 5px #77c4ff;padding: 0;">点击查看报价表</div>'
                                          +  '</a>'
                                          +'</li>'
                    })
                    var ad = res.data.ad[0]
                    var a = ''
                    if( res.data.ad.length>0){
                        a = "<li onclick='openBox("+ad.link_phone+")' class='openBox'><img src='"+ad.ad_code_show+"' width='457' height='88'> </li>"
                    }else{
                        a= ''
                    }
                    var b = a + todayOfferHtml

                    var c = '<div class="swiper-slide"><ul>' + b + '</ul></div>'
                    todayOfferHtmlList = todayOfferHtmlList + c
                });
                
                $('#swiperToday').html(todayOfferHtmlList)
				// $('#today_offer_list').html(b);
				// $('#dayprice').html(b);
              }
            }
        })
    }
});

function openBox(msg){
	LCGT.msg({content: msg});
}
function purchase_upload1(file) {
    $('input#file_name').val(file.object);
    LCGT.msg({
        content: "上传成功"
    });
    $('.purchase_upload1').html('已上传');
}
