var table = $('#table1');
var token = $.cookie("token");

$(document).ready(function(){
    getProvinceCounty($("#searchProvince"), 0, "请选择省")
});

laydate.render({
    elem: '#searchTime',
    type: 'date',
    theme: '#1e90ff',
    range: '~',
});


$('.search').click(function () {
    initTable(token);
})

//添加
$('.add').click(function () {
    layer.open({
        type: 2,
        title: '添加客户信息',
        maxmin: true, //开启最大化最小化按钮
        area: ['80%', '80%'],
        content: 'addOrEdit.html'
    });
})

//修改
var did;
$('.change').click(function () {
    var ids = $.map(table.bootstrapTable('getSelections'), function (row) {
        return row.F_Id;
    });
    did = ids.toString();
    if (ids.length != 1) {
        layer.confirm('请选择一行进行修改！', {
            btn: ['确定']
        });
        return;
    } else {
        layer.open({
            type: 2,
            title: '修改客户信息',
            maxmin: true, //开启最大化最小化按钮
            area: ['80%', '80%'],
            content: 'addOrEdit.html?ids=' + did
        });
    }
})

//删除
var delid;
$('.del').click(function () {
    var ids = $.map(table.bootstrapTable('getSelections'), function (row) {
        return row.F_Id;
    });
    delid = ids;
    if (ids.length <= 0) {
        layer.confirm('请选择要删除的行！', {
            btn: ['确定']
        });
        return;
    } else {
        var laye = layer.confirm('您确定要删除吗？', {
            btn: ['确定', '取消'] //可以无限个按钮
        }, function () {
            //按钮【按钮一】的回调
            $.ajax({
                type: "post",
                url: huayi.config.callcenter_url + "Customer/DelCustomer",
                async: true,
                dataType: "json",
                data: {
                    token: token,
                    ids: delid
                },
                success: function (data) {
                    if (data.state.toLowerCase() == 'success') {
                        layer.msg("删除成功！");
                        table.bootstrapTable('refresh');
                    }
                }
            });
        }, function (index) {
            //按钮【按钮二】的回调
            layer.close(laye)
        });
    }
})

//列表
initTable(token);
function initTable(token) {
    //先销毁表格
    table.bootstrapTable('destroy');
    //初始化表格,动态从服务器加载数据
    table.bootstrapTable({
        method: "get", //使用get请求到服务器获取数据
        url: huayi.config.callcenter_url + "Customer/GetList", //获取数据的Servlet地址
        contentType: 'application/x-www-form-urlencoded',
        //			url: "kehu.json", //获取数据的Servlet地址
        striped: true, //表格显示条纹
        pagination: true, //启动分页
        pageSize: 10, //每页显示的记录数
        pageNumber: 1, //当前第几页
        pageList: [10, 15, 20, 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: token,
                key: $("#searchKeyword").val().replace(/\s+/g, ""), //关键字
                prov: $("#searchProvince option:selected").text() == "请选择省" ? "" : $("#searchProvince option:selected").text(), //省
                city: $("#searchCity option:selected").text() == "请选择市" ? "" : $("#searchCity option:selected").text(), //城市
                country: $("#searchCounty option:selected").text() == "请选择县/区" ? "" : $("#searchCounty option:selected").text(), //县区
                starttime: $('#searchTime').val() ? $('#searchTime').val().split('~')[0]:"", //开始时间
                endtime: $('#searchTime').val() ? $('#searchTime').val().split('~')[1]:"", //结束时间
                pageindex: params.pageNumber,
                pagesize: params.pageSize,
                isdc: 0, //是否导出 
            };
            return param;
        },
        onLoadSuccess: function () { //加载成功时执行
            //layer.msg("加载成功");
        },
        onLoadError: function () { //加载失败时执行
            //layer.msg("加载数据失败", { time: 1500, icon: 2 });
        }
    });
}

function formatterSpecialTag(val,  row) {
    var specialTagArr = ['否', '是'];
    return specialTagArr[val]
}

//导出
$("#exportButton").click(function() {
    var key = $("#searchKeyword").val().replace(/\s+/g, ""); //关键字
    var prov = $("#searchProvince option:selected").text() == "请选择省" ? "" : $("#searchProvince option:selected").text(); //省
    var city = $("#searchCity option:selected").text() == "请选择市" ? "" : $("#searchCity option:selected").text(); //城市
    var country = $("#searchCounty option:selected").text() == "请选择县/区" ? "" : $("#searchCounty option:selected").text(); //县区
    var starttime = $('#searchTime').val() ? $('#searchTime').val().split('~')[0]:""; //开始时间
    var endtime = $('#searchTime').val() ? $('#searchTime').val().split('~')[1]:""; //结束时间
    var isdc = 1;

    window.location.href = huayi.config.callcenter_url + "Customer/GetList?token"+ token + "&key=" + key + "&prov=" + prov + "&city=" + city + "&country=" + country + "&starttime=" + starttime + "&endtime=" + endtime + "&isdc=" + isdc;
})

//上传文件
$("#btndr").click(function () {
    $("#upFile").trigger("click");
})
$("#upFile").change(function () {
    upload();
})

function ExcelMod() {
	window.location.href ='../../commonTpl/客户列表.xls';
}

//上传文件
function upload() {
    if (document.getElementById("upFile").files.length > 0) {
        var formData = new FormData();
        formData.append("upFile", document.getElementById("upFile").files[0]);
        formData.append("type", 1);
        formData.append("token", $.cookie("token"));
        $.ajax({
            url: huayi.config.callcenter_url + "Customer/ImportExcel",
            type: "POST",
            data: formData,
            contentType: false,
            processData: false,
            success: function (result) {
                document.getElementById("upFile").outerHTML = document.getElementById("upFile").outerHTML;
                $("#upFile").change(function () {
                    upload();
                });
                var r = $.parseJSON(result);
                if (r.state.toLowerCase() == "success") {
                	debugger
                	layer.msg("导入成功");
                	initTable(token);
                }
            }
        });
    } else {
        layer.confirm('请上传文件！', {
            btn: ['确定']
        });
    }
}
//按enter搜索
document.onkeydown = function (e) { // 回车提交表单
    var theEvent = window.event || e;
    var code = theEvent.keyCode || theEvent.which || theEvent.charCode;
    if (code == 13) {
    	initTable(token);
    }
}

/* 
    获取 省 市 县/区
    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>");
			})
		}
	})
}

$("#searchProvince").on('change',function(){
	getProvinceCounty($("#searchCity"), $("#searchProvince").val(), "请选择市");
});
$("#searchCity").on('change',function(){
	getProvinceCounty($("#searchCounty"), $("#searchCity").val(), "请选择县/区");
});

// 按回车搜索
document.onkeydown = function (e) {
    var theEvent = window.event || e;
    var code = theEvent.keyCode || theEvent.which || theEvent.charCode;
    if (code == 13) {
        initTable(token);
    }
}