var permApprove = $("#perm-approve").val();//审核权限

/**
 * 维修订单详情
 * 2018/5/7 by liufang
 */
$(function(){
	var layer;
	layui.use('layer', function(){
		   layer = layui.layer;  
	}); 
	var tpl = {
			"detailTpl": '<div class="dialog-wp">\
				<div class="mask"></div>\
				<div class="dialog dialog-detail-con">\
					<div class="title-wp">\
						<span>报修详情\
						</span>\
						<span class="close-btn"></button>\
					</div>\
					<div class="dialog-detail-wp">\
						<div class="dialog-detail-header">\
							<div class="detail-top clearfloat">\
								<div class="detail-top-item clearfloat">\
									<span class="tips">维修单编号：</span>\
									<span class="top-item-value"><%=s_no %></span>\
								</div>\
								<div class="detail-top-item clearfloat">\
									<span class="tips">报修时间：</span>\
									<span class="top-item-value"><%=created_at_str %></span>\
								</div>\
								<div class="detail-top-item clearfloat">\
									<span class="tips">报修人：</span>\
									<span class="top-item-value"><%=repair_username + repair_phone%></span>\
								</div>\
								<div class="detail-top-item clearfloat">\
									<span class="tips">公司：</span>\
									<span class="top-item-value"><%=company_name%></span>\
								</div>\
								<div class="detail-top-item clearfloat">\
									<span class="tips">地址：</span>\
									<span class="top-item-value"><%=build_name+build_floor+build_room %></span>\
								</div>\
							</div>\
							<div class="detail-middle">\
									<div class="repair-descript">报修描述：<%=remarks%></div>\
								</div>\
							<% if(status==1){%>\
							<div class="detail-middle">\
								<div class="repair-descript">客服处理人：<%=updated_by_name%></div>\
								<div class="repair-descript">订单完结时间：<%=updated_at_str%></div>\
							</div>\
							<%}%>\
							</div>\
					   </div>\
				   </div>		\
				</div>\
			</div>	',
			"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-right">\
								<h3 class="title">工程人员</h3>\
								<div class="person-list clearfloat">\
									<% for(var i=0;i<data.length;i++){%>\
									<div class="person-item">\
										<div class="radio-wp" >\
											<span class="radio-input">\
												<input type="radio" id="outdate-<%=i%>"  class="radio-item" name="date" data-id="<%=data[i].id%>" <%if(i==0){%> checked <%}%>/>\
												<span class="radio-inner"></span>\
											</span>		\
											<label class="radio-con" for="outdate-<%=i%>"><%=data[i].name%></label>\
										</div>\
									</div>\
									<%}%>\
								</div>\
							</div>\
						</div>\
						<div class="choose-person-btns">\
							<button class="btn-red choose-perosn-btn">确认</button>\
						</div>\
					</div>\
				</div>\
			</div>	',
	};
	var layer;
	var table;
	layui.use('layer', function(){
		   layer = layui.layer;  
	}); 
	var launchRepair = {
			init: function(){
				this.render();
				this.bindEvent();
			},
			render: function(){
				var _this = this;
				_this.renderTable();
//				$("body").append(template.render(tpl.detailTpl));
//				$(".close-btn").on("click",function(){
//					$(".dialog-wp").remove();
//				});
//				//回访编辑
//				$(".evalu-edit-btn").on("click",function(){
//					_this.showVisitDialog();
//				})
			},
			bindEvent: function(){
				var _this = this;
				
				//查询
				$("#conditionform input[type='text']").on("keydown",function(event){
					if(event.keyCode == 13){
						$("#conditionform .search-btn").click();
					}
				});
				layui.use('laydate', function(){
					  var laydate = layui.laydate;
					  
					  //执行一个laydate实例
					  laydate.render({
					    elem: '#c_startTime' //提交开始时间
				    	
					  });
					  laydate.render({
						    elem: '#c_endTime' //提交结束时间
					   
						  })
					});
//				//提交开始时间
//				$("#c_startTime").on("click",function(){
//					laydate({
//			            elem: document.getElementById('c_startTime'),
////						max: laydate.now(), //-1代表昨天，-2代表前天，以此类推
//			        });
//				});
//				//提交结束时间
//				$("#c_endTime").on("click",function(){
//					laydate({
//			            elem: document.getElementById('c_endTime'),
////						min: laydate.now(), //-1代表昨天，-2代表前天，以此类推
//			        });
//				});
				//重置
				$(".set-btn").on("click",function(){
					$("#conditionform select,#conditionform input").val("");
					$("#conditionform select").val("");
					_this.againRenderTable();
				});
				
			},
			renderTable: function(){
				var _this = this;
				layui.use('table', function(){
					  table = layui.table;
					  
					  //方法级渲染
					  table.render({
					    elem: '#LAY_table_user',
					    method: 'post'
					    	 ,skin: 'nob' //行边框风格
					    		  ,even: true //开启隔行背景
					    		  ,size: 'lg' //小尺寸的表格
					    ,url: $("#contextPath").val()+ "/repairService/repairList"
					    ,cols: [[
						  {

							  title: '序号',
							  templet: '#indexTpl',
							  width: 80
						  } ,{
				    		   field:'s_no', 
				    		   title: '维修单编号', 
				    		   minWidth:150
				    	  },{
				    		  field:'repair_username',
				    		  title: '报修人',
				    		  minWidth:150
			    		  },{
			    			  field:'repair_phone', 
			    			  title: '报修人手机', 
			    			  width:200
		    			  },{
		    				  field:'created_at_str', 
		    				  title: '报修时间', 
		    				  width:200
		  				  },{
		  					  field:'status', 
		  					  title: '订单状态', 
		  					 width: 200,
		  					  templet: function(data){
		  						  if(data.status==0){
		  							  return '待处理'
		  						  }else if(data.status==1){
		  							  return '已处理'
		  						  }
		  					  }
						  },{
		  					  field:'id', 
		  					  title: '订单详情', 
		  					 width: 150,
		  					  templet: function(data){
		  						return "<span data-id="+data.id+" data-status= "+data.status+" class='check-blue-btn'>查看详情<span>"
		  					  }
						  },{
							  field:'id', 
							  title: '操作', 
							  width: 150,
							  fixed: 'right', 
							  templet: function(data){
								  var str = '';
								  if (permApprove == 1){
                                      if(data.status == 0){
                                          str += '<button class="t-btn t-red-btn t-reject-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
						    	}   ,
						    done: function(res, curr, count){
						        //如果是异步请求数据方式，res即为你接口返回的信息。
						        $(".check-blue-btn").on("click",function(){
						        	var id = $(this).data("id")
						        	var status = $(this).data("status")
						        	//查看订单详情
						        	_this.ajaxDetail(id,status);	
						        });
						        //拒绝
						        $(".t-reject-btn").on("click",function(){
						        	var id = $(this).data("id");
						        	var type = $(this).data("type");
						        	_this.ajaxPass(type,id);
						        });
						        //通过
						        $(".t-publish-btn").on("click",function(){
						        	var id = $(this).data("id");
						        	var type = $(this).data("type");
						        	_this.ajaxPass(type,id);
						        });
						        //派单
						        $(".t-send-btn").on("click",function(){
						        	var id = $(this).data("id");
						        	_this.showChoosePersonDialog(id);
						        })
						      }
					  });
					  //查询
					  $('#conditionform  .searcher-btn').on('click', function(){
						  _this.againRenderTable();
					  });
					});
			},
			/*重新渲染table*/
			againRenderTable: function(){
				table.reload('testReload', {
					  where: { //设定异步数据接口的额外参数，任意设
						  status: $(".repair-status").val(),
					    	startTime: $("#c_startTime").val(),
				  			endTime: $("#c_endTime").val(),
				  			phone : $(".mobilephone").val(),
							username : $(".username").val(),
//				  			repairWay: $(".select-repair-way").val(),
//				  			repairArea: $(".select-repair-place").val(),
//				  			repairType: $(".select-repair-type").val(),
				  			code: $(".repair-code").val()
					  }
					  ,page: {
					    curr: 1 //重新从第 1 页开始
					  }
				}); 
			},
			/*
			 * 通过
			 * @param type 1 通过 2 拒绝
			 * @param id 维修单id
			 */
			ajaxPass: function(type,id){
				var _this = this;
				if(type==1){
					layer.confirm('确定处理完成?', {
						  btn: ['确定', '取消'] 
						}, function(index, layero){
							 layer.close(index); //如果设定了yes回调，需进行手工关闭
							_this.ajaxPassC(type,id);
						}, function(index){
							
						});
				}else{
					layer.confirm('确定拒绝?', {
						  btn: ['确定', '取消'] 
						}, function(index, layero){
							 layer.close(index); //如果设定了yes回调，需进行手工关闭
							_this.ajaxPassC(type,id);
						}, function(index){
							
						});
				}
				
				
			},
			/*
			 * @param type 1 通过 2 拒绝
			 * @param id 维修单id
			 */
			ajaxPassC:function(type,id){
				var _this = this;
				$.ajax({
					   type: "post",
					   url: $("#contextPath").val()+ "/repairService/repairApproval", 
					   data: {
						   "operateType": type,
						   "id": id
					   },
					   success: function(data){
						   if(data.code == '200'){
							   if(type==1){
								   layer.msg('通过成功！');
							   }else{
								   layer.msg('拒绝成功！');
							   }
							   $(".dialog-wp").remove();
							   _this.againRenderTable()
						   }else{
							   layer.msg(data.msg)
						   }   
					   },
					   error: function(error){  
						   layer.msg('error')
					   }
			   });
			},
			/**
			 * 显示获取可指派人员的弹窗
			 * @param id 维修单id
			 */
			showChoosePersonDialog: function(id){
				var _this = this;
				$.ajax({
					   type: "post",
					   url: $("#contextPath").val()+ "/repairBill/getRepairUser", 
					   data:{
						   "id": id
					   },
					   success: function(data){
//						   var data = JSON.parse(data);
						   if(data.code == '200'){
							   //显示可指派弹窗
							  $("body").append(template.render(tpl.choosePersonTpl)(data));
							  $(".close-btn").on("click",function(){
									 $(this).closest(".dialog-wp").remove();
								 })
							  //派单
							  $(".choose-perosn-btn").on("click",function(){
								  var receiverId = $(".person-item .radio-item:checked").data("id");
								  _this.ajaxSlip(id,receiverId,$(".dialog-wp"));
							  })
						   }else{
							   layer.msg(data.msg)
						   }   
					   },
					   error: function(error){  
						   layer.msg('error')
					   }
			   });
			},
			/**
			 * 转单
			 * @param id 维修单id
			 * @param receiverId 接收人ID
			 * @param $dom 弹窗
			 */
			ajaxSlip: function(id,receiverId){
				var _this = this;
				$.ajax({
					   type: "post",
					   url: $("#contextPath").val()+ "/repairBill/sendBill", 
					   data:{
						   "id": id,
						   "receiverId": receiverId
					   },
					   success: function(data){
//						   var data = JSON.parse(data);
						   if(data.code == '200'){
							  layer.msg("派单成功！");
							  $(".dialog-wp").remove();
							  _this.againRenderTable()
						   }else{
							   layer.msg(data.msg)
						   }   
					   },
					   error: function(error){  
						   layer.msg('error')
					   }
			   });
			},
			/**
			 * 查看订单详情
			 * @param id 维修单id
			 * @param status  维修单状态
			 * 
			 */
			ajaxDetail: function(id,status){
				var _this = this;
				$.ajax({
					   type: "post",
					   url: $("#contextPath").val()+ "/repairService/repairInfo", 
					   data:{
						   "id": id
					   },
					   success: function(data){
//						   var data = JSON.parse(data);
						   if(data.code == '200'){
							 $("body").append(template.render(tpl.detailTpl)(data.data));
							 //关闭详情弹窗
							 $(".close-btn").on("click",function(){
								 $(this).closest(".dialog-wp").remove();
							 });
							 $(".dialog .repair-img-item .img").zoomify()
							 //拒绝
							 $(".detail-reject-btn").on("click",function(){
								 _this.ajaxPass(2,id);
								
							 });
							 //通过
							 $(".detail-pass-btn").on("click",function(){
								 _this.ajaxPass(1,id);
							 });
							 //派单
							 $(".dialog-wp .send-order").on("click",function(){
								 _this.showChoosePersonDialog(id);
							 })
						   }else{
							   layer.msg(data.msg)
						   }   
					   },
					   error: function(error){  
						   layer.msg('error')
					   }
			   });
			}
	};
	launchRepair.init();
})