
//来电时传输的数据
var Number = helper.request.queryString("Number");
var CallID = helper.request.queryString("CallID");
var seartGroup = '';
$(document).ready(function () {
    //获取省
    getProvinceCounty($("#formProvince"), 0, "请选择省")
    getProvinceCounty($("#customerProvince"), 0, "请选择省")
    //获取当前登录人
    getCurrentLoginInformation()
    //来电弹屏
    // laydate.skin('molv'); 
    laydate({
        elem: '#old_startTime',
        event: 'focus'
    });
    laydate({
        elem: '#old_endTime',
        event: 'focus'
    });
    // laydate({
    //     elem: '#con_startTime',
    //     event: 'focus'
    // });
    // laydate({
    //     elem: '#con_endTime',
    //     event: 'focus'
    // });
    
    //弹屏右侧切换效果
    $(".ldtp-cr ul.ld-service li").click(function () {
        $(this).addClass("cr-click").siblings().removeClass("cr-click");
        loadOld();
    });
    $('.pre-add').click(function () {
        var par = $(this).parent().parent();
        par.hide().siblings().show();
    })
    $(".mfhtel").val(Number);
    $(".hidTel").val(Number);
    $(".tel").text(Number);
    $("#zxdh_").val(Number);
    $("#tsdh").val(Number);
    $(".ldtime").text(top.getNowFormatDate());
    $(".thsc").text("00:00");
    $(".hidCallID").val(CallID);
    $(".ldtel").text(Number);
    $("#tsdh").val(Number);
    $(".ldtel1").val(Number); //左侧联系电话
    $("#marketTel").val(Number);//右侧市场部  新增工单电话
    if (Number) {
        //获取电话所属地
        $.getJSON(huayi.config.callcenter_url + 'CallInScreen/GetPhoneLocation', {
            "tel": Number,
            "token": $.cookie("token")
        }, function (result) {
            if (result.state.toLowerCase() == "success") {
                $(".khgsd").text(result.data);
            }
        })
        //获取客户信息
        $.ajax({
            type: "get",
            url: huayi.config.callcenter_url + "Customer/GetCustomerByTel",
            dataType: 'json',
            async: false,
            data: {
                token: $.cookie("token"),
                tel: Number,
            },
            success: function (result) {
                if (result.state.toLowerCase() == "success") {
                    if (result.data != null) {
                        $("#name").val(result.data.F_Name);
                        $("#tel").val(result.data.F_Phone);
                        $("#khid").val(result.data.F_Id);
                        $('.ldname').val(result.data.F_Name); //客户姓名
                        $("#customerSex").val(result.data.F_Sex);
                        $("#specialPetitioners").val((result.data.F_SpecialTag).toString());
                        if (result.data.F_Province) {
                            // $("#shengshi").val(result.data.F_Province + "/" + result.data.F_City); //省份
                            // $('.khprovince').val(result.data.F_Province);
                            // $('.khcity').val(result.data.F_City);
                            $("#customerProvince option:selected").text(result.data.F_Province)
                            $("#customerProvince option:selected").val(result.data.F_Province)
                            $("#customerCity option:selected").text(result.data.F_City)
                            $("#customerCity option:selected").val(result.data.F_City)
                            $("#customerCounty option:selected").text(result.data.F_County)
                            $("#customerCounty option:selected").val(result.data.F_County)
                            $("#customerAddress").val(result.data.F_Address)
                        } else {
                            // $("#shengshi").val('');
                        }
                        $("#formName").val(result.data.F_Name);
                        $("#formTel").val(result.data.F_Phone);
                        $("#formSex").val(result.data.F_Sex)
                        $("#formProvince option:selected").text(result.data.F_Province)
                        $("#formProvince option:selected").val(result.data.F_Province)
                        $("#formCity option:selected").text(result.data.F_City)
                        $("#formCity option:selected").val(result.data.F_City)
                        $("#formCounty option:selected").text(result.data.F_County)
                        $("#formCounty option:selected").val(result.data.F_County)
                        $("#formAddress").val(result.data.F_Address)
                    }
                } else {
                    $('.ldname').val("");
                    // $("#shengshi").val('');
                }
            }
        })
    }
    $('.head-pic .lahei .la-before').show();
    $('.head-pic .lahei .la-after').hide();
    //点击挂断
    $('.head-pic .td-call .take').click(function () {
        //      top.obj.Type = "DropCall";
        //      top.obj.AgentID = $.cookie("zx_user");
        //      top.obj.AgentExten = $.cookie("extno");
        top.obj.Type = "TurnIvr";
        top.obj.IvrName = "MYD";
        top.obj.IvrPos = "1";
        top.Send();
    });
    //点击拉黑事件				
    $('.head-pic .lahei .la-before').click(function () {
        if (!$(".hidTel").val()) {
            layer.confirm('来电号码为空！', {
                btn: ['确定']
            });
            return;
        }
        $("#time-word").val('');
        $('.ldtp-con .hei-list').show();

    })
    //拉黑输入框事件
    $('.hei-list .bacha').click(function () {
        $('.ldtp-con .hei-list').hide();
        $("#time-word").val('');
    })
    var reg = /^\+?[1-9][0-9]*$/;
    $('#bc').click(function () {
        var n = $("#time-word").val();
        var val = $("input[name='time']:checked").val();
        if (n) {
            if (!(reg.test(n))) {
                layer.confirm('请输入整数时间！', {
                    btn: ['确定']
                });
                return;
            }
        } else {
            if (val == '4') {
                n = 0;
            } else {
                layer.confirm('请输入整数时间！', {
                    btn: ['确定']
                });
                return;
            }
        }
        $.post(huayi.config.callcenter_url + 'CallInScreen/AddBlack', {
            tel: $(".hidTel").val(),
            num: n,
            type: val,
            "token": $.cookie("token")
        }, function (result) {
            result = $.parseJSON(result);
            if (result.state.toLowerCase() == "success") {
                layer.msg("拉入黑名单成功");
                $('.la-shichang .blackTime').html(result.data);
                //$('.ldtp-con .hei-list').removeClass('bounceIn');
                //$('.ldtp-con .hei-list').addClass('bounceOutUp');
                $('.ldtp-con .hei-list').hide();
                $('.head-pic .lahei .la-before').hide();
                $('.head-pic .lahei .la-after').show();
                $('.head-pic .lahei .retur').show();
            }
        })
    })
    $('.la-after').click(function () {
        if (!$(".hidTel").val()) {
            layer.confirm('来电号码为空！', {
                btn: ['确定']
            });
            return;
        }

        $("#time-word").val('');
        $('.ldtp-con .hei-list').show();
        $('.ldtp-con .hei-list').removeClass('bounceOutUp');
        $('.ldtp-con .hei-list').addClass('bounceIn');
    })
    $('.head-pic .lahei .retur').click(function () {
        $.getJSON(huayi.config.callcenter_url + 'CallInScreen/DelBlack', {
            tel: $(".hidTel").val(),
            "token": $.cookie("token")
        }, function (result) {
            if (result.state.toLowerCase() == "success") {
                layer.msg("取消黑名单成功");
                $('.head-pic .lahei .retur').hide();
                $('.head-pic .lahei .la-after').hide();
                $('.head-pic .lahei .la-before').show();
            } else {
                layer.msg("取消黑名单失败");
            }
        })
    })
    $(".col-sm-3").mouseleave(function () {
        $(".ztree").parent().hide();
    })
    $('.areaDown').click(function () {
        if ($('.treeList1').css('display') == 'block') {
            $('.treeList1').css('display', 'none')
        } else {
            $('.treeList1').css('display', 'block')
        }
    })
    $('#typeclass').click(function () {
        $('.treeList1').css('display', 'block')
    })
    $('#shengshi').click(function () {
        $('.treeList').css('display', 'block')
    })
    $('.treeList1').mouseleave(function () {
        $(this).css('display', 'none')
    })
    $('.treeList').mouseleave(function () {
        $(this).css('display', 'none')
    })
    $(".orderType").change(function () {
        if ($(".orderType option:selected").text() != "投诉") {
            $(".complainDiv2").show();
            typeSmall =$(".complaintType2").val();
            $(".complainDiv").hide();
        } else {
            $(".complainDiv2").hide();
            $(".complainDiv").show();
            typeSmall =$(".complaintType1").val();
        }
    });
    $(".complaintType2").change(function () {
		typeSmall=$(".complaintType2").val();
    });
    $(".complaintType1").change(function () {
		typeSmall=$(".complaintType1").val();
    });
    //客户资料
    $('.khzl tbody>tr>td input').attr('readonly', true);
    $('.save').hide();
    $('.cancel').hide();
    $('.edit').click(function () {
        $('.save').show();
        $('.cancel').show();
        $(".time-box_flbox").show();
        $("#typeclass1").val($(".countryName").val())
        $('.edit').hide();
        $('.khzl tbody>tr>td input').attr('readonly', false);
        $('.khzl tbody>tr>td input').css('border-bottom', "1px solid #b3b3b3");
        $(".ldlocation").hide();
    })
    $('.cancel').click(function () {
        $('.khzl tbody>tr>td input').attr('readonly', true);
        $('.khzl tbody>tr>td input').css('border', "0");
        $('.save').hide();
        $('.cancel').hide();
        $('.edit').show();
        $(".ldlocation").show();
    })
    //保存客户
    $(".save").click(function () {
        if (!$(".khmc").val()) {
            layer.confirm('请输入客户名称！', {
                btn: ['确定']
            });
            return;
        }
        if (!$(".ldtel1").val()) {
            layer.confirm('请输入客户电话！', {
                btn: ['确定']
            });
            return;
        }
        $.post(huayi.config.callcenter_url + 'Customer/SaveCustomer', {
            id: $("#khid").val(),
            type: 1,
            name: $(".khmc").val(),
            province: $("#customerProvince option:selected").text() === "请选择省" ? "" : $("#customerProvince option:selected").text(),
            city: $("#customerCity option:selected").text() === "请选择市" ? "" : $("#customerCity option:selected").text(),
            country: $("#customerCounty option:selected").text() === "请选择县/区" ? "" : $("#customerCounty option:selected").text(),
            address: $("#customerAddress").val(),
            tel: $(".ldtel1").val(),
            sex: $("#customerSex").val(),
            specialTag: $("#specialPetitioners").val(),
            "token": $.cookie("token")
        }, function (result) {
            result = $.parseJSON(result);
            if (result.state.toLowerCase() == "success") {
                $("#khid").val(result.data);
                $("#tskh").val($(".khmc").val());
                layer.msg("保存成功");
                $('.khzl tbody>tr>td input').css('border', "0");
                $('.save').hide();
                $('.cancel').hide();
                $('.edit').show();
                $("#formName").val($(".khmc").val());//姓名
                $("#formTel").val($(".ldtel1").val());//电话
                $("#formSex").val($("#customerSex").val());//性别
                $("#formProvince option:selected").text($('#customerProvince option:selected').text());//省
                $("#formCity option:selected").text($('#customerCity option:selected').text());//市
                $("#formCounty option:selected").text($('#customerCounty option:selected').text());//县/区
                $("#formAddress").val($('#customerAddress').val());//详细地址
            }
        })
    })
    //获取归属地
    getAreaType();
    //被投诉单位所属办事处
    getComplainedUnitOffice();
    //投诉案件承办人
    getComplaintUndertaker();
    //咨询问题级别
    getQuestionLevel();
    //新建
    $('.customerSubmit').click(function () {
        judgmentFormComplainedUnit();
        saveCustomer();
    });
    //隐藏提交按钮
    $(".customerSubmitRepeat").hide();
    //获取知识库
    loadZSK();
    //知识库查询
    $(".searIcon").click(function () {
        loadZSK();
    })
    //按enter查询知识库
    $('.search').bind('keypress', function (event) {
	  	if (event.keyCode == "13") {
        	loadZSK();
   			return false;
		}
    });
    
    //历史记录查询
    $(".searchbtn").click(function () {
        loadOld();
    })
    //按enter查询历史记录
    $('#old_startTime, #old_endTime').bind('keypress', function (event) {
	  	if (event.keyCode == "13") {
        	loadOld();
   			return false;
		}
	});
});


