/*2014-05-30 add by yb
 * describe:系统用户信息管理
 * userType 1-admin 2-系统管理员 3-校区管理员 4-普通管理员
 */
$(function(){
	var ERROR_OK = 200;
	var contextPath=$("#contextPath").val();
	var list = [];

    var zTreeObj = null;
    var setting = {
        view : {
            dblClickExpand : false,
            showLine : false,
            showIcon: false
        },
        check : {
            enable : true,
            chkStyle: "radio",  //单选框
            radioType: "all"   //对所有节点设置单选
        },
        data : {
            simpleData : {
                enable : true
            }
        },
        callback : {
        }
    };

	layui.use('layer', function(){
		   layer = layui.layer;  
	});
	var tpl = {
		positionTpl: "<option value=''>请选择职位</option>\
				<%for(var i=0;i<data.length;i++){%>\
					<option value='<%=data[i].id%>'><%=data[i].name%></option> 	 \
				<%}%>" ,
		choosePersonTpl: '<div class="dialog-wp">\
					<div class="mask"></div>\
					<div class="dialog dialog-choose-con">\
						<div class="title-wp">\
							<span>添加系统角色</span>\
							<span class="close-btn"></button>\
						</div>\
						<div class="dialog-choose-wp">\
							<div class="choose-person-wp clearfloat">\
								<div class="choose-person-left">\
									<div class="person-list">\
										<% for(var i=0;i<personList.length;i++){%>\
											<div class="person-item <%if(i==0){%> active<%}%>" data-type="<%=personList[i].dataType%>" data-id="<%=personList[i].id%>" data-name="<%=personList[i].name%>"><%=personList[i].name%></div>\
										<%} %>\
									</div>\
								</div>\
								<div class="choose-person-right">\
									<% if(roleList.length>0){%>\
										<div class="choose-all-wp clearfloat">\
											<div class="radio-wp choose-all" style="float: left" data-type="0">\
												<span class="radio-input">\
													<input type="radio" id="indate"  class="radio-item" name="date" />\
													<span class="radio-inner"></span>\
												</span>		\
												<label class="radio-con" for="indate">全选</label>\
											</div>\
											<div class="radio-wp no-choose-all" style="float: left"  data-type="1">\
												<span class="radio-input">\
													<input type="radio" id="outdate"  class="radio-item" name="date" />\
													<span class="radio-inner"></span>\
												</span>		\
												<label class="radio-con" for="outdate">全不选</label>\
											</div>\
										</div>	\
										<% for(var j=0;j<roleList.length;j++){%>\
											<div class="respons-item" data-id="<%=roleList[j].id%>" data-name="<%=roleList[j].name%>"><%=roleList[j].name%><%if(type==1){%> 楼<%}%></div>\
										<%}%>\
									<%}else{%>\
										<div class="no-respons">该角色无可选项，点击“确认”直接添加即可</div>\
									<%}%>\
								</div>\
							</div>\
							<div class="choose-person-btns">\
								<button class="btn-red choose-person-sure-btn">确认</button>\
							</div>\
						</div>\
					</div>\
				</div>	',		
		roleTpl: '<% if(roleList.length>0){%>\
							<div class="choose-all-wp clearfloat">\
								<div class="radio-wp choose-all" style="float: left"  data-type="0">\
									<span class="radio-input">\
										<input type="radio" id="indate"  class="radio-item" name="date" />\
										<span class="radio-inner"></span>\
									</span>		\
									<label class="radio-con" for="indate">全选</label>\
								</div>\
								<div class="radio-wp no-choose-all" style="float: left"  data-type="1">\
									<span class="radio-input">\
										<input type="radio" id="outdate"  class="radio-item" name="date" />\
										<span class="radio-inner"></span>\
									</span>		\
									<label class="radio-con" for="outdate">全不选</label>\
								</div>\
							</div>	\
							<% for(var j=0;j<roleList.length;j++){%>\
							<div class="respons-item" data-id="<%=roleList[j].id%>" data-name="<%=roleList[j].name%>"><%=roleList[j].name%><%if(type==1){%>楼<%}%></div>\
						<%}%>\
						<%}else{%>\
							<div class="no-respons">该角色无可选项，点击“确认”直接添加即可</div>\
						<%}%>',
		roleItemTpl : '<% for(i=0;i<list.length;i++){%>\
							<div class="role-line">\
								<div class="role-name"><%=list[i].name%></div>\
								<div class="role-charge">负责<%if(list[i].dataType == 1){%>楼层<%}else if(list[i].dataType == 2){%>维修类型<%}%>：\
									<%if(list[i].dataType == 1){%>\
										<% for(var j=0;j<list[i].list.length;j++){%>\
											<%if(j==list[i].list.length-1){%>\
												<%=list[i].list[j].name%>楼\
											<%}else{%>\
												<%=list[i].list[j].name%>、\
											<%}%>\
										<%}%>	\
									<%}else{%>\
									  <% for(var j=0;j<list[i].list.length;j++){%>\
										<%if(j==list[i].list.length-1){%>\
											<%=list[i].list[j].name%>\
										<%}else{%>\
											<%=list[i].list[j].name%>、\
										<%}%>\
									 <%}%>	\
									<%}%>\
								</div>\
								<div class="del-btn" data-id="<%=list[i].id%>">\
									<span class="del-icon"></span>\
									删除\
								</div>\
							</div>\
						<%}%>'
	}

	var userForm = {
			init: function(){
				this.render();
				this.bindEvent();
			},
			render: function(){
				this.renderPosition();
			},
			bindEvent: function(){
				var _this = this;
				//添加系统角色
				$(".add-role-btn").on("click",function(){
					//校验是否选中运营中心
                    var companyid = $("#companyid").val();
                    if(!companyid){
                        layer.msg("请选择运营中心");
                        return false;
                    };
					//添加角色前检验是否选中校区
                    var organizationNodes=zTreeObj.getCheckedNodes(true);
                    if (organizationNodes.length <= 0){
                        layer.msg("请选择校区");
                    	return false;
					}
                    var orgId = organizationNodes[0].id;
					_this.getRoleList(orgId,function(data){
						_this.getRoleFloorOrRepair(data)
					})
				});
				//确定保存
				$(".sure-btn").on("click",function(){
					_this.saveForm();
				});
                //切换公司部门与校区列表也需要更变
                $("#companyid").on("change",function(){
                	var compid = $("#companyid").val();
                    _this.initTree();
                	_this.initTbDept(compid);
                });
                if($("#userType_").val() == 3 && !$("#id").val()){
                    var compid = $("#companyid").val();
                    _this.initTree(1);
                    _this.initTbDept(compid);
				}
			},

			/**
			 * 初始化校区组织树
			 * @param type 为1代表为校区管理员时初始化
			 */
			initTree:function(type){
                var companyId=$("#companyid").val();
                var userId = $("#id").val();
                var contextPath=$("#contextPath").val();
                $.ajax({
                    url :contextPath+"/admin/organization/getCompanyOrgTree",
                    type : "POST",
                    data : {companyId:companyId,userId:userId},
                    dataType:"json",
                    success : function(data) {
                        $.fn.zTree.init($("#tree"), setting, data);
                        zTreeObj=$.fn.zTree.getZTreeObj("tree");
                        if(type ==1){
                            var nodes = zTreeObj.getNodes();
                            zTreeObj.checkNode(nodes[0].children[0], true, true); //选中第一个子节点
						}
						zTreeObj.expandAll(true);


                    },
                    error : function(data) {
                        // alert("系统繁忙,加载功能树失败..");
                    }
                });
			},

			//初始化部门集合
        	initTbDept:function (compid){
				if(compid==""){
					compid=$("#companyid").val();
				}
				var contextPath=$("#contextPath").val();
				$.ajax({
					url :contextPath+"/admin/organization/ajaxGetDeptList",
					type : "GET",
					data : {compid:compid},
					dataType:"json",
					async:false,
					success : function(data) {
						var deptid=$("#deptid");
						var containHtml="<option value=''>请选择部门</option>";
                        deptid.html(containHtml);
						$.each(data,function(index,obj){
							containHtml+="<option value='"+obj.id+"'>"+obj.name+"</option>";
						});
						deptid.html(containHtml);
					},
					error : function(data) {
						// alert("系统繁忙，请稍后再试.");
					}
				});
			},
			//获取职位列表
			renderPosition: function(){
				var _this = this;
				$.ajax({
					url :contextPath+"/admin/users/getPosition",
					type : "post",
					success : function(data) {
						if(data.code == ERROR_OK){
							$(".position-select").html(template.render(tpl.positionTpl)(data));
							if($("#id").val()){//id为用户id
								_this.getDetail($("#id").val())
							}
						}else{
							layer.msg(data.msg);
						}
					},
					error : function(data) {
						// layer.msg("系统繁忙，请稍后再试.");
					}
				});
			},
			/**
			 * 获取详情
			 * @param id
			 */
			getDetail: function(id){
                var _this = this;
				$.ajax({
					url :contextPath+"/admin/users/getUserInfo",
					type : "post",
					data: {
						userId: id
					},
					success : function(data) {
						if(data.code == ERROR_OK){
							$(".user-name").val(data.data.username);
							$(".user-psd").val(data.data.password);
							$(".user-nm").val(data.data.fullName);
							$(".user-phone").val(data.data.telephone);
//							$(".user-workNo").val(data.data.workNo);
							$(".position-select").val(data.data.position);
                            $("#companyid").val(data.data.company);
                            var userType = data.data.userType;
                            $("#userType").val(userType);

                            //如果修改的角色类型为普通管理员,则进行角色显示
                            if (userType == 4){
                                document.getElementById("role").style.display="";//显
							}
                            if (userType > 2){
                                document.getElementById("companyDiv").style.display="";//显
                            }

                            _this.initTree();//初始化校区树
                            _this.initTbDept($("#companyid").val());//初始化部门列表
                            $("#deptid").val(data.data.dept);

							list = data.data.list;
							$(".role-list").html(template.render(tpl.roleItemTpl)({list: list}));
							$(".del-btn").on("click",function(){
								var id = $(this).data("id");
								$(this).closest(".role-line").remove();
								for(var i=0;i<list.length;i++){
									if(list[i].id==id){
										list.splice(i,1);
									}
								};
							})
						}else{
							layer.msg(data.msg);
						}
					},
					error : function(data) {
						// layer.msg("系统繁忙，请稍后再试.");
					}
				});
			},
			/**
			 * 获取所有角色
			 * @param callback  获取第一个角色的对应的楼层或者维修类型
			 */
			getRoleList: function(orgId,callback){
				$.ajax({
					url :contextPath+"/admin/users/getRoleList",
					type : "post",
					data:{
                        orgId:orgId
					},
					success : function(data) {
						if(data.code == ERROR_OK){
							callback(data.data);
						}else{
							layer.msg(data.msg);
						}
					},
					error : function(data) {
						// layer.msg("系统繁忙，请稍后再试.");
					}
				});
			},
			/**
			 * 获取角色对应的楼层或者维修类型
			 * @param data 所有角色
			 */
			getRoleFloorOrRepair: function(personList,type){
				var _this = this;
				if(personList==null||personList.length<=0){
					layer.msg("请先新增角色");
				}else{
					var type = type ? type :personList[0].dataType;
					if(type!=3){
						$.ajax({
							url :contextPath+"/admin/users/getRoleFloorOrRepair",
							type : "post",
							data: {
								type: type
							},
							success : function(data) {
								if(data.code == ERROR_OK){
									$("body").append(template.render(tpl.choosePersonTpl)({personList: personList,roleList: data.data,type:type}));
									_this.popupBindEvent();
									_this.popupRoleEvent();
									_this.sureAdd();
									_this.bindChooseAll();
									$(".close-btn").on("click",function(){
										$(".dialog-wp").remove();
									})
								}else{
									layer.msg(data.msg);
								}
							},
							error : function(data) {
								// layer.msg("系统繁忙，请稍后再试.");
							}
						});
					}else{
						$("body").append(template.render(tpl.choosePersonTpl)({personList: personList,roleList: []}));
						_this.popupBindEvent();
						_this.sureAdd();
						$(".close-btn").on("click",function(){
							$(".dialog-wp").remove();
						})
					}
				}
			},
			/**
			 * 点击角色弹窗交互
			 * 
			 */
			popupBindEvent: function(){
				var _this = this;
				$(".person-item").on("click",function(){
					var type = $(this).data("type");
					$(this).addClass("active").siblings().removeClass("active");
					if(type !=3){
						$.ajax({
							url :contextPath+"/admin/users/getRoleFloorOrRepair",
							type : "post",
							data: {
								type: type
							},
							success : function(data) {
								if(data.code == ERROR_OK){
									$(".choose-person-right").html(template.render(tpl.roleTpl)({roleList: data.data,type: type}));
									_this.popupRoleEvent();
									_this.bindChooseAll();
								}else{
									layer.msg(data.msg);
								}
							},
							error : function(data) {
								// layer.msg("系统繁忙，请稍后再试.");
							}
						});
					}else{
						$(".choose-person-right").html(template.render(tpl.roleTpl)({roleList: [],type: type}));
					}
				})
			},
			/**
			 * 对应的楼层或者维修类型交互
			 * 
			 */
			popupRoleEvent: function(){
				$(".respons-item").on("click",function(){
					$(this).toggleClass("active");
				})
			},
			/**
			 * 确认添加 
			 * 
			 */
			sureAdd: function(){
				var _this = this;
				$(".choose-person-sure-btn").on("click",function(){
					var activeObj = {};
					activeObj.id = $(".person-item.active").data("id");
					activeObj.name=  $(".person-item.active").data("name");
					activeObj.dataType =  $(".person-item.active").data("type");
					if($(".respons-item").length>0){
						if($(".respons-item.active").length>0){
							var list1 = []
							$(".respons-item.active").each(function(index,ele){
								list1.push({
									name: $(ele).data("name"),
									id: $(ele).data("id")
								});
								activeObj.list = list1;
							});
							_this.filterList(activeObj);
							$(".dialog-wp").remove();
						}else{
							layer.msg("请选择对应的楼层或者维修类型");
							return false;
						}
					}else{
						activeObj.list = [];
						_this.filterList(activeObj);
						$(".dialog-wp").remove();
					}
				})
			},
			/**
			 * 合并系统角色 
			 */
			filterList: function(activeObj){
				if(list.length>0){
					var flag = false;
					for(var i=0;i<list.length;i++){
						if(list[i].id==activeObj.id){
							list.splice(i,1,activeObj)  ;
							flag = true;
						}
					};
					if(flag==false){
						list.push(activeObj);
					};
					$(".role-list").html(template.render(tpl.roleItemTpl)({list: list}));
					$(".del-btn").on("click",function(){
						var id = $(this).data("id");
						$(this).closest(".role-line").remove();
						for(var i=0;i<list.length;i++){
							if(list[i].id==id){
								list.splice(i,1);
							}
						};
					})
				}else{
					list.push(activeObj);
					$(".role-list").html(template.render(tpl.roleItemTpl)({list: list}));
					$(".del-btn").on("click",function(){
						var id = $(this).data("id");
						$(this).closest(".role-line").remove();
						for(var i=0;i<list.length;i++){
							if(list[i].id==id){
								list.splice(i,1);
							}
						};
					})
				}
			},
			//全选 全不选
			bindChooseAll: function(){
				$(".choose-all-wp .radio-wp").on("click",function(){
					if($(this).data("type") == 0){//点击全选
						$(".respons-item").addClass("active")
					}else{//点击全不选
						$(".respons-item").removeClass("active")
					}
				})
			},
			/**
			 * 确定保存
			 * 
			 */
			saveForm: function(){
				var _this = this;
				var formData = new FormData();
				
				formData.append("actType", $("#actType").val());
				formData.append("funcid", $("#funcid").val());//功能id
				formData.append("id", $("#id").val());
				//用户名
				var userName = $(".user-name").val();
				if(!userName){
					layer.msg("请输入用户名");
					return false;
				};
				formData.append("username", userName);
				//登陆密码
				var userPsd = $(".user-psd").val();
				if(!$("#id").val()&&!userPsd){
					layer.msg("请输入登录密码");
					return false;
				};
				formData.append("password", userPsd);
				//姓名
				var userNm = $(".user-nm").val();
				if(!userNm){
					layer.msg("请输入姓名");
					return false;
				};
				formData.append("fullName", userNm);
				//电话号码
				var myreg=/^[1][3,4,5,7,8][0-9]{9}$/;
				var userPhone = $(".user-phone").val();
				if(userPhone && !myreg.test(userPhone)){
					layer.msg("请输入正确的手机号码");
					return false;
				};
                //账号类型
                var userType = $("#userType").val();
                if(!userType){
                    layer.msg("请选择账号类型");
                    return false;
                };
                formData.append("userType", userType);
				formData.append("telephone", userPhone);

                //职位
				var position = $(".position-select").val();
				formData.append("position", position);

				if (userType > 2){
					//当创建的用户类型为校区管理员及以下,才需要选取校区及运营中心
                    //所属运营中心
                    var companyid = $("#companyid").val();
                    if(!companyid){
                        layer.msg("请选择运营中心");
                        return false;
                    };
                    formData.append("companyid", companyid);
                    //部门
                    var deptid = $("#deptid").val();
                    formData.append("deptid", deptid);
                    //管辖的组织
                	var organizationNodes=zTreeObj.getCheckedNodes(true);
                    var orgnizationIds="";
                    $.each(organizationNodes,function(index,organizationNode){
                        if(organizationNode.level=="1"){
                            orgnizationIds+=organizationNode.id+";";
                        }
                    });
                    if(!orgnizationIds){
                        layer.msg("请选择校区");
                        return false;
                    };
                    formData.append("orgnizationIds", orgnizationIds);
                }

				//系统角色
				var obj = {};
				var roleIdsArr = [];
				if(userType > 3 && $(".role-line").length==0){
					layer.msg("请添加系统角色");
					return false;
				}else{
					for(var i=0;i<list.length;i++){
						var ids = []
						for(var j =0;j<list[i].list.length;j++){
							ids.push(list[i].list[j].id);
						}
						obj[list[i].id] = {
							floorOrRepairType:  ids,
							type: list[i].dataType
						}
						roleIdsArr.push(list[i].id)
					};

					formData.append("roleIds", roleIdsArr.join(";")+";");
					formData.append("roleMap", JSON.stringify(obj));
				};
				$.ajax({
					   type: "post",
					   url: $("#contextPath").val()+ "/admin/users/form",
					   data: formData,
					   cache: false,                      // 不缓存
				        processData: false,                // 告诉jQuery不要去处理发送的数据
				        contentType: false,                // 告诉jQuery不要去设置Content-Type请求头
//				        dataType: 'text',
					   success: function(data){

						   if(data.code == ERROR_OK){
							   $(".user-name").attr("readonly",true)
							   $("#id").val(data.data.id);
							  layer.msg("保存成功")
//							   layer.msg('发起维修成功！');
						   }else{
							   layer.msg(data.msg)
						   }
					   },
					   error: function(){
//						   $(".repair-btn").attr("disabled",false);
						   layer.msg('error')
					   }
			   });
			}
	};
	userForm.init();
})