/**
 * 发起维修
 * 2018/5/7 by liufang
 */
$(function(){
	var layer;
	layui.use('layer', function(){
		   layer = layui.layer;  
	});
	var contextPath = $("#contextPath").val();
	var tpl = {
			"imgTpl": '<div class="r-item-img-wp">\
						<div class="r-item-img"></div>\
						<span class="r-item-del-btn"></span>\
					 </div>',
			"typeTpl": '<option value="">选择维修小类</option>\
					<% for(i=0;i<data.length;i++){%> \
						<option value="<%=data[i].id%>"><%=data[i].itemname%></option>\
					 <%}%>'		 
	}
	var launchRepair = {
			init: function(){
				this.render();
				this.bindEvent();
			},
			render: function(){
				var _this = this;
			
			},
			bindEvent: function(){
				var _this = this;
				//发起维修
				$(".repair-btn").on("click",function(){
					_this.ajaxSubmit();
				});
				$(".r-choose-wp .radio-wp").on("click",function(){
					if($(this).find(".radio-item:checked").data("type") == 0){
						$(".meetting-time").hide();
					}else{
						$(".meetting-time").show();
					}
					//$(".radio-wp .radio-item:checked").data("status");
				});
				// 模糊搜索
				_this.search_fuzzy()
			
					layui.use('laydate', function(){
						  var laydate = layui.laydate;
						  
						  //执行一个laydate实例
						  laydate.render({
						    elem: '#meeting_time' //指定元素
					    	 ,type: 'datetime'	
					    	,min: 0
						  });
						});
//				});
				//维修方式
//				$(".repair-way").on("change",function(){
//					var val = $(this).val();
//					if(val){
//						//选择内部报修
//						if(val == 265){
//							$(".repair-place option").each(function(index,ele){
//								if($(ele).val() == 266 || $(ele).val() == 268){
//									$(ele).attr("disabled",false);
//								}else if($(ele).val() != ''){
//									$(ele).attr("disabled",true);
//								}
//							})
//						}else if(val == 264){
//							//客户来电
//							$(".repair-place option").each(function(index,ele){
//								if($(ele).val() == 267){
//									$(ele).attr("disabled",false);
//								}else if($(ele).val() != ''){
//									$(ele).attr("disabled",true);
//								}
//							})
//						}	
//					}else{
//						$(".repair-place option").each(function(index,ele){
//							if($(ele).val() != ''){
//								$(ele).attr("disabled",true);
//							}
//						})
//					}
//				});
				//维修小类
				$(".repair-type").on("change",function(){
					var val = $(this).val();
					if(!val){
						$(".repair-type-detail").html($("<option value=''>选择维修小类</option>"));
					}else{
						_this.ajaxType(val);
					}
				})
				//上传图片
				$(".r-img-file").on("change",function(){
					var fileName=document.getElementsByClassName("r-img-file")[0].value;  
				    var suffixIndex=fileName.lastIndexOf(".");  
				    var suffix=fileName.substring(suffixIndex+1).toUpperCase();  
				    if(suffix!="BMP"&&suffix!="JPG"&&suffix!="JPEG"&&suffix!="PNG"&&suffix!="GIF"){  
				     layer.alert( "请上传图片（格式BMP、JPG、JPEG、PNG等）!");  
				     return false;
				    }  
					$(".r-item-img-list").append(tpl.imgTpl);
					_this.selectFileImage($(".r-img-file"),$(".r-item-img-wp").eq($(".r-item-img-wp").length-1).find(".r-item-img"),function(){
						$(".r-item-del-btn").on("click",function(){
							$(this).closest(".r-item-img-wp").remove();
						})
					})
				})
			},
			// 模糊搜索事件
			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.organ-id',
				});

				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})
			},
			/**
			 * 请求小类
			 * @param repairTypeId
			 * 
			 */
			ajaxType: function(repairTypeId){
				$.ajax({
					   type: "post",
					   url: $("#contextPath").val()+ "/repairBill/getRepairTypeaDetail", 
					   data: {
						   repairTypeId: repairTypeId
					   },
					   success: function(data){
						   if(data.code== 200){
							   $(".repair-type-detail").html(template.render(tpl.typeTpl)(data));
						   }else{
							   layer.msg(data.msg);
						   }   
					   },
					   error: function(){   
					   }
			   });
			},
			/**
			 * 发起维修
			 * 
			 */
			ajaxSubmit: function(){
				var formData = new FormData();
				var _this = this;
				
				//校区Id
				var orgId = $("#orgId").attr('org__id')
				if(!orgId){
					layer.msg("请选择校区");
					return false;
				};
				formData.append("orgId", orgId);
				
				//报修方式
				var repairWay = $(".repair-way").val();
				if(!repairWay){
					layer.msg("请选择报修方式");
					return false;
				};
				formData.append("repairWay", repairWay);
				//维修区域
				var repairArea = $(".repair-place").val();
				if(!repairArea){
					layer.msg("请选择维修区域");
					return false;
				};
				formData.append("repairArea", repairArea);
				//维修类型
				var repairType = $(".repair-type").val();
				if(!repairType){
					layer.msg("请选择维修大类");
					return false;
				};
				formData.append("repairType", repairType);
				//维修小类型
				var repairTypeDetail = $(".repair-type-detail").val();
				if(!repairTypeDetail){
					layer.msg("请选择维修小类");
					return false;
				};
				formData.append("repairTypeDetail", repairTypeDetail);
				//报修人
				var repairUser = $(".repair-person").val();
				if(!repairUser){
					layer.msg("请输入报修人");
					return false;
				};
				formData.append("repairUser", repairUser);
				//联系方式
				//var myreg=/^[1][3,4,5,6,7,8][0-9]{9}$/;
				var myreg=/^[0-9]{11}$/;
				var contactWay = $(".repair-phone").val();
				if(!contactWay){
					layer.msg("请输入联系方式");
					return false;
				}else if(!myreg.test(contactWay)){
					layer.msg("请输入正确的联系方式");
					return false;
				};
				formData.append("contactWay", contactWay);
				
				//预约时间
				if($(".r-choose-wp .radio-item:checked").data("type")!=0 && $(".r-choose-wp .radio-item:checked").data("type")!=1){
					layer.msg("请选择上门时间");
					return false
				};
				
				if($(".r-choose-wp .radio-item:checked").data("type")==1){
					var meettingTime =  $(".meetting-time").val();
					if(!meettingTime){
						layer.msg("请选择时间");
						return false;
					}else{
						var oDate1 = new Date();
					    var oDate2 = new Date($(".meetting-time").val());
					    if(oDate1.getTime() > oDate2.getTime()){
					    	layer.msg("选择时间必须大于当前时间！");
					    	return false;
					    }
					}
					formData.append("meettingTime", meettingTime);
				}
				
				//地址
				var  address =  $(".repair-address").val();
				if(!address){
					layer.msg("请输入地址");
					return false;
				};
				formData.append("address", address);
				//报修描述
				var description = $(".repair-descript").val();
				if(!description){
					layer.msg("请输入报修描述");
					return false;
				};
				formData.append("description", description);
				//发起方式
				formData.append("billFrom", 1);
				$(".r-item-img-wp").each(function(index,ele){
					console.log("ele:",ele)
					formData.append("file"+(+index+1), $(ele).data("file"));
				})
				$(".repair-btn").attr("disabled",true)
				$.ajax({
					   type: "post",
					   url: $("#contextPath").val()+ "/repairBill/repair", 
					   data: formData,
					   cache: false,                      // 不缓存
				        processData: false,                // 告诉jQuery不要去处理发送的数据
				        contentType: false,                // 告诉jQuery不要去设置Content-Type请求头
				        dataType: 'text',
//					   data: {
//						   "repairWay": repairWay,
//						   "repairArea": repairArea,
//						   "repairType": repairType,
//						   "repairUser": repairUser,
//						   "contactWay": contactWay,
//						   "address": address,
//						   "description": description,
//						   "billFrom": 1
//					   },
					   success: function(data){
						   $(".repair-btn").attr("disabled",false)
						   var data = JSON.parse(data);
						   if(data.code == '200'){
							  $("#conditionform").find(".default-select,.repair-textarea,.repair-text").val("");
							 
							  $("#conditionform").find(".r-item-img-list").html("");
							   layer.msg('发起维修成功！');
						   }else{
							   layer.msg(data.msg)
						   }   
					   },
					   error: function(){   
						   $(".repair-btn").attr("disabled",false);
						   layer.msg('error')
					   }
			   });
			},
			/**
			 * 上传图片
			 * @param $dom 上传按钮
			 * @param $imgWp 图片容器
			 * @param $base64Wp 存放base64得input
			 * @param callback 回调
			 */
			selectFileImage:function ($dom,$imgWp,callback) {
				
				var file = $dom[0].files[0];
				var Orientation = null;
				$dom.val("");//上传传按钮
				
				$imgWp.closest(".r-item-img-wp").data("file",file)
				if (file) {
					console.log("正在上传,请稍后...");
//					var rFilter = /^(image\/jpeg|image\/png)$/i; // 检查图片格式
//					if (!rFilter.test(file.type)) {
//						layer.msg('图片格式有误，请上传(jpeg,png)');
//						return;
//					}
					EXIF.getData(file, function() {
						EXIF.getAllTags(this);
						Orientation = EXIF.getTag(this, 'Orientation');
					});

					var oReader = new FileReader();
					oReader.onload = function(e) {
						var image = new Image();
						image.src = e.target.result;
						image.onload = function() {
							var expectWidth = this.naturalWidth;
							var expectHeight = this.naturalHeight;

							if (this.naturalWidth > this.naturalHeight
									&& this.naturalWidth > 800) {
								expectWidth = 800;
								expectHeight = expectWidth * this.naturalHeight
										/ this.naturalWidth;
							} else if (this.naturalHeight > this.naturalWidth
									&& this.naturalHeight > 1200) {
								expectHeight = 1200;
								expectWidth = expectHeight * this.naturalWidth
										/ this.naturalHeight;
							}
							var canvas = document.createElement("canvas");
							var ctx = canvas.getContext("2d");
							canvas.width = expectWidth;
							canvas.height = expectHeight;
							ctx.drawImage(this, 0, 0, expectWidth, expectHeight);
							var base64 = null;
							var clearBase64 = null;
							base64 = canvas.toDataURL("image/png", 2);
							if (base64 != null) {
								clearBase64 = base64.substr(base64.indexOf(',') + 1)
							}
							$imgWp.html("<img src='"+base64+"' alt='' />");//图片容器
//							$base64Wp.val(clearBase64);//存放base64得
							callback(base64);
						};
					};
					oReader.readAsDataURL(file);
				}
			},
	};
	launchRepair.init();
})