//获取知识库
function loadZSK() {
	$.getJSON(huayi.config.callcenter_url + 'CallInScreen/GetZSKList', {
		"keywords": $(".search").val(),
		"token": $.cookie("token")
	}, function(result) {
		if(result.state.toLowerCase() == "success") {
			$(".ldcr-bottom .detail-con ul").empty();
			$(result.data).each(function(i, n) {
				var html = '<li>' +
					'   <div class="zhishi-title clearfix">' +
					'	    <a href="javascript:void(0);" >' + n.F_Title + '</a>' +
					'	    <em >' + n.F_CreateOn + '</em>' +
					'   </div>' +
					'   <div class="explancon">' +
					n.F_Content +
					'   </div>' +
					'</li>';
				$(html).appendTo($(".ldcr-bottom .detail-con ul")).find(".zhishi-title").click(function(event) {
					event.stopPropagation();
					if($(this).hasClass("active")) {
						$(this).removeClass("active")
					} else {
						$(".zhishi-title").removeClass("active");
						$(this).addClass("active");
					}
				})
			})
		}
	})
}

//获取历史记录
function loadOld() {
    var type = $(".ldtp-cr ul.ld-service .cr-click").attr("itemtype");
    $(".complain").hide();
    $(".complain").eq(type).show();
    if (type == '2') {
        //先销毁表格
        $('#orderlist').bootstrapTable('destroy');
        //初始化表格,动态从服务器加载数据
        $("#orderlist").bootstrapTable({
            method: "get", //使用get请求到服务器获取数据
            url: huayi.config.callcenter_url + "RegRecords/GetList", //获取数据的Servlet地址
            contentType: 'application/x-www-form-urlencoded',
            striped: true, //表格显示条纹
            pagination: true, //启动分页
            pageSize: 5, //每页显示的记录数
            pageNumber: 1, //当前第几页
            pageList: [5, 10, 50, 100], //记录数可选列表
            search: false, //是否启用查询
            showColumns: false, //显示下拉框勾选要显示的列
            showRefresh: false, //显示刷新按钮
            sidePagination: "server", //表示服务端请求
            //设置为undefined可以获取pageNumber，pageSize，searchText，sortName，sortOrder
            //设置为limit可以获取limit, offset, search, sort, order
            queryParamsType: "undefined",
            queryParams: function queryParams(params) { //设置查询参数
                var param = {
                    token: $.cookie("token"),
                    tel: Number,
					pageindex: params.pageNumber, //页码
					pagesize: params.pageSize, //条数
                };
                return param;
            },
            onLoadSuccess: function() { //加载成功时执行
                //layer.msg("加载成功");
            },
            onLoadError: function() { //加载失败时执行
                //layer.msg("加载数据失败", { time: 1500, icon: 2 });
            }
        });
    } else if (type == '1') {
        //先销毁表格
        $('#oldlist').bootstrapTable('destroy');
        //初始化表格,动态从服务器加载数据
        $("#oldlist").bootstrapTable({
            method: "get", //使用get请求到服务器获取数据
            url: huayi.config.callcenter_url + "CallInScreen/GetOldList", //获取数据的Servlet地址
            contentType: 'application/x-www-form-urlencoded',
            striped: true, //表格显示条纹
            pagination: true, //启动分页
            pageSize: 5, //每页显示的记录数
            pageNumber: 1, //当前第几页
            pageList: [5, 10, 50, 100], //记录数可选列表
            search: false, //是否启用查询
            showColumns: false, //显示下拉框勾选要显示的列
            showRefresh: false, //显示刷新按钮
            sidePagination: "server", //表示服务端请求
            //设置为undefined可以获取pageNumber，pageSize，searchText，sortName，sortOrder
            //设置为limit可以获取limit, offset, search, sort, order
            queryParamsType: "undefined",
            queryParams: function queryParams(params) { //设置查询参数
                var param = {
                    page: params.pageNumber,
                    pagesize: params.pageSize,
                    tel: $(".hidTel").val(),
                    starttime: $("#old_startTime").val(),
                    endtime: $("#old_endTime").val(),
                    token: $.cookie("token")

                };
                return param;
            },
            onLoadSuccess: function() { //加载成功时执行
                //layer.msg("加载成功");
            },
            onLoadError: function() { //加载失败时执行
                //layer.msg("加载数据失败", { time: 1500, icon: 2 });
            }
        });
    } else if (type == '3') {
        // window.onload = function () {
            // window.frames["relatedCasesFrames"].postMessage({mobile: 15512102563}, 'http://222.143.48.99:82')
            window.frames["relatedCasesFrames"].postMessage({mobile: Number}, 'http://222.143.48.99:82')
        // }
    } else if (type == '4') {
        // window.onload = function () {
            window.frames["serviceDocumentFrames"].postMessage({mobile: Number}, 'http://222.143.48.99:82')
        // }
    }
}

