
var permApprove = $("#perm-approve").val();
/**
 * 放行审批
 * 2018/5/25 by liufang
 *
 */
$(function(){
	var layer;
	var table;
	var ERROR_OK = 200;
	layui.use('layer', function(){
		   layer = layui.layer;  
	});
	var layer_index=0;
	
	$("#operate").click(function () {
		layui.use('layer', function(){
			layer = layui.layer;
			$('#showVirPerm').empty();
			$('#showRole').empty();
			$("#role").empty();
			$("#virPerm").empty();
			operateSetting.getVirPerm(function(virList){
				operateSetting.getRoleList(function(roleList){
					operateSetting.getGoodsConfig(virList,roleList);
				});
			});

			layer_index=layer.open({
				type: 1,
				area: ['722px', '534px'], //宽高
				title: '配置流程', //不显示标题
				content: $('#block_1'), //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
				cancel: function(){
					// layer.msg('捕获就是从页面已经存在的元素上，包裹layer的结构', {time: 5000, icon:6});
				}
			});
$(".cancel-btn").on("click",function(){
				
				layer.closeAll(); 
			})
		});
	})
	$('#addVirPerm').click(function(){
		if($("#virPerm").val()===''||$("#virPerm").val()===null){
			return false;
		}
		$('#showVirPerm').append('<span class="del-select-btn delRole" data-role="'+$("#virPerm").val()+'">'+$("#virPerm").find("option:selected").text()+'<i class="del"></i></span>');
	})
	$("#showVirPerm").on('click','.delRole',function(){
		this.remove();
	});
	$('#addRole').click(function(){
		if($("#role").val()===''||$("#role").val()===null){
			return false;
		}
		$('#showRole').append('<span class="del-select-btn delRole" data-role="'+$("#role").val()+'">'+$("#role").find("option:selected").text()+'<i class="del"></i></span>');
	})
	$("#showRole").on('click','.delRole',function(){
		this.remove();
	});
	$('#sure').click(function(){
        let vir = '';
        let rol = '';
        $.each($('#showRole span'),function (item) {
            rol+=$(this).attr('data-role')+";";
        })
        $.each($('#showVirPerm span'),function (item) {
            vir+=$(this).attr('data-role')+";";
        })
        rol=rol.substring(0,rol.length-1);
        vir=vir.substring(0,vir.length-1);
        if(rol===''&&vir===''){
            layer.msg("请选择功能权限");
            return false;
        }
		operateSetting.saveOrUpdateGoodsConfig(vir,rol);
	})

	var operateSetting={
	    //公司审核
		getVirPerm:function (callback) {
      let that=this;
			$.ajax({
				type: "post",
				url: $("#contextPath").val()+ "/admin/virPerm/getPermByCheckRole",
				data: {
					orgId: $("#orgId").attr('org__id')
				},
				success: function(data){
					if(data.code== ERROR_OK){
						data.data.forEach(function (item) {
							$("#virPerm").append("<option value='"+item.id+"'>"+item.name+"</option>");
						})
						callback && callback(data.data)
					}else{
						layer.msg(data.msg);
					}
				},
				error: function(){
				}
			});
		},
		//物业
		getRoleList:function (callback) {
			let that=this;
			$.ajax({
				type: "post",
				url: $("#contextPath").val()+ "/admin/role/getRoleByOrgAndSysCode",
				data: {
					orgId: $("#orgId").attr('org__id')
				},
				success: function(data){
					if(data.code== ERROR_OK){
						data.data.forEach(function (item) {
							$("#role").append("<option value='"+item.ID+"'>"+item.NAME+"</option>");
						})
						callback && callback(data.data)
					}else{
						layer.msg(data.msg);
					}
				},
				error: function(){
				}
			});
		},
		saveOrUpdateGoodsConfig:function (virList,proList) {
			let that=this;
			$.ajax({
				type: "post",
				url: $("#contextPath").val()+ "/admin/virPerm/saveOrUpdateGoodsConfig",
				data: {
					orgId: $("#orgId").attr('org__id'),
					virList:virList,
					proList:proList
				},
				success: function(data){
					if(data.code== ERROR_OK){
						layer.close(layer_index);
					}else{
						layer.msg(data.msg);
					}
				},
				error: function(){
				}
			});
		},
		getGoodsConfig:function (virList,roleList) {
			let that=this;
			$.ajax({
				type: "post",
				url: $("#contextPath").val()+ "/admin/virPerm/getGoodsConfig",
				data: {
					orgId: $("#orgId").attr('org__id')
				},
				success: function(data){
					if(data.code== ERROR_OK){
						var virtObj = {},roleObj ={};
						for(var i=0;i<virList.length;i++){
							virtObj[virList[i].id] = virList[i].name
						}
//						console.log('virtObj',virtObj)
						for(var j=0;j<roleList.length;j++){
							roleObj[roleList[j].ID] = roleList[j].NAME
						}
//						console.log('roleObj',roleObj)
						data.data.virList.forEach(function (val) {
							$('#showVirPerm').append('<span class="del-select-btn delRole" data-role="'+val.roleId+'">'+virtObj[val.roleId]+'<i class="del"></i></span>');
						})
						data.data.proList.forEach(function (val) {
							$('#showRole').append('<span class="del-select-btn delRole" data-role="'+val.roleId+'">'+roleObj[val.roleId]+'<i class="del"></i></span>');
						})
					}else{
						layer.msg(data.msg);
					}
				},
				error: function(){
				}
			});
		}
	}
	var tpl = {
			"picTpl": '<div class="dialog-wp">\
				<div class="mask"></div>\
				<div class="dialog dialog-pic-con">\
					<div class="title-wp">\
						<span><%if(type==1){%>申请<%}else if(type==2){%> 放行<%}%>图片</span>\
						<span class="close-btn"></button>\
					</div>\
					<div class=" dialog-pic-wp ">\
						<div class="pic-list">\
							<% if(listImg.length>0){%>\
								<% for(i=0;i<listImg.length;i++){%>\
									<% var img = listImg[i].split("@")[0]%>\
									<% var descript = listImg[i].split("@")[1]%>\
									<div class="pic-item clearfloat">\
										<div class="pic-left"><img class="img " src="<%=img%>"></div>\
										<div class="pic-right">\
											<div class="title">图片<%=i+1%>的描述</div>\
											<div class="descript"><%=descript%></div>\
										</div>\
									</div>\
								<%} %>\
							<%}else{%>\
								<div class="no-data">暂无数据</div>\
							<%} %>\
						</div>\
				   </div>		\
				</div>\
			</div>	',
			"releaseTpl": '<div class="dialog-wp">\
				<div class="mask"></div>\
				<div class="dialog dialog-release-con">\
					<div class="title-wp">\
						<span>订单动态</span>\
						<span class="close-btn"></button>\
					</div>\
					<div class=" dialog-release-wp ">\
						<%if(!!operateDto && operateDto.length>0){%>\
							<div class="release-list">\
								<% for(var i=0;i<operateDto.length;i++){%>\
									<div class="release-item"><%=operateDto[i].auditTime%> &nbsp;&nbsp;<%=operateDto[i].auditUser%>&nbsp;&nbsp;<%=operateDto[i].auditResult%>&nbsp;&nbsp;<span class="red-text"><%=operateDto[i].remark%></span></div>\
								<%}%>\
							</div>\
						<%}else{%>\
							<div class="no-data">暂无数据</div>\
						<%}%>\
				   </div>		\
				</div>\
			</div>	',
			"goodTpl": '<div class="dialog-wp">\
				<div class="mask"></div>\
				<div class="dialog dialog-good-con">\
					<div class="title-wp">\
						<span>放行物品</span>\
						<span class="close-btn"></button>\
					</div>\
					<div class=" dialog-good-wp ">\
						<%if(!!list && list.length>0){%>\
							<div class="good-list">\
								<% for(var i=0;i<list.length;i++){%>\
									<div class="good-item">\
										<div class="good-name">物品<%=i+1%>名称：<%=list[i].goodsName%></div>\
										<div class="good-num">物品<%=i+1%>数量：<%=list[i].amount%></div>\
									</div>\
								<%}%>\
							</div>\
						<%}else{%>\
							<div class="no-data">暂无数据</div>\
						<%}%>\
				   </div>		\
				</div>\
			</div>	',
			"checkTpl":  '<div class="dialog-wp">\
				<div class="mask"></div>\
				<div class="dialog dialog-check-con">\
					<div class="title-wp">\
						<span>提示</span>\
						<span class="close-btn"></button>\
					</div>\
					<div class="dialog-check-wp ">\
						<div class="dialog-choose-person-header">\
							<h2 class="check-title">\
								<% if(type ==1){%>\
									通过放行申请！\
								<% }else{ %>	\
									拒绝放行申请！\
								<%}%>\
							</h2>\
							<div class="check-reason-wp clearfloat">\
								<span class="tips">\
									<% if(type ==1){%>\
										通过意见\
									<% }else{ %>	\
										拒绝意见\
									<%}%>\
								</span>\
								<textarea class="check-reason" placeholder="请输入意见"></textarea>\
							</div>\
						</div>\
						<div class="dialog-choose-person-footer">\
							<button class="btn-red sure-operate" data-type="<%=type%>">\
								<% if(type ==1){%>\
									确认通过\
								<% }else{ %>	\
									确认拒绝\
								<%}%>\
							</button>\
						</div>\
				   </div>		\
				</div>\
			</div>	',
	}
	var releaseApprove = {
			init: function(){
				this.render();
				this.bindEvent();
				
			},
			render: function(){
				this.renderTable();
			},
			bindEvent: function(){
				//查询
				$("#conditionform input[type='text']").on("keydown",function(event){
					if(event.keyCode == 13){
						$("#conditionform .search-btn").click();
					}
				});
				//发起开始时间
				$("#billStartDate").on("click",function(){
					laydate({
			            elem: document.getElementById('billStartDate')
			        });
				});
				//发起结束时间
				$("#billEndDate").on("click",function(){
					laydate({
			            elem: document.getElementById('billEndDate')
			        });
				});
				//放行开始时间
				$("#releaseStartDate").on("click",function(){
					laydate({
			            elem: document.getElementById('releaseStartDate')
			        });
				});
				//放行结束时间
				$("#releaseEndDate").on("click",function(){
					laydate({
			            elem: document.getElementById('releaseEndDate')
			        });
				});
				//重置
				$(".set-btn").on("click",function(){
					$("#conditionform input:not('#orgId')").val("");
        })
        // 模糊搜索
       this.search_fuzzy()
      },
      	// 模糊搜索事件
        search_fuzzy: function(){
          $('body').on("input",'#orgId',function(event){
            var _this = $(this)
            cjqt.search_fuzzy.event_input(_this,'org__id','org__span',$("#contextPath").val(),'/admin/templ/getOrgListByName')
          });
          $('body').on("focus",'#orgId',function(event){
            var _this = $(this)
            cjqt.search_fuzzy.event_focus(_this,'org__id','org__span',$("#contextPath").val(),'/admin/templ/getOrgListByName')
          });
          $('body').on('blur','#orgId',function(event) {
            var _this = $(this)
            cjqt.search_fuzzy.event_blur(_this,'org__id')
          });
          $('body').on('click','.select_wrap>.org__span', function(event) {
            event.preventDefault();
            event.stopPropagation();
            /* Act on the event */
            var _this = $(this)
            cjqt.search_fuzzy.event_click(_this,'org__id','#orgId')
            $('#showVirPerm').empty();
            $('#showRole').empty();
            $("#role").empty();
            $("#virPerm").empty();
            operateSetting.getVirPerm(function(virList){
				operateSetting.getRoleList(function(roleList){
					operateSetting.getGoodsConfig(virList,roleList);
				});
			});
          });
        },
			renderTable: function(){
				var _this = this;
				layui.use('table', function(){
					  table = layui.table;
					  
					  //方法级渲染
					  table.render({
					    elem: '#LAY_table_user',
					    method: 'post'
					    ,url: $("#contextPath").val()+ "/release/list"
					    ,skin: 'nob' //行边框风格
				    		  ,even: true //开启隔行背景
				    		  ,size: 'lg' //小尺寸的表格
					    ,cols: [[
						  {
							  title: '序号',
							  templet: '#indexTpl',
							  width: 80
						  } ,{
				    		   field:'releaseCode', 
				    		   title: '放行编号', 
				    		   minWidth: 200
				    	  },{
				    		  field:'createTime',
				    		  title: '发起时间',
				    		  minWidth: 200
			    		  },{
				    		  field:'applyUserInfo',
				    		  title: '发起人',
				    		  minWidth: 200
			    		  },{
			    			  field:'companyName', 
			    			  title: '校区', 
			    			  minWidth: 200
		  				  // },{
		  					//   field:'companyHeadUser',
		  					//   title: '校区负责人',
		  					// 	 minWidth: 200
		  					 
						  },{
							  field:'releaseDesc', 
							  title: '放行描述',
							  minWidth: 200
							
						  // },{
							//   field:'releaseTypeName',
							//   title: '申请类型',
							//   minWidth: 200
							  
							
						  },{
				    		  title: '放行物品',
				    		  minWidth: 200,
				    		  templet: function(data){
								  return "<span class='deep-blue-text check-apply-pic' data-id="+data.id+"  data-type='4'>查看物品</span>"
							  }  
			    		  },{
							  field:'repairTypeName', 
							  title: '申请图片',
							  templet: function(data){
								  return "<span class='deep-blue-text check-apply-pic' data-id="+data.id+" data-type='1'>查看</span>"
							  }
							  
							
//						  },{
//							  field:'repairTypeName', 
//							  title: '放行图片',
//							  minWidth: 200,
//							  templet: function(data){
//								  return "<span class='deep-blue-text check-release-pic'  data-id="+data.id+" data-type='2'>查看</span>"
//							  }
							
//						  },{
//							  field:'isSendSettle', 
//							  title: '放行动态',
//							  minWidth: 200,
//							  templet: function(data){
//								  return "<span class='deep-blue-text check-release'  data-id="+data.id+" data-type='3'>查看</span>"
//								  
//							  }
//							
						  },{
							  field:'id', 
							  title: '操作', 
							  width: 120,
							  fixed: 'right', 
							  templet: function(data){
								  var str = '';
								  if (permApprove == 1){
								    str += '<button class="t-btn t-red-btn t-publish-btn" data-id='+data.id+' data-type="1" data-roleid='+data.roleId+'>通过</button>';
	  								str += '<button class="t-btn t-white-btn t-reject-btn" data-id='+data.id+' data-type="2" data-roleid='+data.roleId+'>拒绝</button>';
                                  }
	  								return str;
							  }
						  }
						  ]]
						    ,id: 'testReload'
						    ,page: true,
						    request: {
						    	  pageName: 'pageNo' //页码的参数名称，默认：page
						    	  ,limitName: 'pageSize' //每页数据量的参数名，默认：limit
					    	}, 
						    response: {
						    	  statusName: 'code' //数据状态的字段名称，默认：code
						    	  ,statusCode: 200 //成功的状态码，默认：0
						    	  ,countName: "count"//数据总数的字段名称，默认：count
						    	  ,dataName: "data" //数据列表的字段名称，默认：data
						    	}   ,
						    	where: {
						    		releaseStatus: 10
						    	},
						  
						    done: function(res, curr, count){
						    	//查看申请图片
						    	$(".check-apply-pic").on("click",function(){
						    		var id = $(this).data("id");
						    		var type = $(this).data("type");
						    		_this.showPicDialog(type,id);
						    	});
						    	
						    	//查看放行图片 放行物品
						    	$(".check-release-pic").on("click",function(){
						    		var id = $(this).data("id");
						    		var type = $(this).data("type");
						    		_this.showPicDialog(type,id);
						    	});
						    	//通过
						    	$(".t-reject-btn").on("click",function(){
						    		var id = $(this).data("id");
						    		var type = $(this).data("type");
						    		var roleId = $(this).data("roleid")
						    		_this.showPassDialog(type,id,roleId)
						    	});
						    	//拒绝
						    	$(".t-publish-btn").on("click",function(){
						    		var id = $(this).data("id");
						    		var type = $(this).data("type");
						    		var roleId = $(this).data("roleid")
						    		_this.showPassDialog(type,id,roleId)
						    	});
						
						      }
					  });
					  //查询
					  $('#conditionform  .search-btn').on('click', function(){
						  _this.againRenderTable();
					  });
					});
			},
			/*重新渲染table*/
			againRenderTable: function(){
				table.reload('testReload', {
					where: {
						
					} ,
					  page: {
					    curr: 1 //重新从第 1 页开始
					  }
				}); 
			},
			/**
			 * 显示图片弹窗
			 * @param type 1申请图片 2放行图片 3放行动态 4方向物品
			 * @param id 放行id
			 */
			showPicDialog: function(type,id){
				var _this = this;
				$.ajax({
					   type: "post",
					   url: $("#contextPath").val()+ "/release/getDetail", 
					   data: {
						   id: id
					   },
					   success: function(data){
						   if(data.code== ERROR_OK){
							   
							   if(type ==1){
								   var listImg = !!data.data.applypicUrl ?  data.data.applypicUrl.split(";") : [];
								   $("body").append(template.render(tpl.picTpl)({type: type,listImg: listImg}));
								   $(".pic-left .img").zoomify()
							   }else if(type ==2){
								   var listImg = !!data.data.releasepicUrl ?  data.data.releasepicUrl.split(";") : [];
								   $("body").append(template.render(tpl.picTpl)({type: type,listImg: listImg}));
								   $(".pic-left .img").zoomify()
							   }else if(type ==4){
								   
								   $("body").append(template.render(tpl.goodTpl)({list: data.data.goodsDetails}));
							   }else{
								   $("body").append(template.render(tpl.releaseTpl)(data.data))
							   }
								$(".close-btn").on("click",function(){
									   $(this).closest(".dialog-wp").remove();
							    });
//								_this.settledBindEvent(callback);
						   }else{
							   layer.msg(data.msg);
						   }   
					   },
					   error: function(){  
					   }
			   });
				
			},
			/**
			 * 显示拒绝或者通过弹窗
			 * @param type 1通过 2拒绝
			 * @param id
			 * @param roleId
			 */
			showPassDialog: function(type,id,roleId){
				var _this = this;
				$("body").append(template.render(tpl.checkTpl)({type: type}));
			    $(".sure-operate").on("click",function(){
				   var $dom = $(this).closest(".dialog-wp")
				   _this.ajaxEnterReason($dom,type,id,roleId);
			    })
				$(".close-btn").on("click",function(){
				   $(this).closest(".dialog-wp").remove();
			    });
			},
			/**
			 * 发送拒绝或者通过原因
			 * @param $dom
			 * @param type
			 * @param enterId
			 */
			ajaxEnterReason: function($dom,type,id,roleId){
				var _this = this;
				var reason = $dom.find(".check-reason").val();
				if(!reason && type ==2){
					layer.alert("请输入意见！");
					return false;
				}
				if(type==1){
					_this.ajaxPass(id,reason,$dom,roleId)
				}else{
					_this.ajaxFail(id,reason,$dom,roleId);
				}
			},
			/**
			 * 通过
			 * @paranm id
			 * @param remark
			 */
			ajaxPass: function(id,remark,$dom,roleId){
				
				var _this = this;
				var formData = new FormData();
				formData.append("id",id);
				formData.append("remark",remark);
				formData.append("roleId",roleId);
				$.ajax({
					   type: "post",
					   url: $("#contextPath").val()+ "/release/agree", 
					   data: formData,
					   cache: false,                      // 不缓存
				        processData: false,                // 告诉jQuery不要去处理发送的数据
				        contentType: false,     
					   success: function(data){
						   if(data.code== ERROR_OK){
								layer.msg("通过成功！")  ;
							   $dom.remove();
							   _this.againRenderTable();
						   }else{
							   layer.msg(data.msg);
						   }   
					   },
					   error: function(){   
					   }
			   });
			},
			/**
			 * 通过
			 * @paranm id
			 * @param remark
			 * @param $dom 弹窗dom
			 */
			ajaxFail: function(id,remark,$dom,roleId){
				var _this = this;
				$.ajax({
					   type: "post",
					   url: $("#contextPath").val()+ "/release/refuse", 
					   data: {
						   remark: remark,
						   id: id,
						   roleId:roleId
					   },
					   success: function(data){
						   if(data.code== ERROR_OK){
								layer.msg("拒绝成功！")  ;
							   $dom.remove();
							   _this.againRenderTable();
						   }else{
							   layer.msg(data.msg);
						   }   
					   },
					   error: function(){   
					   }
			   });
			},
	};
	releaseApprove.init();
})