var active;

$(function () {
    // function test(){
    //     alert(123);
    // }
    var all_tabs = [];
    //获取所有tab，初始化tab数，以确定后续加载规则
    $("#all_number").children().each(function(i,item){
        if($(item) && $(item).attr("id")){
            all_tabs.push($(item).attr("id"));
        }
    });
    var contextArr=[];
    var fp_auth;
    //select事件
    var selectFn = function () {
        $(".dropdown a").on("click", function () {
            $(this).parents(".dropdown").find("ul").toggle();
            $(this).toggleClass("dropdown-up");
        });
        $(".dropdown ul li a").on("click", function () {
            var text = $(this).html();
            $(this).parents(".dropdown").find(".dropdown-span").html(text);
            $(this).parents(".dropdown").find("ul").hide();
            $(".dropdown a").removeClass("dropdown-up");
        });
        $(document).bind('click', function (e) {
            var $clicked = $(e.target);
            if (!$clicked.parents().hasClass("dropdown"))
                $(".dropdown ul").hide();
        });
    };
    selectFn();
    pageInit();
    //表单
    layui.use('form', function () {
        var form = layui.form;
    });

    //日历
    layui.use('laydate', function () {
        var now = new Date(); //当前日期
        var date1 = new Date(),
            time1=date1.getFullYear()+"-"+(date1.getMonth()+1)+"-"+date1.getDate();//time1表示当前时间
        var date2 = new Date(date1);
        date2.setDate(date1.getDate()-7);
        var time2 = date2.getFullYear()+"-"+(date2.getMonth()+1)+"-"+date2.getDate();
        var nowM = date1.getMonth()+1;
        if (nowM < 10) {
            nowM = "0" + nowM;
        }
        var startMonth = date2.getFullYear()+"-"+nowM+"-01";
        //var thisMonth = date2.getFullYear()+"-"+
        var laydate = layui.laydate;
        //单控件
        // 开始时间
        laydate.render({
            elem: '#start_time'
            , value: $("#start_time").val()
            , trigger: 'click'
            , type:'datetime'
            , format:'yyyy-MM-dd HH:mm'
            // , btns: ['clear', 'now', 'confirm']
        });
        // 结束时间
        laydate.render({
            elem: '#end_time'
            , value: $("#end_time").val()
            , trigger: 'click'
            , type:'datetime'
            , format:'yyyy-MM-dd HH:mm'
            // , btns: ['clear', 'now', 'confirm']
        });
        // 获取日期
        laydate.render({
            elem: '#lr_create_time'
            , format: 'yyyy-MM-dd HH:mm:ss'
            , value: $("#lr_create_time").val()
            ,type: 'datetime'
            , trigger: 'click'
        });
        // 预拍日期
        laydate.render({
            elem: '#yp_day'
            , format: 'yyyy-MM-dd H:m:s'
            , value: $("#yp_day").val()
            , trigger: 'click'
        });
        // 客户生日
        laydate.render({
            elem: '#customer_birthday'
            , format: 'yyyy-MM-dd'
            , value: $("#customer_birthday").val()
            , trigger: 'click'
        });
        // 客户生日
        laydate.render({
            elem: '#lr_customer_birthday'
            , format: 'yyyy-MM-dd'
            , value: $("#lr_customer_birthday").val()
            , trigger: 'click'
        });
        // 配偶生日
        laydate.render({
            elem: '#mate_birthday'
            , format: 'yyyy-MM-dd'
            , value: $("#mate_birthday").val()
            , trigger: 'click'
        });
        // 配偶生日
        laydate.render({
            elem: '#lr_mate_birthday'
            , format: 'yyyy-MM-dd'
            , value: $("#lr_mate_birthday").val()
            , trigger: 'click'
        });
        // 标记日期
        laydate.render({
            elem: '#op_signday'
            , format: 'yyyy-MM-dd H:m:s'
            ,type:'datetime'
            , value: $("#op_signday").val()
        });
        // 标记日期
        laydate.render({
            elem: '#op_signday_aaa'
            , format: 'yyyy-MM-dd H:m:s'
            ,min: -7
            ,max:7
            ,type:'datetime'
            , value: $("#op_signday").val()
        });
        // 登记日期
        laydate.render({
            elem: '#dj_day'
            , format: 'yyyy-MM-dd H:m:s'
            , value: $("#dj_day").val()
            , trigger: 'click'
        });
        // 邀约日期
        laydate.render({
            elem: '#yjd_day'
            , format: 'yyyy-MM-dd H:m:s'
            , value: $("#yjd_day").val()
            , range: true
            , trigger: 'click'
        });
        // 邀约日期
        laydate.render({
            elem: '#zz_yjd_day'
            , format: 'yyyy-MM-dd H:m:s'
            ,type:'datetime'
            , trigger: 'click'
        });
        // 订单日期
        laydate.render({
            elem: '#order_day'
            , format: 'yyyy-MM-dd'
            , value: $("#order_day").val()
            , trigger: 'click'
        });
        // 进店日期
        laydate.render({
            elem: '#syjd_day'
            , format: 'yyyy-MM-dd H:m:s'
            , value: $("#syjd_day").val()
            , trigger: 'click'
        });
        // 结婚日期
        laydate.render({
            elem: '#marry_day'
            , format: 'yyyy-MM-dd'
            , value: $("#marry_day").val()
            , trigger: 'click'
        });
        laydate.render({
            elem: '#lr_marry_day'
            , format: 'yyyy-MM-dd'
            , value: $("#lr_marry_day").val()
            , trigger: 'click'
        });
        // 预产日期
        laydate.render({
            elem: '#ready_baby_day'
            , format: 'yyyy-MM-dd'
            ,type:'datetime'
            , value: $("#ready_baby_day").val()
            , trigger: 'click'
        });
        // 宝宝生日
        laydate.render({
            elem: '#baby_birthday'
            , format: 'yyyy-MM-dd'
            , value: $("#baby_birthday").val()
            , trigger: 'click'
        });
        // 开始时间
        if(yearCus == 1){
            laydate.render({
                elem: '#start_time'
                , value: $("#start_time").val()
                , trigger: 'click'
                , type:'datetime'
                , format:'yyyy-MM-dd HH:mm'
                , min:-365
                // , btns: ['clear', 'now', 'confirm']
            });
            // 结束时间
            laydate.render({
                elem: '#end_time'
                , value: $("#end_time").val()
                , trigger: 'click'
                , type:'datetime'
                , format:'yyyy-MM-dd HH:mm'
                , min:-365
                // , btns: ['clear', 'now', 'confirm']
            });
        }else{
            laydate.render({
                elem: '#start_time'
                , value: $("#start_time").val()
                , trigger: 'click'
                , type:'datetime'
                , format:'yyyy-MM-dd HH:mm'
                // , btns: ['clear', 'now', 'confirm']
            });
            // 结束时间
            laydate.render({
                elem: '#end_time'
                , value: $("#end_time").val()
                , trigger: 'click'
                , type:'datetime'
                , format:'yyyy-MM-dd HH:mm'
                // , btns: ['clear', 'now', 'confirm']
            });
        }
        // 加好友时间
        laydate.render({
            elem: '#df_add_friend_time'
            ,format: 'yyyy-MM-dd H:m:s'
            ,type:'datetime'
            ,trigger: 'click'
        });
        // 婚期时间
        laydate.render({
            elem: '#df_marry_day'
            ,format: 'yyyy-MM-dd'
            ,type:'date'
            ,trigger: 'click'
        });
        // 再约
        laydate.render({
            elem: '#df_next_time'
            ,format: 'yyyy-MM-dd HH:mm:ss'
            ,type:'datetime'
            ,trigger: 'click'
            ,min: "{$now_time}"
        });
        
        // lay('.hour-item').each(function () {
        //     laydate.render({
        //         elem: this
        //         , type: 'time'
        //         , done: function (value, date, endDate) {
        //             console.log(value, date, endDate);
        //         }
        //         , change: function (value, date, endDate) {
        //             //this.elem.val(value)
        //         }
        //     });
        // });
    });

    //弹窗
    layui.use(['layer','layedit'], function () {
        var $ = layui.jquery, layer = layui.layer,layedit = layui.layedit; //独立版的layer无需执行这一句
        //触发事件
        customer_list_active = active = {
        	// 录入客资（添加）
            add: function (cus) {
                showAddCustomerForm();
                /*layer.open({
                    title: '客资登记',
                    type: 2,
                    skin: 'layui-layer-rim',
                    area: ['760px', '620px'],
                    //content: $('#add-box'),
                    content: "/crm/customer/customerAdd",
                    btn: ['提交', '取消'],
                    yes: function (iframeDom,index) {
                        var shade = layer.load(1, {shade: 0.3});
                        // return false;
                        var div = $(".layui-layer-content iframe").contents().children().find('.layui-this').html();
                        var cus = $(".layui-layer-content iframe").contents().children();

                            // 获取 iframe
                            var iframeWin = window[$(index).find('iframe')[0]['name']];
                            // 通过 getupContent 方法对 img_record 重新赋值
                            // cus.find("#form1").find("#img_record").text(iframeWin.getupContent());

                            var customer = cus.find("#form1").serialize();
                            // console.log(customer);return;
                            // 20200414
                            // var img_record = customer.img_record;
                            // console.log(img_record);return;
                            // var img_record = iframeWin.getupContent();
                            // var img_record = iframeWin.getupContent().replace(/&nbsp;/g,"");
                            // img_record = encodeURI(img_record);
                            // customer = customer+'&img_record='+img_record;

                            var name     = trim(cus.find("#customer_name").val());
                            var tel      = trim(cus.find("#customer_tel").val());
                            var wechat   = trim(cus.find('#customer_wechat').val());
                            var weibo    = cus.find('#customer_weibo').val() ? trim(cus.find('#customer_weibo').val()) : '';
                            var mate_tel = trim(cus.find('#mate_tel').val());
                            var qq       = trim(cus.find('#customer_qq').val());

                            var customer_channel, customer_cource, access_model, consultation_type, customer_intention, customer_area, customer_region, province, city, county,consulation_shop,shop_name;
                            var customer_channel_id = cus.find("#customer_channel").val();
                            var access_model_id = cus.find("#access_model").val();
                            var consultation_type_id = cus.find("#consultation_type").val();
                            var p = '';
                            if(cus.find('#customer_type').val() == 2){
                                var add_code = cus.find('#add_shop_code').val();
                                var dj_id = cus.find('#dj_staff_id').val() ? cus.find('#dj_staff_id').val() : '';
                                var dj_staff = cus.find('#dj_staff_id option:selected').html() ? cus.find('#dj_staff_id option:selected').html() : '';
                                p += '&dj_staff='+dj_staff;
                                if(add_code){
                                    if(!dj_id || dj_id == '' || dj_id == null || dj_id == undefined){
                                        layer.alert('必选选择提报人');
                                        layer.close(shade);
                                        return false;
                                    }
                                }
                                if(cus.find('#zjs_from').val() == 1){
                                    var intro_tel = cus.find("#introducer_tel").val();
                                    var intro_order = cus.find("#introducer_ordernum").val();
                                    var intro_name = cus.find("#introducer_name").val();
                                    if((intro_name && intro_tel) || (intro_name && intro_order)){

                                    }else{
                                        layer.alert('老顾客转介绍时必须选择介绍人');
                                        layer.close(shade);
                                        return false;
                                    }
                                }
                            }
                            if (cus.find('#customer_channel').val()) {
                                customer_channel = cus.find('#customer_channel option:selected').html();//渠道
                            } else {
                                customer_channel = "";
                            }

                            if (cus.find('#customer_cource').val()) {
                                customer_cource = cus.find('#customer_cource option:selected').html();//来源
                            } else {
                                customer_cource = "";
                            }

                            if (cus.find('#access_model').val()) {
                                access_model = cus.find('#access_model option:selected').html();//获取方式
                            } else {
                                access_model = "";
                            }

                            if (cus.find('#consultation_type').val()) {
                                consultation_type = cus.find('#consultation_type option:selected').html();//消费类型
                            } else {
                                consultation_type = "";
                            }

                            if (cus.find('#customer_intention').val()) {
                                customer_intention = cus.find('#customer_intention option:selected').html();//客户意向
                            } else {
                                customer_intention = "";
                            }

                            if (cus.find('#customer_area').val()) {
                                customer_area = cus.find('#customer_area option:selected').html();//客户分区
                            } else {
                                customer_area = "";
                            }

                            if (cus.find('#customer_region').val()) {
                                customer_region = cus.find('#customer_region option:selected').html();//客户地域
                            } else {
                                customer_region = "";
                            }
                            if (cus.find('#province_id').val()) {
                                province = cus.find('#province_id option:selected').html();//省
                            } else {
                                province = "";
                                //layer.alert('省市不能为空！');
                                //layer.close(shade);
                                //return false;
                            }
                            if (cus.find('#city_id').val()) {
                                city = cus.find('#city_id option:selected').html();//市
                            } else {
                                city = "";
                                //layer.alert('省市不能为空！');
                                //layer.close(shade);
                                //return false;
                            }
                            if (cus.find('#county_id').val()) {
                                county = cus.find('#county_id option:selected').html();//区
                            } else {
                                county = "";
                            }
                            if (cus.find('#consulation_shop_code').val()) {
                                consulation_shop = cus.find('#consulation_shop_code option:selected').html();//区
                            } else {
                                consulation_shop = "";
                            }
                            if (cus.find('#shop_code').val()) {
                                shop_name = cus.find('#shop_code option:selected').html();//区
                            } else {
                                shop_name = "";
                            }
                            //var patrn = /^0?(13[0-9]|15[012356789]|18[0236789]|14[57])[0-9]{8}$/;
                            var patrn = /^1[3|4|5|6|7|8|9][0-9]{9}$/;

                            if(isInArray('customer_name',jslrMust)){
                                if (!name) {
                                    layer.alert("客户姓名不能为空");
                                    layer.close(shade);
                                    return false;
                                }
                            }
                            if (name) {
                                var name_reg=/^[a-zA-Z0-9_.\u4e00-\u9fa5]{0,}$/;
                                if(!name_reg.exec(name)){
                                    layer.alert("姓名只能输入汉字、英文、数字和下划线");
                                    layer.close(shade);
                                    return false;
                                }
                            }
                            //if(tel&&!check_tel(tel)){
                            //    layer.alert("手机号输入错误");
                            //    return false;
                            //}
                            // if (tel && !patrn.exec(tel)) {
                            //     layer.alert("手机号输入错误");
                            //     layer.close(shade);
                            //     return false;
                            // }
                            // if (mate_tel && !patrn.exec(mate_tel)) {
                            //     layer.alert("配偶手机号输入错误");
                            //     layer.close(shade);
                            //     return false;
                            // }
                            // var rege=/.*[\u4e00-\u9fa5]+.*$/;
                            var rege=/[.*]/;
                            if(qq&&rege.test(qq)){
                                layer.alert('QQ号输入错误');
                                layer.close(shade);
                                return false;
                            }
                            if(isInArray('customer_cource',jslrMust)){
                                if (!customer_cource) {
                                    layer.alert("客户来源不能为空");
                                    layer.close(shade);
                                    return false;
                                }
                            }
                            if(isInArray('access_model',jslrMust)){
                                if (!access_model) {
                                    layer.alert("获取方式不能为空");
                                    layer.close(shade);
                                    return false;
                                }
                            }
                            if(isInArray('consultation_type',jslrMust)){
                                if (!consultation_type) {
                                    layer.alert("消费类型不能为空");
                                    layer.close(shade);
                                    return false;
                                }
                            }
                            if(isInArray('customer_intention',jslrMust)){
                                if (!customer_intention) {
                                    layer.alert("客户意向不能为空");
                                    layer.close(shade);
                                    return false;
                                }
                            }
                            if(isInArray('province',jslrMust)){
                                if (!province) {
                                    layer.alert("省不能为空");
                                    layer.close(shade);
                                    return false;
                                }
                            }
                            if(isInArray('city',jslrMust)){
                                if (!city) {
                                    layer.alert("市不能为空");
                                    layer.close(shade);
                                    return false;
                                }
                            }

                            if(isInArray('customer_cource',jslrMust)){
                                if (!customer_cource) {
                                    layer.alert("客户来源不能为空");
                                    layer.close(shade);
                                    return false;
                                }
                            }
                            if(isInArray('access_model',jslrMust)){
                                if (!access_model) {
                                    layer.alert("获取方式不能为空");
                                    layer.close(shade);
                                    return false;
                                }
                            }
                            if(cus.find('#customer_type').val() != 2) {
                                if (isInArray('customer_channel', jslrMust)) {
                                    if (!customer_channel) {
                                        layer.alert("渠道名称不能为空");
                                        layer.close(shade);
                                        return false;
                                    }
                                }
                                if(isInArray('channel_plan_number',jslrMust)){
                                    if (!cus.find("#channel_plan_number").val()) {
                                        layer.alert("推广编号不能为空");
                                        layer.close(shade);
                                        return false;
                                    }
                                }
                            }
                            if(isInArray('customer_sex',jslrMust)){
                                if (!cus.find("#customer_sex").val()) {
                                    layer.alert("性别不能为空");
                                    layer.close(shade);
                                    return false;
                                }
                            }
                            
                            if (!tel && !wechat && !qq) {
                                layer.alert("请填写手机号、微信、QQ任一项联系方式");
                                layer.close(shade);
                                return false;
                            }
                            if(isInArray('tracksign',jslrMust)){
                                if (!cus.find("#sign").val()) {
                                    layer.alert("请选择客资标记");
                                    layer.close(shade);
                                    return false;
                                }
                            }
                        var brandclass_id = cus.find("#brandclass_id").val();
                        if(typeof brandclass_id != 'undefined' && brandclass_id != null && brandclass_id != ''){
                            p += "&brandclass="+cus.find("#brandclass_id option:selected").html();
                        }else{
                            p += "&brandclass=";
                        }
                        var company_shop_code = cus.find("#company_shop_code").val();
                        if(typeof company_shop_code != 'undefined' && company_shop_code != null && company_shop_code != ''&& company_shop_code != undefined){
                            p += "&company_shop_name="+cus.find("#company_shop_code option:selected").html();
                        }else{
                            p += "&company_shop_name=''";
                        }
                        // 追踪人
                        var sales_staff_id = cus.find("#sales_staff_id").val();
                        if(sales_staff_id == undefined ||sales_staff_id == null||sales_staff_id == 0 ||sales_staff_id == ''|| typeof(sales_staff_id) == 'undefined'){
                            p += "";
                        }else{
                            p += "&sales_staff="+cus.find("#sales_staff_id option:selected").html();
                        }
                        // 筛客人
                        var sk_staff_id = cus.find("#sk_staff_id").val();
                        if(sk_staff_id == undefined ||sk_staff_id == null||sk_staff_id == 0 ||sk_staff_id == ''|| typeof(sk_staff_id) == 'undefined'){
                            p += "";
                        }else{
                            p += "&sk_staff="+cus.find("#sk_staff_id option:selected").html();
                        }

                        if(isInArray('sales_staff_id',jslrMust)){
                            if (!sales_staff_id) {
                                layer.alert("追踪人不能为空");
                                layer.close(shade);
                                return false;
                            }
                        }
                        var add_shop_code = cus.find("#add_shop_code").val();
                        if(add_shop_code){
                            var add_shop_name = cus.find('#add_shop_code option:selected').html();
                            p += " &add_shop_name="+add_shop_name;
                        }
                        if(cus.find('#add_shop_code').length > 0){
                            if(add_shop_code == undefined || add_shop_code == null || add_shop_code == ''|| add_shop_code == 'undefined'){
                                layer.alert('请选择提报店');
                                layer.close(shade);
                                return false;
                            }
                        }
                        var shop_code = cus.find('#shop_code').val();
                        if(shop_code){
                            var shop_name = cus.find('#shop_code option:selected').html();
                            p += " &shop_name="+shop_name;
                        }
                        if(cus.find('#shop_code').length > 0){
                            if(shop_code == undefined || shop_code == null || shop_code == ''|| shop_code == 'undefined'){
                                layer.alert('请选择归属店');
                                layer.close(shade);
                                return false;
                            }
                        }
                        // 客资标记
                        var sign_id =  cus.find('#sign option:selected').val();
                        if(sign_id == 'undefined' || sign_id == '' || sign_id == null){
                            var sign_name = '';
                        }else{
                            var sign_name = cus.find('#sign option:selected').html();
                        }
                        //客资标签
                        var customer_label='';
                        for(var i=0;i<cus.find('.customer_label').length;i++){
                            customer_label+=cus.find('.customer_label').eq(i).attr("title")+',';
                        }
                        // 20200304
                        // console.log(customer);
                        var all = customer + '&sign_name=' +sign_name + '&customer_channel=' + customer_channel + '&customer_cource=' + customer_cource + '&access_model=' + access_model + '&consultation_type=' + consultation_type + '&customer_intention=' + customer_intention + '&customer_region=' + customer_region+'&province='+province+'&city='+city+'&county='+county+"&consulation_shop="+consulation_shop+p+"&customer_label="+customer_label;

                        $.ajax({
                            type: "POST",
                            url: 'addCustomer',
                            // data: customer + '&sign_name=' +sign_name + '&customer_channel=' + customer_channel + '&customer_cource=' + customer_cource + '&access_model=' + access_model + '&consultation_type=' + consultation_type + '&customer_intention=' + customer_intention + '&customer_region=' + customer_region+'&province='+province+'&city='+city+'&county='+county+"&consulation_shop="+consulation_shop+p+"&customer_label="+customer_label,
                            data:{all:all},
                            // data:{img_record:img_record,all:all},
                            success: function (msg) {
                                //alert(msg.data.all_crm);console.log(msg.data.all_crm);
                                if (msg.code == 1) {
                                    //jQuery("#Example").trigger("reloadGrid");
                                    //parent.location.reload();
                                    //layer.close();
                                    //layer.close(layer.index);
                                    layer.closeAll();
                                    //reloadGrid();
                                    setTimeout(
                                        reloadGrid(),1000
                                    )
                                    //
                                     // $("#Example").jqGrid('setGridParam', {
                                     // datatype: 'json',
                                     // postData: '/crm/Customer/customerList',
                                     // page: '#pager'
                                     // }).trigger("reloadGrid"); //重新载入

                                     // $("#all_crm").html(msg.data.all_crm);
                                     // $("#no_track").html(msg.data.no_traking);
                                     // $("#no_crm_fp").html(msg.data.no_fp);
                                     // $("#tracking").html(msg.data.traking);
                                     // $("#customer_order").html(msg.data.crm_order);
                                     // $("#customer_jdwd").html(msg.data.jdwd);
                                     //
                                } else {
                                    layer.alert(msg.msg);
                                    layer.close(shade);
                                    return false;
                                }
                            },
                            error:function(){
                                layer.alert('客资录入失败');
                                layer.close(shade);
                                return false;
                            }
                        });
                    }
                });*/
            },
        	// 批量录入客资（添加）
            add_more: function (cus) {
                layer.open({
                    title: '批量客资登记',
                    type: 2,
                    skin: 'layui-layer-rim',
                    area: ['950px', '620px'],
                    //content: $('#add-box'),
                    content: "/crm/customer/customerAddMore",
                    btn: ['提交', '取消'],
                    yes: function (iframeDom,index) {
                        var shade = layer.load(1, {shade: 0.3});
                        // return false;
                        var div = $(".layui-layer-content iframe").contents().children().find('.layui-this').html();
                        var cus = $(".layui-layer-content iframe").contents().children();
                            var customer = cus.find("#form1").serialize();
                            var customer_channel, customer_cource, access_model, consultation_type, customer_intention, customer_area, customer_region, province, city, county,consulation_shop,shop_name;
                            var customer_channel_id = cus.find("#customer_channel").val();
                            var access_model_id = cus.find("#access_model").val();
                            var consultation_type_id = cus.find("#consultation_type").val();
                            var p = '';

                            if (cus.find('#customer_channel').val()) {
                                customer_channel = cus.find('#customer_channel option:selected').html();//渠道
                            } else {
                                customer_channel = "";
                            }

                            if (cus.find('#customer_cource').val()) {
                                customer_cource = cus.find('#customer_cource option:selected').html();//来源
                            } else {
                                customer_cource = "";
                            }

                            if (cus.find('#access_model').val()) {
                                access_model = cus.find('#access_model option:selected').html();//获取方式
                            } else {
                                access_model = "";
                            }

                            if (cus.find('#consultation_type').val()) {
                                consultation_type = cus.find('#consultation_type option:selected').html();//消费类型
                            } else {
                                consultation_type = "";
                            }

                            if (cus.find('#customer_intention').val()) {
                                customer_intention = cus.find('#customer_intention option:selected').html();//客户意向
                            } else {
                                customer_intention = "";
                            }

                            if (cus.find('#customer_area').val()) {
                                customer_area = cus.find('#customer_area option:selected').html();//客户分区
                            } else {
                                customer_area = "";
                            }

                            if (cus.find('#customer_region').val()) {
                                customer_region = cus.find('#customer_region option:selected').html();//客户地域
                            } else {
                                customer_region = "";
                            }
                            if (cus.find('#province_id').val()) {
                                province = cus.find('#province_id option:selected').html();//省
                            } else {
                                province = "";
                                //layer.alert('省市不能为空！');
                                //layer.close(shade);
                                //return false;
                            }
                            if (cus.find('#city_id').val()) {
                                city = cus.find('#city_id option:selected').html();//市
                            } else {
                                city = "";
                                //layer.alert('省市不能为空！');
                                //layer.close(shade);
                                //return false;
                            }
                            if (cus.find('#county_id').val()) {
                                county = cus.find('#county_id option:selected').html();//区
                            } else {
                                county = "";
                            }
                            if (cus.find('#consulation_shop_code').val()) {
                                consulation_shop = cus.find('#consulation_shop_code option:selected').html();//区
                            } else {
                                consulation_shop = "";
                            }
                            if (cus.find('#shop_code').val()) {
                                shop_name = cus.find('#shop_code option:selected').html();//区
                            } else {
                                shop_name = "";
                            }

                            if(isInArray('customer_cource',jslrMust)){
                                if (!customer_cource) {
                                    layer.alert("客户来源不能为空");
                                    layer.close(shade);
                                    return false;
                                }
                            }
                            if(isInArray('access_model',jslrMust)){
                                if (!access_model) {
                                    layer.alert("获取方式不能为空");
                                    layer.close(shade);
                                    return false;
                                }
                            }
                            if(isInArray('consultation_type',jslrMust)){
                                if (!consultation_type) {
                                    layer.alert("消费类型不能为空");
                                    layer.close(shade);
                                    return false;
                                }
                            }
                            if(isInArray('customer_intention',jslrMust)){
                                if (!customer_intention) {
                                    layer.alert("客户意向不能为空");
                                    layer.close(shade);
                                    return false;
                                }
                            }


                            if(isInArray('customer_cource',jslrMust)){
                                if (!customer_cource) {
                                    layer.alert("客户来源不能为空");
                                    layer.close(shade);
                                    return false;
                                }
                            }

                            if(cus.find('#customer_type').val() != 2) {
                                if (isInArray('customer_channel', jslrMust)) {
                                    if (!customer_channel) {
                                        layer.alert("渠道名称不能为空");
                                        layer.close(shade);
                                        return false;
                                    }
                                }
                            }

                            if(isInArray('channel_plan_number',jslrMust)){
                                if (!cus.find("#channel_plan_number").val()) {
                                    layer.alert("推广编号不能为空");
                                    layer.close(shade);
                                    return false;
                                }
                            }
                            if(isInArray('consulation_shop',jslrMust)){
                                if (!cus.find("#consulation_shop_code").val()) {
                                    layer.alert("意向店面不能为空");
                                    layer.close(shade);
                                    return false;
                                }
                            }

                            if(isInArray('tracksign',jslrMust)){
                                if (!cus.find("#sign").val()) {
                                    layer.alert("请选择客资标记");
                                    layer.close(shade);
                                    return false;
                                }
                            }
                        var brandclass_id = cus.find("#brandclass_id").val();
                        if(typeof brandclass_id != 'undefined' && brandclass_id != null && brandclass_id != ''){
                            p += "&brandclass="+cus.find("#brandclass_id option:selected").html();
                        }else{
                            p += "&brandclass=";
                        }
                        var company_shop_code = cus.find("#company_shop_code").val();
                        if(typeof company_shop_code != 'undefined' && company_shop_code != null && company_shop_code != ''&& company_shop_code != undefined){
                            p += "&company_shop_name="+cus.find("#company_shop_code option:selected").html();
                        }else{
                            p += "&company_shop_name=''";
                        }
                        // 追踪人
                        var sales_staff_id = cus.find("#sales_staff_id").val();
                        if(sales_staff_id == undefined ||sales_staff_id == null||sales_staff_id == 0 ||sales_staff_id == ''|| typeof(sales_staff_id) == 'undefined'){
                            p += "";
                        }else{
                            p += "&sales_staff="+cus.find("#sales_staff_id option:selected").html();
                        }


                        if(isInArray('sales_staff_id',jslrMust)){
                            if (!sales_staff_id) {
                                layer.alert("追踪人不能为空");
                                layer.close(shade);
                                return false;
                            }
                        }
                        var add_shop_code = cus.find("#add_shop_code").val();
                        if(add_shop_code){
                            var add_shop_name = cus.find('#add_shop_code option:selected').html();
                            p += " &add_shop_name="+add_shop_name;
                        }
                        if(cus.find('#add_shop_code').length > 0){
                            if(add_shop_code == undefined || add_shop_code == null || add_shop_code == ''|| add_shop_code == 'undefined'){
                                layer.alert('请选择提报店');
                                layer.close(shade);
                                return false;
                            }
                        }
                        var shop_code = cus.find('#shop_code').val();
                        if(shop_code){
                            var shop_name = cus.find('#shop_code option:selected').html();
                            p += " &shop_name="+shop_name;
                        }
                        if(cus.find('#shop_code').length > 0){
                            if(shop_code == undefined || shop_code == null || shop_code == ''|| shop_code == 'undefined'){
                                layer.alert('请选择归属店');
                                layer.close(shade);
                                return false;
                            }
                        }
                        // 客资标记
                        var sign_id =  cus.find('#sign option:selected').val();
                        if(sign_id == 'undefined' || sign_id == '' || sign_id == null){
                            var sign_name = '';
                        }else{
                            var sign_name = cus.find('#sign option:selected').html();
                        }

                        $.ajax({
                            type: "POST",
                            url: 'addCustomerMore',
                            data: customer + '&sign_name=' +sign_name + '&customer_channel=' + customer_channel + '&customer_cource=' + customer_cource + '&access_model=' + access_model + '&consultation_type=' + consultation_type + '&customer_intention=' + customer_intention + '&customer_region=' + customer_region+'&province='+province+'&city='+city+'&county='+county+"&consulation_shop="+consulation_shop+p,
                            success: function (msg) {
                                //alert(msg.data.all_crm);console.log(msg.data.all_crm);
                                if (msg.code == 1) {
                                    layer.closeAll();
                                    //reloadGrid();
                                    setTimeout(
                                        reloadGrid(),1000
                                    )
                                } else {
                                    layer.alert(msg.msg);
                                    layer.close(shade);
                                    return false;
                                }
                            },
                            error:function(){
                                layer.alert('客资录入失败');
                                layer.close(shade);
                                return false;
                            }
                        });
                    }
                });
            },
            // 新版客资登记 20210222
            addnew:function(){
                showAddCustomerForm();

            },
            // 删除客资
            delete: function () {
                $.ajax({
                    type: "POST",
                    url: 'check_right',
                    data: {code: 'menu1512970570'},
                    success: function (msg) {
                        //console.log(msg);return false;
                        if (msg.code != 1||msg.data !=1) {
                            layer.alert('抱歉，您没有权限删除客资');
                            return false;
                        }else{
                            var cus_id = jQuery("#Example").jqGrid('getGridParam', 'selarrrow');
                            if (cus_id == '' || cus_id == null) {
                                layer.alert('请选中某行再操作');
                                return false;
                            }
                            var num = cus_id.length;
                            layer.confirm('确定删除这 '+num+' 条客资吗？', {
                                title: '删除提醒',
                                btn: ['确定', '取消'], //按钮
                                area: ['400px', '176px'],
                                yes: function (index) {

                                    //删除
                                    if (cus_id.length > 0) {
                                        $.ajax({
                                            type: "POST",
                                            url: 'delCustomer',
                                            data: {id: cus_id},
                                            success: function (msg) {
                                                if (msg.code == 1) {
                                                    layer.close(index);
                                                    if (msg.data.length > 1) {
                                                        for (var i = 0; i < msg.data.length; i++) {
                                                            $("#Example").jqGrid('delRowData', msg.data[i]);
                                                        }
                                                    } else {
                                                        $("#Example").jqGrid('delRowData', msg.data);
                                                    }
                                                    //jQuery("#Example").jqGrid('delRowData', cus_id);
                                                    reloadGrid();
                                                    layer.alert(msg.msg);
                                                }else{
                                                    layer.alert(msg.msg);
                                                }
                                            }
                                        });
                                    } else {
                                        layer.alert("请选择您将要删除的客资");
                                    }
                                }
                            });
                        }
                    }
                });
            },
            // 退单
            del_order: function () {
                $.ajax({
                    type: "POST",
                    url: 'check_right',
                    data: {code: 'menu1572077805'},
                    success: function (msg) {
                        //console.log(msg);return false;
                        if (msg.code != 1||msg.data !=1) {
                            layer.alert('抱歉，您没有权限操作退单');
                            return false;
                        }else{
                            var id = $('#Example').jqGrid('getGridParam','selarrrow');
                            console.log(id)
                            if (id == '' || id == null) {
                                layer.alert('请选中某行再操作');
                                return false;
                            }
                            layer.confirm('确定退单吗？', {
                                title: '退单',
                                btn: ['确定', '取消'], //按钮
                                area: ['400px', '176px'],
                                yes: function (index) {
                                    //删除
                                    $.ajax({
                                        type: "POST",
                                        url: 'delOrder/id/'+id,
                                        success: function (msg) {
                                            if (msg.code == 200) {
                                                layer.close(index);
                                                $("#Example").jqGrid('setRowData',id,{'is_success':'未订单','order_number':'','order_day':'','order_type':'','order_start_time':'','totalpay_money':'','order_fact':'','fact_money':'','order_amount':''});
                                                layer.alert(msg.msg);
                                            }else{
                                                layer.alert(msg.msg);
                                            }
                                        }
                                    });
                                }
                            });
                        }
                    }
                });
            },
            // 客资分配
            allot: function () {
                $.ajax({
                    type: "POST",
                    url: 'check_right',
                    data: {code: 'menu1512970623'},
                    success: function (msg) {
                        //console.log(msg);return false;
                        if (msg.code != 1 || msg.data != 1) {
                            layer.alert('抱歉，您没有权限分配客资');
                            return false;
                        } else {
                            var id = $('#Example').jqGrid('getGridParam', 'selarrrow');
                            if (id == '' || id == null) {
                                layer.alert('请选中某行再操作');
                                return false;
                            }

                            $.ajax({
			                    type: "POST",
			                    url: 'checkOrderCustomer',
			                    data: {id:id},
			                    success: function (msg) {
			                        //console.log(msg);return false;
			                        if (msg.code == 200) {
			                        	if (msg.data>0) {
			                        		layer.confirm('存在已订单客资，确定继续分配吗？', {
							                    btn: ['确定','取消'] //按钮
							                }, function(index){
							                	setTimeout(function(){
					                                load_page_post(
					                                    //'{:url("crm/Customer/allotReceive",["id"=>'+id+'])}',
					                                    '/crm/customer/customerAllot/',
					                                    '客资分配',
					                                    function(){
					                                        allotReceive(id,function(){reloadGrid()});
					                                    },
					                                    ['分配','取消'],
					                                    900,500,'','','POST',{id:id}
					                                );
					                            },10);
							                })
			                        	}else{
						                	setTimeout(function(){
				                                load_page_post(
				                                    //'{:url("crm/Customer/allotReceive",["id"=>'+id+'])}',
				                                    '/crm/customer/customerAllot/',
				                                    '客资分配',
				                                    function(){
				                                        allotReceive(id,function(){reloadGrid()});
				                                    },
				                                    ['分配','取消'],
				                                    900,500,'','','POST',{id:id}
				                                );
				                            },10);
						                }
			                        } else {
			                            layer.alert(msg.msg);
                                		return false;
			                        }
			                    }
			                });
                        }
                    }
                });
            },
            // 客资再分配
            another_allot: function () {
                $.ajax({
                    type: "POST",
                    url: 'check_right',
                    data: {code: 'menu1541663886'},
                    success: function (msg) {
                        //console.log(msg);return false;
                        if (msg.code != 1 || msg.data != 1) {
                            layer.alert('抱歉，您没有权限再分配客资');
                            return false;
                        } else {
                            var id = $('#Example').jqGrid('getGridParam', 'selarrrow');
                            if (id == '' || id == null) {
                                layer.alert('请选中某行再操作');
                                return false;
                            }
                            // alert(id);
                            setTimeout(function(){
                                load_page_post(
                                    //'{:url("crm/Customer/allotReceive",["id"=>'+id+'])}',
                                    '/crm/customer/customerAllot/',
                                    '客资再分配',
                                    function(){
                                        anotherAllotReceive(id,function(){reloadGrid()});
                                    },
                                    ['分配','取消'],
                                    900,500,'','','POST',{id:id}
                                );
                            },10);
                        }
                    }
                });
            },
            // 分配筛客
            allot_sk:function(){
                $.ajax({
                    type: "POST",
                    url: 'check_right',
                    data: {code: 'menu1512970623'},
                    success: function (msg) {
                        //console.log(msg);return false;
                        if (msg.code != 1 || msg.data != 1) {
                            layer.alert('抱歉，您没有权限分配客资');
                            return false;
                        } else {
                            setTimeout(function(){
                                load_page(
                                    '/crm/customer/customerAllotSk',
                                    '分配筛客人',
                                    function(){
                                        customerAllotSk(function(){reloadGrid()});
                                    },
                                    ['分配','取消'],
                                    920,500
                                );
                            },10);
                        }
                    }
                });
            },
            // 导出
            export: function () {
                var validstr = '';
                $.each($(".is_valid input[name='is_valid']"),function(id,item){
                    if($(item).is(':checked')){
                        validstr += ','+$(item).val();
                    }
                })
                validstr = validstr.substr(1);
                
                var loss_check = $(".is_valid input[name='is_loss']");
                if (loss_check.is(':checked')) {
                    // is_loss = '';
                    is_loss = 1;
                }else{
                    is_loss = 2;
                }
                layer.confirm('确定导出？', {
                    title: '客资导出',
                    btn: ['导出', '取消'], //按钮
                    area: ['400px', '176px'],
                    yes: function (index) {
                        var cus_id = jQuery("#Example").jqGrid('getGridParam', 'selarrrow');
                        var data_id = jQuery("#Example").jqGrid('getDataIDs');
                        if (cus_id && cus_id.length > 0) {
                            location.href = "export?cus_id=" + cus_id;
                            layer.close(index);
                        } else if (data_id) {
                            var customer_channel = $('#check-wrap2').val() ? $('#check-wrap2').val() : '';
                            //var add_shop_code = $('#shop_code').val();
                            //var data = 'all_time=' + all_time + '&start_time=' + start_time + '&end_time=' + end_time + '&dj_staff_id=' + dj_staff_id + '&consultation_type_id=' + consultation_type_id + '&customer_intention_id=' + customer_intention_id + '&customer_cource_id=' + customer_cource_id + '&type_info='+type_info+ '&is_intostore=' + is_intostore + '&is_success=' + is_success+'&more_like='+more_like+"&is_valid="+validstr+"&is_loss="+is_loss+"&get_contact="+get_contact+'&tab='+tab+"&city_id="+city_id+"&customer_channel="+customer_channel+"&add_shop_code="+add_shop_code;
                            //location.href = "export?" + $('.layui-form').serialize();
                            var validstr = '';
                            $.each($(".is_valid input[name='is_valid']"),function(id,item){
                                if($(item).is(':checked')){
                                    validstr += ','+$(item).val();
                                }
                            })
                            var all_time = $('#all_time').val();//日期条件
                            var start_time = $('#start_time').val();//开始时间
                            var end_time = $('#end_time').val();//结束时间
                            var dj_staff_id = $('#dj_staff_id').val();//登记者id
                            var consultation_type_id = $('#consultation_type_id').val();//消费类型
                            var customer_intention_id = $('#customer_intention_id').val();//客户意向
                            var is_intostore = $('#is_intostore').val();//进店状态
                            var is_success = $('#is_success').val();//成交状态
                            var customer_cource_id = $('#customer_cource_id').val();//客资来源
                            var type_info = $('#type_info').val();//多查询条件拼接成的字符串
                            var more_like=$('#more_like').val();//手机号QQ微信微博
                            var get_contact=$('#get_contact').val(); //是否获取手机号
                            var city_id=$('#staCity').val();
                            var province_id=$('#province_id').val();
                            var add_shop_code=$('#shop_code').val();
                            var is_fp=$('#is_fp').val();
                            
                            var group=$('#group').val();
                            if(typeof group == undefined || group == null || group == 'undefined' || group == ''){
                                group = 0;
                            }
                            var dep = $('#dep').val();
                            if(typeof dep == undefined || dep == null || dep == 'undefined' || dep == ''){
                                dep = 0;
                            }
                            validstr = validstr.substr(1);
                            var params = {
                                'all_time':all_time,
                                'start_time':start_time,
                                'end_time':end_time,
                                'dj_staff_id':dj_staff_id,
                                'consultation_type_id':consultation_type_id,
                                'customer_intention_id':customer_intention_id,
                                'customer_cource_id':customer_cource_id,
                                'is_intostore':is_intostore,
                                'is_success':is_success,
                                'more_like':more_like,
                                'is_valid':validstr,
                                'is_loss':is_loss,
                                'get_contact':get_contact,
                                'tab':tab,
                                'city_id':city_id,
                                'add_shop_code':add_shop_code,
                                'customer_channel':customer_channel,
                                'type_info':type_info,
                                'group':group,
                                'dep' :dep,
                            };
                            postExcelFile(params, "export");
                            layer.close(index);
                        }
                    }
                });
            },
            // 导入
            import: function () {
                $.ajax({
                    type: "POST",
                    url: 'check_shop_message',
                    success: function (msg) {
                        if(msg.code==1){
                            load_page(
                                '/crm/customer/import',
                                '客资导入',
                                function(){
                                    layer.close(layer.index);
                                },
                                ['取消'],
                                980,550
                            )
                            reloadGrid();
                        }else{
                            layer.alert('抱歉，无法获取您的店面信息，不可导入数据');
                        }
                    }
                });


                //layer.open({
                //    title: '客资导入',
                //    type: 2,
                //    skin: 'layui-layer-rim',
                //    area: ['820px', '550px'],
                //    content: '/crm/customer/import'
                //});
                //element.progress('im-progress', '30%')
            },
            // 刷新列表
            refresh: function () {
                reloadGrid();
            },
            // 转客资
            zhuankezi: function () {
                load_page(
                    '/crm/customer/zhuanCustomer',
                    '新客资来电列表',
                    function(){
                        layer.close(layer.index);
                    },
                    ['取消'],
                    1280,500
                );
            },
            // 删除自定义列
            delSalfColumn: function () {
                $.ajax({
                    type: "POST",
                    url: '/crm/Customer/delSalfColumn',
                    data: {},
                    success: function (msg) {
                        if(msg.code==200){
                            layer.alert(msg.msg);
                            location.reload();
                        }else{
                            layer.alert(msg.msg);
                        }
                    }
                });
            },
            // 介绍人搜索
            jieshao_search: function () {
                $.ajax({
                    type: "POST",
                    url: '/crm/Customer/searchCustomers',
                    data: {customer_name:$('#search_content').val()},
                    success: function (msg) {
                        if (msg.Code == 200) {

                            var jsrPop=layer.open({
                                type: 1,
                                title: '介绍人搜索',
                                skin: 'layui-layer-rim',
                                area: ['420px', '90%'],
                                content: $('#jieshao_intro'),
                                btn:'关闭',
                                success:function(index){
                                    var a = msg.Data;
                                    var crmItem = '';
                                    for(var i=0;i< a.length;i++){
                                        crmItem +='<div class="jieshao" onclick="testlick(this);"><p class="old_order_item" name="s" cus_name="'+a[i]['customer_name']+'">姓名：'+a[i]['customer_name']+'</p><p cus_tel="'+a[i]['customer_tel']+'">手机号：'+a[i]['customer_tel']+'</p><p cus_order="'+a[i]['order_number']+'">订单编号：'+a[i]['order_number']+'</p></div>';
                                    }
                                    $("#jieshao_intro").html(crmItem);
                                    $("body").on("click",".jieshao",function(){
                                        layer.close(jsrPop);
                                    })
                                },
                                //yes:function(index) {
                                //    layer.close(index);
                                //    //$(".layui-layer-content iframe").contents().children().find("#jieshao_intro").html(crmItem);
                                //},
                                //cancel:function(index) {
                                //    layer.close(index);
                                //},
                            });
                        }else{
                            layer.alert('未搜索到对应数据！');
                            return false;
                        }
                    }
                })
            },
            // 失败再分配
            customerReAllot: function () {//转客资
                $.ajax({
                    type: "POST",
                    url: 'customerReAllot',
                    success: function(msg){
                        // if( msg.code == 200 ){
                        //     layer.alert(msg.msg);
                        //     reloadGrid();
                        //     return false;
                        // }else{
                        //     layer.alert(msg.msg);
                        // }
                        layer.alert('开始重新分配');
                    },
                    error:function(){
                        layer.alert('操作有误');
                    }
                });
            },
            // 详情 20200623
            detail: function () {
                // 右键id
                setTimeout(function(){

                    var idr = $('#Example').jqGrid('getGridParam','selarrrow');
                    //if (idr == '') {
                    //    // 双击id
                    //    var id = $(this).attr("id");
                    //}else{
                    var id = idr;
                    load_page(
                        '/crm/customer/customerinfo/id/'+id,
                        '客资详情',
                        function(){
                            eidtCustomerInfo(function(){reloadRow(id)});
                        },
                        ['保存','取消'],
                        740,700
                    );
                },10);
            },
            // 介绍人信息修改
            introducer: function () {
                // 右键id

                setTimeout(function(){

                    var idr = $('#Example').jqGrid('getGridParam','selarrrow');
                    //if (idr == '') {
                    //    // 双击id
                    //    var id = $(this).attr("id");
                    //}else{
                    var myrow = $('#Example').jqGrid('getRowData',$('#Example').jqGrid('getGridParam','selarrrow'));
                     if('转介绍' != myrow.customer_type){
                         layer.alert('不是转介绍客资，不能修改介绍人信息!');
                         return false;
                     }
                    var id = idr;
                    load_page(
                        '/crm/customer/editIntroducer/id/'+id,
                        '修改介绍人信息',
                        function(){
                            editIntroducer(function(){reloadRow(id)});
                        },
                        ['保存','取消'],
                        700,450
                    );
                },10);
            },
            // 追踪标记
            flag: function () {
                setTimeout(function(){
                    var id=jQuery("#Example").jqGrid('getGridParam', 'selarrrow');
                    if(id == '' || id == null){
                        layer.alert('请选中某行再操作');
                        return false;
                    }
                    if(id.length > 1){
                        layer.alert('请选中一个时再标记');
                        return false;
                    }
                    //var myrow = $('#Example').jqGrid('getRowData',$('#Example').jqGrid('getGridParam','selarrrow'));
                    //if(staff_name != myrow.sales_staff){
                    //    layer.alert('您不是此客资的追踪人，不能标记');
                    //    return false;
                    //}
                    var param = "id="+id;
                    $.ajax({
                        type: "POST",
                        url: 'getCustomerInfo',
                        data: param,
                        success: function(msg){
                            if(msg){
                                //$("#quick-flag select[name=is_valid]").val(msg['is_valid']);
                                //$("#quick-flag select[name=is_loss]").val(msg['is_loss']);
                                //$("#quick-flag select[name=customer_intention]").val(msg['customer_intention_id']);
                                //$("#quick-flag select[name=is_urgent]").val(msg['is_urgent']);
                                //$("#quick-flag select[name=customer_area]").val(msg['customer_area_id']);
                                $("#op_signinfo").val(msg['op_signinfo_id']);
                                //$("#quick-flag #is_next").val(msg['is_next']);
                                //$("#quick-flag #next_time").val(msg['next_time']);
                                //$("#quick-flag select[name=customer_area_id]").val(msg['customer_area_id']);
                                //$("#quick-flag select[name=customer_capacity]").val(msg['customer_capacity_id']);
                                //$("#quick-flag select[name=is_intostore]").val(msg['is_intostore']);
                                //$("#quick-flag select[name=is_success]").val(msg['is_success']);
                                //$("#quick-flag select[name=is_dive]").val(msg['is_dive']);
                                //$("#quick-flag select[name=is_fp]").val(msg['is_fp']);
                                //$("#quick-flag select[name=reason]").val(msg['seles_error_id']);
                                $('#quick-flag #op_signday_aaa').val(msg['op_signday'])
                                //$("#quick-flag input[name=totalpay_money]").val(msg['totalpay_money']);
                                //$('input[name=syjd_day]').val(msg['syjd_day'])
                                //$('input[name=order_day]').val(msg['order_day'])
                                layui.form.render(); //更新全部
                            }else{
                                layer.alert(msg.msg);
                            }
                        }
                    });
                    //var rowData = $('#Example').jqGrid('getRowData',jQuery("#Example").jqGrid('getGridParam', 'selarrrow'));
                    //console.log(rowData);
                    layer.open({
                        title: '追踪标记',
                        type: 1,
                        skin: 'layui-layer-rim',
                        area: ['500px', '180px'],
                        content: $('#quick-flag'),
                        btn: ['保存'],
                        yes:function(index){
                            //var is_valid = $("#quick-flag select[name=is_valid] option:selected").val();
                            //var is_loss = $("#quick-flag select[name=is_loss] option:selected").val();
                            //var customer_intention_id = $("#quick-flag select[name=customer_intention] option:selected").val();
                            //var customer_intention = $("#quick-flag select[name=customer_intention] option:selected").html();
                            //if(customer_intention == '请选择'){
                            //    customer_intention = '';
                            //}
                            //var is_urgent = $("#quick-flag select[name=is_urgent] option:selected").val();
                            //var is_dive = $("#quick-flag select[name=is_dive] option:selected").val();
                            //var is_fp = $("#quick-flag select[name=is_fp] option:selected").val();
                            var op_signinfo_id = $("#op_signinfo option:selected").val();
                            var op_signinfo = $("#op_signinfo option:selected").html();
                            if(!op_signinfo_id){
                                layer.alert('请选择标记后再提交');
                                return false;
                            }
                            if(op_signinfo == '请选择'){
                                op_signinfo = '';
                            }
                            //var customer_capacity_id = $("#quick-flag select[name=customer_capacity] option:selected").val();
                            //var totalpay_money = $("#quick-flag input[name=totalpay_money]").val();
                            //var customer_capacity = $("#quick-flag select[name=customer_capacity] option:selected").html();
                            //if(customer_capacity == '请选择'){
                            //    customer_capacity = '';
                            //}
                            //var is_intostore = $("#quick-flag select[name=is_intostore] option:selected").val();
                            //var is_next = $("#is_next option:selected").val();
                            //var is_success = $("#quick-flag select[name=is_success] option:selected").val();
                            //var seles_error_id = $("#quick-flag select[name=reason] option:selected").val();
                            //var seles_error_reason = $("#quick-flag select[name=reason] option:selected").html();
                            var op_signday = $('#op_signday_aaa').val()
                            //var next_time = $('#next_time').val()
                            //var totalpay_money = $('input[name=totalpay_money]').val()
                            //var syjd_day = $('input[name=syjd_day]').val()
                            //var order_day = $('input[name=order_day]').val()

                            //if(op_signday != ''){
                            //    op_signday =op_signday;
                            //}else{
                            //    op_signday = null;
                            //}
                            //if(syjd_day != ''){
                            //    syjd_day = syjd_day;
                            //}else{
                            //    syjd_day = null;
                            //}
                            //if(order_day != ''){
                            //    order_day = order_day;
                            //}else{
                            //    order_day = null;
                            //}
                            //if(next_time != ''){
                            //    next_time = next_time;
                            //}else{
                            //    next_time = null;
                            //}
                            //data += "id="+id+"&is_valid="+is_valid+"&is_loss="+is_loss+"&customer_intention="+customer_intention+"&is_urgent="+is_urgent+"&op_signinfo="+op_signinfo+"&customer_area="+customer_area+"&customer_capacity="+customer_capacity+"&is_intostore="+is_intostore+"&is_success="+is_success+"&customer_intention_id="+customer_intention_id+"&customer_capacity_id="+customer_capacity_id+"&customer_area_id="+customer_area_id+"&op_signday="+op_signday+"&syjd_day="+syjd_day+"&order_day="+order_day+"&is_dive="+is_dive+"&is_fp="+is_fp+"&seles_error_id="+seles_error_id+"&seles_error_reason="+seles_error_reason+"&totalpay_money="+totalpay_money+"&is_next="+is_next+"&next_time="+next_time;
                            var data = "id="+id+"&op_signinfo_id="+op_signinfo_id+"&op_signinfo="+op_signinfo+"&op_signday="+op_signday;
                            //alert(data);return false;
                            $.ajax({
                                type: "POST",
                                url: 'customerSign',
                                data: data,
                                success: function(msg){
                                    if( msg.code == 200 ){
                                        layer.alert(msg.msg);
                                        $("#Example").jqGrid('setRowData',id,{'op_signinfo':op_signinfo});
                                        //reloadGrid();
                                        return false;
                                    }else{
                                        layer.alert(msg.msg);
                                    }
                                },
                                error:function(){
                                    layer.alert('操作有误');
                                }
                            });
                            layer.close(index);
                        }
                    });
                },10);
            },
            // 客资标记
            cus_flag: function () {
                setTimeout(function(){
                    var id=jQuery("#Example").jqGrid('getGridParam', 'selarrrow');
                    if(id == '' || id == null){
                        layer.alert('请选中某行再操作');
                        return false;
                    }
                    if(id.length > 1){
                        layer.alert('请选中一个时再标记');
                        return false;
                    }
                    // var myrow = $('#Example').jqGrid('getRowData',$('#Example').jqGrid('getGridParam','selarrrow'));
                    // if(staff_name != myrow.sales_staff){
                    //     layer.alert('您不是此客资的追踪人，不能标记');
                    //     return false;
                    // }
                    var param = "id="+id;
                    $.ajax({
                        type: "POST",
                        url: 'getCustomerInfo',
                        data: param,
                        success: function(msg){
                            if(msg){
                                $("#sign_id").val(msg['sign_id']);
                                layui.form.render(); //更新全部
                            }else{
                                layer.alert(msg.msg);
                            }
                        }
                    });
                    //var rowData = $('#Example').jqGrid('getRowData',jQuery("#Example").jqGrid('getGridParam', 'selarrrow'));
                    //console.log(rowData);
                    layer.open({
                        title: '客资标记',
                        type: 1,
                        skin: 'layui-layer-rim',
                        area: ['300px', '180px'],
                        content: $('#cus-flag'),
                        btn: ['保存'],
                        yes:function(index){
                            var sign_id = $("#sign_id option:selected").val();
                            var sign_name = $("#sign_id option:selected").html();
                            if(sign_name == '请选择'){
                                sign_name = '';
                            }

                            var data = "id="+id+"&sign_id="+sign_id+"&sign_name="+sign_name;
                            //alert(data);return false;
                            $.ajax({
                                type: "POST",
                                url: 'customerSign',
                                data: data,
                                success: function(msg){
                                    if( msg.code == 200 ){
                                        layer.alert(msg.msg);
                                        $("#Example").jqGrid('setRowData',id,{'sign_name':sign_name});
                                        //reloadGrid();
                                        return false;
                                    }else{
                                        layer.alert(msg.msg);
                                    }
                                },
                                error:function(){
                                    layer.alert('操作有误');
                                }
                            });
                            layer.close(index);
                        }
                    });
                },10);
            },
            // 预约进店
            yyjd: function () {
                setTimeout(function(){
                    var id=jQuery("#Example").jqGrid('getGridParam', 'selarrrow');
                    if(id == '' || id == null){
                        layer.alert('请选中某行再操作');
                        return false;
                    }
                    if(id.length > 1){
                        layer.alert('请选中一个时再操作');
                        return false;
                    }
                     var myrow = $('#Example').jqGrid('getRowData',$('#Example').jqGrid('getGridParam','selarrrow'));
                    // if(staff_name != myrow.sales_staff){
                    //     layer.alert('您不是此客资的追踪人，不能预约');
                    //     return false;
                    // }
                    //if( myrow.is_valid != '是'){
                    //    layer.alert('不是有效客资，不能预约进店');
                    //    return false;
                    //}
                    load_page(
                        '/crm/customer/yyjd/id/'+id,
                        '预约进店',
                        function(){
                            yyjd(function(){reloadRow(id);});
                        },
                        ['保存','取消'],
                        500,380
                    );
                },10);
            },
            //转订单
            order_manager: function () {
                setTimeout(function(){
                    var id=jQuery("#Example").jqGrid('getGridParam', 'selarrrow');
                    if(id == '' || id == null){
                        layer.alert('请选中某行再操作');
                        return false;
                    }
                    if(id.length > 1){
                        layer.alert('请选中一个时再操作');
                        return false;
                    }
                    // var myrow = $('#Example').jqGrid('getRowData',$('#Example').jqGrid('getGridParam','selarrrow'));
                    // if(staff_name != myrow.sales_staff){
                    //     layer.alert('您不是此客资的追踪人，不能转订单');
                    //     return false;
                    // }
                    //if( myrow.is_valid != '是'){
                    //    layer.alert('不是有效客资，不能转订单');
                    //    return false;
                    //}
                    $.ajax({
                        type: "POST",
                        url: '/crm/Customer/checkCustomerOrder',
                        data: "id="+id,
                        success: function(msg){
                            if (msg['error'] == 1) {
                                layer.alert(msg['msg']);
                                return false;
                            }
                            // 已经安装erp
                            if (msg['erp'] == 1) {
                                // 没订单过
                                if (msg['code'] == 200) {
                                    if(ORDER_URL == 'order'){
                                        load_page(
                                            '/crm/Customer/'+ORDER_URL+'/id/'+id,
                                            // '/crm/Customer/orderManager/id/'+id,
                                            Lang_orderFunctionName,
                                            function(){
                                                order(function(){reloadRow(id);});
                                            },
                                            ['保存','取消'],
                                            640,580
                                        );
                                    }else{
                                        load_page(
                                            '/crm/Customer/'+ORDER_URL+'/id/'+id,
                                            // '/crm/Customer/orderManager/id/'+id,
                                            Lang_orderFunctionName,
                                            function(){
                                                order(function(){reloadRow(id);});
                                            },
                                            ['保存','取消'],
                                            520,415
                                        );
                                    }
                                }
                                // 有过订单
                                else{
                                    layer.confirm('已订单客资，确定再次转订单吗？', {
                                        title: '转订单提醒',
                                        btn: ['确定', '取消'], //按钮
                                        area: ['400px', '176px'],
                                        yes: function (index) {
                                            layer.close(index);
                                            if(ORDER_URL == 'order'){
                                                load_page(
                                                    '/crm/Customer/'+ORDER_URL+'/id/'+id,
                                                    Lang_orderFunctionName,
                                                    function(){
                                                        order(function(){reloadRow(id);});
                                                    },
                                                    ['保存','取消'],
                                                    640,580
                                                );
                                            }else{
                                                load_page(
                                                    '/crm/Customer/'+ORDER_URL+'/id/'+id,
                                                    // '/crm/Customer/orderManager/id/'+id,
                                                    Lang_orderFunctionName,
                                                    function(){
                                                        order(function(){reloadRow(id);});
                                                    },
                                                    ['保存','取消'],
                                                    520,415
                                                );
                                            }
                                        }
                                    });
                                }
                            }
                            // 没有安装erp
                            else if (msg['erp'] == 2) {
                                // 没订单过
                                if (msg['code'] == 200) {
                                    load_page(
                                        //'/crm/Customer/'+ORDER_URL+'/id/'+id,
                                         '/crm/Customer/orderManager/id/'+id,
                                        Lang_orderFunctionName,
                                        function(){
                                            //orderEdit(function(){reloadGrid()});
                                            order(function(){reloadRow(id);});
                                        },
                                        ['保存','取消'],
                                        550,500
                                    );
                                }
                                // 有过订单
                                else{
                                    layer.confirm('已订单客资，确定再次转订单吗？', {
                                        title: Lang_orderFunctionName+'提醒',
                                        btn: ['确定', '取消'], //按钮
                                        area: ['400px', '176px'],
                                        yes: function (index) {
                                            layer.close(index);
                                            load_page(
                                                //'/crm/Customer/'+ORDER_URL+'/id/'+id,
                                                '/crm/Customer/orderManager/id/'+id,
                                                // '转订单',
                                                Lang_orderFunctionName,
                                                function(){
                                                    //orderEdit(function(){reloadGrid()});
                                                    order(function(){reloadRow(id);});
                                                },
                                                ['保存','取消'],
                                                550,500
                                            );
                                        }
                                    });
                                }
                            }
                        }
                    });
                    // load_page(
                    //     '/crm/Customer/orderManager/id/'+id,
                    //     // '/crm/Customer/orderManager/id/'+id,
                    //     '转订单',
                    //     function(){
                    //         //orderEdit(function(){reloadGrid()});
                    //         orderManager(function(){reloadRow(id);});
                    //     },
                    //     ['保存','取消'],
                    //     550,500
                    // );
                },10);
            },
            //编辑订单
            order_edit: function () {
                setTimeout(function(){
                    var id=jQuery("#Example").jqGrid('getGridParam', 'selarrrow');
                    if(id == '' || id == null){
                        layer.alert('请选中某行再操作');
                        return false;
                    }
                    if(id.length > 1){
                        layer.alert('请选中一个时再操作');
                        return false;
                    }
                     var myrow = $('#Example').jqGrid('getRowData',$('#Example').jqGrid('getGridParam','selarrrow'));
                    // if(staff_name != myrow.sales_staff){
                    //     layer.alert('您不是此客资的追踪人，不能编辑订单');
                    //     return false;
                    // }
                    //if( myrow.is_valid != '是'){
                    //    layer.alert('不是有效客资，不能编辑订单');
                    //    return false;
                    //}
                    if(ERP == false){
                        load_page(
                            '/crm/Customer/orderEdit/id/'+id,
                            '编辑订单',
                            function(){
                                orderEdit(function(){reloadRow(id)});
                            },
                            ['保存','取消'],
                            500,250
                        );
                    }else{
                        layer.alert('已安装erp，不能编辑订单');
                        return false;
                    }

                },10);
            },
            //筛客
            sk_flag: function () {
                setTimeout(function(){
                    var id=jQuery("#Example").jqGrid('getGridParam', 'selarrrow');
                    if(id == '' || id == null){
                        layer.alert('请选中某行再操作');
                        return false;
                    }
                    if(id.length > 1){
                        layer.alert('请选中一个时再标记');
                        return false;
                    }
                    // var myrow = $('#Example').jqGrid('getRowData',$('#Example').jqGrid('getGridParam','selarrrow'));
                    // if(staff_name != myrow.sk_staff){
                    //     layer.alert('您不是此客资的筛客人，不能筛客');
                    //     return false;
                    // }
                    var param = "id="+id;
                    $.ajax({
                        type: "POST",
                        url: 'getCustomerInfo',
                        data: param,
                        success: function(msg){
                            if(msg){
                                $("#sk-flag #sk_customer_name").val(msg['customer_name']);
                                $("#sk-flag #sk_customer_tel").val(msg['customer_tel']);
                                $("#sk-flag #sk_customer_channel_id").val(msg['customer_channel_id']);
                                $("#sk-flag #sk_customer_channel").val(msg['customer_channel_name']);
                                $("#sk-flag #sk_customer_wechat").val(msg['customer_wechat']);
                                $("#sk-flag #sk_customer_qq").val(msg['customer_qq']);
                                $("#sk-flag #sk_customer_sex").val(msg['customer_sex']);
                                $("#sk-flag #sk_consultation_type").val(msg['consultation_type_id']);
                                $("#sk-flag #sk_customer_region").val(msg['customer_region_id']);
                                $("#sk-flag #sk_is_valid").val(msg['is_valid']);
                                $("#sk-flag #sk_customer_remark").val(msg['customer_remark']);

                                if(msg['auth_tel']=='no'){
                                    $("#sk-flag #sk_customer_tel").attr('disabled',true);
                                }else{
                                    $("#sk-flag #sk_customer_tel").attr('disabled',false);
                                }

                                if(msg['auth_customer_channel']=='no'){
                                    $("#sk-flag #sk_customer_channel").attr('disabled',true);
                                }else{
                                    $("#sk-flag #sk_customer_channel").attr('disabled',false);
                                }

                                if(msg['auth_qq']=='no'){
                                    $("#sk-flag #sk_customer_qq").attr('disabled',true);
                                }else{
                                    $("#sk-flag #sk_customer_qq").attr('disabled',false);
                                }

                                if(msg['auth_wechat']=='no'){
                                    $("#sk-flag #sk_customer_wechat").attr('disabled',true);
                                }else{
                                    $("#sk-flag #sk_customer_wechat").attr('disabled',false);
                                }
                                layui.form.render(); //更新全部
                            }else{
                                layer.alert(msg.msg);
                            }
                        }
                    });

                    //var rowData = $('#Example').jqGrid('getRowData',jQuery("#Example").jqGrid('getGridParam', 'selarrrow'));
                    //console.log(rowData);
                    layer.open({
                        title: '筛客',
                        type: 1,
                        skin: 'layui-layer-rim',
                        area: ['500px', '370px'],
                        content: $('#sk-flag'),
                        btn: ['保存'],
                        yes:function(index){
                            var customer_name = $("#sk-flag #sk_customer_name").val();
                            var customer_tel = $("#sk-flag #sk_customer_tel").val();
                            var customer_wechat = $("#sk-flag #sk_customer_wechat").val();
                            var customer_qq = $("#sk-flag #sk_customer_qq").val();
                            var customer_sex = $("#sk-flag #sk_customer_sex option:selected").val();
                            var consultation_type_id = $("#sk-flag #sk_consultation_type option:selected").val();
                            var consultation_type = $("#sk-flag #sk_consultation_type option:selected").html();
                            var customer_region_id = $("#sk-flag #sk_customer_region option:selected").val();
                            var customer_region = $("#sk-flag #sk_customer_region option:selected").html();
                            var customer_channel_id = $("#sk-flag #sk_customer_channel_id").val();
                            var customer_channel = $("#sk-flag #sk_customer_channel").val();
                            var is_valid = $("#sk_is_valid option:selected").val();
                            var customer_remark = $("#sk-flag #sk_customer_remark").val();
                            // if(customer_tel&&customer_tel.indexOf('*')==-1&&!check_tel(customer_tel)){
                            //     layer.alert("手机号输入错误");return false;
                            // }
                            check_tel_customer(customer_tel);
                            var data = "id="+id+"&customer_name="+customer_name+"&customer_tel="+customer_tel+"&customer_wechat="+customer_wechat+"&customer_qq="+customer_qq+"&customer_sex="+customer_sex+"&consultation_type_id="+consultation_type_id+"&consultation_type="+consultation_type+"&customer_region_id="+customer_region_id+"&customer_region="+customer_region+"&is_valid="+is_valid+"&customer_remark="+customer_remark+"&customer_channel_id="+customer_channel_id+"&customer_channel="+customer_channel+"&is_already_sk=1";
                            //alert(data);return false;
                            $.ajax({
                                type: "POST",
                                url: '/crm/Customer/skCustomer',
                                data: data,
                                success: function(msg){
                                    if( msg.code == 1 ){
                                        layer.alert(msg.msg);
                                        layer.close(index);
                                        //reloadGrid();
                                        reloadRow(id);
                                        return false;
                                    }else{
                                        layer.alert(msg.msg);
                                    }
                                },
                                error:function(){
                                    layer.alert('操作有误');
                                }
                            });

                        }
                    });
                },10);
            },
            //追踪人员修改弹窗
            zz_flag: function () {
                setTimeout(function(){
                    var id=jQuery("#Example").jqGrid('getGridParam', 'selarrrow');
                    if(id == '' || id == null){
                        layer.alert('请选中某行再操作');
                        return false;
                    }
                    if(id.length > 1){
                        layer.alert('请选中一个时再标记');
                        return false;
                    }
                    var param = "id="+id;
                    $.ajax({
                        type: "POST",
                        url: '/crm/Customer/getCustomerInfo',
                        data: param,
                        success: function(msg){
                            if(msg){
                                $("#zz-flag #zz_customer_tel").val(msg['customer_tel']);
                                $("#zz-flag #zz_customer_qq").val(msg['customer_qq']);
                                $("#zz-flag #zz_customer_weibo").val(msg['customer_weibo']);
                                $("#zz-flag #zz_customer_wechat").val(msg['customer_wechat']);
                                $("#zz-flag #zz_customer_name").val(msg['customer_name']);
                                $("#zz-flag #zz_customer_channel_id").val(msg['customer_channel_id']);
                                $("#zz-flag #zz_customer_channel").val(msg['customer_channel']);
                                $("#zz-flag #zz_customer_sex").val(msg['customer_sex']);
                                $("#zz-flag #zz_sign_id").val(msg['sign_id']);
                                $("#zz-flag #budget").val(msg['budget']);
                                $("#zz-flag #zz_yjd_day").val(msg['yjd_day']);
                                $("#zz-flag #wedding_date").val(msg['wedding_date']);
                                $("#zz-flag #zz_customer_region").val(msg['customer_region_id']);
                                $("#zz-flag #zz_consulation_shop_code").val(msg['consulation_shop_code']);
                                $("#zz-flag #zz_intostore_note").val(msg['intostore_note']);
                                $("#zz-flag #order_number").val(msg['order_number']);
                                $("#zz-flag #totalpay_money").val(msg['totalpay_money']);
                                $("#zz-flag #fact_money").val(msg['fact_money']);
                                if(msg['auth_tel']=='no'){
                                    $("#zz-flag #zz_customer_tel").attr('disabled',true);
                                }else{
                                    $("#zz-flag #zz_customer_tel").attr('disabled',false);
                                }

                                if(msg['auth_customer_channel']=='no'){
                                    $("#zz-flag #zz_customer_channel").attr('disabled',true)
                                }else{
                                    $("#zz-flag #zz_customer_channel").attr('disabled',false)
                                }
                                layui.form.render(); //更新全部
                            }else{
                                layer.alert(msg.msg);
                            }
                        }
                    });
                    //var rowData = $('#Example').jqGrid('getRowData',jQuery("#Example").jqGrid('getGridParam', 'selarrrow'));
                    //console.log(rowData);
                    layer.open({
                        title: '追踪修改',
                        type: 1,
                        skin: 'layui-layer-rim',
                        area: ['510px', '450px'],
                        content: $('#zz-flag'),
                        btn: ['保存'],
                        yes:function(index){
                            var customer_name = $("#zz-flag #zz_customer_name").val();
                            var customer_tel = $("#zz-flag #zz_customer_tel").val();
                            var customer_wechat = $("#zz-flag #zz_customer_wechat").val();
                            var customer_qq = $("#zz-flag #zz_customer_qq").val();
                            var customer_weibo = $("#zz-flag #zz_customer_weibo").val();
                            var customer_channel_id = $("#zz-flag #zz_customer_channel_id").val();
                            var customer_channel = $("#zz-flag #zz_customer_channel").val();
                            var customer_sex = $("#zz-flag #zz_customer_sex").val();
                            var sign_id = $("#zz-flag #zz_sign_id").val();
                            var budget = $("#zz-flag #budget").val();
                            var yjd_day = $("#zz-flag #zz_yjd_day").val();
                            var wedding_date = $("#zz-flag #wedding_date").val();
                            var customer_region_id = $("#zz-flag #zz_customer_region").val();
                            var customer_region = $("#zz-flag #zz_customer_region option:selected").html();
                            var consulation_shop_code = $("#zz-flag #zz_consulation_shop_code").val();
                            var intostore_note = $("#zz-flag #zz_intostore_note").val();
                            var order_number = $("#zz-flag #order_number").val();
                            var totalpay_money = $("#zz-flag #totalpay_money").val();
                            var fact_money = $("#zz-flag #fact_money").val();
                            // if(customer_tel&&customer_tel.indexOf('*')==-1&&!check_tel(customer_tel)){
                            //     layer.alert("手机号输入错误");return false;
                            // }
                            check_tel_customer(customer_tel);
                            var data = "id="+id+"&customer_name="+customer_name+"&sign_id="+sign_id+"&consulation_shop_code="+consulation_shop_code+"&customer_sex="+customer_sex+"&customer_region_id="+customer_region_id+"&customer_region="+customer_region+"&customer_channel_id="+customer_channel_id+"&customer_channel="+customer_channel+"&budget="+budget+"&yjd_day="+yjd_day+"&wedding_date="+wedding_date+"&customer_tel="+customer_tel+"&intostore_note="+intostore_note+"&order_number="+order_number+"&totalpay_money="+totalpay_money+"&fact_money="+fact_money+"&customer_qq="+customer_qq+"&customer_weibo="+customer_qq+"&customer_wechat="+customer_wechat;
                            //alert(data);return false;
                            $.ajax({
                                type: "POST",
                                url: '/crm/Customer/customerInfo',
                                data: data,
                                success: function(msg){
                                    if( msg.code == 1 ){
                                        layer.close(index);
                                        //reloadGrid();
                                        return false;
                                    }else{
                                        layer.alert(msg.msg);
                                    }
                                },
                                error:function(){
                                    layer.alert('操作有误');
                                }
                            });
                        }
                    });
                },10);
            },
            // 发送短信
            msgsend: function () {
                //var rowData = $('#Example').jqGrid('getRowData',$('#Example').jqGrid('getGridParam','selarrrow'));
                //$('input[name=receive_name]').val(rowData['customer_name']);
                setTimeout(function(){
                    var selr = jQuery('#Example').jqGrid('getGridParam','selarrrow');
                    if(selr == '' || selr == null){
                        layer.alert('请选中某行再操作');
                        return false;
                    }
                    if(selr.length) {
                        var str = '';
                        for (var i = 0; i < selr.length; i++) {
                            var myrow = jQuery('#Example').jqGrid('getRowData', selr[i]);
                            str += (myrow.customer_name)+',';
                        }
                        $('input[name=receive_name]').val(str);
                    }
                    if(selr.length == 1){
                        var myrow = $('#Example').jqGrid('getRowData',$('#Example').jqGrid('getGridParam','selarrrow'));
                        if(myrow.customer_tel == '' || myrow.customer_tel == null || myrow.customer_tel == 'undefined'){
                            layer.alert('该客资没有手机号，不能发送短信');
                            return false;
                        }
                    }
                    // var myrow = $('#Example').jqGrid('getRowData',$('#Example').jqGrid('getGridParam','selarrrow'));
                    // if(staff_name != myrow.sales_staff){
                    //     layer.alert('您不是此客资的追踪人，不能发送短信');
                    //     return false;
                    // }
                    $.ajax({
                        type: "POST",
                        url: '/crm/Setting/getModalToJSON',
                        data: {},
                        success: function(rea){
                            // console.log('rea',rea)
                            if (rea.data.length > 0) {
                                var sms_data = rea.data;
                                var model_html ="<option value=''>请选择</option>";
                                for (var i = 0; i < sms_data.length; i++) {
                                    model_html+= "<option value='"+sms_data[i].id+"'>"+sms_data[i].mtemplate_name+"</option>";
                                }
                                $("#model").html(model_html);
                                layui.form.render('select'); 
                            };
                        }
                    });
                    layui.form.render(); //更新全部
                    $('#send_msg').val('');
                    layer.open({
                        title: '资源客户即时短信发送',
                        type: 1,
                        skin: 'layui-layer-rim',
                        area: ['500px', '350px'],
                        content: $('#sms-sending'),
                        btn: ['确定', '取消'],
                        yes:function(index){
                            var ids=$('#Example').jqGrid('getGridParam','selarrrow');
                            var content = $('#send_msg').val()
                            var model_id = $('#model').val();
                            var receive_name = $('input[name=receive_name]').val()
                            var data = "ids="+ids+"&send_msg="+content+"&receive_name="+receive_name+"&model_id="+model_id;
                            if(typeof content == 'undefined' || content == ''){
                                layer.alert('请输入短信内容');
                                return false;
                            }
                            $.ajax({
                                type: "POST",
                                url: '/crm/Customer/send_message',
                                data: data,
                                success: function(ret){
                                    if(ret.code){
                                        layer.alert(ret.msg);
                                        return false;
                                    }else{
                                        layer.alert(ret.msg);
                                    }
                                }
                            });
                            layer.close(index);
                        }
                    });
                },10);
            },
            // 向员工发送消息 发送站内信
            sendMsgToStaff: function () {
                var id = $('#Example').jqGrid('getGridParam','selarrrow');
                setTimeout(function(){
                    load_page(
                        '/crm/Customer/sendMsgToStaff?cid='+id,
                        '发送站内信',
                        function(){
                            sendMsgToStaff(id,function(){reloadRow(id)});
                        },
                        ['确定','取消'],
                        500,390
                    );
                },10);
            },
            // 新版电访 20201022
            interview:function(){
                dianfangPageNew();
            },
            /*
            // 追踪
            interview: function () {
                setTimeout(function(){
                    var id=jQuery("#Example").jqGrid('getGridParam', 'selarrrow');
                    if(id == '' || id == null){
                        layer.alert('请选中某行再操作');
                        return false;
                    }
                    if(id.length > 1){
                        layer.alert('追踪时只能选择一个人');
                        return false;
                    }

                    // var myrow = $('#Example').jqGrid('getRowData',$('#Example').jqGrid('getGridParam','selarrrow'));
                    // if(staff_name != myrow.sales_staff){
                    //     layer.alert('您不是此客资的追踪人，不能追踪');
                    //     return false;
                    // }
                    // load_page(
                    //     '/crm/Customer/dianfang/id/'+id,
                    //     '客资追踪',
                    //     function(){
                    //         dianfang(function(){reloadRow(id);});
                    //     },
                    //     ['保存','取消'],
                    //     520,600,
                    //     function(){
                    //         return quxiaoTable();
                    //     },
                    //     function(){
                    //         return closeTable();
                    //     }
                    // );
                    // 网页可用高度
                    var sHeihgt = $(window).height();
                    var height = 750;
                    if (sHeihgt>900) {
                        height = 750;
                    }else if (sHeihgt>700 && sHeihgt<800) {
                        height = 650;
                    }else if (sHeihgt>600 && sHeihgt<700) {
                        height = 550;
                    }else if (sHeihgt<600) {
                        height = 450;
                    }
                    var dianfang = layer.open({
                        title: '追踪',
                        type: 2,
                        skin: 'layui-layer-rim',
                        area: ['760px', '750px'],
                        maxmin: true,
                        //content: $('#add-box'),
                        content: '/crm/Customer/dianfang/id/'+id,
                        btn: ['提交', '取消'],
                        yes: function (iframeDom,index) {
                            var shade = layer.load(1, {shade: 0.2});
                            // 获取 iframe
                            var iframeWin = window[$(index).find('iframe')[0]['name']];
                            // 通过 getupContentFbh 方法 重新赋值 
                            var cus = $(".layui-layer-content iframe").contents().children();
                            // cus.find("#customerTrack").find("#sales_remark").text(iframeWin.getupContentTrack());
                            var customer_id = cus.find('#customerId').val();
                            var customer_name = cus.find('#df_customer_name').val();
                            if(isInArray('customer_name',dfMust)){
                                if (!customer_name) {
                                    layer.alert("客户姓名不能为空");
                                    layer.close(shade);
                                    return false;
                                }
                            } 
                            var customer_number = cus.find('#power-interview #customer_number').val();
                            var customer_sex = cus.find('#df_customer_sex option:selected').val();
                            var age_area = cus.find('#df_age_area option:selected').val();
                            // 沟通方式 (电话，qq，微信，其他)
                            var gtType = cus.find('.gtType:checked').val();
                            var customer_tel = cus.find('#df_customer_tel').val();
                            if(isInArray('customer_tel',dfMust)){
                                if (!customer_tel) {
                                    layer.alert("客户手机不能为空");
                                    layer.close(shade);
                                    return false;
                                }
                            } 
                            var customer_wechat = cus.find('#df_customer_wechat').val();
                            if(isInArray('customer_wechat',dfMust)){
                                if (!customer_wechat) {
                                    layer.alert("客户微信不能为空");
                                    layer.close(shade);
                                    return false;
                                }
                            }
                            if (!customer_tel && !customer_wechat) {
                                layer.alert("请填写手机号、微信任一项联系方式");
                                layer.close(shade);
                                return false;
                            }
                            var wechat_status = cus.find('input[name=wechat_status]').val();
                            var add_friend_time = cus.find('input[name=add_friend_time]').val();
                            if(isInArray('add_friend_time',dfMust)){
                                if (!add_friend_time) {
                                    layer.alert("添加好友时间不能为空");
                                    layer.close(shade);
                                    return false;
                                }
                            }
                            var customer_qq = cus.find('#df_customer_qq').val();
                            if(isInArray('df_customer_qq',dfMust)){
                                if (!df_customer_qq) {
                                    layer.alert("客户QQ不能为空");
                                    layer.close(shade);
                                    return false;
                                }
                            }
                            // 追踪情况（接通，未接通，空号，不是本人）
                            var tel_static = cus.find("input[name='tel_static']:checked").val();
                            // 追踪备注 20200523
                            // var sales_remark = iframeWin.getupContentTrack();
                            var sales_remark = cus.find("#df_sales_remark iframe").contents().children().find('.view').html();
                            if(isInArray('sales_remark',dfMust)){
                                if (!sales_remark) {
                                    layer.alert('备注不能为空');
                                    layer.close(shade);
                                    return false;
                                }
                            }
                            // 消费类型
                            var consultation_type_id =  cus.find("#df_consultation_type option:selected").val();
                            if(consultation_type_id == 'undefined' || consultation_type_id == '' || consultation_type_id == null){
                                var consultation_type = '';
                            }else{
                                var consultation_type =  cus.find("#df_consultation_type option:selected").html();
                            }
                            var mate_name = cus.find('#df_mate_name').val();
                            var mate_tel = cus.find('#df_mate_tel').val();
                            var mate_wechat = cus.find('#df_mate_wechat').val();
                            var data = {};
                            data.customer_id     = customer_id;
                            data.customer_name   = customer_name;
                            data.customer_number = customer_number;
                            data.customer_sex    = customer_sex;
                            data.age_area    = age_area;
                            data.gtType          = gtType;
                            data.customer_tel    = customer_tel;
                            data.customer_wechat = customer_wechat;
                            data.mate_name   = mate_name;
                            data.mate_tel    = mate_tel;
                            data.mate_wechat = mate_wechat;
                            data.wechat_status = wechat_status;
                            data.add_friend_time = add_friend_time;
                            data.customer_qq = customer_qq;
                            data.tel_static      = tel_static;
                            data.sales_remark    = sales_remark;
                            data.consultation_type_id = consultation_type_id;
                            data.consultation_type    = consultation_type;
                            // 三级地区 省
                            var province_id = cus.find('#df_province_id').val();
                            if(province_id == 'undefined' || province_id == '' || province_id == null){
                                var province = '';
                            }else{
                                var province = cus.find('#df_province_id option:selected').html();
                            };
                            // 三级地区 市
                            var city_id = cus.find('#df_city_id').val();
                            if(city_id == 'undefined' || city_id == '' || city_id == null){
                                var city = '';
                            }else{
                                var city = cus.find('#df_city_id option:selected').html();
                            };
                            // 三级地区 地区
                            var county_id = cus.find('#df_county_id').val();
                            if(county_id == 'undefined' || county_id == '' || county_id == null){
                                var county = '';
                            }else{
                                var county = cus.find('#df_county_id option:selected').html();
                            }
                            // 消费能力
                            var capacity_id =  cus.find('#df_customer_capacity option:selected').val();
                            if(capacity_id == 'undefined' || capacity_id == '' || capacity_id == null || capacity_id == 0){
                                var customer_capacity = '';
                                if(isInArray('customer_capacity',dfMust)){
                                    layer.alert("消费能力不能为空");
                                    layer.close(shade);
                                    return false;
                                }
                            }else{
                                var customer_capacity = cus.find('#df_customer_capacity option:selected').html();
                            }
                            var sign_id =  cus.find('#df_sign_id').val();
                            if(sign_id == 'undefined' || sign_id == '' || sign_id == null || sign_id == 0){
                                var sign_name = '';
                            }else{
                                var sign_name = cus.find('#df_sign_id option:selected').html();
                            }

                            var customer_cource_id =  cus.find('#df_customer_cource_id').val();
                            if(customer_cource_id == 'undefined' || customer_cource_id == '' || customer_cource_id == null || customer_cource_id == 0){
                                var customer_cource = '';
                            }else{
                                var customer_cource = cus.find('#df_customer_cource_id option:selected').html();
                            }

                            // 预算
                            var budget = cus.find("#df_budget").val();
                            // 再约时间
                            var next_time = cus.find("#df_next_time").val();
                            data.province_id = province_id;
                            data.province    = province;
                            data.city_id     = city_id;
                            data.city        = city;
                            data.county_id   = county_id;
                            data.county      = county;
                            data.customer_capacity_id   = capacity_id;
                            data.customer_capacity = customer_capacity;
                            data.next_time = next_time;
                            data.sign_id   = sign_id;
                            data.sign_name = sign_name;
                            data.budget    = budget;

                            // 电费情况->功能选择（继续追踪，驳回，预约进店，不在追踪）
                            var noTrack = cus.find('input[name=noTrack]:checked').val();

                            if(noTrack == 1){
                                // 客资状态是否有效
                                var is_valid = cus.find('#df_is_valid').val();
                                if(isInArray('is_valid',dfMust)){
                                    if (!is_valid) {
                                        layer.alert("客资状态不能为空");
                                        layer.close(shade);
                                        return false;
                                    }
                                }
                                if (is_valid==3) {
                                    unvalid_id = cus.find('#df_unvalid_reason').val();
                                    unvalid_reason = cus.find('#df_unvalid_reason option:selected').html();
                                }else{
                                    unvalid_id = '';
                                    unvalid_reason = '';
                                }
                                if(isInArray('customer_capacity',dfMust)){
                                    layer.alert("消费能力不能为空");
                                    layer.close(shade);
                                    return false;
                                }

                                if(isInArray('sign_id',dfMust)){
                                    if (sign_id == 'undefined' || sign_id == '' || sign_id == null || sign_id == 0) {
                                        layer.alert("客资标记不能为空");
                                        layer.close(shade);
                                        return false;
                                    }
                                }
                                // 追踪标记
                                var op_signinfo_id =  cus.find('#df_op_signinfo_id option:selected').val();
                                if(op_signinfo_id == 'undefined' || op_signinfo_id == '' || op_signinfo_id == null){
                                    var op_signinfo = '';
                                }else{
                                    var op_signinfo = cus.find('#df_op_signinfo_id option:selected').html();
                                }
                                if(isInArray('sign_id',dfMust)){
                                    if (!sign_id) {
                                        layer.alert("追踪标记不能为空");
                                        layer.close(shade);
                                        return false;
                                    }
                                }
                                // 客户意向
                                var customer_intention_id =  cus.find("#df_customer_intention option:selected").val();
                                if(customer_intention_id == 'undefined' || customer_intention_id == '' || customer_intention_id == null){
                                    var customer_intention = '';
                                }else{
                                    var customer_intention = cus.find("#df_customer_intention option:selected").html();
                                }


                                if(isInArray('budget',dfMust)){
                                    if (!budget) {
                                        layer.alert('预算不能为空');
                                        layer.close(shade);
                                        return false;
                                    }
                                }
                                // 婚期
                                var marry_day = cus.find("#df_marry_day").val();
                                if (marry_day == 'undefined' || marry_day == '' || marry_day == null) {
                                    marry_day = '';
                                }
                                if(isInArray('marry_day',dfMust)){
                                    if (!marry_day) {
                                        layer.alert("结婚不能为空");
                                        layer.close(shade);
                                        return false;
                                    }
                                }
                                // 预计婚期
                                var ready_marry_day = cus.find("#df_ready_marry_day").val();
                                if (ready_marry_day == 'undefined' || ready_marry_day == '' || ready_marry_day == null) {
                                    ready_marry_day = '';
                                }
                                if(isInArray('ready_marry_day',dfMust)){
                                    if (!ready_marry_day) {
                                        layer.alert("预计婚期不能为空");
                                        layer.close(shade);
                                        return false;
                                    }
                                }
                                // 再约时间
                                if(isInArray('next_time',dfMust)){
                                    if (!next_time) {
                                        layer.alert('再约时间不能为空');
                                        layer.close(shade);
                                        return false;
                                    }
                                }
                                // 追踪阶段
                                var seles_step =  cus.find("#df_seles_step option:selected").val();
                                if(seles_step == 'undefined' || seles_step == '' || seles_step == null){
                                    var step_name = '';
                                }else{
                                    var step_name =  cus.find("#df_seles_step option:selected").html();
                                }

                                // 是否取消预约（2：取消预约）
                                var quit_yjd = cus.find("select[name=quit_yjd] option:selected").val();
                                //客资标签
                                var customer_label='';
                                for(var i=0;i<cus.find('.customer_label').length;i++){
                                    customer_label+=cus.find('.customer_label').eq(i).attr("title")+',';
                                }
                                data.customer_intention_id= customer_intention_id;
                                data.customer_intention   = customer_intention;
                                data.is_valid  = is_valid;
                                data.unvalid_id = unvalid_id;
                                data.unvalid_reason = unvalid_reason;
                                data.op_signinfo_id   = op_signinfo_id;
                                data.op_signinfo = op_signinfo;
                                data.marry_day = marry_day;
                                data.ready_marry_day = ready_marry_day;
                                data.seles_step= seles_step;
                                data.step_name = step_name;
                                data.noTrack   = noTrack;
                                data.quit_yjd  = quit_yjd;
                                data.customer_label  = customer_label;
                            }else if(noTrack == 2){
                                var reject_reason = cus.find('select[name=reject_reason]').val();
                                if(reject_reason == 'undefined' || reject_reason == '' || reject_reason == null){
                                    layer.alert('请选择驳回原因');
                                    layer.close(shade);
                                    return false;
                                }else{
                                    var reject_reason = cus.find('select[name=reject_reason] option:selected').html();
                                }
                                var reject_staff_id = cus.find("#df_reject_staff_id option:selected").val();
                                data.reject_reason = reject_reason;
                                data.noTrack = noTrack;
                                data.reject_staff_id = reject_staff_id;
                            }else if(noTrack == 3){
                                // 客资状态是否有效
                                var is_valid = cus.find('#df_is_valid').val();
                                if(isInArray('is_valid',dfMust)){
                                    if (!is_valid) {
                                        layer.alert('客资状态不能为空');
                                        layer.close(shade);
                                        return false;
                                    }
                                }
                                if(isInArray('customer_cource',dfMust)){
                                    if (!customer_cource) {
                                        layer.alert("客户来源不能为空");
                                        layer.close(shade);
                                        return false;
                                    }
                                }

                                // 意向店面
                                var consulation_shop_code = cus.find("#df_consulation_shop_code option:selected").val();
                                if (consulation_shop_code == 'undefined' || consulation_shop_code == '' || consulation_shop_code == null) {
                                    //if(isInArray('consulation_shop',dfMust)){
                                        layer.alert('请选择意向店面');
                                        layer.close(shade);
                                        return false;
                                    //}
                                }else {
                                    var consulation_shop = cus.find("#df_consulation_shop_code option:selected").html();
                                }
                                // 预计进店时间
                                var yjd_day = cus.find("#df_yjd_day").val();
                                if (yjd_day == 'undefined' || yjd_day == '' || yjd_day == null) {
                                    // 预约进店 预约时间是否必选（深圳天长定制） 默认0（必选） 天长1（非必选）
                                    if (cus.find("#isYjdMust").val()!=1) {
                                        layer.alert('请选择预约进店时间');
                                        layer.close(shade);
                                        return false;
                                    }
                                }
                                // 接待人员
                                var reception_id = cus.find('#df_reception_id option:selected').val();
                                if (reception_id == 'undefined' || reception_id == '' || reception_id == null) {
                                    var reception_id = 0;
                                    var reception_name = '';
                                }else{
                                    var reception_name = cus.find('#df_reception_id option:selected').html();
                                }

                                // 预算
                                var budget = cus.find("#df_budget").val();
                                if(isInArray('budget',dfMust)){
                                    if (!budget) {
                                        layer.alert('预算不能为空');
                                        layer.close(shade);
                                        return false;
                                    }
                                }
                                // 婚期
                                var marry_day = cus.find("#df_marry_day").val();
                                if (marry_day == 'undefined' || marry_day == '' || marry_day == null) {
                                    marry_day = '';
                                }
                                if(isInArray('marry_day',dfMust)){
                                    if (!marry_day) {
                                        layer.alert("婚期不能为空");
                                        layer.close(shade);
                                        return false;
                                    }
                                }
                                // 短信模板
                                //var model_id = cus.find("#sms_model_id").val();
                                // 短信发送标记
                                var receiver_flag = cus.find("#receiver_flag").val();
                                data.sign_id = sign_id;
                                data.sign_name = sign_name;
                                data.customer_cource_id = customer_cource_id;
                                data.customer_cource = customer_cource;
                                data.is_valid = is_valid;
                                data.consulation_shop_code = consulation_shop_code;
                                data.consulation_shop = consulation_shop;
                                data.yjd_day = yjd_day;
                                data.reception_id = reception_id;
                                data.reception_name = reception_name;
                                data.budget    = budget;
                                data.marry_day = marry_day;
                                data.next_time = next_time;
                                data.noTrack = noTrack;
                                data.receiver_flag = receiver_flag;
                            }else if(noTrack == 4){
                                // 客资状态是否有效
                                var is_valid = cus.find('#df_is_valid').val();
                                if(isInArray('is_valid',dfMust)){
                                    if (!is_valid) {
                                        layer.alert("客资状态不能为空");
                                        layer.close(shade);
                                        return false;
                                    }
                                }
                                if (is_valid==3) {
                                    unvalid_id = cus.find('#df_unvalid_reason').val();
                                    unvalid_reason = cus.find('#df_unvalid_reason option:selected').html();
                                }else{
                                    unvalid_id = '';
                                    unvalid_reason = '';
                                }
                                // 不在追踪原因
                                var reason_id = cus.find('#reason option:selected').val();

                                if (reason_id == 'undefined' || reason_id == '' || reason_id == null) {
                                    layer.alert('请选择不追原因');
                                    layer.close(shade);
                                    return false;
                                }else{
                                    var reason = cus.find('#reason option:selected').html();
                                }
                                data.is_valid  = is_valid;
                                data.unvalid_id = unvalid_id;
                                data.unvalid_reason = unvalid_reason;
                                data.reason = reason;
                                data.noTrack= noTrack;
                            }
                            
                            $.ajax({
                                type:"POST",
                                url: "/crm/Customer/editSalesTracking",
                                data: data,
                                success: function (ret) {
                                    if (ret.code == 200) {
                                        layer.alert(ret.msg);
                                        layer.close(shade);
                                        layer.close(dianfang);
                                        reloadRow(id);
                                    } else {
                                        layer.alert(ret.msg);
                                        layer.close(shade);
                                        return false;
                                    }
                                },
                                error: function (XMLHttpRequest, textStatus, errorThrown) {
                                    var ret = XMLHttpRequest.responseJSON
                                    layer.alert('操作有误');
                                    layer.close(shade);
                                    return false;
                                }
                            });
                            //最后关闭弹出层
                            // layer.closeAll();
                        }
                    })
                },10);
            },*/
            // 新客资来电提醒
            newCus: function () {
                setTimeout(function(){
                    /*layui.use('upload', function () {
                     var upload = layui.upload;
                     var id=$('#append').val();
                     upload.render({
                     elem: '.test6'
                     ,url: 'upload_photo'
                     ,accept: 'audio' //音频
                     ,field:'file'
                     ,data:{id:id}
                     ,done: function(res){
                     if(res.state==1){
                     layer.alert(res.msg);
                     layui.form.render();
                     }else{
                     layer.alert(res.msg);
                     }},
                     error:function(){
                     layer.alert("录音上传失败，请重试。");
                     }
                     });
                     });*/
                    layer.open({
                        title: '新客资来电提醒',
                        type: 1,
                        skin: 'layui-layer-rim',
                        area: ['550px', '450px'],
                        content: $('#new-customer'),
                        btn: ['关闭'],
                        yes:function(index){
                            layer.close(index);
                            /*var dianfang_end = $('#dianfang_end').html();
                             if(dianfang_end == ''){
                             layer.alert('请挂断后再保存');
                             return false;
                             }*/
                            /*var customer_name = $('#new-customer input[name=customer_name]').val();
                             var consultation_type =  $("#new-customer #new_consultation_type option:selected").html();
                             var sex =  $("#new-customer #new_sex option:selected").val();
                             var customer_region =  $("#new-customer #new_customer_region option:selected").html();
                             var op_signinfo =  $("#new-customer #new_op_signinfo option:selected").html();
                             var customer_cource =  $("#new-customer #new_customer_cource option:selected").html();
                             var customer_channel =  $("#new-customer #new_customer_channel option:selected").html();
                             var access_model =  $("#new-customer #new_access_model option:selected").html();
                             var customer_tel =  $('#tel').html();
                             var tel_alltime = $('#new-customer_alltime').html();
                             var sales_remark = $('#remark').val();
                             var tel_alltime = $('#new-customer_alltime').html();

                             if(tel_alltime != ''){
                             tel_alltime = tel_alltime;
                             }else{
                             tel_alltime = null;
                             }

                             var data = "customer_id="+id+"&customer_name="+customer_name+"&consultation_type="+consultation_type+"&tel_alltime="+tel_alltime+"&customer_remark="+sales_remark+"&customer_sex="+sex+"&customer_region="+customer_region+"&op_signinfo="+op_signinfo+"&customer_cource="+customer_cource+"&customer_channel="+customer_channel+"&access_model="+access_model+"&customer_tel="+customer_tel;
                             //alert(data);return false;
                             $.ajax({
                             type: "POST",
                             url: 'addNewCusCall',
                             data: data,
                             success: function(msg){
                             if(msg){
                             parent.location.reload();
                             }else{
                             layer.msg(msg.msg);
                             }
                             }
                             });
                             },
                             cancel:function(){
                             var dianfang_end = $('#dianfang_end').html();
                             if(dianfang_end == ''){
                             layer.alert('请挂断后再关闭');
                             return false;
                             }*/
                        }
                    });
                },10);
            },
            // 老客资来电提醒
            oldCus: function () {
                setTimeout(function(){
                    //var id=jQuery("#Example").jqGrid('getGridParam', 'selarrrow');
                    //if(id == '' || id == null){
                    //    layer.alert('请选中某行再操作');
                    //    return false;
                    //}
                    var tel = $('#in_tel').val();
                    var param = "customer_tel="+tel;
                    $.ajax({
                        type: "POST",
                        url: '/crm/Customer/getCustomerByTel',
                        data: param,
                        success: function(ret) {
                            if (ret.code == 200) {
                                var msg = ret.data;
                                $("#old-customer #customer_number").html(msg['customer_number']);
                                if (msg['customer_type'] == 1) {
                                    $("#old-customer #customer_leixing").html('新单');
                                } else if (msg['customer_type'] == 12) {
                                    $("#old-customer #customer_leixing").html('转介绍');
                                }
                                if(msg['customer_tel']){
                                    $("#old_tel_info").html(msg.telInfo.tel_belong);
                                }else{
                                    $("#old_tel_info").html('');
                                }
                                $("#customer_id").val(msg.id);
                                $('#old-customer #old_customer_name').val(msg['customer_name'])
                                $('#old-customer input[name=mate_tel]').val(msg['mate_tel'])
                                $('#old-customer #telphone').html(msg['customer_tel'])
                                $('#old-customer input[name=customer_tel]').val(msg['customer_tel'])
                                $('#old-customer input[name=kehu_tel]').val(msg['customer_tel'])
                                $('#old-customer #customer_from').html(msg['customer_cource'])
                                $('#old-customer #jiedandian').html(msg['customer_orderaddress'])
                                $('#old-customer #xiaofeileixing').html(msg['consultation_type'])
                                $('#old-customer #fenqu').html(msg['customer_area'])
                                $('#old-customer #yaoyueren').html(msg['introducer_name'])
                                $('#old-customer #flag').html(msg['op_signinfo'])
                                $('#old-customer #qd').html(msg['customer_channel'])
                                layui.form.render(); //更新全部
                            } else {
                                parent.layer.msg(msg.msg, {
                                    icon: 5,
                                    shade: [0.6, '#393D49'],
                                    time: 1500
                                });
                            }
                        }
                    });
                    layer.open({
                        title: '老客资来电提醒',
                        type: 1,
                        skin: 'layui-layer-rim',
                        area: ['500px', '500px'],
                        content: $('#old-customer'),
                        btn:'关闭',
                        yes:function(index){
                            layer.close(index);
                            /*var dianfang_end = $('#dianfang_end').html();
                             if(dianfang_end == ''){
                             layer.alert('请挂断后再保存');
                             return false;
                             }*/
                            /* var customer_name = $('#old_customer_name').val();
                             var consultation_type =  $("#xiaofeileixing").html();
                             var customer_area =  $("#fenqu").html();
                             var introducer_name =  $("#yaoyueren").html();
                             var op_signinfo =  $("#flag").html();
                             var customer_channel =  $("#qd").html();
                             var customer_cource =  $("#customer_from").html();
                             var customer_tel =  $('#telphone').html();
                             var customer_orderaddress = $('#jiedandian').html();
                             var tel_alltime = $('#old-customer_alltime').html();
                             if(tel_alltime != ''){
                             tel_alltime = tel_alltime;
                             }else{
                             tel_alltime = null;
                             }
                             var data = "customer_id="+id+"&customer_name="+customer_name+"&consultation_type="+consultation_type+"&tel_alltime="+tel_alltime+"&customer_area="+customer_area+"&op_signinfo="+op_signinfo+"&customer_cource="+customer_cource+"&customer_channel="+customer_channel+"&introducer_name="+introducer_name+"&customer_tel="+customer_tel+"&customer_orderaddress="+customer_orderaddress;
                             //alert(data);return false;
                             $.ajax({
                             type: "POST",
                             url: 'addOldCusCall',
                             data: data,
                             success: function(msg){
                             if(msg){
                             parent.location.reload();
                             }else{
                             parent.layer.msg(msg.msg, {
                             icon: 5,
                             shade: [0.6, '#393D49'],
                             time:1500
                             });
                             }
                             }
                             });*/
                        },
                        cancel:function(){
                            /*var dianfang_end = $('#dianfang_end').html();
                             if(dianfang_end == ''){
                             layer.alert('请挂断后再关闭');
                             return false;
                             }*/
                        }
                    });
                },10);
            },
            // 追踪记录
            cusMsg: function () {
                setTimeout(function(){
                    var id=jQuery("#Example").jqGrid('getGridParam', 'selarrrow');
                    if(id == 'undefined' || id == null){
                        layer.alert('请选中某行再操作');
                        return false;
                    }
                    if(id.length > 1){
                        layer.alert('请选中一个时查看');
                        return false;
                    }
                    $('#customer-sms').parent().attr('overflow','auto');
                    /*var data = "id="+id;
                     $('#log').empty();
                     $('#history_order').empty();
                     $.ajax({
                     type: "POST",
                     url: 'call_log',
                     data: data,
                     success: function(msg){
                     if(msg){
                     for(var i=0;i<msg['track'].length;i++){
                     var time = msg['track'][i]['sales_day'].split(' ');
                     var inp = '<li class="layui-timeline-item"><div class="layui-timeline-date">'+time[0]+'&nbsp;</div><i class="layui-icon layui-timeline-axis">&#xe63f;</i><div class="layui-timeline-content layui-text"><div>时      间：'+time[1]+'</div><div>沟通人员：'+msg['track'][i]["sales_staff"]+'</div><div>拨打电话：'+msg['track'][i]["customer_tel"]+'</div><div>通话时长：'+msg['track'][i]["tel_alltime"]+'</div><div>咨询类型：'+msg['track'][i]["consultation_type"]+'</div><div>客户意向：'+msg['track'][i]["customer_intention"]+'</div><div>备注信息：'+msg['track'][i]["sales_remark"]+'</div></div></li>'
                     $('#log').append(inp);
                     }
                     for(var i=0;i<msg['order'].length;i++){
                     var inp = '<tr><td>'+msg["order"][i]["order_sn"]+'</td><td>'+msg["order"][i]["create_time"]+'</td><td>'+msg["order"][i]["consultation_type"]+'</td><td>'+msg["order"][i]["order_amount"]+'</td><td>'+msg["order"][i]["shop_name"]+'</td><td>'+msg["order"][i]["customer_orderaddress"]+'</td> </tr>'
                     $('#history_order').append(inp);
                     }
                     //parent.location.reload();
                     }else{
                     parent.layer.msg(msg.msg, {
                     icon: 5,
                     shade: [0.6, '#393D49'],
                     time:1500
                     });
                     }
                     }
                     });*/
                    var id = $('#Example').jqGrid('getGridParam','selarrrow');
                    layer.open({
                        offset: 'rb',
                        title: '追踪记录',
                        type: 2,
                        skin: 'layui-layer-rim',
                        area: ['700px', '430px'],
                        //content: $('#customer-sms')
                        content: '/crm/Customer/trackLog/id/'+id
                    });
                },10);
            },
            // 客资驳回
            is_valid: function () {
                var id = $('#Example').jqGrid('getGridParam','selarrrow');
                // var myrow = $('#Example').jqGrid('getRowData',$('#Example').jqGrid('getGridParam','selarrrow'));
                // if(staff_name != myrow.sales_staff){
                //     layer.alert('您不是此客资的追踪人，不能驳回');
                //     return false;
                // }
                setTimeout(function(){
                    load_page(
                        '/crm/Customer/customerValid?cid='+id,
                        '客资驳回',
                        function(){
                            seveValid(id,function(){reloadRow(id)});
                        },
                        ['确定','取消'],
                        740,500
                        ,function(){
                            delValid(id);
                        }
                        ,function(){
                            delValid(id);
                        }
                    );
                },10);
            },
            // 客资反驳回 20200616
            is_unvalid: function (cus) {
                var id = $('#Example').jqGrid('getGridParam','selarrrow');
                var myrow = $('#Example').jqGrid('getRowData',$('#Example').jqGrid('getGridParam','selarrrow'));
                if(myrow.is_valid == '驳回'){
                    layer.open({
                        title: '反驳回',
                        type: 2,
                        skin: 'layui-layer-rim',
                        area: ['570px', '370px'],
                        //content: $('#add-box'),
                        content: "/crm/customer/customerUnValid?cid="+id,
                        btn: ['提交', '取消'],
                        yes: function (iframeDom,index) {
                            var shade = layer.load(1, {shade: 0.3});
                            /*
                            // 获取 iframe
                            var iframeWin = window[$(index).find('iframe')[0]['name']];
                            // 通过 getupContentFbh 方法 重新赋值 
                            var cus = $(".layui-layer-content iframe").contents().children();
                            cus.find("#customerFbh").find("#fbhReason").text(iframeWin.getupContentFbh());

                            var unvalid = cus.find("#customerFbh").serialize();
                            // 客资状态
                            //var is_valid_fbh_id = cus.find('#is_valid_fbh').val();
                            // console.log(is_valid_fbh_id);
                            var is_valid_fbh = '';
                            //if(is_valid_fbh_id == 'undefined' || is_valid_fbh_id == '' || is_valid_fbh_id == null){
                            //    layer.alert('请选择客资状态');
                            //    layer.close(shade);
                            //    return false;
                            //}
                            
                            // 反驳回原因
                            var fbhReason = cus.find('#fbhReason').val();
                            if(fbhReason == 'undefined' || fbhReason == '' || fbhReason == null){
                                layer.alert('请填写反驳回理由');
                                layer.close(shade);
                                return false;
                            }
                            */
                            var cus = $(".layui-layer-content iframe").contents().children();
                            var fbhReason = cus.find("#customerFbh").serialize();
                            var data = fbhReason+"&cid="+id+"&is_valid_fbh=5";
                            $.ajax({
                                type:"POST",
                                url: "/crm/Customer/customerUnValidUpdate",
                                data: data,
                                success: function (ret) {
                                    if (ret) {
                                        layer.alert(ret.msg);
                                        reloadRow(id)
                                    } else {
                                        layer.alert('操作失败');
                                        layer.close(shade);
                                        return false;
                                    }
                                },
                                error: function (XMLHttpRequest, textStatus, errorThrown) {
                                    var ret = XMLHttpRequest.responseJSON
                                    layer.alert('操作有误');
                                    layer.close(shade);
                                    return false;
                                }
                            });
                            //最后关闭弹出层
                            layer.closeAll();
                        }
                    })
                }else{
                    layer.alert('不是被驳回客资，不能反驳回');
                    layer.close(shade);
                    return false;
                }
            },
            // is_unvalid: function () {
            //     var id = $('#Example').jqGrid('getGridParam','selarrrow');
            //     var myrow = $('#Example').jqGrid('getRowData',$('#Example').jqGrid('getGridParam','selarrrow'));
            //     if(myrow.is_valid == '驳回给电商'){
            //         load_page(
            //             '/crm/Customer/customerUnValid?cid='+id,
            //             '客资反驳回给网销',
            //             function(){
            //                 seveUnValid(function(){reloadRow(id)});
            //             },
            //             ['确定','取消'],
            //             570,370
            //             ,function(){
            //                 delValid(id);
            //             }
            //             ,function(){
            //                 delValid(id);
            //             }
            //         );
            //     }else{
            //         layer.alert('不是被驳回客资，不能反驳回');
            //         return false;
            //     }
            // },
            // 撤销
            revoke: function () {
                var id = $('#Example').jqGrid('getGridParam','selarrrow');
                setTimeout(function() {
                    layer.confirm('确定此客资撤销吗？',{}, function(index){
                        $.ajax({
                            type: "POST",
                            url: '/crm/Customer/customerRevoke',
                            data: "id=" + id,
                            success: function (msg) {
                                if (msg.code == 200) {
                                    layer.alert(msg.msg);
                                    reloadGrid();
                                } else {
                                    layer.alert(msg.msg);
                                }
                            },
                            error: function () {
                                layer.alert('操作有误');
                            }
                        });
                    });
                }, 10);
            },
            // 一键标记有效
            sign_valid: function () {
                var id = $('#Example').jqGrid('getGridParam','selarrrow');
                // var myrow = $('#Example').jqGrid('getRowData',$('#Example').jqGrid('getGridParam','selarrrow'));
                // if(myrow.is_valid == '是'){
                //     layer.alert('已经是有效客资，不能再标记有效');
                //     return false;
                // }
                setTimeout(function() {
                    layer.confirm('确定把此客资标记为有效吗？',{}, function(index){
                        $.ajax({
                            type: "POST",
                            url: '/crm/Customer/signValid',
                            data: "id=" + id,
                            success: function (msg) {
                                if (msg.code == 200) {
                                    layer.alert(msg.msg);
                                    $("#Example").jqGrid('setRowData',id,{'is_valid':'有效'});
                                    //reloadGrid();
                                } else {
                                    layer.alert(msg.msg);
                                }
                            },
                            error: function () {
                                layer.alert('操作有误');
                            }
                        });
                    });
                }, 10);
            },
            // 一键标记无效
            sign_unvalid: function () {
                var id = $('#Example').jqGrid('getGridParam','selarrrow');
               setTimeout(function(){
                    if(id == '' || id == null){
                        layer.alert('请选中某行再操作');
                        return false;
                    }
                    if(id.length > 1){
                        layer.alert('请选中一个时再操作');
                        return false;
                    }
                    layer.open({
                        title: '标记无效',
                        type: 1,
                        skin: 'layui-layer-rim',
                        area: ['400px', '180px'],
                        content: $('#unValidReason'),
                        btn: ['保存'],
                        yes:function(index){
                            var unvalid_id = $("#unValidReason #unvalid_id").val();
                            var unvalid = $("#unValidReason #unvalid_id option:selected").html();
                            if(unvalid == '请选择'){
                                unvalid = '';
                            }
                            if(!unvalid_id|| unvalid_id == undefined || unvalid_id == '' || unvalid_id == null){
                                layer.alert('请选择无效原因!');
                                return false;
                            }
                            var data = "id="+id+"&unvalid_id="+unvalid_id+"&unvalid_reason="+unvalid;
                            //alert(data);return false;
                            $.ajax({
                                type: "POST",
                                url: 'signUnvalid',
                                data: data,
                                success: function(msg){
                                    if( msg.code == 200 ){
                                        layer.alert(msg.msg);
                                        $("#Example").jqGrid('setRowData',id,{'is_valid':'无效'});
                                        //reloadGrid();
                                        return false;
                                    }else{
                                        layer.alert(msg.msg);
                                    }
                                },
                                error:function(){
                                    layer.alert('操作有误');
                                }
                            });
                            layer.close(index);
                        }
                    });
                },10);
            },
            // 批量标记待定
            customerMoreDd: function () {
                var selr = jQuery('#Example').jqGrid('getGridParam','selarrrow');
                if(selr == '' || selr == null){
                    layer.alert('请选中某行再操作');
                    return false;
                }

                setTimeout(function() {
                    layer.confirm('确定批量把客资标记为待定吗？',{}, function(index){
                        $.ajax({
                            type: "POST",
                            url: '/crm/Customer/customerMoreDd',
                            data: "id=" + selr,
                            success: function (msg) {
                                if (msg.code == 200) {
                                    layer.alert(msg.msg);
                                    reloadGrid();
                                } else {
                                    layer.alert(msg.msg);
                                }
                            },
                            error: function () {
                                layer.alert('操作有误');
                            }
                        });
                    });
                }, 10);
            },
            // 批量标记有效
            customerMoreValid: function () {
                var selr = jQuery('#Example').jqGrid('getGridParam','selarrrow');
                if(selr == '' || selr == null){
                    layer.alert('请选中某行再操作');
                    return false;
                }

                setTimeout(function() {
                    layer.confirm('确定批量把客资标记为有效吗？',{}, function(index){
                        $.ajax({
                            type: "POST",
                            url: '/crm/Customer/customerMoreValid',
                            data: "id=" + selr,
                            success: function (msg) {
                                if (msg.code == 200) {
                                    layer.alert(msg.msg);
                                    reloadGrid();
                                } else {
                                    layer.alert(msg.msg);
                                }
                            },
                            error: function () {
                                layer.alert('操作有误');
                            }
                        });
                    });
                }, 10);
            },
            // 批量标记无效
            customerMoreUnValid: function () {
                var selr = jQuery('#Example').jqGrid('getGridParam','selarrrow');
                if(selr == '' || selr == null){
                    layer.alert('请选中某行再操作');
                    return false;
                }

                setTimeout(function() {
                    layer.open({
                        title: '批量标记无效',
                        type: 1,
                        skin: 'layui-layer-rim',
                        area: ['400px', '180px'],
                        content: $('#unValidReason'),
                        btn: ['保存'],
                        yes:function(index){
                            var unvalid_id = $("#unValidReason #unvalid_id").val();
                            var unvalid = $("#unValidReason #unvalid_id option:selected").html();
                            if(unvalid == '请选择'){
                                unvalid = '';
                            }
                            if(!unvalid_id|| unvalid_id == undefined || unvalid_id == '' || unvalid_id == null){
                                layer.alert('请选择无效原因!');
                                return false;
                            }
                            var data = "id="+selr+"&unvalid_id="+unvalid_id+"&unvalid_reason="+unvalid;
                            //alert(data);return false;
                            $.ajax({
                                type: "POST",
                                url: 'customerMoreUnValid',
                                data: data,
                                success: function(msg){
                                    if( msg.code == 200 ){
                                        layer.alert(msg.msg);
                                        reloadGrid();
                                        return false;
                                    }else{
                                        layer.alert(msg.msg);
                                    }
                                },
                                error:function(){
                                    layer.alert('操作有误');
                                }
                            });
                            layer.close(index);
                        }
                    });
                }, 10);
            },
            // 奖金标记
            bonus: function () {
                var selr = jQuery('#Example').jqGrid('getGridParam','selarrrow');
                if(selr == '' || selr == null){
                    layer.alert('请选中某行再操作');
                    return false;
                }

                setTimeout(function() {
                    layer.open({
                        title: 'A客奖金',
                        type: 1,
                        skin: 'layui-layer-rim',
                        area: ['400px', '180px'],
                        content: $('#bonus-box'),
                        btn: ['保存'],
                        yes:function(index){
                            var bonus = $("#bonus-box #bonus").val();

                            if(!bonus|| bonus == undefined || bonus == '' || bonus == null){
                                layer.alert('请选择A客奖金!');
                                return false;
                            }
                            var data = "id="+selr+"&bonus="+bonus;
                            //alert(data);return false;
                            $.ajax({
                                type: "POST",
                                url: 'customerBonus',
                                data: data,
                                success: function(msg){
                                    if( msg.code == 200 ){
                                        layer.alert(msg.msg);
                                        reloadGrid();
                                        return false;
                                    }else{
                                        layer.alert(msg.msg);
                                    }
                                },
                                error:function(){
                                    layer.alert('操作有误');
                                }
                            });
                            layer.close(index);
                        }
                    });
                }, 10);
            },
            // 成交奖金
            bonus_deal: function () {
                var selr = jQuery('#Example').jqGrid('getGridParam','selarrrow');
                if(selr == '' || selr == null){
                    layer.alert('请选中某行再操作');
                    return false;
                }

                setTimeout(function() {
                    layer.open({
                        title: '成交奖金',
                        type: 1,
                        skin: 'layui-layer-rim',
                        area: ['400px', '180px'],
                        content: $('#bonus_deal-box'),
                        btn: ['保存'],
                        yes:function(index){
                            var bonus_deal = $("#bonus_deal-box #bonus_deal").val();

                            if(!bonus_deal|| bonus_deal == undefined || bonus_deal == '' || bonus_deal == null){
                                layer.alert('请选择成交奖金!');
                                return false;
                            }
                            var data = "id="+selr+"&bonus_deal="+bonus_deal;
                            //alert(data);return false;
                            $.ajax({
                                type: "POST",
                                url: 'customerBonusDeal',
                                data: data,
                                success: function(msg){
                                    if( msg.code == 200 ){
                                        layer.alert(msg.msg);
                                        reloadGrid();
                                        return false;
                                    }else{
                                        layer.alert(msg.msg);
                                    }
                                },
                                error:function(){
                                    layer.alert('操作有误');
                                }
                            });
                            layer.close(index);
                        }
                    });
                }, 10);
            },
            // 客资交接
            // move: function () {
            //     var id = $('#Example').jqGrid('getGridParam', 'selarrrow');
            //     setTimeout(function () {
            //         if (id == '' || id == null) {
            //             layer.alert('请选中某行再操作');
            //             return false;
            //         }
            //         layer.open({
            //             title: '客资交接',
            //             type: 1,
            //             skin: 'layui-layer-rim',
            //             area: ['400px', '230px'],
            //             content: $('#cus_move'),
            //             btn: ['保存'],
            //             yes: function (index) {
            //                 var staff_id = $("#cus_move #staff_id").val();
            //                 var staff_name = $("#cus_move #staff_id option:selected").html();
            //                 var move = $("input[name=move]:checked").val();
            //                 if (move == '' || move == undefined||move == null || move == 'undefined') {
            //                     layer.alert('请选择交接方式');
            //                     return false;
            //                 }
            //                 if (staff_id == '' || staff_id == undefined||staff_id == null || staff_id == 'undefined') {
            //                     layer.alert('请选择要交接给谁');
            //                     return false;
            //                 }
            //                 var data = "id="+id+"&staff_id=" + staff_id + "&staff_name=" + staff_name + "&move=" + move;
            //                 //alert(data);return false;
            //                 $.ajax({
            //                     type: "POST",
            //                     url: 'customerMove',
            //                     data: data,
            //                     success: function (msg) {
            //                         if (msg.code == 200) {
            //                             layer.alert(msg.msg);
            //                             reloadGrid();
            //                             return false;
            //                         } else {
            //                             layer.alert(msg.msg);
            //                         }
            //                     },
            //                     error: function () {
            //                         layer.alert('操作有误');
            //                     }
            //                 });
            //                 layer.close(index);
            //             }
            //         });
            //     }, 10);
            // },
            // 客资转移
            change: function () {
                var id = $('#Example').jqGrid('getGridParam', 'selarrrow');
                setTimeout(function () {
                    if (id == '' || id == null) {
                        layer.alert('请选中某行再操作');
                        return false;
                    }
                    load_page(
                        '/crm/Customer/customerChange',
                        '客资转移',
                        function(){
                            cusChange(id,function(){reloadRow(id)});
                        },
                        ['确定','取消'],
                        350,250
                        ,function(){
                        }
                        ,function(){
                        }
                    );
                }, 10);
            },
            //不再追踪
            not_traking:function () {
                setTimeout(function(){
                    var id=jQuery("#Example").jqGrid('getGridParam', 'selarrrow');
                    if(id == '' || id == null){
                        layer.alert('请选中某行再操作');
                        return false;
                    }
                    if(id.length > 1){
                        layer.alert('请只选中一个时再操作');
                        return false;
                    }
                    $('#loss_cause_two').val('');

                    layer.open({
                        title: '不再追踪',
                        type: 1,
                        skin: 'layui-layer-rim',
                        area: ['500px', '220px'],
                        content: $('#cus_loss_cause'),
                        btn: ['保存'],
                        yes:function(index){
                            var loss_cause=$('#loss_cause_two').val();
                            var data = "id="+id+"&loss_cause="+loss_cause;
                            $.ajax({
                                type: "POST",
                                url: '/crm/Customer/notTraking',
                                data: data,
                                success: function(msg){
                                    if( msg.code == 200 ){
                                        layer.alert(msg.msg);
                                        //reloadGrid();
                                        $("#Example").jqGrid('setRowData',id,{'is_loss':'是'});
                                        return false;
                                    }else{
                                        layer.alert(msg.msg);
                                    }
                                },
                                error:function(){
                                    layer.alert('操作有误');
                                }
                            });
                            layer.close(index);
                        }
                    });
                },10);
            }
        };

        //excel
        layui.use('upload', function () {
            var upload = layui.upload;
            upload.render({
                elem: '#import'
                , url: 'uploadExcel'
                , accept: 'file' //普通文件
                , exts: 'xlsx' //只允许excel文件
                , done: function (res) {
                    if (res.code == 1) {
                        layer.close();
                    } else {
                        layer.alert(res.msg)
                    }
                }
            });
            /*upload.render({
             elem: '.test6'
             ,url: 'upload_photo'
             ,accept: 'audio' //音频
             ,field:'file'
             //,data:{id:$('#append').val()}
             ,before: function(res){
             var id = $('#append').val();
             var append_type = $('#append_type').val();
             this.data={id:id,append_type:append_type}
             }
             ,done: function(res){
             if(res.state==1){
             layer.alert(res.msg);
             layui.form.render();
             }else{
             layer.alert(res.msg);
             }},
             error:function(){
             layer.alert("录音上传失败，请重试。");
             }
             });*/
        });
        $('.cus-model-btn').on('click', function () {
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
            $(this).addClass("active").siblings(".cus-model-btn").removeClass("active");
            if (type == "allot") {
                $("#allot-box").parent().css("overflow", "inherit");
            }
        });
        //鼠标双击事件
        $('.ui-jqgrid-btable').delegate("tr", "dblclick", function () {
            active["interview"] ? active["interview"].call(this) : '';
        });
        $("#Example").delegate("tr","contextmenu",function(e){
            e.preventDefault();
            jQuery("#Example").jqGrid('resetSelection');
            var q=$(this).attr("id");
            jQuery("#Example").jqGrid('setSelection',q);

        });
        /*
            定义所有菜单，按顺序，
            {
                menu_id:'common',//如果不需要控制权限的菜单，menu_id都写common,否则写上menu里的code
                label: '筛客',
                icon: function(){
                                return 'fa fa-filter';
                            },
                action: function () {
                                active["sk_flag"] ? active["sk_flag"].call(this) : '';
                            }
            },
         */
        var all_menu = [
            {
                menu_id:'menu1519635403',
                label: '筛客', icon: function () {
                    return 'fa fa-filter';
                }, action: function () {
                    active["sk_flag"] ? active["sk_flag"].call(this) : '';
                }
            },
            {
                menu_id:'menu1512971662',
                label: '追踪', icon: function () {
                    return 'fa fa-paper-plane';
                }, action: function () {
                    active["interview"] ? active["interview"].call(this) : '';
                }
            },
            {
                menu_id:'menu1546854995',
                label: '标记有效', icon: function () {
                    return 'fa fa-check-circle';
                }, action: function () {
                    active["sign_valid"] ? active["sign_valid"].call(this) : '';
                }
            },
            {
                menu_id:'menu1517129331',
                label: '标记无效', icon: function () {
                    return 'fa fa-times-circle';
                }, action: function () {
                    active["sign_unvalid"] ? active["sign_unvalid"].call(this) : '';
                }
            },
            {
                menu_id:'menu1519632099',
                label: '追踪标记', icon: function () {
                    return 'fa fa-tags';
                }, action: function () {
                    active["flag"] ? active["flag"].call(this) : '';
                }
            },
            {
                menu_id:'menu1512971583',
                label: '追踪记录', icon: function () {
                    return 'fa fa-navicon';
                }, action: function () {
                    active["cusMsg"] ? active["cusMsg"].call(this) : '';
                }
            },
            /*   {
                            menu_id:'common',
                            label: '驳回给电商', icon: function () {
                            return 'fa fa-user-times';
                        }, action: function () {
                            active["is_valid"] ? active["is_valid"].call(this) : '';
                        }
                        },*/
            {
                menu_id:'menu1517278844',
                label: '反驳回', icon: function () {
                    return 'fa fa-user-plus';
                }, action: function () {
                    active["is_unvalid"] ? active["is_unvalid"].call(this) : '';
                }
            },
            {
                menu_id:'menu1512971646',
                label: '发送短信', icon: function () {
                    return 'fa fa-envelope';
                }, action: function () {
                    active["msgsend"] ? active["msgsend"].call(this) : '';
                }
            },
            {
                menu_id:'menu1584353494',
                label: '发送站内信', icon: function () {
                    return 'fa fa-envelope';
                }, action: function () {
                    active["sendMsgToStaff"] ? active["sendMsgToStaff"].call(this) : '';
                }
            },
            {
                menu_id:'menu1512970623',
                label: '客资分配', icon: function () {
                    return 'fa fa-random';
                }, action: function () {
                    active["allot"] ? active["allot"].call(this) : '';
                }
            },
            {
                menu_id:'menu1519633870',
                label: '预约进店', icon: function () {
                    return 'fa fa-calendar-check-o';
                }, action: function () {
                    active["yyjd"] ? active["yyjd"].call(this) : '';
                }
            },
            {
                menu_id:'menu1522653972',
                label: '修改介绍人', icon: function () {
                    return 'fa fa-address-book-o';
                }, action: function () {
                    active["introducer"] ? active["introducer"].call(this) : '';
                }
            },
            {
                menu_id:'menu1519633959',
                 label: '订单编辑', icon: function () {
                     return 'fa fa-plus';
                 }, action: function () {
                     active["order_edit"] ? active["order_edit"].call(this) : '';
                 }
            },
            {
                menu_id:'menu1519633923',
                label: Lang_orderFunctionName, icon: function () {
                // label: '{:lang("网付订单")}', icon: function () {
                    return 'fa fa-plus';
                }, action: function () {
                    active["order_manager"] ? active["order_manager"].call(this) : '';
                }
            },
            {
                menu_id:'menu1572077805',
                label: '退单', icon: function () {
                    return 'fa fa-trash';
                }, action: function () {
                    active["del_order"] ? active["del_order"].call(this) : '';
                }
            },
            {
                menu_id:'menu1519633436',
                label: '不再追踪', icon: function () {
                    return 'fa fa-trash';
                }, action: function () {
                    active["not_traking"] ? active["not_traking"].call(this) : '';
                }
            },
            {
                menu_id:'menu1520675106',
                label: '撤销', icon: function () {
                    return 'fa fa-plus';
                }, action: function () {
                    active["revoke"] ? active["revoke"].call(this) : '';
                }
            },
            {
                menu_id:'menu1512970667',
                label: '修改', icon: function () {
                    return 'fa fa-pencil';
                }, action: function () {
                    active["detail"] ? active["detail"].call(this) : '';
                }
            },
            {
                menu_id:'menu1512970570',
                label: '删除', icon: function () {
                    return 'fa fa-trash';
                }, action: function () {
                    active["delete"] ? active["delete"].call(this) : '';
                }
            },
            ];
        //    鼠标右击事件
        $('.ui-jqgrid-btable').contextPopup({
            //title: 'My Popup Menu',
            arrFun: function () {
                contextArr = [];
                var this_menu =[];
                if(tab == 8){
                    this_menu = ['筛客','追踪','标记有效','标记无效','追踪标记','追踪记录'];
                }else if(tab == 9){
                    this_menu = ['标记有效','标记无效','反驳回','追踪记录'];
                }else if(tab == 2 || tab == 4 || tab == 10 || tab == 11 || tab == 12 ){
                    this_menu = ['追踪','标记无效','标记有效','反驳回','追踪记录','追踪标记','发送短信','发送站内信','预约进店','修改介绍人',Lang_orderFunctionName,'不再追踪'];
                }
                else if(tab == 5 || tab == 6 ){
                    if(!ERP){
                        this_menu = ['订单编辑',Lang_orderFunctionName,'退单','追踪','追踪记录'];
                    }else{
                        this_menu = ['订单编辑',Lang_orderFunctionName,'追踪','追踪记录'];
                    }
                }else if(tab==7){
                    this_menu = ['追踪记录','追踪标记','撤销'];
                }else if(tab == 3){
                    this_menu = ['客资分配','追踪记录'];
                }else{
                    this_menu = ['追踪','标记有效','标记无效','客资标记','追踪标记','追踪记录','反驳回','客资分配','发送短信','发送站内信','预约进店','修改介绍人',Lang_orderFunctionName,'修改','删除','不再追踪'];
                }
                for (let i in all_menu) {
                    if($.inArray(all_menu[i].menu_id,R_menu_all) >= 0 && $.inArray(all_menu[i].label,this_menu) >= 0){
                        contextArr.push(all_menu[i]);
                    }
                }
                return contextArr;
            }
        });

    });

    function check_right(code){
        $.ajax({
            type: "POST",
            url: 'check_right',
            data: 'code='+code,
            success: function(msg){
                fp_auth= msg.data;
            }
        });
    }

    //省市县
    layui.use('form', function () {
        var form = layui.form;
        //事业部监听
        form.on('select(brandclass_id)', function(data){
            var brandclass_id = data.value;
            $.ajax({
                type:"POST",
                url: '/crm/Customer/getBelongShopInfo',
                data: "brandclass_id="+brandclass_id,
                success: function (msg) {
                    if(msg.length == 1){
                        var replace = '';
                    }else{
                        var replace = '<option value="">请选择</option>';
                    }
                    /*for(var i=0;i<msg.length;i++){
                        replace += '<option value="'+msg[i]['shop_code']+'">'+msg[i]['shop_name']+'</option>';
                    }*/
                    for(var key in msg){
                        replace += '<option value="'+msg[key]['shop_code']+'">'+msg[key]['shop_name']+'</option>';
                    }
                    $("#company_shop_code").html(replace);
                    form.render();
                }
            });
        });
        //提报店监听
        form.on('select(add_shop_code)', function(data){
            var shop_code = data.value;
            var shop_name = $('#add_shop_code option:selected').html();
            $.ajax({
                type:"POST",
                url: '/crm/Customer/getBelongShop',
                data: "shop_code="+shop_code+"&shop_name="+shop_name,
                success: function (msg) {
                    if(msg.length == 1){
                        var replace = '';
                    }else{
                        var replace = '<option value="">请选择</option>';
                    }
                    for(var i=0;i<msg.length;i++){
                        replace += '<option value="'+msg[i]['shop_code']+'">'+msg[i]['shop_name']+'</option>';
                    }
                    $("#shop_code").html(replace);
                    $("#company_shop_code").html(replace);
                    form.render();
                }
            });
        });
        //渠道录入监听
        form.on('select(dj_shop)', function (data) {
            //选择店时插入店下的部门
            var shop_code = data.value;
            if (shop_code.length > 0) {
                $.ajax({
                    type: "POST",
                    url: '/crm/Customer/getDepartmentList',
                    data: "shop_code="+shop_code,
                    success: function (msg) {
                        var inp = '<option value="">请选择</option>';
                        for (var i = 0; i < msg.length; i++) {
                            inp += '<option value="' + msg[i]['id'] + '">' + msg[i]['department_name'] + '</option>';
                        }
                        $("#dj_department_id").html(inp);
                        form.render();

                    }
                });
                $.ajax({
                    type: "POST",
                    url: '/crm/Customer/getShopStaffs',
                    data: "shop_code="+shop_code,
                    success: function (msg) {
                        var inp = '<option value="">请选择</option>';
                        for (var i = 0; i < msg.length; i++) {
                            inp += '<option value="' + msg[i]['id'] + '">' + msg[i]['staffname'] + '</option>';
                        }
                        $("#dj_staff_id").html(inp);
                        form.render();

                    }
                });
            }else{
                $("#dj_department_id").html('<option value="">请选择</option>');
                $("#dj_staff_id").html('<option value="">请选择</option>');
                form.render();
            }
        })
        //转介绍类型监听
        form.on('select(introducer)', function (data) {
            var zjs_from = data.value;
            if(zjs_from == 1){
                $('.introducer').css('display','inline-block');
            }else{
                $('.introducer').css('display','none');
            }
        })
        //监听部门
        form.on('select(dj_department_id)', function (data) {
            //选择店时插入店下的部门
            var department = data.value;
            var add_shop_code = $('#add_shop_code').val();
            $.ajax({
                type: "POST",
                url: '/crm/Customer/getDepartmentStaff',
                data: {id:department,shop_code:add_shop_code},
                // data: "id="+department,
                success: function (msg) {
                    var inp = '<option value="">请选择</option>';
                    for (var i = 0; i < msg.length; i++) {
                        inp += '<option value="' + msg[i]['id'] + '">' + msg[i]['staffname'] + '</option>';
                    }
                    $("#dj_staff_id").html(inp);
                    form.render();

                }
            });
        })
        //加载短信模板
        form.on('select(sms)',function(data){
            var sms = data.value;
            if(sms == 1){
                if($("#model").length==0){
                    var inp = '<div class="layui-inline" id="model"><label class="layui-form-label"><i class="input-sign"><img src="/img/cus-ufrom.png" alt=""></i>短信模板：</label><div class="layui-input-block"> <select name="sms_model" id="sms_model" class="cus-input"><option value="">请选择</option>';
                    $.ajax({
                        type: "POST",
                        url: '/crm/Customer/getSmsModel',
                        data: {},
                        success: function (msg) {
                            if(msg.code == 200){
                                var len = msg.data.length;
                                var data = msg.data;
                                for (var i=0;i<len;i++){
                                    inp += '<option value="'+data[i]["id"]+'">'+data[i]["mtemplate_name"]+'</option>';
                                }
                                inp += '</select></div></div>';
                                $('#send_sms').after(inp);
                                form.render('select');
                            }
                        }
                    })
                }
            }else{
                $('#model').remove();
            }
        })
        //客资列表页 上方条件 省
        form.on('select(staProvince)', function(data){
            var province_id = data.value;
            if (province_id > 0) {
                $.ajax({
                    type:"POST",
                    url: '/crm/Customer/searchCity',
                    data: "pid="+province_id+"&type=2",
                    success: function (msg) {
                        var replace = '<select name="staCity" id="staCity" lay-filter="staCity" lay-search=""><option value="">请选择</option>';
                        for(var i=0;i<msg.length;i++){
                            replace += '<option value="'+msg[i]['id']+'">'+msg[i]['name']+'</option>';
                        }
                        replace +='</select>';
                        $("#staCity").html(replace);
                        $("#staCounty").html('<option value="">请选择</option>');
                        form.render();
                    }
                });
            }else{
                $("#staCity").html('<option value="">请选择</option>');
                $("#staCounty").html('<option value="">请选择</option>');
                form.render();
            }
        });
        //客资列表页 上方条件 市
        form.on('select(staCity)', function (data) {
            var city = data.value;
            if(city > 0){
                $.ajax({
                    type: "POST",
                    url: 'searchCity',
                    data: "pid=" + city+"&type=3",
                    success: function (msg) {

                        var replace = '<option value="">请选择</option>';
                        for (var i = 0; i < msg.length; i++) {
                            replace += '<option value="' + msg[i]['id'] + '">' + msg[i]['name'] + '</option>';
                        }
                        $("#staCounty").html(replace);
                        form.render();
                    }
                });
            }else{
                var replace = '<option value="">请选择</option>';
                $("#staCounty").html(replace);
                form.render();
            }
        });
        form.on('select(province)', function (data) {
            var province = data.value;
            if(province){
                $.ajax({
                    type: "POST",
                    url: 'searchCity',
                    data: "pid=" + province+"&type=2",
                    success: function (msg) {
                        var replace = '<select name="city_id" id="city_id" lay-filter="city" class="cus-input"><option value="">请选择</option>';
                        for (var i = 0; i < msg.length; i++) {
                            replace += '<option value="' + msg[i]['id'] + '">' + msg[i]['name'] + '</option>';
                        }
                        replace += '</select>';
                        $(".city").html(replace);
                        var county = '<select name="county_id" id="county_id" lay-filter="county" class="cus-input"><option value="">请选择</option></select>';
                        $(".county").html(county);
                        form.render();
                    }
                });
            }else{
                var replace = '<select name="city_id" id="city_id" lay-filter="city" class="cus-input"><option value="">请选择</option></select>';
                $(".city").html(replace);
                var county = '<select name="county_id" id="county_id" lay-filter="county" class="cus-input"><option value="">请选择</option></select>';
                $(".county").html(county);
                form.render();
            }
        });
        form.on('select(city)', function (data) {
            var city = data.value;
            if(city){
                $.ajax({
                    type: "POST",
                    url: 'searchCity',
                    data: "pid=" + city+"&type=3",
                    success: function (msg) {

                        var replace = '<select name="county_id" id="county_id" lay-filter="county" class="cus-input"><option value="">请选择</option>';
                        for (var i = 0; i < msg.length; i++) {
                            replace += '<option value="' + msg[i]['id'] + '">' + msg[i]['name'] + '</option>';
                        }
                        replace += '</select>';
                        $(".county").html(replace);
                        form.render();

                    }
                });
            }else{
                var replace = '<select name="county_id" id="county_id" lay-filter="county" class="cus-input"><option value="">请选择</option></select>';
                $(".county").html(replace);
                form.render();
            }
        });
        // 客资分配，部门--->员工选择，联动
        form.on('select(department)', function (data) {
            var department_id = data.value;
            $.ajax({
                type: "POST",
                url: 'getDepartmentStaffs',
                data: "department_id="+department_id,
                success: function (msg) {
                    var replace = '<select name="staff_id" id="staff_id' +
                        '" lay-filter="staff" class="cus-input" ><option value="">请选择员工</option>';
                    for (var i = 0; i < msg.length; i++) {
                        replace += '<option value="' + msg[i]['id'] + '">' + msg[i]['staffname'] + '</option>';
                    }
                    replace += '</select>';
                    $(".staff").html(replace);
                    form.render();
                }
            });
        });
        var consultation_type_id =  $("#consultation_type option:selected").val();
        if(consultation_type_id == 'undefined' || consultation_type_id == '' || consultation_type_id == null){
            var consultation_type = '';
        }else{
            var consultation_type =  $("#consultation_type option:selected").val();
        }
        form.on('select(consultation_types)',function(data){
            consultation_type = data.value;
        })
        $('#customer_qq').blur(function() {
            var qq = $('#customer_qq').val();
            qq = $.trim(qq);
            if(qq != null && qq != undefined && qq!=""){
                //验证手机号是否重复
                $.ajax({
                    type: "POST",
                    url: '/crm/Customer/check_customer',
                    data: {contact:qq,consultation_type:consultation_type},
                    success: function (msg) {
                        if(msg.code == 201){
                            layer.alert(msg.msg);
                            return false;
                        }
                        if(msg.code == 205){
                            layer.alert(msg.msg);
                            return false;
                        }
                    }
                })
            }
        })
        $('#customer_wechat').blur(function() {
            var wx = $('#customer_wechat').val();
            wx = $.trim(wx);
            if(wx!=null&&wx!=undefined&&wx!=""){
                //验证手机号是否重复
                $.ajax({
                    type: "POST",
                    url: '/crm/Customer/check_customer',
                    data: {contact:wx,consultation_type:consultation_type},
                    success: function (msg) {
                        if(msg.code == 201){
                            layer.alert(msg.msg);
                            return false;
                        }
                        if(msg.code == 205){
                            layer.alert(msg.msg);
                            return false;
                        }
                    }
                })
            }
        })
        $('#mate_tel').blur(function() {
            var mate_tel = $('#mate_tel').val();
            mate_tel = $.trim(mate_tel);
            if(mate_tel!=null&&mate_tel!=undefined&&mate_tel!=""){
                //验证手机号是否重复
                $.ajax({
                    type: "POST",
                    url: '/crm/Customer/check_customer',
                    data: {contact:mate_tel,consultation_type:consultation_type},
                    success: function (msg) {
                        if(msg.code == 201){
                            layer.alert(msg.msg);
                            return false;
                        }
                        if(msg.code == 205){
                            layer.alert(msg.msg);
                            return false;
                        }
                    }
                })
            }
        })
        //归属地
        var oldTel = $('#customer_tel').val();
        $('#customer_tel').blur(function(){
            var tel = $('#customer_tel').val();
            tel = $.trim(tel);
            if(tel!=null&&tel!=undefined&&tel!=""){
                //验证手机号是否重复
                $.ajax({
                    type: "POST",
                    url: '/crm/Customer/check_customer',
                    data: {contact:tel,consultation_type:consultation_type},
                    success: function (msg) {
                        if (msg.code == 201) {
                            layer.alert(msg.msg);
                            return false;
                        }
                        if(msg.code == 205){
                            layer.alert(msg.msg);
                            return false;
                        }
                    }
                })
                var ex = /^1[3|4|5|6|7|8|9][0-9]{9}$/;
                if(!tel){
                    return false;
                }
                if(!ex.exec(tel) && tel){
                    //layer.alert('手机号输入有误');
                    $('#tel_belong').html('');
                    return false;
                }
                $.ajax({
                    type: "POST",
                    url: '/crm/Customer/insTelInfo',
                    data: "tel=" + tel,
                    success: function (msg) {
                        if(msg == false){
                            $('#tel_belong').html('');
                            return false;
                        }
                        $('#tel_belong').html(msg.tel_belong);
                        $.ajax({
                            type: "POST",
                            url: '/crm/Customer/getAddressInfo',
                            data: {name:msg.tel_belong},
                            success: function (ret) {
                                // if(ret.cid == undefined){
                                //     var cid = ret.pid[1].id;//市id
                                // }else{
                                    var cid = ret.cid[0].id;//市id
                                // }

                                $('#province_id').val(ret.pid[0].id);
                                layui.form.render('select');
                                $.ajax({
                                    type: "POST",
                                    url: '/crm/Customer/searchCity',
                                    data: "pid=" + ret.pid[0].id,//省id
                                    success: function (msg) {
                                        var replace = '<select name="city_id" id="city_id" lay-filter="cityI" class="cus-input"><option value="">请选择</option>';
                                        for (var i = 0; i < msg.length; i++) {
                                            replace += '<option value="' + msg[i]['id'] + '">' + msg[i]['name'] + '</option>';
                                        }
                                        replace += '</select>';
                                        $(".city").html(replace);
                                        $('#city_id').val(cid);
                                        $.ajax({
                                            type: "POST",
                                            url: '/crm/Customer/searchCity',
                                            data: "pid=" + cid,
                                            success: function (msg) {

                                                var replace = '<select name="county_id" id="county_id" lay-filter="countyI" class="cus-input"><option value="">请选择</option>';
                                                for (var i = 0; i < msg.length; i++) {
                                                    replace += '<option value="' + msg[i]['id'] + '">' + msg[i]['name'] + '</option>';
                                                }
                                                replace += '</select>';
                                                $(".county").html(replace);
                                                form.render();

                                            }
                                        });
                                        layui.form.render('select');
                                    }
                                });
                            }
                        })
                    }
                })
            }
        })
        $('#mate_tel').blur(function(){
            var tel = $('#mate_tel').val();
            $.ajax({
                type: "POST",
                url: '/crm/Customer/insTelInfo',
                data: "tel=" + tel,
                success: function (msg) {
                    $('#mTel_belong').html(msg.tel_belong);
                }
            })
        })
        //加载短信模板
        form.on('select(sms)',function(data){
            var sms = data.value;
            if(sms == 1){
                if($("#model").length==0){
                    var inp = '<div class="layui-inline" id="model"><label class="layui-form-label"><i class="input-sign"><img src="__PUBLIC__/img/cus-ufrom.png" alt=""></i>短信模板：</label><div class="layui-input-block"> <select name="sms_model" id="sms_model" class="cus-input"><option value="">请选择</option>';
                    $.ajax({
                        type: "POST",
                        url: '/crm/Customer/getSmsModel',
                        data: {},
                        success: function (msg) {
                            if(msg.code == 200){
                                var len = msg.data.length;
                                var data = msg.data;
                                for (var i=0;i<len;i++){
                                    inp += '<option value="'+data[i]["id"]+'">'+data[i]["mtemplate_name"]+'</option>';
                                }
                                inp += '</select></div></div>';
                                $('#send_sms').after(inp);
                                form.render('select');
                            }
                        }
                    })
                }
            }else{
                $('#model').remove();
            }
        })
        // 客资详情、编辑 地区三级联动
        form.on('select(provinceI)', function (data) {
            var province = data.value;
            if(province){
                $.ajax({
                    type: "POST",
                    url: '/crm/Customer/searchCity',
                    data: "pid=" + province+"&type=2",
                    success: function (msg) {

                        var replace = '<select name="city_id" id="info_city_id" lay-filter="cityI" class="cus-input"><option value="">请选择</option>';
                        for (var i = 0; i < msg.length; i++) {
                            replace += '<option value="' + msg[i]['id'] + '">' + msg[i]['name'] + '</option>';
                        }
                        replace += '</select>';
                        // alert(replace);
                        $(".cityI").html(replace);
                        var county = '<select name="county_id" id="county_id" lay-filter="countyI" class="cus-input"><option value="">请选择</option></select>';
                        $(".countyI").html(county);
                        form.render();

                    }
                });
            }else{
                var replace = '<select name="city_id" id="info_city_id" lay-filter="city" class="cus-input"><option value="">请选择</option></select>';
                $(".cityI").html(replace);
                var county = '<select name="county_id" id="county_id" lay-filter="county" class="cus-input"><option value="">请选择</option></select>';
                $(".countyI").html(county);
                form.render();
            }
        });
        form.on('select(cityI)', function (data) {
            var city = data.value;
            if(city){
                $.ajax({
                    type: "POST",
                    url: '/crm/Customer/searchCity',
                    data: "pid=" + city+"&type=3",
                    success: function (msg) {

                        var replace = '<select name="county_id" id="county_id" lay-filter="countyI" class="cus-input"><option value="">请选择</option>';
                        for (var i = 0; i < msg.length; i++) {
                            replace += '<option value="' + msg[i]['id'] + '">' + msg[i]['name'] + '</option>';
                        }
                        replace += '</select>';
                        $(".countyI").html(replace);
                        form.render();

                    }
                });
            }else{
                var replace = '<select name="county_id" id="county_id" lay-filter="county" class="cus-input"><option value="">请选择</option></select>';
                $(".countyI").html(replace);
                form.render();
            }
        });
    });

    //选项卡
    layui.use('element', function () {
        var element = layui.element;
    });

    //    滚动条问题
    $(".layui-layer-content").scroll(function () {
        console.log(1);
        $("body").preventDefault();
    })


    // 筛选条件添加
    layui.use('form', function () {
        var form = layui.form;
        var name1, name2, array = [], objname = {};
        form.on('select(shop_code)', function (data) {
            //选择店时插入店下的部门
            var shop_code = data.value;
            if (shop_code.length > 0) {
                $.ajax({
                    type: "POST",
                    url: '/crm/Customer/getDepartmentList',
                    data: "shop_code="+shop_code,
                    success: function (msg) {
                        var inp = '<option value="">请选择</option>';
                        for (var i = 0; i < msg.length; i++) {
                            inp += '<option value="' + msg[i]['id'] + '">' + msg[i]['department_name'] + '</option>';
                        }
                        //if($('#department').length == 0){
                        //    $("#appShop").after(inp);
                        //}else{
                        //    var inp1 = '<option value="">请选择</option>';
                        //    for (var i = 0; i < msg.length; i++) {
                        //        inp1 += '<option value="' + msg[i]['id'] + '">' + msg[i]['department_name'] + '</option>';
                        //    }
                            $("#department").html(inp);
                        //}

                        form.render();

                    }
                });
                $.ajax({
                    type: "POST",
                    url: '/crm/Customer/getShopStaffs',
                    data: "shop_code="+shop_code,
                    success: function (msg) {
                        var inp = '<option value="">请选择</option>';
                        for (var i = 0; i < msg.length; i++) {
                            inp += '<option value="' + msg[i]['id'] + '">' + msg[i]['staffname'] + '</option>';
                        }
                        $("#sales_staff_id").html(inp);
                        $("#dj_staff_id").html(inp);
                        form.render();

                    }
                });
            }else{
                $("#department").html('<option value="">请选择</option>');
                $("#dj_staff_id").html('<option value="">请选择</option>');
                form.render();
            }
        })

        //监听部门
        form.on('select(department)', function (data) {
            //选择店时插入店下的部门
            var department = data.value;
            if(department > 0){
                $.ajax({
                    type: "POST",
                    url: '/crm/Customer/getDepartmentStaff',
                    data: "id="+department,
                    success: function (msg) {
                        var inp = '<option value="">请选择</option>';
                        for (var i = 0; i < msg.length; i++) {
                            inp += '<option value="' + msg[i]['id'] + '">' + msg[i]['staffname'] + '</option>';
                        }
                        $("#dj_staff_id").html(inp);
                        form.render();

                    }
                });
            }else{
                $("#dj_staff_id").html('<option value="">请选择</option>');
                form.render();
            }
        })
        form.on('select(zjs_belong_shop_code)', function (data) {
            //选择店时插入店下的追踪人
            var shop_code = data.value;
            console.log(shop_code)
            $.ajax({
                type: "POST",
                url: '/crm/Customer/getStaffByWorkType',
                data: "shop_code="+shop_code+"&work_type=21",
                success: function (msg) {
                    var inp = '<option value="">请选择</option>';
                    for (var i = 0; i < msg.length; i++) {
                        inp += '<option value="' + msg[i]['id'] + '">' + msg[i]['staffname'] + '</option>';
                    }
                    $("#sales_staff_id").html(inp);
                    form.render();

                }
            });
        })
        form.on('select(choose01)', function (data) {
            name1 = data.value;

            $.ajax({
                type: "POST",
                url: 'searchTwo',
                data: "name=" + name1,
                success: function (msg) {
                    if(msg.code == -2){
                        layer.alert('您已掉线，请重新登录。')
                        // layer.alert('您的帐号在其他地方已登录，请重新登录。')
                        return false;
                    }
                    var replace = '<select name="select_name" lay-filter="choose02" lay-search=""><option value="">请选择</option>';
                    for (var i = 0; i < msg.length; i++) {
                        if(name1 == 'customer_channel'){
                            replace += '<option value="' + msg[i]['name'] + '">' + msg[i]['name'] + '</option>';
                        }else{
                            replace += '<option value="' + msg[i]['id'] + '">' + msg[i]['name'] + '</option>';
                        }
                    }
                    replace += '</select>';
                    var sel = $("#cus-select").html(replace);
                    form.render();

                }
            });
        });

        form.on('select(choose02)', function (data) {
            name2 = data.value;
            var name3 = $("#cus-top select[name=select_name] option:selected").html();
            if (name2 != 0) {
                var filterwrap;
                if (name1 == "customer_type") {
                    filterwrap = '<div class="filter-wrap"><span class="filter-text type-val" value="' + name1 + '=' + name2 + '">客户类型:' + name3 + '</span><span class="cus-close">&times;</span></div>';
                    //转介绍时在登记人前面插入店，部门，替换人员
                    //if($('#choose01').val() == 'customer_type' && name2 == 2){
                    //    $.ajax({
                    //        type: "POST",
                    //        url: 'searchShop',
                    //        data: "",
                    //        success: function (msg) {
                    //            var inp = '<div class="layui-inline" id="appShop"><label class="layui-form-label">选择店面：</label> <div class="layui-input-block w-120"><select name="shop_code" id="shop_code"lay-filter="shop_code"><option value="">请选择</option>';
                    //            for (var i = 0; i < msg.length; i++) {
                    //                inp += '<option value="' + msg[i]['shop_code'] + '">' + msg[i]['shop_name'] + '</option>';
                    //            }
                    //            inp += '</select></div></div>';
                    //            if($('#appShop').length == 0){
                    //                $(".cus-top-right").prepend(inp);
                    //            }
                    //            form.render();
                    //
                    //        }
                    //    });
                    //}
                } else if (name1 == "order_type") {
                    filterwrap = '<div class="filter-wrap"><span class="filter-text type-val" value="' + name1 + '=' + name2 + '">订单类型:' + name3 + '</span><span class="cus-close">&times;</span></div>';
                } else if (name1 == "access_model_id") {
                    filterwrap = '<div class="filter-wrap"><span class="filter-text type-val" value="' + name1 + '=' + name2 + '">获取方式:' + name3 + '</span><span class="cus-close">&times;</span></div>';
                } else if (name1 == "customer_area_id") {
                    filterwrap = '<div class="filter-wrap"><span class="filter-text type-val" value="' + name1 + '=' + name2 + '">客户分区:' + name3 + '</span><span class="cus-close">&times;</span></div>';
                } else if (name1 == "customer_region_id") {
                    filterwrap = '<div class="filter-wrap"><span class="filter-text type-val" value="' + name1 + '=' + name2 + '">客户地域:' + name3 + '</span><span class="cus-close">&times;</span></div>';
                } else if(name1 == "op_signinfo_id"){
                    filterwrap = '<div class="filter-wrap"><span class="filter-text type-val" value="' + name1 + '=' + name2 + '">追踪标记:' + name3 + '</span><span class="cus-close">&times;</span></div>';
                }else if (name1 == "sign_name") {
                    filterwrap = '<div class="filter-wrap"><span class="filter-text type-val" value="' + name1 + '=' + name2 + '">客资标记:' + name3 + '</span><span class="cus-close">&times;</span></div>';
                }else if (name1 == "shop_code") {
                    filterwrap = '<div class="filter-wrap"><span class="filter-text type-val" value="' + name1 + '=' + name2 + '">归属店面:' + name3 + '</span><span class="cus-close">&times;</span></div>';
                }else if (name1 == "sales_staff_id") {
                    filterwrap = '<div class="filter-wrap"><span class="filter-text type-val" value="' + name1 + '=' + name2 + '">追踪人:' + name3 + '</span><span class="cus-close">&times;</span></div>';
                }else if (name1 == "dj_group_id") {
                    filterwrap = '<div class="filter-wrap"><span class="filter-text type-val" value="' + name1 + '=' + name2 + '">登记小组:' + name3 + '</span><span class="cus-close">&times;</span></div>';
                }else if (name1 == "sales_group_id") {
                    filterwrap = '<div class="filter-wrap"><span class="filter-text type-val" value="' + name1 + '=' + name2 + '">追踪小组:' + name3 + '</span><span class="cus-close">&times;</span></div>';
                }else if (name1 == "seles_step") {
                    filterwrap = '<div class="filter-wrap"><span class="filter-text type-val" value="' + name1 + '=' + name2 + '">追踪阶段:' + name3 + '</span><span class="cus-close">&times;</span></div>';
                }else if (name1 == "unvalid_id") {
                    filterwrap = '<div class="filter-wrap"><span class="filter-text type-val" value="' + name1 + '=' + name2 + '">无效原因:' + name3 + '</span><span class="cus-close">&times;</span></div>';
                }else if (name1 == "consulation_shop_code") {
                    filterwrap = '<div class="filter-wrap"><span class="filter-text type-val" value="' + name1 + '=' + name2 + '">意向店面:' + name3 + '</span><span class="cus-close">&times;</span></div>';
                }else if (name1 == "is_loss") {
                    filterwrap = '<div class="filter-wrap"><span class="filter-text type-val" value="' + name1 + '=' + name2 + '">不再追踪:' + name3 + '</span><span class="cus-close">&times;</span></div>';
                }else if (name1 == "loss_cause") {
                    filterwrap = '<div class="filter-wrap"><span class="filter-text type-val" value="' + name1 + '=' + name2 + '">不追原因:' + name3 + '</span><span class="cus-close">&times;</span></div>';
                }else if (name1 == "customer_sex") {
                    filterwrap = '<div class="filter-wrap"><span class="filter-text type-val" value="' + name1 + '=' + name2 + '">性别:' + name3 + '</span><span class="cus-close">&times;</span></div>';
                }else if (name1 == "consultation_type_id") {
                    filterwrap = '<div class="filter-wrap"><span class="filter-text type-val" value="' + name1 + '=' + name2 + '">消费类型:' + name3 + '</span><span class="cus-close">&times;</span></div>';
                }else if (name1 == "zjs_from") {
                    filterwrap = '<div class="filter-wrap"><span class="filter-text type-val" value="' + name1 + '=' + name2 + '">转介绍类型:' + name3 + '</span><span class="cus-close">&times;</span></div>';
                }else if (name1 == "sales_department_id") {
                    filterwrap = '<div class="filter-wrap"><span class="filter-text type-val" value="' + name1 + '=' + name2 + '">追踪部门:' + name3 + '</span><span class="cus-close">&times;</span></div>';
                }else if (name1 == "customer_cource_id") {
                    filterwrap = '<div class="filter-wrap"><span class="filter-text type-val" value="' + name1 + '=' + name2 + '">客资来源:' + name3 + '</span><span class="cus-close">&times;</span></div>';
                }
                objname = name1 + '=' + name2;

                if (array.length == 0) {
                    $(".cus-filter").append(filterwrap);
                    array.push(objname);
                } else {
                    var num = array.indexOf(objname);
                    if (num == '-1') {
                        $(".cus-filter").append(filterwrap);
                        array.push(objname);
                    }
                }
                var detail = array.join(",");
                $('#type_info').val(detail);
            }


        });

        //    删除筛选条件
        $('.cus-close').live("click", function () {
            //清除部门
            //$('#appDepartment').remove();
            //清除店
            //$('#appShop').remove();
            //点叉号删除条件时 清空下拉框选中项
            var con1 = $("#con1");
            con1.find("div>input.layui-input ").val("");
            var con2=$('#cus-select');
            con2.find("div>input.layui-input ").val("");
            //删除条件
            var type_val = $(this).parent().find(".type-val").attr("value");
            for (var i = 0; i < array.length; i++) {
                if (array[i] == type_val) {
                    array.splice(i, 1);
                }
            }
            $(this).parent().remove();
            var detail = array.join(",");
            $('#type_info').val(detail);
        })
    });

    var all_time = "";//日期条件
    var start_time = "";//开始时间
    var end_time = "";//结束时间
    var dj_staff_id = "";//登记者id
    var consultation_type_id ="";//消费类型
    var customer_intention_id = "";//客户意向
    var customer_cource_id = "";//客资来源
    var type_info = "";//所有条件
    var is_intostore="";//进店状态
    var is_success="";//成交状态
    var is_valid="";//客资状态
    var more_like="";//手机号qq微信微博
    var city_id='';//市id
    var province_id='';//省id
    var county_id = ''//区id
    var tab = 1;//选项卡
    var get_contact="";//是否获取手机号
    var add_shop_code = '';
    var brandclass_id = '';
    var department_id = '';
    var is_fp = '';
    var group = $('#group').val();
    if(typeof group == undefined || group == null || group == 'undefined' || group == ''){
        group = 0;
    }
    var dep = $('#dep').val();
    if(typeof dep == undefined || dep == null || dep == 'undefined' || dep == ''){
        dep = 0;
    }
    //var brandclass_id = '';
    //var allShop = '';
    //layui.use('layer', function () {
    //    var $ = layui.jquery, layer = layui.layer; //独立版的layer无需执行这一句
    //    //触发事件
    //    var active = {
    //        refresh: function () {//刷新列表
    //            reloadGrid();
    //        }
    //    }
    //});
    layui.use('form', function () {
        var form = layui.form;
        form.on('select(search_time)', function (data) {
            var search_time = data.value;
            var now = new Date(); //当前日期
            var nowDayOfWeek = now.getDay(); //今天本周的第几天
            var nowDay = now.getDate(); //当前日
            var nowMonth = now.getMonth(); //当前月
            var nowYear = now.getYear(); //当前年
            nowYear += (nowYear < 2000) ? 1900 : 0; //
            var lastMonthDate = new Date(); //上月日期
            lastMonthDate.setDate(1);
            lastMonthDate.setMonth(lastMonthDate.getMonth() - 1);
            var lastYear = lastMonthDate.getYear();
            var lastMonth = lastMonthDate.getMonth();
            //格式化日期：yyyy-MM-dd
            function formatDate(date) {
                var myyear = date.getFullYear();
                var mymonth = date.getMonth() + 1;
                var myweekday = date.getDate();
                
                if (mymonth < 10) {
                    mymonth = "0" + mymonth;
                }
                if (myweekday < 10) {
                    myweekday = "0" + myweekday;
                }
                return (myyear + "-" + mymonth + "-" + myweekday);
            }

            //获得某月的天数
            function getMonthDays(myMonth) {
                var monthStartDate = new Date(nowYear, myMonth, 1);
                var monthEndDate = new Date(nowYear, myMonth + 1, 1);
                var days = (monthEndDate - monthStartDate) / (1000 * 60 * 60 * 24);
                return days;
            }

            if (search_time == "week") {
                var weekStartDate = new Date(nowYear, nowMonth, nowDay + (1 - nowDayOfWeek));
                var weekEndDate = new Date(nowYear, nowMonth, nowDay + (7 - nowDayOfWeek));
                $('#start_time').val(formatDate(weekStartDate)+' 00:00');//开始时间
                $('#end_time').val(formatDate(weekEndDate)+' 23:59');//结束时间
                start_time=formatDate(weekStartDate)+' 00:00';
                end_time=formatDate(weekEndDate)+' 23:59';
            } else if (search_time == "last_week") {
                var weekStartDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek - 6);
                var weekEndDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek);
                $('#start_time').val(formatDate(weekStartDate)+' 00:00');//开始时间
                $('#end_time').val(formatDate(weekEndDate)+' 23:59');//结束时间
                start_time=formatDate(weekStartDate)+' 00:00';
                end_time=formatDate(weekEndDate)+' 23:59';
            } else if (search_time == "month") {
                var monthStartDate = new Date(nowYear, nowMonth, 1);
                var monthEndDate = new Date(nowYear, nowMonth, getMonthDays(nowMonth));
                $('#start_time').val(formatDate(monthStartDate)+' 00:00');//开始时间
                $('#end_time').val(formatDate(monthEndDate)+' 23:59');//结束时间
                start_time=formatDate(monthStartDate)+' 00:00';
                end_time=formatDate(monthEndDate)+' 23:59';
            } else if (search_time == "last_month") {
                if(lastMonth==11){
                    nowYear=nowYear-1;
                }
                var lastMonthStartDate = new Date(nowYear, lastMonth, 1);
                var lastMonthEndDate = new Date(nowYear, lastMonth, getMonthDays(lastMonth));
                $('#start_time').val(formatDate(lastMonthStartDate)+' 00:00');//开始时间
                $('#end_time').val(formatDate(lastMonthEndDate)+' 23:59');//结束时间
                start_time=formatDate(lastMonthStartDate)+' 00:00';
                end_time=formatDate(lastMonthEndDate)+' 23:59';
            }else if (search_time == "today") {
                var today = new Date(nowYear, nowMonth, nowDay);
                $('#start_time').val(formatDate(today)+' 00:00');//开始时间
                $('#end_time').val(formatDate(today)+' 23:59');//结束时间
                start_time=formatDate(today)+' 00:00';
                end_time=formatDate(today)+' 23:59';
            }else if (search_time == "yestoday") {
                var yestoday = new Date(nowYear, nowMonth, nowDay-1);
                $('#start_time').val(formatDate(yestoday)+' 00:00');//开始时间
                $('#end_time').val(formatDate(yestoday)+' 23:59');//结束时间
                start_time=formatDate(yestoday)+' 00:00';
                end_time=formatDate(yestoday)+' 23:59';
            };

            all_time = $('#all_time').val();//日期条件
            start_time = $('#start_time').val();//开始时间
            end_time = $('#end_time').val();//结束时间
            dj_staff_id = $('#dj_staff_id').val();//登记者id
            consultation_type_id = $('#consultation_type_id').val();//消费类型
            customer_intention_id = $('#customer_intention_id').val();//客户意向
            is_intostore = $('#is_intostore').val();//进店状态
            is_success = $('#is_success').val();//成交状态
            is_valid = $('#is_valid').val();//客资状态
            customer_cource_id = $('#customer_cource_id').val();//客资来源
            type_info = $('#type_info').val();//多查询条件拼接成的字符串
            more_like=$('#more_like').val();//手机号QQ微信微博
            get_contact=$('#get_contact').val(); //是否获取手机号
            province_id=$('#province_id').val();
            city_id=$('#staCity').val();
            county_id=$('#staCounty').val();
            add_shop_code=$('#shop_code').val();
            department_id=$('#department').val();
            //brandclass_id=$('#brandclass_id').val();
            group=$('#group').val();
            is_fp=$('#is_fp').val();
            if(typeof group == undefined || group == null || group == 'undefined' || group == ''){
                group = 0;
            }
            dep=$('#dep').val();
            if(typeof dep == undefined || dep == null || dep == 'undefined' || dep == ''){
                dep = 0;
            }
            //brandclass_id=$('#brandclass_id').val();
            //allShop=$('#allShop').val();
            var data = "search_time=" + search_time + '&all_time=' + all_time + '&start_time=' + start_time + '&end_time=' + end_time + '&dj_staff_id=' + dj_staff_id + '&consultation_type_id=' + consultation_type_id + '&customer_intention_id=' + customer_intention_id + '&is_intostore=' + is_intostore + '&is_success=' + is_success + '&customer_cource_id=' + customer_cource_id +'&more_like='+more_like+ '&type_info=' + type_info+"&is_valid="+is_valid+"&get_contact="+get_contact+"&city_id="+city_id+"&county_id="+county_id+"&add_shop_code="+add_shop_code+"&department_id="+department_id+"&province_id="+province_id+"&group="+group+"&dep="+dep+"&is_fp="+is_fp;
            reloadGrid("all");
        });

        form.on('submit(search)', function (val) {
            var detail = val.field;
            all_time = detail.all_time;//日期条件
            start_time = detail.start_time;//开始时间
            end_time = detail.end_time;//结束时间
            dj_staff_id = detail.dj_staff_id;
            consultation_type_id = detail.consultation_type_id;
            customer_intention_id = detail.customer_intention_id;
            customer_cource_id = detail.customer_cource_id;
            type_info = detail.type_info;
            is_intostore=detail.is_intostore;
            is_success=detail.is_success;
            is_valid=detail.is_valid;
            more_like=detail.more_like;
            get_contact=detail.get_contact;
            province_id=detail.province_id;
            city_id=detail.customer_city_id;
            county_id=detail.customer_county_id;
            add_shop_code=detail.shop_code;
            //brandclass_id=detail.brandclass_id
            department_id=detail.department;
            is_fp=detail.is_fp;
            group=$('#group').val();
            if(typeof group == undefined || group == null || group == 'undefined' || group == ''){
                group = 0;
            }
            dep=$('#dep').val();
            if(typeof dep == undefined || dep == null || dep == 'undefined' || dep == ''){
                dep = 0;
            }
            //brandclass_id=detail.brandclass_id;
            //allShop=detail.allShop;
            if(add_shop_code == 'undefined' || !add_shop_code){
                add_shop_code = '';
            }
            if(department_id == 'undefined' || !department_id){
                department_id = '';
            }
            //var data = 'all_time=' + all_time + '&start_time=' + start_time + '&end_time=' + end_time + '&dj_staff_id=' + dj_staff_id + '&consultation_type_id=' + consultation_type_id + '&customer_intention_id=' + customer_intention_id + '&customer_cource_id=' + customer_cource_id + '&type_info='+type_info+ '&is_intostore=' + is_intostore + '&is_success=' + is_success +'&tab='+tab;
            reloadGrid('all');
            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
        });
    });

    // 测试 test
    $("#test_eric").click(function () {
        var data = 'all_time=' + all_time + '&start_time=' + start_time + '&end_time=' + end_time + '&dj_staff_id=' + dj_staff_id + '&consultation_type_id=' + consultation_type_id + '&customer_intention_id=' + customer_intention_id + '&customer_cource_id=' + customer_cource_id + '&type_info='+type_info+ '&is_intostore=' + is_intostore + '&is_success=' + is_success+'&more_like='+more_like+"&is_valid="+is_valid+"&get_contact="+get_contact+"&city_id="+city_id+"&department_id="+department_id+"&add_shop_code="+add_shop_code+"&province_id="+province_id+"&is_fp="+is_fp;
        $.ajax({
            type: "POST",
            url: '/crm/Testcustomer/customerList',
            data: data,
            success: function(msg){
                console.log(msg);
                return false;
            }
        });
        return false;
    });

    // 重置搜索条件
    $("#reset_btn").click(function (val) {
        $("#sform")[0].reset();
        return false;
    });

    function trim(str){
        return str.replace(/(^\s*)|(\s*$)/g, "");
    }

    // function check_tel(tel){
    //     var patrn = /^1[3|4|5|6|7|8|9][0-9]{9}$/;
    //     if(patrn.exec(tel)){
    //         return true;
    //     }else{
    //         return false;
    //     }
    // }
    // function reloadRow(id){
    //     setTimeout(function(){
    //         $.ajax({
    //             type: "POST",
    //             url: '/crm/Customer/getCustomerInfo',
    //             data: "id="+id,
    //             success: function(msg){
    //                     if(msg){
    //                         var valid = '';
    //                         if(msg.is_valid == 1){
    //                             valid = '有效';
    //                         }
    //                         if(msg.is_valid == 2){
    //                             valid = '待定';
    //                         }
    //                         if(msg.is_valid == 3){
    //                             valid = '无效';
    //                         }
    //                         if(msg.is_valid == 4){
    //                             valid = '驳回';
    //                         }
    //                         if(msg.is_valid == 5){
    //                             valid = '反驳回';
    //                         }
    //                         var intostore = '';
    //                         if(msg.is_intostore == 1){
    //                             intostore = '未进店';
    //                         }
    //                         if(msg.is_intostore == 2){
    //                             intostore = '进店进客';
    //                         }
    //                         if(msg.is_intostore == 3){
    //                             intostore = '进店非进客';
    //                         }
    //                         if(msg.is_intostore == 4){
    //                             intostore = '邀约流失';
    //                         }
    //                         if(msg.is_intostore == 5){
    //                             intostore = '进店流失';
    //                         }
    //                         var success = '';
    //                         if(msg.is_success == 1){
    //                             success = '已成交';
    //                         }
    //                         if(msg.is_success == 2){
    //                             success = '未成交';
    //                         }
    //                         if(msg.is_success == 3){
    //                             success = '已订金';
    //                         }
    //                         var fp = '';
    //                         if(msg.is_fp == 1){
    //                             fp = '已分配';
    //                         };
    //                         if(msg.is_fp == 2){
    //                             fp = '未分配';
    //                         }
    //                         if(msg.is_fp == 3){
    //                             fp = '待接收';
    //                         }
    //                         if(msg.is_fp == 4){
    //                             fp = '分配失败';
    //                         }
    //                         var loss = '';
    //                         if(msg.is_loss == 1){
    //                             loss = '是';
    //                         }
    //                         if(msg.is_loss == 2){
    //                             loss = '否';
    //                         }
    //                         var urgent = '';
    //                         if(msg.is_urgent == 1){
    //                             urgent = '是';
    //                         }
    //                         if(msg.is_urgent == 2){
    //                             urgent = '否';
    //                         }
    //                         var erp_loss = '';
    //                         if(msg.erp_loss == 1){
    //                             erp_loss = '否';
    //                         }
    //                         if(msg.erp_loss == 2){
    //                             erp_loss = '是';
    //                         }
    //                         var introducer_type = '';
    //                         if(msg.introducer_type == 1){
    //                             introducer_type = '新客';
    //                         }
    //                         if(msg.introducer_type == 2){
    //                             introducer_type = '现客';
    //                         }
    //                         if(msg.introducer_type == 3){
    //                             introducer_type = '老客';
    //                         }
    //                         var customer_type = '';
    //                         if(msg.customer_type == 1){
    //                             customer_type = '新客资';
    //                         }
    //                         if(msg.customer_type == 2){
    //                             customer_type = '转介绍';
    //                         }
    //                         var order_type = '';
    //                         if(msg.order_type == 1){
    //                             order_type = '线上';
    //                         }
    //                         if(msg.order_type == 2){
    //                             order_type = '线下';
    //                         }
    //                         var marry_day = '';
    //                         if(msg.marry_day){
    //                             marry_day = msg.marry_day.slice(0,10);
    //                         }
    //                         var yjd_day = '';
    //                         if(msg.yjd_day){
    //                             yjd_day = msg.yjd_day.slice(0,16);
    //                         }
    //                         var yjd_action_day = '';
    //                         if(msg.yjd_action_day){
    //                             yjd_action_day = msg.yjd_action_day.slice(0,10);
    //                         }
    //                         var order_day = '';
    //                         if(msg.order_day){
    //                             order_day = msg.order_day.slice(0,10);
    //                         }
    //                         var order_start_time = '';
    //                         if(msg.order_start_time){
    //                             order_start_time = msg.order_start_time.slice(0,10);
    //                         }
    //                         var syjd_day = '';
    //                         if(msg.syjd_day){
    //                             syjd_day = msg.syjd_day.slice(0,10);
    //                         }
    //                         var next_time = '';
    //                         if(msg.next_time){
    //                             next_time = msg.next_time.slice(0,10);
    //                         }
    //                         $("#Example").jqGrid('setRowData',id,{'customer_channel':msg.customer_channel,'sign_name':msg.sign_name,'is_valid':valid,'unvalid_reason':msg.unvalid_reason,'customer_number':msg.customer_number,'customer_name':msg.customer_name,'customer_sex':msg.customer_sex,'customer_tel':msg.customer_tel,'customer_wechat':msg.customer_wechat,'customer_weibo':msg.customer_weibo,'customer_qq':msg.customer_qq,'add_friend_time':msg.add_friend_time,'province':msg.province,'city':msg.city,'customer_address':msg.customer_address,'customer_key':msg.customer_key,'marry_day':marry_day,'budget':msg.budget,'consulation_shop':msg.consulation_shop,'reception_name':msg.reception_name,'channel_plan_number':msg.channel_plan_number,'next_time':next_time,'yjd_action_day':yjd_action_day,'yjd_day':yjd_day,'customer_remark':msg.customer_remark,'step_name':msg.step_name,'track_record':msg.track_record,'customer_label':msg.customer_label,'is_intostore':intostore,'syjd_day':syjd_day,'is_success':success,'order_number':msg.order_number,'order_start_time':order_start_time,'order_day':order_day,'order_type':order_type,'totalpay_money':msg.totalpay_money,'fact_money':msg.fact_money,'loss_cause':msg.loss_cause,'erp_loss_reason':msg.erp_loss_reason,'customer_type':customer_type,'create_time':msg.create_time,'is_fp':fp,'is_loss':loss,'erp_loss':erp_loss,'dj_staff':msg.dj_staff,'sales_staff':msg.sales_staff,'sk_staff':msg.sk_staff,'introducer_name':msg.introducer_name,'introducer_tel':msg.introducer_tel,'introducer_ordernum':msg.introducer_ordernum,'tel_visit_num':msg.tel_visit_num,'c_star_day':msg.c_star_day,'last_trackday':msg.last_trackday,'consultation_type':msg.consultation_type,'introducer_type':introducer_type,'customer_cource':msg.customer_cource,'customer_intention':msg.customer_intention,'access_model':msg.access_model,'customer_orderaddress':msg.customer_orderaddress,'customer_area':msg.customer_area,'brandclass':msg.brandclass,'shop_name':msg.shop_name,'add_shop_name':msg.add_shop_name,'op_signinfo':msg.op_signinfo,'is_urgent':urgent,'fp_staff':msg.fp_staff,'dj_department_name':msg.dj_department_name,'sales_department_name':msg.sales_department_name});
    //                     }
    //             }
    //         });
    //     },2000);
    // }
    function getTabId(divid){
        var allTab = [
            {'id':1,'div':'tab_all'},
            {'id':2,'div':'tab_no_tracking'},
            {'id':3,'div':'tab_no_fp'},
            {'id':4,'div':'tab_tracking'},
            {'id':5,'div':'tab_order'},
            {'id':6,'div':'tab_jdwd'},
            {'id':7,'div':'tab_loss'},
            {'id':8,'div':'tab_no_sk'},
            {'id':9,'div':'tab_already_sk'},
            {'id':10,'div':'tab_today_receive'},
            // {'id':11,'div':'tab_three_tracking'},
            {'id':12,'div':'tab_today_yjd'},
            {'id':13,'div':'validCustomer'},
            {'id':14,'div':'unValidCustomer'},
            // {'id':15,'div':'daiDingCustomer'},
            // {'id':16,'div':'boHuiCustomer'},
            {'id':17,'div':'tab_today_sales'},
            // {'id':18,'div':'over_cus'},
            // {'id':19,'div':'tab_weixin'},
            {'id':100,'div':'tab_bp'},
        ];
        for(var i in allTab){
            if(allTab[i].div == divid){
                return allTab[i].id;
            }
        }
    }
    // function refreshTabNumber(data,all){
    //     for(var i in all_tabs){
    //         if(all=='all' || all == all_tabs[i]){
    //             var tabid = getTabId(all_tabs[i]);
    //             $.ajax({
    //                 type: "POST",
    //                 url: "/crm/Customer/refreshNumber",
    //                 data: data+'&tab='+tabid,
    //                 dataType: 'json',
    //                 success: function (res) {
    //                     if (res.code == 1) {
    //                         var res_number = 0;
    //                         for(var ii in res.data){
    //                             var obj = $("#"+ii).find('.layui-badge');
    //                             if(typeof obj == 'object'){
    //                                 obj.html(res.data[ii]);
    //                             }
    //                         }
    //                         if(res.data.is_validShow == 1 && res.data.tab == 1){
    //                             // console.log('data=',res.data.tab);
    //                             layui.use('form', function () {
    //                                 var form = layui.form;
    //                                 console.log("待定=",res.data.ddValidCustomer);
    //                                 console.log("有效=",res.data.validCustomer);
    //                                 var yxListNum = "有效 "+res.data.validCustomer+"("+Math.round(res.data.validCustomer / res.data.tab_all * 10000)/100+"%)";
    //                                 $("#yxListNum").attr('title',yxListNum);
    //                                 var ddListNum = "待定 "+res.data.ddValidCustomer+"("+Math.round(res.data.ddValidCustomer / res.data.tab_all * 10000)/100+"%)";
    //                                 $("#ddListNum").attr('title',ddListNum);
    //                                 var wxListNum = "无效 "+res.data.unValidCustomer+"("+Math.round(res.data.unValidCustomer / res.data.tab_all * 10000)/100+"%)";
    //                                 $("#wxListNum").attr('title',wxListNum);
    //                                 form.render('checkbox');
    //                             })
    //                         }
    //                     }
    //                 }
    //             });
    //         }
    //     }
    // }
    function reloadGrid(all) {
        all_time = $('#all_time').val();//日期条件
        start_time = $('#start_time').val();//开始时间
        end_time = $('#end_time').val();//结束时间
        var customer_channel = $('#check-wrap2').val() ? $('#check-wrap2').val() : '';

        var validstr = '';
        $.each($(".is_valid input[name='is_valid']"),function(id,item){
            if($(item).is(':checked')){
                validstr += ','+$(item).val();
            }
        })
        validstr = validstr.substr(1);
        var loss_check = $(".is_valid input[name='is_loss']");
        if (loss_check.is(':checked')) {
            // is_loss = '';
            is_loss = 1;
        }else{
            is_loss = 2;
        }
        var data = 'all_time=' + all_time + '&start_time=' + start_time + '&end_time=' + end_time + '&dj_staff_id=' + dj_staff_id + '&consultation_type_id=' + consultation_type_id + '&customer_intention_id=' + customer_intention_id + '&customer_cource_id=' + customer_cource_id + '&type_info='+type_info+ '&is_intostore=' + is_intostore + '&is_success=' + is_success+'&more_like='+more_like+"&is_valid="+validstr+"&get_contact="+get_contact+"&province_id="+province_id+"&city_id="+city_id+"&county_id="+county_id+"&department_id="+department_id+"&add_shop_code="+add_shop_code+"&group="+group+"&dep="+dep+"&is_fp="+is_fp+"&customer_channel="+customer_channel+"&is_loss="+is_loss;
        // console.log(data);
        // return false;
        $("#Example").jqGrid('setGridParam', {
            datatype: 'json',
            url: "/crm/Customer/customerList",
            postData: {tab:tab,all_time:all_time,start_time:start_time,end_time:end_time,dj_staff_id:dj_staff_id,consultation_type_id:consultation_type_id,customer_intention_id:customer_intention_id,customer_cource_id:customer_cource_id,type_info:type_info,is_intostore:is_intostore,is_success:is_success,more_like:more_like,is_valid:validstr,get_contact:get_contact,city_id:city_id,county_id:county_id,department_id:department_id,add_shop_code:add_shop_code,province_id:province_id,group:group,dep:dep,is_fp:is_fp,customer_channel:customer_channel,is_loss:is_loss,client_customer_id:0},  //发送数据
        }).trigger("reloadGrid");

        if (list_customerinfo_refreshnumber != 1) {
            data += '&tab=' + tab;
        }
        $.ajax({
            type: "POST",
            url: "/crm/Customer/refreshNumber",
            data: data,
            dataType: 'json',
            success: function (res) {
                if (res.code == 1) {
                    var res_number = 0;
                    for(var ii in res.data){
                        var obj = $("#"+ii).find('.layui-badge');
                        if(typeof obj == 'object'){
                            obj.html(res.data[ii]);
                        }
                    }
                    if(res.data.is_validShow == 1 && res.data.tab == 1){
                        // console.log('data=',res.data.tab);
                        layui.use('form', function () {
                            var form = layui.form;
                            console.log("待定=",res.data.ddValidCustomer);
                            console.log("有效=",res.data.validCustomer);
                            var yxListNum = "有效 "+res.data.validCustomer+"("+Math.round(res.data.validCustomer / res.data.tab_all * 10000)/100+"%)";
                            $("#yxListNum").attr('title',yxListNum);
                            var ddListNum = "待定 "+res.data.ddValidCustomer+"("+Math.round(res.data.ddValidCustomer / res.data.tab_all * 10000)/100+"%)";
                            $("#ddListNum").attr('title',ddListNum);
                            var wxListNum = "无效 "+res.data.unValidCustomer+"("+Math.round(res.data.unValidCustomer / res.data.tab_all * 10000)/100+"%)";
                            $("#wxListNum").attr('title',wxListNum);
                            form.render('checkbox');
                        })
                    }
                }
            }
        });
    }

    //所有客资
    $("#tab_all").click(function () {
        tab = getTabId('tab_all');
        reloadGrid('tab_all');
    });

    //待追踪
    $("#tab_no_tracking").click(function () {
        tab = getTabId('tab_no_tracking');
        reloadGrid('tab_no_tracking');
    });

    //待分配
    $("#tab_no_fp").click(function () {
        tab=getTabId('tab_no_fp');
        reloadGrid('tab_no_fp');
    });

    //追踪中
    $("#tab_tracking").click(function () {
        tab=getTabId('tab_tracking');
        reloadGrid('tab_tracking');
    });

    //已订单
    $("#tab_order").click(function () {
        tab=getTabId('tab_order');
        reloadGrid('tab_order');
    });
    //进店未成交
    $("#tab_jdwd").click(function () {
        tab=getTabId('tab_jdwd');
        /*  var dj_staff_id = $('#dj_staff_id').val();//登记者id
         var consultation_type_id = $('#consultation_type_id').val()//消费类型
         var customer_intention_id = $('#customer_intention_id').val()//客户意向
         var is_intostore=$('#is_intostore').val();//进店状态
         var is_success=$('#is_success').val()//成交状态
         var customer_cource_id = $('#customer_cource_id').val();//客资来源
         var type_info = $('#type_info').val();//多查询条件拼接成的字符串
         var data = 'all_time=' + all_time + '&start_time=' + start_time + '&end_time=' + end_time + '&dj_staff_id=' + dj_staff_id + '&consultation_type_id=' + consultation_type_id + '&customer_intention_id=' + customer_intention_id + '&is_intostore=' + is_intostore + '&is_success=' + is_success + '&customer_cource_id=' + customer_cource_id + '&type_info=' + type_info+'&tab='+tab;
         */
        reloadGrid('tab_jdwd');
    });
    $("#tab_loss").click(function(){
        tab=getTabId('tab_loss');
        reloadGrid('tab_loss');
    });
    $("#tab_no_sk").click(function(){
        tab=getTabId('tab_no_sk');
        reloadGrid('tab_no_sk');
    });
    $("#tab_already_sk").click(function(){
        tab=getTabId('tab_already_sk');
        reloadGrid('tab_already_sk');
    });
    $("#tab_today_receive").click(function(){
        tab=getTabId('tab_today_receive');
        reloadGrid('tab_today_receive');
    });
    $("#tab_three_tracking").click(function(){
        tab=getTabId('tab_three_tracking');
        reloadGrid('tab_three_tracking');
    });
    $("#tab_today_yjd").click(function(){
        tab=getTabId('tab_today_yjd');
        reloadGrid('tab_today_yjd');
    });
    // 有效客资
    $("#validCustomer").click(function(){
        tab=getTabId('validCustomer');
        reloadGrid('validCustomer');
    });
    // 无效客资
    $("#unValidCustomer").click(function(){
        tab=getTabId('unValidCustomer');
        reloadGrid('unValidCustomer');
    });
    $("#daiDingCustomer").click(function(){
        tab=getTabId('daiDingCustomer');
        reloadGrid('daiDingCustomer');
    });
    $("#boHuiCustomer").click(function(){
        tab=getTabId('boHuiCustomer');
        reloadGrid('boHuiCustomer');
    });
    //今日需追踪
    $("#tab_today_sales").click(function () {
        tab = getTabId('tab_today_sales');
        reloadGrid('tab_today_sales');
    });
    //过期客资
    $("#over_cus").click(function () {
        tab=getTabId('over_cus');
        reloadGrid('over_cus');
    });
    //已加微信
    $("#tab_weixin").click(function () {
        tab=getTabId('tab_weixin');
        reloadGrid('tab_weixin');
    });
    //客资爆破
    $("#tab_bp").click(function(){
        tab=getTabId('tab_bp');
        reloadGrid('tab_bp');
    });

});
// 列头 列表字段
function pageInit() {
    var client_customer_id = $('#client_customer_id').val();
    //创建jqGrid组件
    //var colNames = [];
    //var colModel = [];
    var newColModel = [];
    for (var i = 0; i < colModel.length; i++) {
        newColModel[colModel[i]['name']] = colModel[i]['width'];
    };
    var shop_default_model = {};
    shop_default_model.编号 = {
        name: 'customer_number',
        index: 'customer_number',
        width: newColModel.customer_number ? newColModel.customer_number : 90,
        align: "left",
        editable: true,
        editoptions: {size: 25}
    };
    shop_default_model.渠道名称 = {name: 'customer_channel',
        index: 'customer_channel',
        width: newColModel.customer_channel ? newColModel.customer_channel : 75,
        align: "left",
        editoptions: {readonly: true, size: 10}
    };
    shop_default_model.姓名 = {
        name: 'customer_name',
        index: 'customer_name',
        width: newColModel.customer_name ? newColModel.customer_name :60,
        align: "center",
        frozen: true,
        editable: true,
        search: true,
        editoptions: {size: 25}
    };
    // shop_default_model.性别 = {
    //     name: 'customer_sex',
    //     index: 'customer_sex',
    //     editable: true,
    //     align: "center",
    //     editoptions: {size: 25},
    //     width: newColModel.customer_sex ? newColModel.customer_sex : 40,
    //     search: true,
    //     stype: 'select',
    //     searchoptions:{value:":全部;男:男;女:女"}
    // };
    shop_default_model.手机号 = {
        name: 'customer_tel',
        index: 'customer_tel',
        editable: true,
        align: "left",
        width: newColModel.customer_tel ? newColModel.customer_tel : 100,
        editoptions: {size: 25}
    };
    shop_default_model.微信 = {
        name: 'customer_wechat',
        index: 'wechat_status',
        width: newColModel.customer_wechat ? newColModel.customer_wechat : 100,
        align: "left",
        editoptions: {readonly: true, size: 10},
        search: true,
        stype: 'select',
        sopt:['in'],
        searchoptions:{value:":全部;0:未标记;1:待通过;2:已通过;3:未通过"},
        cellattr: function (cellvalue, options, rowObject) {
	        return "style=overflow: visible;";
	    },
    };
    shop_default_model.微博 = {
        name: 'customer_weibo',
        index: 'customer_weibo',
        width: newColModel.customer_weibo ? newColModel.customer_weibo : 80,
        align: "center",
        editoptions: {readonly: true, size: 10}
    };
    shop_default_model.QQ = {
        name: 'customer_qq',
        index: 'customer_qq',
        width: newColModel.customer_qq ? newColModel.customer_qq : 80,
        align: "center",
        editoptions: {readonly: true, size: 10}
    };
    shop_default_model.配偶姓名 = {
        name: 'mate_name',
        index: 'mate_name',
        width: newColModel.mate_name ? newColModel.mate_name : 60,
        align: "center",
        frozen: true,
        editable: true,
        editoptions: {size: 25}
    };
    shop_default_model.配偶手机 = {
        name: 'mate_tel',
        index: 'mate_tel',
        editable: true,
        align: "center",
        width: newColModel.mate_tel ? newColModel.mate_tel : 80,
        editoptions: {size: 25}
    };
    shop_default_model.配偶微信 = {
        name: 'mate_wechat',
        index: 'mate_wechat',
        width: newColModel.mate_wechat ? newColModel.mate_wechat : 80,
        align: "center",
        editoptions: {readonly: true, size: 10}
    };
    shop_default_model.客资标记 ={
        name: 'sign_name',
        index: 'sign_name',
        width: newColModel.sign_name ? newColModel.sign_name : 60,
        align: "center",
        editoptions: {readonly: true, size: 10},
        search: true,
        stype: 'select',
        searchoptions:{value:listSign}
    };
    shop_default_model.是否有效 ={
        name: 'is_valid',
        index: 'is_valid',
        align: "center",
        width: newColModel.is_valid ? newColModel.is_valid : 60,
        editoptions: {readonly: true, size: 10}
    };
    shop_default_model.无效原因 ={
        name: 'unvalid_reason',
        index: 'unvalid_reason',
        align: "center",
        width: newColModel.unvalid_reason ? newColModel.unvalid_reason : 60,
        editoptions: {readonly: true, size: 10}
    };
    shop_default_model.登记日期 = {
        name: 'dj_day',
        index: 'dj_day',
        width: newColModel.dj_day ? newColModel.dj_day : 120,
        align: "center",
        editoptions: {readonly: true, size: 10}
    }
    // shop_default_model.未追踪时间 = {
    //     name: 'noTrackDay',
    //     index: 'noTrackDay',
    //     width: newColModel.noTrackDay ? newColModel.noTrackDay : 80,
    //     align: "center",
    //     editoptions: {readonly: true, size: 10}
    // }
    shop_default_model.获取日期 = {
        name: 'create_time',
        index: 'create_time',
        width: newColModel.create_time ? newColModel.create_time : 100,
        align: "center",
        editoptions: {readonly: true, size: 10}
    }
    shop_default_model.分配日期 = {
        name: 'fp_day',
        index: 'fp_day',
        width: newColModel.fp_day ? newColModel.fp_day : 100,
        align: "center",
        editoptions: {readonly: true, size: 10}
    }
    shop_default_model.是否分配 = {
        name: 'is_fp',
        index: 'is_fp', 
        width: newColModel.is_fp ? newColModel.is_fp : 60,
        align: "center", 
        editoptions: {readonly: true, size: 10},
    }
    shop_default_model.追踪标记 ={
        name: 'op_signinfo',
        index: 'op_signinfo',
        width: newColModel.op_signinfo ? newColModel.op_signinfo : 80,
        align: "center",
        editoptions: {readonly: true, size: 10},
        search: true,
        stype: 'select',
        searchoptions:{value:listMark},
    }
    shop_default_model.加好友时间 = {
        name: 'add_friend_time',
        index: 'add_friend_time',
        width: newColModel.add_friend_time ? newColModel.add_friend_time : 100,
        align: "center",
        editoptions: {readonly: true, size: 10}
    }
    shop_default_model.再约时间 = {
        name: 'next_time',
        index: 'next_time',
        width: newColModel.next_time ? newColModel.next_time : 100,
        align: "center",
        editable: true,
        edittype: "checkbox",
        editoptions: {value: "Yes:No"}
    }
    shop_default_model.预约操作时间 = {
        name: 'yjd_action_day',
        index: 'yjd_action_day',
        width: newColModel.yjd_action_day ? newColModel.yjd_action_day : 80,
        align: "center",
        editable: true,
        edittype: "checkbox",
        editoptions: {value: "Yes:No"}
    }
    shop_default_model.预约进店时间 = {
        name: 'yjd_day',
        index: 'yjd_day',
        width: newColModel.yjd_day ? newColModel.yjd_day : 100,
        align: "center",
        editable: true,
        edittype: "checkbox",
        editoptions: {value: "Yes:No"}
    }
    shop_default_model.意向店面 = {
        name: 'consulation_shop',
        index: 'consulation_shop',
        width: newColModel.consulation_shop ? newColModel.consulation_shop : 100,
        align: "center",
        editable: true,
        edittype: "checkbox",
        editoptions: {value: "Yes:No"}
    }
    shop_default_model.接待人员 = {
        name: 'reception_name',
        index: 'reception_name',
        width: newColModel.reception_name ? newColModel.reception_name : 80,
        align: "center",
        editable: true,
        edittype: "checkbox",
        editoptions: {value: "Yes:No"}
    }
    shop_default_model.是否成交 = {
        name: 'is_success',
        index: 'is_success',
        width: newColModel.is_success ? newColModel.is_success : 60,
        align: "center",
        editoptions: {readonly: true, size: 10}
    }
    shop_default_model.订单开始时间 = {
        name: 'order_start_time',
        index: 'order_start_time',
        width: newColModel.order_start_time ? newColModel.order_start_time : 120,
        align: "center",
        editoptions: {readonly: true, size: 10}
    }
    shop_default_model.成交日期 = {
        name: 'order_day',
        index: 'order_day',
        width: newColModel.order_day ? newColModel.order_day : 100,
        align: "center",
        editoptions: {readonly: true, size: 10}
    }
    shop_default_model.订单号 = {
        name: 'order_number',
        index: 'order_number',
        width: newColModel.order_number ? newColModel.order_number : 80,
        align: "center",
        editoptions: {readonly: true, size: 10}
    }
    shop_default_model.订单类型 = {
        name: 'order_type',
        index: 'order_type',
        width: newColModel.order_type ? newColModel.order_type : 60,
        align: "center",
        editoptions: {readonly: true, size: 10}
    }
    shop_default_model.订单金额 = {
        name: 'totalpay_money',
        index: 'totalpay_money',
        width: newColModel.totalpay_money ? newColModel.totalpay_money : 70,
        align: "center",
        editoptions: {readonly: true, size: 10}
    }
    shop_default_model.一销实收 = {
        name: 'order_fact',
        index: 'order_fact',
        width: newColModel.order_fact ? newColModel.order_fact : 70,
        align: "center",
        editoptions: {readonly: true, size: 10}
    }
    shop_default_model.一销套系 = {
        name: 'order_amount',
        index: 'order_amount',
        width: newColModel.order_amount ? newColModel.order_amount : 70,
        align: "center",
        editoptions: {readonly: true, size: 10}
    }
    shop_default_model.实收金额 = {
        name: 'fact_money',
        index: 'fact_money',
        width: newColModel.fact_money ? newColModel.fact_money : 80,
        align: "center",
        editoptions: {readonly: true, size: 10}
    }
    shop_default_model.省 = {
        name: 'province',
        index: 'province',
        width: newColModel.province ? newColModel.province : 60,
        align: "center",
        editoptions: {readonly: true, size: 10}
    }
    shop_default_model.城市 = {
        name: 'city',
        index: 'city',
        width: newColModel.city ? newColModel.city : 60,
        align: "center",
        editoptions: {readonly: true, size: 10}
    }
    shop_default_model.区县 = {
        name: 'county',
        index: 'county',
        width: newColModel.county ? newColModel.county : 60,
        align: "center",
        editoptions: {readonly: true, size: 10}
    }
    shop_default_model.详细地址 = {
        name: 'customer_address',
        index: 'customer_address',
        width: newColModel.customer_address ? newColModel.customer_address : 80,
        align: "center",
        editoptions: {readonly: true, size: 10}
    }
    shop_default_model.关键字 = {
        name: 'customer_key',
        index: 'customer_key',
        width: newColModel.customer_key ? newColModel.customer_key : 60,
        align: "center",
        editoptions: {readonly: true, size: 10}
    }
    shop_default_model.婚期 = {
        name: 'marry_day',
        index: 'marry_day',
        width: newColModel.marry_day ? newColModel.marry_day : 60,
        align: "center",
        editable: true,
        edittype: "checkbox",
        editoptions: {value: "Yes:No"}
    }
    shop_default_model.推广编号 = {
        name: 'channel_plan_number',
        index: 'channel_plan_number',
        width: newColModel.channel_plan_number ? newColModel.channel_plan_number : 80,
        align: "center",
        editable: true,
        edittype: "checkbox",
    }
    shop_default_model.预算 = {
        name: 'budget',
        index: 'budget',
        width: newColModel.budget ? newColModel.budget : 70,
        align: "center",
        editable: true,
        edittype: "checkbox",
        editoptions: {value: "Yes:No"}
    }
    shop_default_model.客资备注 = {
        name: 'customer_remark',
        index: 'customer_remark',
        width: newColModel.customer_remark ? newColModel.customer_remark : 120,
        align: "center",
        editoptions: {readonly: true, size: 10}
    }
    shop_default_model.广告页 = {
        name: 'ad_page',
        index: 'ad_page',
        width: newColModel.ad_page ? newColModel.ad_page : 100,
        align: "center",
        editoptions: {readonly: true, size: 10}
    }
    shop_default_model.追踪阶段 = {
        name: 'step_name',
        index: 'step_name',
        width: newColModel.step_name ? newColModel.step_name : 100,
        align: "center",
        editoptions: {readonly: true, size: 10}
    }
    shop_default_model.追踪记录 = {
        name: 'track_record',
        index: 'track_record',
        width: newColModel.track_record ? newColModel.track_record : 200,
        align: "left",
        editable: true,
        edittype: "checkbox",
        editoptions: {value: "Yes:No"}
    }
    shop_default_model.客资标签 = {
        name: 'customer_label',
        index: 'customer_label',
        width: newColModel.customer_label ? newColModel.customer_label : 200,
        align: "left",
        editable: true,
        edittype: "checkbox",
        editoptions: {value: "Yes:No"}
    }
    shop_default_model.是否进店 = {
        name: 'is_intostore',
        index: 'is_intostore',
        width: newColModel.is_intostore ? newColModel.is_intostore : 60,
        align: "center",
        editoptions: {readonly: true, size: 10}
    }
    shop_default_model.进店时间 = {
        name: 'syjd_day',
        index: 'syjd_day',
        width: newColModel.syjd_day ? newColModel.syjd_day : 70,
        align: "center",
        editoptions: {readonly: true, size: 10}
    }

    shop_default_model.是否加急 = {
        name: 'is_urgent',
        index: 'is_urgent',
        width: newColModel.is_urgent ? newColModel.is_urgent : 60,
        align: "center",
        editoptions: {readonly: true, size: 10}
    }
    shop_default_model.不再追踪原因 = {
        name: 'loss_cause',
        index: 'loss_cause',
        width: newColModel.loss_cause ? newColModel.loss_cause : 60,
        align: "center",
        editoptions: {readonly: true, size: 10}
    }
    shop_default_model.流失原因 = {
        name: 'erp_loss_reason',
        index: 'erp_loss_reason',
        width: newColModel.erp_loss_reason ? newColModel.erp_loss_reason : 60,
        align: "center",
        editoptions: {readonly: true, size: 10}
    }
    shop_default_model.客户类型 = {
        name: 'customer_type',
        index: 'customer_type',
        editable: true,
        width: newColModel.customer_type ? newColModel.customer_type : 60,
        align: "center",
        edittype: "textarea",
        editoptions: {rows: "2", cols: "20"},
        search: true,
        stype: 'select',
        size: 10
    }
    shop_default_model.不再追踪 = {
        name: 'is_loss',
        index: 'is_loss',
        align: "center",
        width: newColModel.is_loss ? newColModel.is_loss : 60,
        editoptions: {readonly: true, size: 10}
    }
    shop_default_model.是否流失 = {
        name: 'erp_loss',
        index: 'erp_loss',
        align: "center",
        width: newColModel.erp_loss ? newColModel.erp_loss : 60,
        editoptions: {readonly: true, size: 10}
    }
    shop_default_model.登记人 = {
        name: 'dj_staff',
        index: 'dj_staff',
        width: newColModel.dj_staff ? newColModel.dj_staff : 60,
        align: "center",
        editable: true,
        edittype: "checkbox",
        editoptions: {value: "Yes:No"}
    }
    shop_default_model.追踪人 = {
        name: 'sales_staff',
        index: 'sales_staff',
        width: newColModel.sales_staff ? newColModel.sales_staff : 60,
        align: "center",
        editable: true,
        edittype: "checkbox",
        editoptions: {value: "Yes:No"}
    }
    shop_default_model.筛客人 = {
        name: 'sk_staff',
        index: 'sk_staff',
        width: newColModel.sk_staff ? newColModel.sk_staff : 60,
        align: "center",
        editable: true,
        edittype: "checkbox",
        editoptions: {value: "Yes:No"}
    }
    shop_default_model.分配人 = {
        name: 'fp_staff',
        index: 'fp_staff',
        width: newColModel.fp_staff ? newColModel.fp_staff : 60,
        align: "center",
        editable: true,
        edittype: "checkbox",
        editoptions: {value: "Yes:No"}
    }
    shop_default_model.转介绍人 = {
        name: 'introduce_staff_name',
        index: 'introduce_staff_name',
        width: newColModel.introduce_staff_name ? newColModel.introduce_staff_name : 60,
        align: "center",
        editable: true,
        edittype: "checkbox",
        editoptions: {readonly: true, size: 10}
    }
    shop_default_model.老顾客姓名 = {
        name: 'introducer_name',
        index: 'introducer_name',
        width: newColModel.introducer_name ? newColModel.introducer_name : 60,
        align: "center",
        editable: true,
        edittype: "checkbox",
        editoptions: {readonly: true, size: 10}
    }
    shop_default_model.老顾客电话 = {
        name: 'introducer_tel',
        index: 'introducer_tel',
        width: newColModel.introducer_tel ? newColModel.introducer_tel : 60,
        align: "center",
        editable: true,
        edittype: "checkbox",
        editoptions: {readonly: true, size: 10}
    }
    shop_default_model.老顾客单号 = {
        name: 'introducer_ordernum',
        index: 'introducer_ordernum',
        width: newColModel.introducer_ordernum ? newColModel.introducer_ordernum : 100,
        align: "center",
        editable: true,
        edittype: "checkbox",
        editoptions: {readonly: true, size: 10}
    }
    shop_default_model.老顾客类型 = {
        name: 'introducer_type',
        index: 'introducer_type',
        width: newColModel.introducer_type ? newColModel.introducer_type : 60,
        align: "center",
        editable: true,
        edittype: "checkbox",
        editoptions: {readonly: true, size: 10}
    }
    shop_default_model.电访量 = {
        name: 'tel_visit_num',
        index: 'tel_visit_num',
        width: newColModel.tel_visit_num ? newColModel.tel_visit_num : 60,
        align: "center",
        editable: true,
        edittype: "checkbox",
        editoptions: {value: "Yes:No"}
    }
    shop_default_model.开始追踪时间 = {
        name: 'c_star_day',
        index: 'c_star_day',
        width: newColModel.c_star_day ? newColModel.c_star_day : 100,
        align: "center",
        editable: true,
        edittype: "checkbox",
        editoptions: {value: "Yes:No"}
    }
    shop_default_model.最后追踪时间 = {
        name: 'last_trackday',
        index: 'last_trackday',
        width: newColModel.last_trackday ? newColModel.last_trackday : 100,
        align: "center",
        editable: true,
        edittype: "checkbox",
        editoptions: {value: "Yes:No"}
    }
    shop_default_model.消费类型 = {
        name: 'consultation_type',
        index: 'consultation_type',
        width: newColModel.consultation_type ? newColModel.consultation_type : 70,
        align: "center",
        editable: true,
        editoptions: {size: 10}
    }
    shop_default_model.客户来源 = {
        name: 'customer_cource',
        index: 'customer_cource',
        width: newColModel.customer_cource ? newColModel.customer_cource : 70,
        align: "center",
        editoptions: {readonly: true, size: 10}
    }
    shop_default_model.客户意向 = {
        name: 'customer_intention',
        index: 'customer_intention',
        width: newColModel.customer_intention ? newColModel.customer_intention : 70,
        align: "center",
        editoptions: {readonly: true, size: 10}
    }
    shop_default_model.获取方式 = {
        name: 'access_model',
        index: 'access_model',
        width: newColModel.access_model ? newColModel.access_model : 70,
        align: "center",
        editoptions: {readonly: true, size: 10}
    }
    shop_default_model.接单点 = {
        name: 'customer_orderaddress',
        index: 'customer_orderaddress',
        width: newColModel.customer_orderaddress ? newColModel.customer_orderaddress : 60,
        align: "center",
        editoptions: {readonly: true, size: 10}
    }
    shop_default_model.客户分区 = {
        name: 'customer_area',
        index: 'customer_area',
        width: newColModel.customer_area ? newColModel.customer_area : 60,
        align: "center",
        editoptions: {readonly: true, size: 10}
    }
    shop_default_model.A客奖金 = {
        name: 'bonus',
        index: 'bonus',
        width: newColModel.bonus ? newColModel.bonus : 60,
        align: "center",
        editoptions: {readonly: true, size: 10}
    }
    shop_default_model.成交奖金 = {
        name: 'bonus_deal',
        index: 'bonus_deal',
        width: newColModel.bonus_deal ? newColModel.bonus_deal : 60,
        align: "center",
        editoptions: {readonly: true, size: 10}
    }
    shop_default_model.品牌 = {
        name: 'brandclass',
        index: 'brandclass',
        width: newColModel.brandclass ? newColModel.brandclass : 100,
        align: "center",
        editoptions: {readonly: true, size: 10}
    }
    
    shop_default_model.提报店 = {
        name: 'add_shop_name',
        index: 'add_shop_name',
        width: newColModel.add_shop_name ? newColModel.add_shop_name : 100,
        align: "center",
        editoptions: {readonly: true, size: 10}
    }
    shop_default_model.登记部门 = {
        name: 'dj_department_name',
        index: 'dj_department_name',
        width: newColModel.dj_department_name ? newColModel.dj_department_name : 60,
        align: "center",
        editoptions: {readonly: true, size: 10}
    }
    shop_default_model.登记小组 = {
        name: 'dj_group_name',
        index: 'dj_group_name',
        width: newColModel.dj_group_name ? newColModel.dj_group_name : 60,
        align: "center",
        editoptions: {readonly: true, size: 10}
    }
    shop_default_model.归属店 = {
        name: 'shop_name',
        index: 'shop_name',
        width: newColModel.shop_name ? newColModel.shop_name : 60,
        align: "center",
        editoptions: {readonly: true, size: 10}
    }
    shop_default_model.追踪部门 = {
        name: 'sales_department_name',
        index: 'sales_department_name',
        width: newColModel.sales_department_name ? newColModel.sales_department_name : 60,
        align: "center",
        editoptions: {readonly: true, size: 10}
    }
    shop_default_model.追踪小组 = {
        name: 'sales_group_name',
        index: 'sales_group_name',
        width: newColModel.sales_group_name ? newColModel.sales_group_name : 60,
        align: "center",
        editoptions: {readonly: true, size: 10}
    }
    var col = [];
    var forNames = colNames;
    colNames = [];
    //把自定义里面所有无效的去除掉，以防止控件报错
    for(var i=0;i<forNames.length;i++){
        var key = forNames[i];
        if(typeof shop_default_model[key] == 'object'){
            col.push(shop_default_model[key]);
            colNames.push(key);
        }
    }
    if(colNames.length > 0){
        //把所有自定义列里没有的，放到最后，并设置隐藏
        colNames.unshift('客资ID');
        col.unshift({name: 'id',index: 'id',width: 80, align: "center", search: true, stype: 'select',hidedlg: true, searchoptions: {dataUrl: '', sopt: ['eq', 'ne']},editoptions: {readonly: true, size: 10},font: {size: 10},hidden: false});
        forNames = '';
        for(forNames in shop_default_model){
            if($.inArray(forNames, colNames) == -1){
                shop_default_model[forNames].hidden = true;
                col.push(shop_default_model[forNames]);
                colNames.push(forNames);
            }
        }
        colModel = col;
    }else{
        //没有自定义列，循环所有列，生成列配置
        colNames.unshift('客资ID');
        colModel.unshift({name: 'id',index: 'id',width: 80, align: "center", search: true, stype: 'select',hidedlg: true, searchoptions: {dataUrl: '', sopt: ['eq', 'ne']},editoptions: {readonly: true, size: 10},font: {size: 10},hidden: false});
        for(forNames in shop_default_model){
            colNames.push(forNames);
            colModel.push(shop_default_model[forNames]);
        }
    }
    
    var url = '/crm/Customer/customerList';

    var validstr = '';
    $.each($(".is_valid input[name='is_valid']"),function(id,item){
        if($(item).is(':checked')){
            validstr += ','+$(item).val();
        }
    })
    validstr = validstr.substr(1);
    
    var loss_check = $(".is_valid input[name='is_loss']");
    if (loss_check.is(':checked')) {
        // is_loss = '';
        is_loss = 1;
    }else{
        is_loss = 2;
    }

    // var defaultJqRowNum = $.cookie('defaultJqRowNum');
    // if(!defaultJqRowNum) defaultJqRowNum = 100;
    var mygrid =jQuery("#Example").jqGrid(
        {
            url: url,//组件创建完成之后请求数据的url
            postData:{is_valid:validstr,is_loss:is_loss,client_customer_id:client_customer_id},
            datatype: "json",//请求数据返回的类型。可选json,xml,txt
            colNames: colNames,//jqGrid的列显示名字
            colModel: colModel,
            height: 390,//默认高度
            width: "100%",//默认宽度
            autowidth: true,
            altRows:true,//隔行变色
            altclass:'ui-widget-content-altclass',//隔行变色样式
            rowNum: 100,//一页显示多少条
            rowList: [20, 50, 100, 200, 300, 500, 1000,5000],//可供用户选择一页显示多少条
            //lastpage: true,
            pager: '#pager',//表格页脚的占位符(一般是div)的id
            page:$("#Example").jqGrid('getGridParam','page'),//获取当前页,
            //sortname: 'id',//初始化的时候排序的字段
            sortorder: "desc",//排序方式,可选desc,asc
            viewrecords: true,
            //onSelectRow : function(rowid) {
            //    if (rowid && rowid !== lastSel) {
            //        jQuery('#Example').jqGrid('restoreRow', lastSel);
            //        jQuery('#Example').jqGrid('editRow', rowid, true);
            //        lastSel = rowid;
            //   }
            //},
            mtype: "post",//向后台请求数据的ajax的类型。可选post,get
            sortable: true,//列排序
            multiselect: true,//tr行多选
            rownumbers: true,
            shrinkToFit:false,
            autoScroll: false,
            jsonReader:{
                root:"new_rows",
                repeatitems: false,
            },
            //editurl : ctx+"/RowEditingsss"
            // 列表页颜色
            gridComplete: function () {
                var ids = $("#Example").getDataIDs();
                for (var i = 0; i < ids.length; i++) {
                    var rowData = $("#Example").getRowData(ids[i]);

                    if (rowData.is_valid == '无效') {//无效
                        $('#' + ids[i]).find("td").removeClass();
                        //$('#' + ids[i]).find("td").addClass("bluebg");
                        $('#' + ids[i]).find("td").css('background',UNVALID_COLOR);
                    }
                    if (rowData.is_valid == '驳回') {//驳回
                        $('#' + ids[i]).find("td").removeClass();
                        //$('#' + ids[i]).find("td").addClass("bluebg");
                        $('#' + ids[i]).find("td").css('background',BH_COLOR);
                    }
                    var signinfo = rowData.op_signinfo;//追踪标记
                    if(signinfo && COLOR[signinfo]){
                        $('#' + ids[i]).find("td").removeClass();
                        $('#' + ids[i]).find("td").css('background','#'+COLOR[signinfo]);
                    }
                    var sign = rowData.sign_name//客资标记
                    if(sign && SIGN_COLOR[sign]){
                        $('#' + ids[i]).find("td").removeClass();
                        $('#' + ids[i]).find("td").css('background','#'+SIGN_COLOR[sign]);
                    }
                    if (rowData.yjd_day) {//预约
                        $('#' + ids[i]).find("td").removeClass();
                        //$('#' + ids[i]).find("td").addClass("bluebg");
                        $('#' + ids[i]).find("td").css('background',YY_NO_INTO_COLOR);
                    }

                    if (rowData.erp_loss == '是') {//ERP流失
                        $('#' + ids[i]).find("td").removeClass();
                        //$('#' + ids[i]).find("td").addClass("graybg");
                        $('#' + ids[i]).find("td").css('background',ERP_LOSS_COLOR);
                    }
                    if (rowData.is_loss == '是') {//不再追踪
                        $('#' + ids[i]).find("td").removeClass();
                        $('#' + ids[i]).find("td").css('background',LOSS_COLOR);
                    }
                    if (rowData.is_intostore == '进店进客') {//进店
                        $('#' + ids[i]).find("td").removeClass();
                        //$('#' + ids[i]).find("td").addClass("bluebg");
                        $('#' + ids[i]).find("td").css('background',INTO_COLOR);
                    }
                    // if (rowData.is_success == '未成交'&&rowData.is_intostore == '进店进客' || rowData.is_intostore == '进店非进客') {//进店未成交(走单)
                    if (rowData.is_intostore == '进店流失' || rowData.is_intostore == '进店非进客') {//进店未成交(走单)
                        $('#' + ids[i]).find("td").removeClass();
                        //$('#' + ids[i]).find("td").addClass("bluebg");
                        $('#' + ids[i]).find("td").css('background',INT_NO_SUC_COLOR);
                    }
                    if (rowData.is_success == '已成交'||rowData.is_success == '已订金') {//如果审核不通过，则背景色置于红色
                        $('#' + ids[i]).find("td").removeClass();
                        //$('#' + ids[i]).find("td").addClass("bluebg");
                        $('#' + ids[i]).find("td").css('background',SUCCESS_COLOR);
                    }
                }
            },
            // 双击事件
            ondblClickRow:function(rowid){
                jQuery("#Example").jqGrid('resetSelection');
                var k=rowid;

                jQuery("#Example").jqGrid('setSelection', k);
            },
            // 单击事件
            onSelectRow:function(rowid,status){//选中变色
                var id=jQuery("#Example").jqGrid('getGridParam', 'selarrrow');
                if(status){
                    //$('#'+rowid).addClass('trSelected');
                    $('#choose_num').html('已选中 '+id.length+' 条');
                    $('#'+rowid).css('background',ON_SELECT_COLOR ? ON_SELECT_COLOR : '#FFD7DC');
                }else{
                    //$('#'+rowid).removeClass('trSelected');
                    $('#choose_num').html('已选中 '+id.length+' 条');
                    $('#'+rowid).css('background','white');
                }
            },
            onSelectAll:function(rowids,statue){ //全选
                var id=jQuery("#Example").jqGrid('getGridParam', 'selarrrow');
                $('#choose_num').html('已选中 '+id.length+' 条');
            },
            // 当点击单元格时触发。rowid：当前行id；iCol：当前单元格索引；cellContent：当前单元格内容；e：event对象
            onCellSelect:function(rowid,iCol,cellcontent,e){
                if (colNames[iCol - 2]=='微信') {
                    var wx = $(this).find(".wx_icon").html();
                    // console.log(e);
                    // console.log(wx);
                    if (wx) {
                        var domStr = '<div class="weChat-model"><div><div><img src="/index/index/qrparsestr?code='+wx+'" /></div><button type="button" class="model-top ivu-btn ivu-btn-small" typeof="ghost"><span><img src="/img/wxtj.png">已添加</span></button><button type="button" class="ivu-btn ivu-btn-small" typeof="ghost"><span><img src="/img/wxwtj.png">未添加</span></button></div></div>';
                        // $(this).find(".wx_icon").append(domStr);
                    };
                }else{
                    $(this).find(".weChat-model").remove();
                }
            }
        });

    /*创建jqGrid的操作按钮容器*/
    //jQuery("#Example").jqGrid('gridResize', {minWidth: 650, maxWidth: "100%", minHeight: 80, maxHeight: 650});//grid改变大小

    jQuery("#Example").jqGrid('navGrid','#pager',{edit:false,add:false,del:false,search:false,refresh:true});//编辑,删除,搜索,刷新

    jQuery("#Example").jqGrid('navButtonAdd', '#pager', {//列选择
        caption: "列选择",
        title: "自定义列",
        onClickButton: function () {
            jQuery("#Example").jqGrid('columnChooser');
            return false;
        }
    });
    jQuery("#Example").jqGrid('navButtonAdd', '#pager', {//恢复默认列
        caption: "默认列",
        title: "恢复默认列",
        onClickButton: function () {
            $.ajax({
                type: "POST",
                url: "/crm/Customer/setJQGrid",
                data: {flag:'home'},
                dataType:'json',
                success: function(ret){
                    //location.reload();
                },
                error:function(){
                    layer.alert('设置有误');
                }
            })
        }
    });

    jQuery("#Example").jqGrid('filterToolbar', {
        //searchOperators : true
    });
    jQuery("#Example").jqGrid('navButtonAdd',"#pager",{caption:"筛选",title:"筛选", buttonicon :'ui-icon-pin-s',
        onClickButton:function(){
            mygrid[0].toggleToolbar();
            var trow = $("tr.ui-search-toolbar");
            if(trow.css("display") === 'none') {
                $('.ui-state-default').find("input").val('');
                $('.ui-state-default').find("select").val('');
                $("#Example").jqGrid('setGridParam',{  // 重新加载数据
                    url:url,
                    postData:''
                }).trigger("reloadGrid");
            }
        }
    });//筛选搜索按钮

    var validstr = '';
    $.each($(".is_valid input[name='is_valid']"),function(id,item){
        if($(item).is(':checked')){
            validstr += ','+$(item).val();
        }
    })
    validstr = validstr.substr(1);

    var loss_check = $(".is_valid input[name='is_loss']");
    if (loss_check.is(':checked')) {
        // is_loss = '';
        is_loss = 1
    }else{
        is_loss = 2;
    }
    //refreshTabNumber("is_valid="+validstr+"&is_loss"+is_loss,'all');

    if(client_customer_id>0){
        $("#all_crm").html(0);
        $("#today_sales_tab").html(0);
        $("#no_track").html(0);
        $("#no_crm_fp").html(0);
        $("#tracking").html(0);
        $("#customer_order").html(0);
        $("#customer_jdwd").html(0);
        $("#customer_loss").html(0);
        $("#customer_sk").html(0);
        $("#customer_already_sk").html(0);
        $("#customer_today_receive").html(0);
        $("#customer_three_tracking").html(0);
        $("#customer_today_yjd").html(0);
        $("#valid_customer").html(0);
        $("#unvalid_customer").html(0);
    }else{
        //*
        $.ajax({
            type: "POST",
            url: "/crm/Customer/refreshNumber",
            data:{is_valid:validstr,is_loss:is_loss},
            dataType: 'json',
            success: function (res) {
                if (res.code == 1) {
                    $("#all_crm").html(res.data.all_crm);//总数
                    $("#today_sales_tab").html(res.data.today_sales);
                    $("#no_track").html(res.data.no_traking);
                    $("#no_crm_fp").html(res.data.no_fp);
                    $("#tracking").html(res.data.traking);
                    $("#customer_order").html(res.data.crm_order);
                    $("#customer_jdwd").html(res.data.jdwd);
                    $("#customer_loss").html(res.data.loss);
                    $("#customer_sk").html(res.data.sk);
                    $("#customer_already_sk").html(res.data.already_sk);
                    $("#customer_today_receive").html(res.data.today_receive);
                    $("#customer_three_tracking").html(res.data.three_tracking);
                    $("#customer_today_yjd").html(res.data.today_yjd);
                    $("#valid_customer").html(res.data.validCustomer);  //有效
                    $("#unvalid_customer").html(res.data.unValidCustomer);//无效
                    if(res.data.is_validShow == 1){
                        layui.use('form', function () {
                            var form = layui.form;
                            var ddListNum = "待定 "+res.data.ddValidCustomer+"("+Math.round(res.data.ddValidCustomer / res.data.all_crm * 10000)/100+"%)";
                            $("#ddListNum").attr('title',ddListNum);
                            var yxListNum = "有效 "+res.data.validCustomer+"("+Math.round(res.data.validCustomer / res.data.all_crm * 10000)/100+"%)";
                            $("#yxListNum").attr('title',yxListNum);
                            var wxListNum = "无效 "+res.data.unValidCustomer+"("+Math.round(res.data.unValidCustomer / res.data.all_crm * 10000)/100+"%)";
                            $("#wxListNum").attr('title',wxListNum);
                            form.render('checkbox');
                        })
                    }
                    
                    //res.data.ddValidCustomer;//待定
                    // $("#daiding_customer").html(res.data.daiding_customer);
                    // $("#bohui_customer").html(res.data.bohui_customer);
                    // $("#over").html(res.data.over_customer);
                    // $("#bp").html(res.data.bp);
                    // $("#wx").html(res.data.friend);
                }
            }
        });
    }
    //表格高度自适应
    $(window).load(function(){
        CpH();
    });
    $(window).resize(function() {
        CpH();
    });
    function CpH() {
        var wdcpH=$(window).height();
        var CpHeight= parseInt(wdcpH)-320;
        $(".ui-jqgrid-bdiv").css("height", CpHeight);
    }
}