//格式化历史记录内处理方式
function formatterDealType(val, row) {
	//处理方式0:IVR处理1骚扰电话2自助服务3转值班电话4留言5呼损6人工处理
	var str = '-';
	switch(val) {
		case 0:
			str = 'IVR处理';
			break;
		case 1:
			str = '骚扰电话';
			break;
		case 2:
			str = '自助服务';
			break;
		case 3:
			str = '转值班电话';
			break;
		case 4:
			str = '留言';
			break;
		case 5:
			str = '呼损';
			break;
		case 6:
			str = '人工处理';
			break;
	}
	return str;
}

// 工单编号
function View(val, row) {
    return '<div class="imgs" ><a class="view" onclick= btn_register_details("' + row.F_ID + '") >' + val + '</a></div>';
}

//登记类型
function formatterRegisterType(val, row) {
    var formatterRegisterTypeArr = ["", "咨询", "投诉", "求助", "其他"]
    return formatterRegisterTypeArr[val]
}

function btn_register_details(id) {
    layer.open({
        type: 2,
        title: '登记详情',
        maxmin: true, //开启最大化最小化按钮
        area: ['80%', '80%'],
        content: '../registrationManagement/registrationList/detail.html?ids=' + id
    });
}

function GetCallState(val) {
	if(val == '1') {
		return '已接通';
	} else {
		return '未接通';
	}
}

