
$(function () {
	var syscPerm = $("#perm-sysc").val();
	var ERROR_OK = 200;
	var contextPath = $("#contextPath").val();
	var table;
	var orgList = [];
	var addressList = [];
	var departList = [];
	var companyList = [];
	var userNumber="";
	var cheakedArr = []
	var messageType //短信：1 邮件：2
	template.config("escape", false);
	var orgId = "";
	pushOrgId = '' //推送时候传的统一orgId（在选中的用户中拿）
	var virAccountInfo = $("#virAccountInfo").val()
	
	var api = {
		init: function () {
			this.render();
			this.bindEvent();
		},
		render: function () {
			this.rendertable();
		},
		bindEvent: function () {
			var _this = this;	
			//重置
			$(".set-btn").on("click", function () {
			  if(virAccountInfo){
		          var $dom = $("#conditionform #departmentId")
		          $dom.val("").removeAttr('dep__id')
		          _this.againRenderTable({type:1});
				}else{
					var $orgId = $("#conditionform  .single-orgid");
					var $dom = $("#conditionform input,#conditionform select")
					if($orgId.length){
						$dom.val("").removeAttr('com__id dep__id')
					}else{
						$dom.val("").removeAttr('org__id com__id dep__id')
					}
					_this.againRenderTable({type:1});
				 }
				});
			$("#importTemplate").on("click",function(){
				_this.exportList();
			})
			_this.search_fuzzy()
		},

		// 模糊搜索事件
		search_fuzzy: function(){
			var default_option = {
				org_attrName:'org__id',
				com_attrName:'com__id',
				dep_attrName:'dep__id',
				org_spanName:'org__span',
				com_spanName:'com__span',
				dep_spanName:'dep__span',
				org_path:'/admin/templ/getOrgListByName',
				com_path:'/admin/templ/getVirList',
				dep_path:'/admin/templ/getDept',
				contextPath:$("#contextPath").val()
			}
			var option_1 = $.extend(true,{},default_option,{
				org_target:'.default-select#orgId',
				com_target:'.default-select#companyId',
				dep_target:'.default-select#departmentId',
			});
			var option_2 = $.extend(true,{},default_option,{
				org_target:'.item-select#orgId',
				com_target:'.item-select#companyId',
				dep_target:'.item-select#departmentId',
			});
			var option_3 = $.extend(true,{},default_option,{
				org_target:'.d-orgid',
				com_target:'.d-companyid'
			});
			var option_4 = $.extend(true,{},default_option,{
				org_target:'.orgUpdate',
				com_target:'.companyUpdate',
				dep_target:'.depUpdate',
			});
			

			function eve(option_,otherOption){
				var obj = $.extend(true, {}, option_, otherOption);
				var type = obj.type
				var _path, _target, _attrName, _spanName
				if(type == 1){
					_path = obj.org_path
					_target = obj.org_target
					_attrName = obj.org_attrName
					_spanName = obj.org_spanName
				}else if(type == 2){
					_path = obj.com_path
					_target = obj.com_target
					_attrName = obj.com_attrName
					_spanName = obj.com_spanName
				}else if(type == 3){
					_path = obj.dep_path
					_target = obj.dep_target
					_attrName = obj.dep_attrName
					_spanName = obj.dep_spanName
				}
				$('body').on("input",_target,function(event){
					var _this = $(this)
					var obj_input = $.extend(true,{}, obj,{"_this":_this});
					cjqt.search_fuzzy.event_input(_this,_attrName,_spanName,contextPath,_path,obj_input)
				});
				$('body').on("focus",_target,function(event){
					var _this = $(this)
					var obj_focus = $.extend(true,{},obj,{"_this":_this});
					cjqt.search_fuzzy.event_focus(_this,_attrName,_spanName,contextPath,_path,obj_focus)
				});
				$('body').on('blur',_target,function(event) {
					var _this = $(this)
					var obj_blur = $.extend(true,{},obj,{"_this":_this});
					cjqt.search_fuzzy.event_blur(_this,_attrName,obj_blur)
				});
				$('body').on('click',_target+'~.select_wrap>.'+_spanName, function(event) {
					event.preventDefault();
					event.stopPropagation();
					/* Act on the event */
					var _this = $(this)
					var obj_click = $.extend(true,{},obj,{"_this":_this});
					cjqt.search_fuzzy.event_click(_this,_attrName,_target,obj_click)
				});

			}
			// 搜索联动
			eve(option_1,{type:1})
			eve(option_1,{type:2})
			eve(option_1,{type:3})
			// 新增联动
			eve(option_2,{type:1,click_callback:function(){
				var orgId = $('.item-select#orgId').attr('org__id')
				$.ajax({
					type: "post",
					url: contextPath + "/admin/appUser/getPassType",
					data:{
						orgId:orgId
					},
					success: function (data) {
						if(data.code==200){
							if(data.data==1){
								$('.addFace').show()
							}else{
								$('.addFace').hide()
							}
						}
					},
					error: function (error) {
						layer.msg('error')
					}
				});
			}})
			eve(option_2,{type:2})
			eve(option_2,{type:3})
			//导入联动
			eve(option_3,{type:1})
			eve(option_3,{type:2})
			//修改联动
			eve(option_4,{type:2})
			eve(option_4,{type:3})
		},
		rendertable: function () {
			var _this = this;
			layui.use(['table','laydate'], function () {
				table = layui.table;
				var layer = layui.layer,
				laydate = layui.laydate;
				//日期
				laydate.render({
					elem: '#date1'
				});
				laydate.render({
					elem: '#date2'
				});
				//方法级渲染
				table.render({
					elem: '#LAY_table_user',
					url: $("#contextPath").val() + "/release/recordlist",
					method: "post",
					skin: 'nob' //行边框风格
						,
					even: true //开启隔行背景
						,
					size: 'lg' //小尺寸的表格
						,
					cols: [
						[{
							field: 'index',
							title: '序号',
							width: '80',
							templet: '#indexTpl'
						}, 
						{
							field: 'createTime',
							title: '通行时间',
							minWidth: 220
						},  
						//{
						//	field: 'virName',
						//	title: '通行企业',
						//	minWidth: 350
						//},
						{
							field: 'applyUser',
							title: '通行人',
							minWidth: 120
						}, 
						{
							field: 'applyTel',
							title: '手机号',
							minWidth: 220
						}, 
						{
							field: 'temperature',
							title: '体温',
							minWidth: 150
							
						}, 
						{
							field: 'status',
							title: '状态',
							minWidth: 150
						},
						{
							field: 'releaseUser',
							title: '放行人',
							minWidth: 150
						}
//						{
//							title: '可操作',
//							fixed: 'right',
//							width: 260,
//							align: 'center',
//							templet: function (data) {
//								var str = '';
//								 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>'; 
//								str += '<button class="t-btn t-red-btn t-detail-btn" data-id=' + data.id + ' data-type="1" >详情</button>';
//
//								return str;
//							}
//						}
						]
					],
					id: 'testReload',
					page: true,
					response: {
						statusName: 'code' //数据状态的字段名称，默认：code
							,
						statusCode: 200 //成功的状态码，默认：0
							,
						countName: "count" //数据总数的字段名称，默认：count
							,
						dataName: "data" //数据列表的字段名称，默认：data
							,
						msgName: 'msg' //规定状态信息的字段名称，默认：msg
					},
					request: {
						pageName: 'pageNo' //页码的参数名称，默认：page
							,
						limitName: 'pageSize' //每页数据量的参数名，默认：limit
					},
					where: {
						orgId: $("#conditionform  #orgId").attr('org__id'),
						virtualArchId: $("#conditionform #companyId").attr("com__id")
					},
					done: function (res, curr, count) {
						//通过
//				    	$(".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)
//				    	});
//						$(".t-detail-btn").on("click",function(){
//							var id = $(this).data("id");
//							_this.showDetailDialog(id)
//						})			
					}
				});

				//查询
				$('#conditionform  .search-btn').on('click', function () {

					_this.againRenderTable();
				});
			});
		},
		/*重新渲染table*/
		againRenderTable: function (option) {
			var obj = $.extend(true, {}, option);
			var type =  obj.type || ''
			var $orgId = $("#conditionform  .single-orgid");
			var orgId = $("#conditionform  #orgId").attr('org__id')
			if(type == 1){
				if(virAccountInfo){
					table.reload('testReload', {
						where: {
							orgId: $orgId.length?orgId:'',
							virtualArchId: $("#conditionform #companyId").attr("com__id"),
							applyUser: $(".loginName").val(),
							applyTel: $(".applyTel").val(),
							releaseStartDate: $("#date1").val(),
							releaseEndDate: $("#date2").val(),
						},
						page: {
							curr: 1 //重新从第 1 页开始
						}
					});
				}else{
					table.reload('testReload', {
						where: {
							
							orgId: $orgId.length?orgId:'',
							virtualArchId: '',
							applyUser: $(".loginName").val(),
							applyTel: $(".applyTel").val(),
							releaseStartDate: $("#date1").val(),
							releaseEndDate: $("#date2").val(),
						},
						page: {
							curr: 1 //重新从第 1 页开始
						}
					});
				}
			}else{
				table.reload('testReload', {
					where: {
						orgId: orgId,
						virtualArchId: $("#companyId").attr('com__id') || '',
						applyUser: $(".loginName").val(),
						applyTel: $(".applyTel").val(),
						releaseStartDate: $("#date1").val(),
						releaseEndDate: $("#date2").val(),
					},
					page: {
						curr: 1 //重新从第 1 页开始
					}
				});
			}
		},
		/**
		 * 显示拒绝或者通过弹窗
		 * @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(){   
				   }
		   });
		},
		//获取详情
		showDetailDialog: function(id){
			$.ajax({
				   type: "post",
				   url: $("#contextPath").val()+ "/release/getDetail", 
				   data: {
					   id: id
				   },
				   success: function(data){
					   if(data.code== ERROR_OK){
						   let applyList = [];
						   if (!!data.data.applypicUrl) {
					            let applyArr = data.data.applypicUrl.split(";");
					            for (let i = 0; i < applyArr.length; i++) {
					              applyList.push({
					                url: applyArr[i].split("@")[0],
					                content: applyArr[i].split("@")[1],
					                showImg: false
					              });
					            }
					          }
						   data.data.applyList = applyList;
						   $("body").append(template.render(tpl.detailTpl)(data.data));
						    
							$(".close-btn").on("click",function(){
							   $(this).closest(".dialog-wp").remove();
						    });
					   }else{
						   layer.msg(data.msg);
					   }   
				   },
				   error: function(){   
				   }
		   });
		},
		exportList: function(){
			var $orgId = $("#conditionform  .single-orgid");
			var orgId = $("#conditionform  #orgId").attr('org__id')
			$.ajax({
				   type: "post",
				   url: $("#contextPath").val()+ "/release/reportRecord", 
				   data: {
					   orgId: orgId,
					   virtualArchId: $("#companyId").attr('com__id') || '',
					   applyUser: $(".loginName").val(),
					   applyTel: $(".applyTel").val(),
					   releaseStartDate: $("#date1").val(),
					   releaseEndDate: $("#date2").val()
				   },
				   success: function(data){
					   if(data.code== ERROR_OK){
						   location.href = $("#contextPath").val() + "/upload/ApplyPassRecord.xls";
					   }else{
						   layer.msg(data.msg);
					   }   
				   },
				   error: function(){   
				   }
		   });
		}
	};
	api.init();
})