function func_str(s, n) {
    return s.slice(0, n).replace(/([^x00-xff])/g,"$1a").slice(0, n).replace(/([^x00-xff])a/g,"$1");
}
layui.use('form', function () {
    var form = layui.form;
    form.on('checkbox(group)', function (obj) {
        if(obj.elem.checked){
            $('#group').val(1);
        }else{
            $('#group').val(0);
        }
    })
    form.on('checkbox(dep)', function (obj) {
        if(obj.elem.checked){
            $('#dep').val(1);
        }else{
            $('#dep').val(0);
        }
    })
})
//post导出
function postExcelFile(params, url) { //params是post请求需要的参数，url是请求url地址
    var form = document.createElement("form");
    form.style.display = 'none';
    form.action = url;
    form.method = "post";
    document.body.appendChild(form);
    for(var key in params){
        var input = document.createElement("input");
        input.type = "hidden";
        input.name = key;
        input.value = params[key];
        form.appendChild(input);
    }
    form.submit();
    form.remove();
}
// 关闭微信弹窗
var wechatSta=1;
$(document).on("click", function () {
    if (wechatSta==1) {
    	$('.weChat_model').hide();
		wechatSta=2;
    };
});
// 显示页面弹窗
function popWx (cid) {
	$('#'+cid+'wxpop').show();
	wechatSta=2;
	setTimeout(function() {
		wechatSta=1;
	},100);
}
// 微信 加上 未加上 状态
function wxStatus (status,cid) {
	$.ajax({
        type: "POST",
        url: 'wxStatus',
        data:{wxstatus:status,cid:cid},
        success: function (msg) {
            if (msg.code == 200) {
                $('#'+cid+'wxpop').hide();
                if (status==2) {
                    $('#'+cid+'wxicon').attr('src','/img/wxtj.png');
                }else if (status==3) {
                    $('#'+cid+'wxicon').attr('src','/img/wxwtj.png');
                };
            } else {
                layer.alert(msg.msg);
                return false;
            }
        },
        error:function(){
            layer.alert('操作失败，请检查网络');
            return false;
        }
    });
}
// 电访 追踪页面 新
let waitTimeout = 0;
function dianfangPageNew (shadeDf) {
    // 加载中 阴影效果
    if (dfSelect==1) {
        waitTimeout++;
        if (!shadeDf) {
            var shadeDf = layer.load(1, {shade: 0.3});
        };
        if(waitTimeout > 10){
            alert('数据加载超时，请按下F5刷新页面后重试。');
            waitTimeout = 0;
            layer.close(shadeDf);
        }else{
            setTimeout(function(){
                dianfangPageNew(shadeDf);
            },200);
        }
    }else{
        layer.close(shadeDf);
        // 加载追踪页面 前 置空数据
        clearDfPage();
        var height= 650;
        var width = 760;
        // 网页可用高度
        var sHeihgt = $(window).height();
        if (sHeihgt>900) {
            height = 750;
        }else if (sHeihgt>700 && sHeihgt<800) {
            height = 650;
        }else if (sHeihgt>600 && sHeihgt<700) {
            height = 550;
        }else if (sHeihgt<600) {
            height = 450;
        }

        var cusInfo = {};
        // 打开追踪页面 并提交信息
        setTimeout(function(){
            var dianfang = layer.open({
                title: '客资追踪',
                type: 1,
                skin: 'layui-layer-rim',
                area: [width+'px', height+'px'],
                content: $('#dianfang_new'),
                btn: ['提交','取消'],
                success:function () {
                    // 获取选中的客资id
                    var id=jQuery("#Example").jqGrid('getGridParam', 'selarrrow');
                    // console.log(id);
                    if(id == '' || id == null){
                        layer.alert('请选中某行再操作');
                        return false;
                    }
                    if(id.length > 1){
                        layer.alert('追踪时只能选择一个人');
                        return false;
                    }
                    var shadeDf = layer.load(1, {shade: 0.3});
                    // 获取客资基本信息
                    $.ajax({
                        type: "POST",
                        url: 'getCustomerInfo',
                        data: {id:id[0]},
                        success: function(msg){
                            // console.log(msg);
                            if (msg) {
                                // 判断电访下拉框是否加载完毕
                                // 赋值客资信息
                                cusInfo = msg;
                                if (!cusInfo) {
                                    layer.alert('没有获取到客资信息，请重试！');
                                    layer.close(shadeDf);
                                    return false;
                                };
                                dfPutCusinfo(cusInfo);
                            }
                            layui.form.render();
                            layer.close(shadeDf);
                        },
                        error:function(){
                            layer.alert('没有获取到客资信息，请重试！');
                            layer.close(shadeDf);
                            return false;
                        }
                    });
                },
                yes:function(index){
                    var shade = layer.load(1, {shade: 0.3});
                    var data = {};

                    var track_id = $('#append').val();
                    var customer_id = $('#df_customer_id').val();
                    var customer_name = $('#df_customer_name').val();
                    if(isInArray('customer_name',dfMust)){
                        if (!customer_name) {
                            layer.alert("客资姓名不能为空");
                            layer.close(shade);
                            return false;
                        }
                    }
                    var customer_tel = $('#df_customer_tel1').val();
                    var customer_wechat = $('#df_customer_wechat1').val();
                    if (!customer_tel && !customer_wechat) {
                        layer.alert("请填写客资手机号、微信任一项联系方式");
                        layer.close(shade);
                        return false;
                    }
                    var mate_name = $('#df_mate_name').val();
                    if(isInArray('mate_name',dfMust)){
                        if (!mate_name) {
                            layer.alert("配偶姓名不能为空");
                            layer.close(shade);
                            return false;
                        }
                    }
                    var mate_tel = $('#df_mate_tel1').val();
                    if(isInArray('mate_tel',dfMust)){
                        if (!mate_tel) {
                            layer.alert("配偶手机不能为空");
                            layer.close(shade);
                            return false;
                        }
                    }
                    var mate_wechat = $('#df_mate_wechat1').val();
                    if(isInArray('mate_wechat',dfMust)){
                        if (!mate_wechat) {
                            layer.alert("配偶微信不能为空");
                            layer.close(shade);
                            return false;
                        }
                    }
                    // 年龄区间
                    var age_area = $('#df_age_area').val();
                    // 加好友时间
                    var add_friend_time = $('#df_add_friend_time').val();
                    if(isInArray('add_friend_time',dfMust)){
                        if (!add_friend_time) {
                            layer.alert("添加好友时间不能为空");
                            layer.close(shade);
                            return false;
                        }
                    }
                    
                    // 沟通方式 (电话，qq，微信，其他)
                    var gtType = $('.gtType:checked').val();
                    // 追踪情况（接通，未接通，空号，不是本人）
                    // var tel_static = $("input[name='tel_static']:checked").val();
                    // 追踪备注
                    var sales_remark = $("#df_sales_remark iframe").contents().children().find('.view').html();
                    if(isInArray('sales_remark',dfMust)){
                        if (!sales_remark) {
                            layer.alert('备注不能为空');
                            layer.close(shade);
                            return false;
                        }
                    }
                    var data = {};
                    data.track_id        = track_id;
                    data.customer_id     = customer_id;
                    data.customer_name   = customer_name;
                    data.customer_tel    = customer_tel;
                    data.customer_wechat = customer_wechat;
                    data.mate_name       = mate_name;
                    data.mate_tel        = mate_tel;
                    data.mate_wechat     = mate_wechat;
                    data.age_area        = age_area;
                    data.add_friend_time = add_friend_time;
                    data.sales_remark    = sales_remark;
                    // data.tel_static      = tel_static;
                    data.gtType          = gtType;
                    // 电访情况->功能选择（继续追踪，驳回，预约进店，不在追踪）
                    var noTrack = $('input[name=noTrack]:checked').val();
                    if(noTrack == 1){
                        data.noTrack = noTrack;
                        // 三级地区 省
                        var province_id = $('#df_province_id').val();
                        if(province_id == 'undefined' || province_id == '' || province_id == null){
                            var province = '';
                        }else{
                            var province = $('#df_province_id option:selected').html();
                        };
                        // 三级地区 市
                        var city_id = $('#df_city_id').val();
                        if(city_id == 'undefined' || city_id == '' || city_id == null){
                            var city = '';
                        }else{
                            var city = $('#df_city_id option:selected').html();
                        };
                        // 三级地区 地区
                        var county_id = $('#df_county_id').val();
                        if(county_id == 'undefined' || county_id == '' || county_id == null){
                            var county = '';
                        }else{
                            var county = $('#df_county_id option:selected').html();
                        }
                        // 详细地址
                        var customer_address = $('#df_customer_address').val();
                        if(isInArray('customer_address',dfMust)){
                            if (!customer_address) {
                                layer.alert("详细地址不能为空");
                                layer.close(shade);
                                return false;
                            }
                        }
                        data.province_id = province_id;
                        data.province    = province;
                        data.city_id     = city_id;
                        data.city        = city;
                        data.county_id   = county_id;
                        data.county      = county;
                        data.customer_address = customer_address;
                        // 客资状态是否有效
                        var is_valid = $('#df_is_valid').val();
                        if(isInArray('is_valid',dfMust)){
                            if (is_valid == 0 || is_valid == 'undefined' || is_valid == '' || is_valid == null) {
                                layer.alert("客资状态不能为空");
                                layer.close(shade);
                                return false;
                            }
                        }
                        data.is_valid = is_valid;
                        // 标记无效记录无效原因
                        if (is_valid==3) {
                            var unvalid_id = $('#df_unvalid_reason').val();
                            var unvalid_reason = $("#df_unvalid_reason option:selected").html();
                            data.unvalid_id = unvalid_id;
                            data.unvalid_reason = unvalid_reason;
                        };
                        // 客资标记
                        var sign_id =  $('#df_sign_id option:selected').val();
                        if(sign_id == 0 || sign_id == 'undefined' || sign_id == '' || sign_id == null){
                            var sign_name = '';
                        }else{
                            var sign_name = $('#df_sign_id option:selected').html();
                        }
                        if(isInArray('sign_id',dfMust)){
                            if (sign_id == 0 || sign_id == 'undefined' || sign_id == '' || sign_id == null) {
                                layer.alert("客资标记不能为空");
                                layer.close(shade);
                                return false;
                            }
                        }
                        data.sign_id   = sign_id;
                        data.sign_name = sign_name;
                        // 客户意向
                        var customer_intention_id =  $("#df_customer_intention option:selected").val();
                        if(customer_intention_id == 'undefined' || customer_intention_id == '' || customer_intention_id == null){
                            var customer_intention = '';
                            if(isInArray('customer_intention',dfMust)){
                                layer.alert("客户意向不能为空");
                                layer.close(shade);
                                return false;
                            }
                        }else{
                            var customer_intention = $("#df_customer_intention option:selected").html();
                        }
                        data.customer_intention_id= customer_intention_id;
                        data.customer_intention   = customer_intention;
                        // 消费能力
                        var customer_capacity_id =  $("#df_customer_capacity option:selected").val();
                        if(customer_capacity_id == 'undefined' || customer_capacity_id == '' || customer_capacity_id == null){
                            var customer_capacity = '';
                            if(isInArray('customer_capacity',dfMust)){
                                layer.alert("消费能力不能为空");
                                layer.close(shade);
                                return false;
                            }
                        }else{
                            var customer_capacity = $("#df_customer_capacity option:selected").html();
                        }
                        data.customer_capacity_id= customer_capacity_id;
                        data.customer_capacity   = customer_capacity;
                        // 结婚日期
                        var marry_day = $("#df_marry_day").val();
                        if(isInArray('marry_day',dfMust)){
                            if (!marry_day) {
                                layer.alert('结婚日期不能为空');
                                layer.close(shade);
                                return false;
                            }
                        }
                        data.marry_day = marry_day;
                        // 预计婚期
                        var ready_marry_day =  $("#df_ready_marry_day option:selected").val();
                        if(ready_marry_day == 'undefined' || ready_marry_day == '' || ready_marry_day == null){
                            if(isInArray('ready_marry_day',dfMust)){
                                layer.alert("预计婚期不能为空");
                                layer.close(shade);
                                return false;
                            }
                        }
                        data.ready_marry_day= ready_marry_day;
                        // 消费类型
                        var consultation_type_id =  $("#df_consultation_type option:selected").val();
                        if(consultation_type_id == 'undefined' || consultation_type_id == '' || consultation_type_id == null){
                            var consultation_type = '';
                            if(isInArray('consultation_type',dfMust)){
                                layer.alert("消费类型不能为空");
                                layer.close(shade);
                                return false;
                            }
                        }else{
                            var consultation_type =  $("#df_consultation_type option:selected").html();
                        }
                        data.consultation_type_id = consultation_type_id;
                        data.consultation_type    = consultation_type;
                        // 预算
                        var budget = $("#df_budget").val();
                        if(isInArray('budget',dfMust)){
                            if (!budget) {
                                layer.alert('预算不能为空');
                                layer.close(shade);
                                return false;
                            }
                        }
                        data.budget = budget;
                        // 再约时间
                        var next_time = $("#df_next_time").val();
                        if(isInArray('next_time',dfMust)){
                            if (!next_time) {
                                layer.alert('再约时间不能为空');
                                layer.close(shade);
                                return false;
                            }
                        }
                        data.next_time = next_time;
                        // 追踪标记
                        var op_signinfo_id =  $('#df_op_signinfo_id option:selected').val();
                        if(op_signinfo_id == 0 || op_signinfo_id == 'undefined' || op_signinfo_id == '' || op_signinfo_id == null){
                            var op_signinfo = '';
                            if(isInArray('op_signinfo',dfMust)){
                                layer.alert('追踪标记不能为空');
                                layer.close(shade);
                                return false;
                            }
                        }else{
                            var op_signinfo = $('#df_op_signinfo_id option:selected').html();
                        }
                        data.op_signinfo_id= op_signinfo_id;
                        data.op_signinfo   = op_signinfo;
                        // 追踪阶段
                        var seles_step =  $("select[name=seles_step] option:selected").val();
                        if(seles_step == 'undefined' || seles_step == '' || seles_step == null){
                            var step_name = '';
                            if(isInArray('seles_step',dfMust)){
                                layer.alert('追踪阶段不能为空');
                                layer.close(shade);
                                return false;
                            }
                        }else{
                            var step_name =  $("select[name=seles_step] option:selected").html();
                        }
                        data.seles_step= seles_step;
                        data.step_name = step_name;
                        // 是否取消预约进店（2：取消预约）
                        var quit_yjd = $("select[name=quit_yjd] option:selected").val();
                        //客资标签
                        var customer_label = '';
                        for(var i=0;i<$('#myTags .customer_label_df').length;i++){
                            customer_label+=$('#myTags .customer_label_df').eq(i).attr("title")+',';
                        }
                        data.customer_label = customer_label;
                    }
                    // 驳回 
                    else if (noTrack == 2) {
                        var reject_reason = $('select[name=reject_reason]').val();
                        if(reject_reason == 'undefined' || reject_reason == '' || reject_reason == null){
                            layer.alert('请选择驳回原因');
                            layer.close(shade);
                            return false;
                        }else{
                            var reject_reason = $('select[name=reject_reason] option:selected').html();
                        }
                        var reject_staff_id = $("#df_reject_staff_id option:selected").val();
                        // if(reject_staff_id == 'undefined' || reject_staff_id == '' || reject_staff_id == null){
                        //     layer.alert('请选择接收员工');
                        //     layer.close(shade);
                        //     return false;
                        // }

                        data.reject_reason = reject_reason;
                        data.noTrack = noTrack;
                        data.reject_staff_id = reject_staff_id;
                    }
                    // 预约进店 
                    else if (noTrack == 3) {
                        // 客资状态是否有效
                        var is_valid = $('#df_is_valid').val();
                        if(isInArray('is_valid',dfMust)){
                            if (is_valid == 0 || is_valid == 'undefined' || is_valid == '' || is_valid == null) {
                                layer.alert("客资状态不能为空");
                                layer.close(shade);
                                return false;
                            }
                        }
                        data.is_valid = is_valid;
                        // 标记无效记录无效原因
                        if (is_valid==3) {
                            var unvalid_id = $('#df_unvalid_reason').val();
                            var unvalid_reason = $("#df_unvalid_reason option:selected").html();
                            data.unvalid_id = unvalid_id;
                            data.unvalid_reason = unvalid_reason;
                        };
                        // 预算
                        var budget = $("#df_budget").val();
                        if(isInArray('budget',dfMust)){
                            if (!budget) {
                                layer.alert('预算不能为空');
                                layer.close(shade);
                                return false;
                            }
                        }
                        data.budget = budget;
                        // 客户来源
                        var customer_cource_id =  $("#df_customer_cource_id option:selected").val();
                        if(customer_cource_id == 'undefined' || customer_cource_id == '' || customer_cource_id == null){
                            var customer_cource = '';
                            if(isInArray('customer_cource',dfMust)){
                                layer.alert("客户来源不能为空");
                                layer.close(shade);
                                return false;
                            }
                        }else{
                            var customer_cource = $("#df_customer_cource_id option:selected").html();
                        }
                        data.customer_cource_id= customer_cource_id;
                        data.customer_cource   = customer_cource;
                        // 意向店面
                        var consulation_shop_code = $("#df_consulation_shop_code option:selected").val();
                        if (consulation_shop_code == 'undefined' || consulation_shop_code == '' || consulation_shop_code == null) {
                            layer.alert('请选择意向店面');
                            layer.close(shade);
                            return false;
                        }else {
                            var consulation_shop = $("#df_consulation_shop_code option:selected").html();
                        }
                        // 预计进店时间
                        var yjd_day = $("#df_yjd_day").val();
                        if (yjd_day == 'undefined' || yjd_day == '' || yjd_day == null) {
                            layer.alert('请选择预约进店时间');
                            layer.close(shade);
                            return false;
                        }
                         // 客资标记
                        var sign_id =  $('#df_sign_id option:selected').val();
                        if(sign_id == 0 || sign_id == 'undefined' || sign_id == '' || sign_id == null){
                            var sign_name = '';
                        }else{
                            var sign_name = $('#df_sign_id option:selected').html();
                        }
                        if(isInArray('sign_id',dfMust)){
                            if (sign_id == 0 || sign_id == 'undefined' || sign_id == '' || sign_id == null) {
                                layer.alert("客资标记不能为空");
                                layer.close(shade);
                                return false;
                            }
                        }
                        data.sign_id   = sign_id;
                        data.sign_name = sign_name;
                        // 接待人员
                        var reception_id = $('#df_reception_id option:selected').val();
                        if (reception_id == 'undefined' || reception_id == '' || reception_id == null) {
                            var reception_id = 0;
                            var reception_name = '';
                        }else{
                            var reception_name = $('#df_reception_id option:selected').html();
                        }
                        // 短信发送标识
                        var receiver_flag = $("#receiver_flag").val();

                        data.consulation_shop_code = consulation_shop_code;
                        data.consulation_shop = consulation_shop;
                        data.yjd_day = yjd_day;
                        data.reception_id = reception_id;
                        data.reception_name = reception_name;
                        data.noTrack = noTrack;
                        data.receiver_flag = receiver_flag;
                    }
                    // 不再追踪
                    else if (noTrack == 4) {
                        // 不在追踪原因
                        var reason_id = $('#reason option:selected').val();
                        if (reason_id == 'undefined' || reason_id == '' || reason_id == null) {
                            layer.alert('请选择不追原因');
                            layer.close(shade);
                            return false;
                        }else{
                            var reason = $('#reason option:selected').html();
                        }
                        data.reason = reason;
                        data.noTrack= noTrack;
                        //匠古定制，标无效时，带上客资标记。
                        if(isjianggu){
                             data.is_valid = $('#df_is_valid').val();
                        }
                       

                    }
                    // console.log(data);
                    $.ajax({
                        type:"POST",
                        url: "/crm/Customer/editSalesTracking",
                        data: data,
                        success: function (ret) {
                            if (ret.code == 200) {
                                layer.alert(ret.msg);
                                layer.close(shade);
                                layer.close(dianfang);
                                reloadRow(customer_id);
                            } else {
                                layer.alert(ret.msg);
                                layer.close(shade);
                                return false;
                            }
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            var ret = XMLHttpRequest.responseJSON
                            layer.alert('操作有误');
                            layer.close(shade);
                            return false;
                        }
                    });
                }
            });
        },100);
    }
}
// 加载追踪页面 前 置空数据
function clearDfPage () {
    // 加载页面 前 置空数据
    $('#df_tel_clock').css('display','none');
    $('#df_customer_telphone').html('');
    $('.df_sel_tel_w').css('disabled','none');
    $('.df_sel_tel_m').css('disabled','none');
    // 客资信息
    $("#df_city_id").html('<option value="">请选择</option>');
    $("#df_county_id").html('<option value="">请选择</option>');
    $('#df_customer_address').val('');
    $('#df_customer_id').val('');
    $('#df_customer_number').val('');
    $('#df_customer_name').val('');
    $('#df_customer_tel1').val('');
    $('#df_customer_wechat1').val('');
    $('#df_mate_name').val('');
    $('#df_mate_tel1').val('');
    $('#df_mate_wechat1').val('');
    $('#df_add_friend_time').val('');
    $('#df_ready_baby_day').val('');
    $('#df_next_time').val('');
    $('#df_customer_remark').val('');
    $('#df_budget').val('');
    // 默认选中 li 追踪
    $('#sales').addClass('layui-this');
    $('#salesTrack').addClass('layui-show');
    // 去掉 追踪记录 选中
    if ( $('#track').hasClass('layui-this') ) {
        $('#track').removeClass('layui-this');
        $('#df_tracklog').removeClass('layui-show');
    };
    // 去掉 操作日志 选中
    if ( $('#log').hasClass('layui-this') ) {
        $('#log').removeClass('layui-this');
        $('#df_log').removeClass('layui-show');
    };
    // 去掉 历史订单 选中
    if ( $('#order').hasClass('layui-this') ) {
        $('#order').removeClass('layui-this');
        $('#df_order').removeClass('layui-show');
    };
    // 去掉 短信记录 选中
    if ( $('#msg').hasClass('layui-this') ) {
        $('#msg').removeClass('layui-this');
        $('#df_msg').removeClass('layui-show');
    };
    $("#df_tracklog").html('');
    $("#changeLog").html('');
    $("#orderLog").html('');
    $("#msgLog").html('');
    // 默认选中 沟通方式
    $("input:radio[name='gtType']").attr("checked",false);
    // 默认选中 功能选择 继续追踪
    $("input:radio[name='noTrack']").attr("checked",false);
    $("input:radio[name='noTrack']").eq(0).attr("checked",'checked');
    // ---- 继续追踪 ---- //
        // 省
        $('#df_province').css('display','inline-block');
        // 市
        $('#df_city').css('display','inline-block');
        // 地区
        $('#df_county').css('display','inline-block');
        // 详细地址
        $('#df_address').css('display','inline-block');
        // 客资状态 有效、无效 
        $('#valid').css('display','inline-block');
        // 无效原因
        $('#unvalid_reason').css('display','none');
        // 客资标记
        $('#sign').css('display','inline-block');
        // 客户意向
        $('#intention').css('display','inline-block');
        // 消费能力
        $('#capacity').css('display','inline-block');
        // 婚期
        $('#dp_marry_day').css('display','inline-block');
        $('#ready_marry_day').css('display','inline-block');
        // 消费类型
        $('#consul').css('display','inline-block');
        // 预算
        $('#budget').css('display','inline-block');
        // 再约时间
        $('#next_time').css('display','inline-block');
        // 追踪阶段
        $('#step').css('display','inline-block');
        // 追踪标记
        $('#mark').css('display','inline-block');
    // ---- 继续追踪 ---- //
    // ----------------------------------
    // ---- 驳回区域 ---- //
        // 驳回 原因 隐藏
        $('#reject_reason').css('display','none');
        // 接收店面 接收员工
        $('#reject_shop').css('display','none');
        $('#reject_staff').css('display','none');
    // ---- 驳回区域 ---- //
    // ----------------------------------
    // ---- 预约进店 ---- //
        // 意向店面
        $('#consulation').css('display','none');
        // 接待人员
        $('#reception').css('display','none');
        // 预约时间
        $('#yy_day').css('display','none');
        // 客户来源
        $('#customer_cource').css('display','none');
        // 接收手机
        $('#receiver').css('display','none');
    // ---- 预约进店 ---- //
    // ----------------------------------
    // 不再追踪 原因 隐藏
    $('#reason').css('display','none');
    // 追踪备注
    $('.remark').html('追踪备注：');
}
// 电访页面 赋值
function dfPutCusinfo (cusInfo) {
    $('#df_customer_id').val(cusInfo.id);
    $('#df_customer_number').val(cusInfo.customer_number);
    // 客资信息
    if (cusInfo.customer_name) {
        $('#df_customer_name').val(cusInfo.customer_name);
    };
    if (cusInfo.customer_tel) {
        $('#df_customer_tel1').val(cusInfo.customer_tel);
        // 显示手机图标及 计时器
        $('#df_tel').val(cusInfo.customer_tel);
        $('#df_tel_clock').css('display','block');
        $('#df_customer_telphone').html(cusInfo.customer_tel);
        // 拨号前显示
        $('.df_sel_tel_w').css('disabled','block');
        // 默认选中
        $("input:radio[name='gtType']").eq(0).attr("checked",'checked');
    };
    if (cusInfo.customer_wechat) {
        $('#df_customer_wechat1').val(cusInfo.customer_wechat);
    };
    // 没有手机 有微信
    if (!cusInfo.customer_tel && cusInfo.customer_wechat) {
        $("input:radio[name='gtType']").eq(1).attr("checked",'checked');
    };
    // 配偶信息
    if (cusInfo.mate_name) {
        $('#df_mate_name').val(cusInfo.mate_name);
    };
    if (cusInfo.mate_tel) {
        $('#df_mate_tel1').val(cusInfo.mate_tel);
        // 拨号前显示
        $('.df_sel_tel_m').css('disabled','block');
    };
    if (cusInfo.mate_wechat) {
        $('#df_mate_wechat1').val(cusInfo.mate_wechat);
    };
    // 年龄区间
    var df_age_area_op = document.getElementById("df_age_area");
    if (df_age_area_op) {
        for(var i=0; i<df_age_area_op.options.length; i++){
            if(df_age_area_op.options[i].value == cusInfo.age_area){
                df_age_area_op.options[i].selected = true;
            }else{
                df_age_area_op.options[i].selected = false;
            }
        }
    };
    // 加好友时间
    if (cusInfo.add_friend_time) {
        $('#df_add_friend_time').val(cusInfo.add_friend_time);
    };
    // 客户备注
    if (cusInfo.customer_remark) {
        $('#df_customer_remark').val(cusInfo.customer_remark)
    };
    // 预算
    if (cusInfo.budget) {
        $('#df_budget').val(cusInfo.budget)
    };
    // 选中 省
    var df_province_id_op = document.getElementById("df_province_id");
    if (df_province_id_op) {
        for(var i=0; i<df_province_id_op.options.length; i++){
            if(df_province_id_op.options[i].value == cusInfo.province_id){
                df_province_id_op.options[i].selected = true;
            }else{
                df_province_id_op.options[i].selected = false;
            }
        };
    };
    // 如果 省 市
    // if (cusInfo.city_id&&cusInfo.province_id) {
    if (cusInfo.province_id) {
        $.ajax({
            type: "POST",
            url: 'searchCity',
            data: "pid=" + cusInfo.province_id+"&type=2",
            success: function (msg) {
                var replace = '<option value="">请选择</option>';
                for (var i = 0; i < msg.length; i++) {
                    if (msg[i]['id']==cusInfo.city_id) {
                        replace += '<option selected value="' + msg[i]['id'] + '">' + msg[i]['name'] + '</option>';
                    }else{
                        replace += '<option value="' + msg[i]['id'] + '">' + msg[i]['name'] + '</option>';
                    }
                }
                $("#df_city_id").html(replace);
                var county = '<option value="">请选择</option>';
                $("#df_county_id").html(county);
                layui.form.render();
            }
        });
    };
    // 如果 市 区
    // if (cusInfo.city_id&&cusInfo.county_id) {
    if (cusInfo.city_id) {
        $.ajax({
            type: "POST",
            url: 'searchCity',
            data: "pid=" + cusInfo.city_id+"&type=3",
            success: function (msg) {
                var replace = '<option value="">请选择</option>';
                for (var i = 0; i < msg.length; i++) {
                    if (cusInfo.county_id==msg[i]['id']) {
                        replace += '<option selected value="' + msg[i]['id'] + '">' + msg[i]['name'] + '</option>';
                    }else{
                        replace += '<option value="' + msg[i]['id'] + '">' + msg[i]['name'] + '</option>';
                    }
                }
                $("#df_county_id").html(replace);
                layui.form.render();
            }
        });
    };
    // df_customer_address 详细地址
    if (cusInfo.customer_address) {
        $('#df_customer_address').val(cusInfo.customer_address)
    };
    // 客资状态
    var df_is_valid_op = document.getElementById("df_is_valid");
    if (df_is_valid_op) {
        for(var i=0; i<df_is_valid_op.options.length; i++){
            if(df_is_valid_op.options[i].value == cusInfo.is_valid){
                df_is_valid_op.options[i].selected = true;
            }else{
                df_is_valid_op.options[i].selected = false;
            }
        }
    };
    // 无效原因
    if (cusInfo.is_valid==3) {
        $('#unvalid_reason').css('display','inline-block');
        var df_unvalid_reason = document.getElementById("df_unvalid_reason");
        if (cusInfo.unvalid_id) {
            for(var i=0; i<df_unvalid_reason.options.length; i++){
                if(df_unvalid_reason.options[i].value == cusInfo.unvalid_id){
                    df_unvalid_reason.options[i].selected = true;
                }else{
                    df_unvalid_reason.options[i].selected = false;
                }
            }
        };
    }else{
        $('#unvalid_reason').css('display','none');
    }
    // 客资标记
    var df_sign_id_op = document.getElementById("df_sign_id");
    if (df_sign_id_op) {
        for(var i=0; i<df_sign_id_op.options.length; i++){
            if(df_sign_id_op.options[i].value == cusInfo.sign_id){
                df_sign_id_op.options[i].selected = true;
            }else{
                df_sign_id_op.options[i].selected = false;
            }
        }
    };
    // 客户意向
    var df_customer_intention_op = document.getElementById("df_customer_intention");
    if (df_customer_intention_op) {
        for(var i=0; i<df_customer_intention_op.options.length; i++){
            if(df_customer_intention_op.options[i].value == cusInfo.customer_intention_id){
                df_customer_intention_op.options[i].selected = true;
            }else{
                df_customer_intention_op.options[i].selected = false;
            }
        }
    };
    // 消费能力
    var df_customer_capacity_op = document.getElementById("df_customer_capacity");
    if (df_customer_capacity_op) {
        for(var i=0; i<df_customer_capacity_op.options.length; i++){
            if(df_customer_capacity_op.options[i].value == cusInfo.customer_capacity_id){
                df_customer_capacity_op.options[i].selected = true;
            }else{
                df_customer_capacity_op.options[i].selected = false;
            }
        }
    };
    // 结婚日期
    if (cusInfo.marry_day) {
        $('#df_marry_day').val(cusInfo.marry_day);
    };
    // 预计婚期
    var df_ready_marry_day_op = document.getElementById("df_ready_marry_day");
    if (df_ready_marry_day_op) {
        for(var i=0; i<df_ready_marry_day_op.options.length; i++){
            if(df_ready_marry_day_op.options[i].value == cusInfo.ready_marry_day){
                df_ready_marry_day_op.options[i].selected = true;
            }else{
                df_ready_marry_day_op.options[i].selected = false;
            }
        }
    };
    // 再约时间
    if (cusInfo.next_time) {
        $('#df_next_time').val(cusInfo.next_time);
    };
    // 消费类型
    var df_consultation_type_op = document.getElementById("df_consultation_type");
    if (df_consultation_type_op) {
        for(var i=0; i<df_consultation_type_op.options.length; i++){
            if(df_consultation_type_op.options[i].value == cusInfo.consultation_type_id){
                df_consultation_type_op.options[i].selected = true;
            }else{
                df_consultation_type_op.options[i].selected = false;
            }
        }
    };
    // 追踪阶段
    var df_seles_step_op = document.getElementById("df_seles_step");
    if (df_seles_step_op) {
        for(var i=0; i<df_seles_step_op.options.length; i++){
            if(df_seles_step_op.options[i].value == cusInfo.seles_step){
                df_seles_step_op.options[i].selected = true;
            }else{
                df_seles_step_op.options[i].selected = false;
            }
        }
    };
    // 追踪标记
    var df_op_signinfo_id_op = document.getElementById("df_op_signinfo_id");
    if (df_op_signinfo_id_op) {
        for(var i=0; i<df_op_signinfo_id_op.options.length; i++){
            if(df_op_signinfo_id_op.options[i].value == cusInfo.op_signinfo_id){
                df_op_signinfo_id_op.options[i].selected = true;
            }else{
                df_op_signinfo_id_op.options[i].selected = false;
            }
        }
    };
    // 驳回原因
    var df_reject_reason_op = document.getElementById("df_reject_reason");
    if (df_reject_reason_op) {
        for(var i=0; i<df_reject_reason_op.options.length; i++){
            if(df_reject_reason_op.options[i].value == cusInfo.reject_reason){
                df_reject_reason_op.options[i].selected = true;
            }else{
                df_reject_reason_op.options[i].selected = false;
            }
        }
    };
    // 客户来源
    var df_customer_cource_id_op = document.getElementById("df_customer_cource_id");
    if (df_customer_cource_id_op) {
        for(var i=0; i<df_customer_cource_id_op.options.length; i++){
            if(df_customer_cource_id_op.options[i].value == cusInfo.customer_cource_id){
                df_customer_cource_id_op.options[i].selected = true;
            }else{
                df_customer_cource_id_op.options[i].selected = false;
            }
        }
    };
    // 意向店面
    var df_consulation_shop_code_op = document.getElementById("df_consulation_shop_code");
    if (df_consulation_shop_code_op) {
        for(var i=0; i<df_consulation_shop_code_op.options.length; i++){
            if(df_consulation_shop_code_op.options[i].value == cusInfo.consulation_shop_code){
                df_consulation_shop_code_op.options[i].selected = true;
            }else{
                df_consulation_shop_code_op.options[i].selected = false;
            }
        }
    };
    // 接待人员
    if (cusInfo.consulation_shop_code) {
        var shop_code = cusInfo.consulation_shop_code;
        var work_type = 1;
        $.ajax({
            type: "POST",
            url: "/crm/Customer/getStaffForWorktype",
            data: {shop_code:shop_code,work_type:work_type},
            dataType: "json",
            success: function (msg) {
                if(msg){
                    $('#df_reception_id').empty();
                    var replace = '<option value="">请选择</option>';
                    for(var i=0;i<msg.length;i++){
                        if (cusInfo.reception_id==msg[i]['id']) {
                            replace += '<option selected value="'+msg[i]['id']+'">'+msg[i]['staffname']+'</option>';
                        }else{
                            replace += '<option value="'+msg[i]['id']+'">'+msg[i]['staffname']+'</option>';
                        }
                    }
                    $("#df_reception_id").html(replace);
                    layui.form.render();
                }else{
                    $('#df_reception_id').empty();
                    layui.form.render();
                }
            }
        })
    };
    // 预约时间
    if (cusInfo.yjd_day) {
        $('#df_yjd_day').val(cusInfo.yjd_day);
    };
    // 不再追踪原因
    var df_reason_op = document.getElementById("df_reason");
    if (df_reason_op) {
        for(var i=0; i<df_reason_op.options.length; i++){
            if(df_reason_op.options[i].value == cusInfo.loss_cause){
                df_reason_op.options[i].selected = true;
            }else{
                df_reason_op.options[i].selected = false;
            }
        }
    };
}
function reloadRow(id){
    setTimeout(function(){
        $.ajax({
            type: "POST",
            url: '/crm/Customer/getCustomerInfo',
            data: "id="+id,
            success: function(res){
                msg = res;
                // msg = res.data;
                if(msg){
                    var valid = '';
                    if(msg.is_valid == 1){
                        valid = '有效';
                    }
                    if(msg.is_valid == 2){
                        valid = '待定';
                    }
                    if(msg.is_valid == 3){
                        valid = '无效';
                    }
                    if(msg.is_valid == 4){
                        valid = '驳回';
                    }
                    if(msg.is_valid == 5){
                        valid = '反驳回';
                    }
                    var intostore = '';
                    if(msg.is_intostore == 1){
                        intostore = '未进店';
                    }
                    if(msg.is_intostore == 2){
                        intostore = '进店进客';
                    }
                    if(msg.is_intostore == 3){
                        intostore = '进店非进客';
                    }
                    if(msg.is_intostore == 4){
                        intostore = '邀约流失';
                    }
                    if(msg.is_intostore == 5){
                        intostore = '进店流失';
                    }
                    var success = '';
                    if(msg.is_success == 1){
                        success = '已成交';
                    }
                    if(msg.is_success == 2){
                        success = '未订单';
                    }
                    if(msg.is_success == 3){
                        success = '已订金';
                    }
                    var fp = '';
                    if(msg.is_fp == 1){
                        fp = '已分配';
                    }
                    if(msg.is_fp == 2){
                        fp = '未分配';
                    }
                    if(msg.is_fp == 3){
                        fp = '待接收';
                    }
                    if(msg.is_fp == 4){
                        fp = '分配失败';
                    }
                    var loss = '';
                    if(msg.is_loss == 1){
                        loss = '是';
                    }
                    if(msg.is_loss == 2){
                        loss = '否';
                    }
                    var urgent = '';
                    if(msg.is_urgent == 1){
                        urgent = '是';
                    }
                    if(msg.is_urgent == 2){
                        urgent = '否';
                    }
                    var erp_loss = '';
                    if(msg.erp_loss == 1){
                        erp_loss = '否';
                    }
                    if(msg.erp_loss == 2){
                        erp_loss = '是';
                    }
                    // var introducer_type = '';
                    // if(msg.introducer_type == 1){
                    //     introducer_type = '新客';
                    // }
                    // if(msg.introducer_type == 2){
                    //     introducer_type = '现客';
                    // }
                    // if(msg.introducer_type == 3){
                    //     introducer_type = '老客';
                    // }
                    var customer_type = '';
                    if(msg.customer_type == 1){
                        customer_type = '新客资';
                    }
                    if(msg.customer_type == 2){
                        customer_type = '转介绍';
                    }
                    var order_type = '';
                    if(msg.order_type == 1){
                        order_type = '线上';
                    }
                    if(msg.order_type == 2){
                        order_type = '线下';
                    }
                    var marry_day = '';
                    if(msg.marry_day){
                        marry_day = msg.marry_day.slice(0,10);
                    }
                    var ready_baby_day = '';
                    if(msg.ready_baby_day){
                        ready_baby_day = msg.ready_baby_day.slice(0,10);
                    }
                    var yjd_day = '';
                    if(msg.yjd_day){
                        yjd_day = msg.yjd_day.slice(0,16);
                    }
                    var yjd_action_day = '';
                    if(msg.yjd_action_day){
                        yjd_action_day = msg.yjd_action_day.slice(0,10);
                    }
                    var order_day = '';
                    if(msg.order_day){
                        order_day = msg.order_day.slice(0,10);
                    }
                    var order_start_time = '';
                    if(msg.order_start_time){
                        order_start_time = msg.order_start_time.slice(0,10);
                    }
                    var syjd_day = '';
                    if(msg.syjd_day){
                        syjd_day = msg.syjd_day.slice(0,10);
                    }
                    var next_time = '';
                    if(msg.next_time){
                        syjd_day = msg.next_time.slice(0,10);
                    }
                    $("#Example").jqGrid('setRowData',id,{'customer_channel':msg.customer_channel,'sign_name':msg.sign_name,'is_valid':valid,'customer_number':msg.customer_number,'baby_name':msg.baby_name,'baby_sex':msg.baby_sex,'baby_birthday':msg.baby_birthday,'ready_baby_day':ready_baby_day,'customer_name':msg.customer_name,'customer_sex':msg.customer_sex,'customer_tel':msg.customer_tel,'customer_wechat':msg.customer_wechat,'customer_weibo':msg.customer_weibo,'customer_qq':msg.customer_qq,'mate_name':msg.mate_name,'mate_tel':msg.mate_tel,'add_friend_time':msg.add_friend_time,'pc_time':msg.pc_time,'baby_address':msg.baby_address,'city':msg.city,'county':msg.county,'customer_address':msg.customer_address,'customer_key':msg.customer_key,'marry_day':marry_day,'budget':msg.budget,'consulation_shop':msg.consulation_shop,'reception_name':msg.reception_name,'next_time':next_time,'yjd_action_day':yjd_action_day,'yjd_day':yjd_day,'customer_remark':msg.customer_remark,'track_record':msg.track_record,'is_intostore':intostore,'syjd_day':syjd_day,'order_type':order_type,'service_sta':msg.service_sta,'is_success':success,'orderIds':msg.orderIds,'order_day':order_day,'order_start_time':order_start_time,'yxtx':msg.yxtx,'yxss':msg.yxss,'extx':msg.extx,'exss':msg.exss,'loss_cause':msg.loss_cause,'customer_type':customer_type,'create_time':msg.create_time,'is_fp':fp,'is_loss':loss,'erp_loss':erp_loss,'dj_staff':msg.dj_staff,'sales_staff':msg.sales_staff,'sk_staff':msg.sk_staff,'introduce_staff_name':msg.introduce_staff_name,'introducer_name':msg.introducer_name,'introducer_tel':msg.introducer_tel,'introducer_ordernum':msg.introducer_ordernum,'tel_visit_num':msg.tel_visit_num,'last_trackday':msg.last_trackday,'consultation_type':msg.consultation_type,'customer_cource':msg.customer_cource,'customer_intention':msg.customer_intention,'access_model':msg.access_model,'customer_orderaddress':msg.customer_orderaddress,'customer_area':msg.customer_area,'brandclass':msg.brandclass,'shop_name':msg.shop_name,'add_shop_name':msg.add_shop_name,'op_signinfo':msg.op_signinfo,'is_urgent':urgent,'fp_staff':msg.fp_staff});
                }
            }
        });
    },2000);
}