//音频
function setCode(val) {
	if(val) {
		return '<div class="imgs" style="cursor: pointer;">' +
			'<img src="../img/vice.png" alt="" onclick= ck(this) item="' + val + '" />' +
			'</div>';
	} else {
		return '';
	}
}
//录音
function ck(val) {
	var path = $(val).attr("item");
	$(".t-shade").addClass("cx");
	$(".gjss").removeClass("cx");
	$(".xqlb").addClass("cx");
	$(".Ly_box").empty();
	$('<audio style="width: 100%;"class=" " src="' + path + '" loop="loop" controls="controls" ></audio>').appendTo(".Ly_box");
}

//关闭录音
$(".setwin").click(function () {
    $(".t-shade").removeClass("cx");
    $('audio')[0].pause();
});

// 获取归属地
function getAreaType() {
    $.get(huayi.config.callcenter_url + 'Area/GetAreaList', {
        "token": $.cookie("token"),
    }, function(result) {
        result = $.parseJSON(result);

        $.fn.zTree.init($("#TreeDemo"), setting, result.data); //实例化树形图
        $.fn.zTree.init($("#TreeDemo1"), setting1, result.data); //实例化树形图
    });
}

var setting = {
    data: {
        key: {
            name: "F_AreaName"
        },
        simpleData: {
            enable: true,
            idKey: "F_Id",
            pIdKey: "F_ParentId",
            rootPId: 0
        }
    },
    callback: {
        onClick: changeTreeClick
    }
}
var setting1 = {
    data: {
        key: {
            name: "F_AreaName"
        },
        simpleData: {
            enable: true,
            idKey: "F_Id",
            pIdKey: "F_ParentId",
            rootPId: 0
        }
    },
    callback: {
        onClick: changeTreeClick1
    }
}
function changeTreeClick(event, treeId, treeNode) {

    var areaParent = treeNode.getPath();
    if (areaParent[1]) {
        areaParent1 = areaParent[0].F_AreaName
        areaParent2 = areaParent[1].F_AreaName

        // $('#shengshi').val(areaParent1 + "/" + areaParent2);
        $('#typeclass').val(areaParent1 + "/" + areaParent2);
        $('.inps3').val(areaParent2);

        // $('.khprovince').val(areaParent1);
        // $('.khcity').val(areaParent2);

    } else {
        layer.msg("请选择最下级菜单");
    }
    $('.addTree').hide();
};
function changeTreeClick1(event, treeId, treeNode) {

    var areaParent = treeNode.getPath();
    if (areaParent[1]) {
        areaParent1 = areaParent[0].F_AreaName
        areaParent2 = areaParent[1].F_AreaName

        $('#typeclass').val(areaParent1 + "/" + areaParent2);
        $('.inps3').val(areaParent2);
    } else {
        layer.msg("请选择最下级菜单");
    }
    $('.addTree1').hide();

};
//清空
function Clean() {
    $('#formName').val('');
    $('#formTel').val('');
    $('#formSex').val('');
    $('#formProvince').val('');
    $('#formCity').val('');
    $('#formCounty').val('');
    $('#formAddress').val('');
    $("#formRegistrationType input[name='type'][value='1']").prop("checked","checked"); //工单类型
    $('#formComplainedUnit').val('');
    $('#formRegistrationContent').val('');
    $('#formRegistrationRemark').val('');
    $('#formComplainedUnitOffice').val('');
    $('#formComplaintUndertaker').val('');
    $('#formQuestionLevel').val('');
    $('#formQuestionType').val('');
    $('#formQuestionType').val('');
    $('#formCitizenClassification').val('农民工');
    $('#formPutRecord input[name="type"][value="是"]').prop('checked', 'checked')
}

