var id; //当前节点id
var pid; //当前父节点ID
$(document).ready(function () {
    //保存
    $('.customerSubmit').click(function() {
        saveCustomer();
    });
    //获取部门
    getDepartment();
    //获取省份
    getProvince($("#source"));
})

//下拉框
$('.inps').focus(function() {
	$(this).siblings('.add-tree').css('display', 'block');
})

$('.drop-down').click(function() {
	var dropDown = $(this).siblings('.add-tree');
	if(dropDown.css('display') == 'block') {
		dropDown.css('display', 'none')
	} else {
		dropDown.css('display', 'block')
	}
})

$('.add-tree').mouseleave(function() {
	$(this).css('display', 'none')
})

//获取所属部门
var setting = {
	data: {
		key: {
			name: "text"
		},
		simpleData: {
			enable: true,
			idKey: "id",
			rootPId: 0
		}
	},
	callback: {
		onClick: ztreeDep
	}
};

var departmentId; //部门id
var departmentName; //部门name
function ztreeDep(event, treeId, treeNode) {
	departmentId = treeNode.id;
	departmentName = treeNode.text;
	$('.inps2').val(departmentName);
};

//获取部门
function getDepartment() {
	$.get(huayi.config.callcenter_url + "Department/GetDeptList", {
		"token": $.cookie("token"),
		"pid": "",
	}, function(result) {
		result = $.parseJSON(result);
		$.fn.zTree.init($("#departmentTree"), setting, result.data); //实例化树形图
	});
}

/*
 * 省
 * 市
 * 区/县
 */

 //省
function getProvince(obj) {
	obj.empty();
	obj.append('<option selected="selected" value="">请选择</option>');
	$.getJSON(huayi.config.callcenter_url + "RegionCategory/GetCountyList", {
		"token": $.cookie("token"),
		pid: 0,
	}, function (data) {
		if (data.state.toLowerCase() == "success") {
			var content = data.data;                 
			$(content).each(function (i, n) {
				$("<option value='" + n.F_RegionId + "'>" + n.F_RegionName + "</option>").appendTo(obj);                       
			})
		}
	})
}
//市
function getCity(obj) {
	obj.empty();
	obj.append('<option selected="selected" value="">请选择</option>');
	$.getJSON(huayi.config.callcenter_url + "RegionCategory/GetCountyList", {
		"token": $.cookie("token"),
		pid:$('#source').val(),
	}, function (data) {
		if (data.state.toLowerCase() == "success") {
			var content = data.data;
			$(content).each(function (i, n) {
				$("<option value='" + n.F_RegionId + "'>" + n.F_RegionName + "</option>").appendTo(obj);					
			})
		}
		
	})
}
//区/县
function getCounty(obj) {
	obj.empty();
	obj.append('<option selected="selected" value="">请选择</option>');
	$.getJSON(huayi.config.callcenter_url + "RegionCategory/GetCountyList", {
		"token": $.cookie("token"),
		pid:$('#type').val(),
	}, function (data) {
		if (data.state.toLowerCase() == "success") {
			var content = data.data;
			$(content).each(function (i, n) {
				$("<option value='" + n.F_RegionId + "'>" + n.F_RegionName + "</option>").appendTo(obj);
			})
		}
	})
}

//通过省获取市
$('#source').on('change',function(){
	getCity($("#type"));
});
//通过市获取区/县
$('#type').on('change',function(){
	getCounty($("#keyid"));
}); 

// 地址（省+市+区/县）
function detailedAddress() {
	if($('#source').val() === ""){
		var province = '';
	} else {
		var province = $('#source').find("option:selected").text()
	}
	if($('#type').val() === ""){
		var city = '';
	} else {
		var city = $('#type').find("option:selected").text()
	}
	if($('#keyid').val() === ""){
		var county = '';
	} else {
		var county = $('#keyid').find("option:selected").text()
	}
	var address = province + '-' + city + '-' + county;
	return address;
}


//保存
function saveCustomer() {
	if(!$('#addUserName').val()) {
		layer.confirm('请输入用户姓名！', {
			icon: 2,
			btn: ['确定']
		});
		return;
	}
	if(!$('#addMobile').val()) {
		layer.confirm('请输入手机！', {
			icon: 2,
			btn: ['确定']
		});
		return;
	}
	if(departmentId == '' || departmentId == undefined) {
		layer.confirm('请选择部门！', {
			icon: 2,
			btn: ['确定']
		});
		return;
	}
	console.log('departmentId',departmentId)
    $.ajax({
        type: "post",
        url: huayi.config.callcenter_url + "AddressBook/Add",
        dataType: 'json',
        async: true,
        beforeSend: function() { //触发ajax请求开始时执行
            $('.customerSubmit').attr("disabled", true);
            $('.customerSubmit').text('确定中...');
        },
        data: {
            token: $.cookie("token"),
            F_Name: $("#addUserName").val(), //用户姓名
            F_Sex: $("#addSex").val(), //性别
            F_Address: detailedAddress(), //地址
            F_Telephone: $("#addTelephone").val(), //内线电话
            F_Mobile: $("#addMobile").val(), //手机
            F_ElseMobile: $("#addElseMobile").val(), //其他号码
//          F_Departmentid: $("#addDepartmentid").val(), //部门ID
            F_Departmentid: departmentId, //部门ID
            F_Position: $("#addPosition").val(), //职位
            F_Note: $("#addNote").val(), //备注
        },
        success: function(data) {
            if (data.state.toLowerCase() == 'success') {
                $('.customerSubmit').attr("disabled", false);
	            $('.customerSubmit').text('确定');
            	var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
				parent.layer.close(index); //再执行关闭
				parent.layer.msg("保存成功！");
				parent.initTable();
            } else {
            	$('.customerSubmit').attr("disabled", false);
	            $('.customerSubmit').text('确定');
            }
        }
    });
}