//保存
function saveCustomer() {
    // if (!$("#khid").val()) {
    //     layer.confirm('请先保存用户档案！', {
    //         btn: ['确定']
    //     });
    //     return;
    // }
    $.ajax({
        type: "post",
        url: huayi.config.callcenter_url + "RegRecords/Save",
        dataType: 'json',
        async: true,
        beforeSend: function() { //触发ajax请求开始时执行
            $('.customerSubmit').attr("disabled", true);
            $('.customerSubmit').text('保存中...');
        },
        data: {
            token: $.cookie("token"),
            cusid: $("#khid").val(), //档案id
            direction: 0, // 0来电，1去电
            type: $('#formRegistrationType input[name="type"]:checked').val(), //登记类型
            userName: $("#formName").val(), //姓名
            userPhone: $("#formTel").val(), //电话
            userSex: $("#formSex").val(), //性别
            userProvince: $("#formProvince option:selected").text(), //省
            userCity: $("#formCity option:selected").text(), //市
            userArea: $("#formCounty option:selected").text(), //县/区
            userAddress: $("#formAddress").val(), //详细地址
            content: $("#formRegistrationContent").val(), //登记内容/投诉事项
            remark: $("#formRegistrationRemark").val(), //备注
            tel: Number,
            callid: CallID,
            unit: $("#formComplainedUnit").val(), //被投诉单位
            unitOffice: $("#formComplainedUnitOffice").val(), //单位办事处
            caseParty: $("#formComplaintUndertaker option:selected").text(), //投诉案件承办人
            CasePartyId: $("#formComplaintUndertaker").val(), //投诉案件承办人id
            citizensType: $("#formCitizenClassification").val(), //市民分类
            putRecord: $("#formPutRecord input[name='putRecord']:checked").val(), //是否立案
            zXZType: seartGroup, //坐席组类型
            problemType:  $("#formQuestionLevel").val(), //问题类型
            ProblemTypeB: $("#formQuestionType").val(), //二级问题类型B
        },
        success: function (data) {
            if (data.state.toLowerCase() == 'success') {
                layer.msg("保存成功！");
                Clean();
                $('.customerSubmit').attr("disabled", false);
	            $('.customerSubmit').text('新建');
            } else {
            	$('.customerSubmit').attr("disabled", false);
	            $('.customerSubmit').text('新建');
            }
        }
    });
}

//获取当前登陆人信息
function getCurrentLoginInformation(){
	$.ajax({
		type: "get",
		url: huayi.config.callcenter_url + 'UserAccount/GetNowUser',
		async: true,
		dataType: 'json',
		data: {
			"token": $.cookie("token")
		},
		success: function(data) {
            seartGroup = data.data.user.F_SeartGroup;
            currentLogInAgentGroup();
		}
	});
}

//当前登陆人判断字段
function currentLogInAgentGroup() {
    if (seartGroup === "劳动仲裁智慧话务") {
        $(".citizenClassificationWrapper").hide();
        $(".putRecordWrapper").hide();
    } else if (seartGroup === "劳动监察智慧话务") {
        $(".citizenClassificationWrapper").show();
        $(".putRecordWrapper").hide();
    } else if (seartGroup === "工伤智慧话务") {
        $(".citizenClassificationWrapper").hide();
        $(".putRecordWrapper").show();
    } else {
        $(".citizenClassificationWrapper").hide();
        $(".putRecordWrapper").hide();
    }
}

/* 
    获取 省 市 县/区
    parameter:
        pid     int
*/
function getProvinceCounty(element, pid, text) {
    element.empty();
    element.append('<option value="">'+ text +'</option>');
	$.getJSON(huayi.config.callcenter_url + "RegionCategory/GetCountyList", {
		"token": $.cookie("token"),
		pid: pid,
	}, function (data) {
		if (data.state.toLowerCase() == "success") {
			var content = data.data;
			$(content).each(function (i, n) {
            	element.append("<option value='" + n.F_RegionId + "'>" + n.F_RegionName + "</option>");
			})
		}
	})
}

$("#customerProvince").on('change',function(){
	getProvinceCounty($("#customerCity"), $("#customerProvince").val(), "请选择市");
});
$("#customerCity").on('change',function(){
	getProvinceCounty($("#customerCounty"), $("#customerCity").val(), "请选择县/区");
});

$("#formProvince").on('change',function(){
	getProvinceCounty($("#formCity"), $("#formProvince").val(), "请选择市");
});
$("#formCity").on('change',function(){
	getProvinceCounty($("#formCounty"), $("#formCity").val(), "请选择县/区");
});

//被投诉单位所属办事处
function getComplainedUnitOffice() {
    $("#formComplainedUnitOffice").empty();
	$("#formComplainedUnitOffice").append("<option value='' selected='selected'>请选择</option>");
    $.ajax({
        type: "get",
        url: huayi.config.callcenter_url + "Dictionary/GetDicValueListByFlag",
        dataType: 'json',
        async: true,
        data: {
            token: $.cookie("token"),
            flag: "BTSDWSSBSC",
        },
        success: function(data) {
            var Count = data.data;
            $(Count).each(function(i, n) {
                $('<option value="' + n.F_Name + '">' + n.F_Name + '</option>').appendTo($("#formComplainedUnitOffice"));
            })
        }
    });
}

//投诉案件承办人
function getComplaintUndertaker () {
    $("#formComplaintUndertaker").empty();
	$("#formComplaintUndertaker").append("<option value='' selected='selected'>请选择</option>");
    $.ajax({
        type: "get",
        url: huayi.config.callcenter_url + "UserAccount/GetSeatList",
        dataType: 'json',
        async: true,
        data: {
            token: $.cookie("token"),
        },
        success: function(data) {
            var Count = data.data;
            $(Count).each(function(i, n) {
                $('<option value="' + n.F_UserId + '">' + n.F_UserName + '</option>').appendTo($("#formComplaintUndertaker"));
            })
        }
    });
}

//咨询问题级别
function getQuestionLevel() {
    $("#formQuestionLevel").empty();
	$("#formQuestionLevel").append("<option value='' selected='selected'>请选择</option>");
    $.ajax({
        type: "get",
        url: huayi.config.callcenter_url + "Dictionary/GetDicValueListByFlag",
        dataType: 'json',
        async: true,
        data: {
            token: $.cookie("token"),
            flag: "ZXWTJB"
        },
        success: function(data) {
            var Count = data.data;
            $(Count).each(function(i, n) {
                $('<option value="' + n.F_Name + '">' + n.F_Name + '</option>').appendTo($("#formQuestionLevel"));
            })
        }
    });
}

// 重要级别原因(Ⅰ级)
function getQuestionTypeOne() {
	$("#formQuestionType").empty();
	$("#formQuestionType").append("<option value='' selected='selected'>请选择</option>");
    $.ajax({
        type: "get",
        url: huayi.config.callcenter_url + "Dictionary/GetDicValueListByFlag",
        dataType: 'json',
        async: true,
        data: {
            token: $.cookie("token"),
            flag: "ZXWTYJFL"
        },
        success: function(data) {
            var Count = data.data;
            $(Count).each(function(i, n) {
                $('<option value="' + n.F_Name + '">' + n.F_Name + '</option>').appendTo($("#formQuestionType"));
            })
        }
    });
}

// 重要级别原因(Ⅱ级)
function getQuestionTypeTwo() {
	$("#formQuestionType").empty();
	$("#formQuestionType").append("<option value='' selected='selected'>请选择</option>");
    $.ajax({
        type: "get",
        url: huayi.config.callcenter_url + "Dictionary/GetDicValueListByFlag",
        dataType: 'json',
        async: true,
        data: {
            token: $.cookie("token"),
            flag: "ZXWTEJFL"
        },
        success: function(data) {
            var Count = data.data;
            $(Count).each(function(i, n) {
                $('<option value="' + n.F_Name + '">' + n.F_Name + '</option>').appendTo($("#formQuestionType"));
            })
        }
    });
}

// 重要级别显示原因
$('#formQuestionLevel').on('change',function(){
	if ($('#formQuestionLevel').val() === '一级分类') {
		$('#formQuestionType').val('');
		getQuestionTypeOne();
	} else if ($('#formQuestionLevel').val() === '二级分类') {
		$('#formQuestionType').val('');
		getQuestionTypeTwo();
	} else {
		$('#formQuestionType').val('');
	}
})

//被投诉单位
function darptSearch() {
    $(".selDpart1").css('display', 'block');
    getFormComplainedUnit();
}

$("#sponsor").on('click', 'li', function() {
	$(".selDpart1").css('display', 'none');
	$("#formComplainedUnit").val($(this).html());
})

function getFormComplainedUnit() {
	$("#sponsor").empty();
    $.ajax({
        type: "get",
        url: huayi.config.callcenter_url + "Docking/SendGetCompanylist",
        dataType: 'json',
        async: true,
        data: {
            token: $.cookie("token"),
            name: $("#formComplainedUnit").val(),
            pageno: 1,
            pagesize: 100,
        },
        success: function(data) {
            if (data.state.toLowerCase() == "success") {
                var content = data.data.records;
                if (content.length === 0) {
                	$(".selDpart1").css('display', 'none');
                } else {
                    $(content).each(function (i, n) {
                        $("<li index='" + n.name + "'>" + n.name + "</li>").appendTo("#sponsor");
                    })
                }
            }
        }
    });
}

//添加被投诉单位
function addFormComplainedUnit() {
    $.ajax({
        type: "get",
        url: huayi.config.callcenter_url + "Docking/SendAddCompany",
        dataType: 'json',
        async: true,
        data: {
            token: $.cookie("token"),
            name: $("#formComplainedUnit").val(),
        },
        success: function(data) {
            if (data.state.toLowerCase() == "success") {
            } else {
                layer.msg("投诉单位添加失败");
            }
        }
    });
}

//判断被投诉单位
function judgmentFormComplainedUnit() {
    $.ajax({
        type: "get",
        url: huayi.config.callcenter_url + "Docking/SendGetCompanylist",
        dataType: 'json',
        async: true,
        data: {
            token: $.cookie("token"),
            name: $("#formComplainedUnit").val(),
            pageno: 1,
            pagesize: 100,
        },
        success: function(data) {
            if (data.state.toLowerCase() == "success") {
                var content = data.data.records;
                if ( content.length === 0 ) {
                    addFormComplainedUnit()
                }
            }
        }
    });
}


// 快捷回复
var quickReplyFloatSign = 1;
$(".quickReplyButton").click(function(){
    if (quickReplyFloatSign === 1) {
        console.log("if")
        $(".quickReplyFloat").show()
        quickReplyFloatSign = 0; 
        quickReplyFloatInitTable()
    } else if (quickReplyFloatSign === 0) {
        console.log("else")
        $(".quickReplyFloat").hide()
        quickReplyFloatSign = 1; 
    }
})

$(".quickReplyFloatTab ul li").click(function () {
    $(this).addClass("quickReplyFloatTabActivity").siblings().removeClass("quickReplyFloatTabActivity");
    quickReplyFloatInitTable()
});

function quickReplyFloatInitTable() {
    var isorPersonType = $(".quickReplyFloatTab ul .quickReplyFloatTabActivity").attr("itemtype");
	//先销毁表格
	$("#quickReplyFloatTable").bootstrapTable('destroy');
	//初始化表格,动态从服务器加载数据
	$("#quickReplyFloatTable").bootstrapTable({
		method: "get", //使用get请求到服务器获取数据
		url: huayi.config.callcenter_url + "AccessLog/GetHightFrequencyList", //获取数据的Servlet地址
		contentType: 'application/x-www-form-urlencoded',
		striped: true, //表格显示条纹
		pagination: true, //启动分页
		pageSize: 5, //每页显示的记录数
		pageNumber: 1, //当前第几页
		pageList: [5, 10, 15], //记录数可选列表
		search: false, //是否启用查询
		showColumns: false, //显示下拉框勾选要显示的列
		showRefresh: false, //显示刷新按钮
		sidePagination: "server", //表示服务端请求
		//设置为undefined可以获取pageNumber，pageSize，searchText，sortName，sortOrder
		//设置为limit可以获取limit, offset, search, sort, order
		queryParamsType: "undefined",
		queryParams: function queryParams(params) { //设置查询参数
			var param = {
				page: params.pageNumber,
				pagesize: params.pageSize,
				token: $.cookie("token"),
				pid: "",
                keywords: "",
                F_isorPerson: isorPersonType,
			};
			return param;
		},
		onLoadSuccess: function() { //加载成功时执行
			//layer.msg("加载成功");
		},
		onLoadError: function() { //加载失败时执行
			//layer.msg("加载数据失败", { time: 1500, icon: 2 });
		}
	});
}

//编号
function setCode(val, row, index) {
	return index + 1;
}

function formatterTitle(val, row){
	if(val.length > 15){
		val = val.substring(0,15) + "...";
	}
	return '<div onclick="btn_knowledge_base_detail('+ row.F_RepositoryId +')" class="knowledgeBaseDetail">' + val + '</div>'
}

function oper(val, row) {
	if(val.length > 20){
		val = val.substring(0,20) + "...";
	}
	return '<div onclick="btn_knowledge_base_detail('+ row.F_RepositoryId +')" class="knowledgeBaseDetail">' + val + '</div>'
}

function formatterKey(val, row) {
	if(val.length > 10){
		val = val.substring(0,10) + "...";
	}
	return val; 
}

//点击标题 内容查看详情
function btn_knowledge_base_detail(seeid) {
	layer.open({
		type: 2,
		title: '查看知识库',
		shadeClose: true, //是否开启点击遮罩关闭
		shade: 0.4, //遮罩
		maxmin: true, //开启最大化最小化按钮
		id: 'LAY_layuipro', //防止重复弹出
		moveType: 1, //拖拽类型 默认的拖拽风格正如你所见到的，会有个过度的透明框。但是如果你不喜欢，你可以设定moveType: 1切换到传统的拖拽模式
		moveOut: true, //拖拽到窗口外
		//resize: true,//是否允许拉伸
		area: ['70%', '70%'],
		content: '../zhiShiKu/addModel.html?changeGetid=' + seeid + ''
	});
}
