var myArray=new Array();
var delArray;
/**
 * 公共服务JS
 */

$(function(){
	myArray=new Array();
	myArray.push(1);
	$("#add-btn").click(function(){
		showAddServiceTypeInfo();
	});
	//删除图片
	$(".uploadimgcancel").click(function(){
		var type = $(this).data("type");
		 if (type == 2){
             $(".showimgApp").html("<img src='../../images/common/inputImg.png' alt='' />");
             $("#grayAppServiceIcon").val("");
         }else if (type == 3){
             $(".showimgWechat").html("<img src='../../images/common/inputImg.png' alt='' />");
             $("#grayWechatServiceIcon").val("");
         }else {
             $(".showimg").html("<img src='../../images/common/inputImg.png' alt='' />");
             $("#serviceIcon").val("");
         }
//		$(".showimg").html("<img src='../../images/common/inputImg.png' alt='' />");
//		$("#serviceIcon").val("");
	});
});

/**
 * 查询
 */
function searchServiceTypeInfo(){
	$("#conditionform").submit();
}

/**
 * 显示新增的动态model
 */
function showAddServiceTypeInfo(){
	$(".form-horizontal")[0].reset();
	$('input[name="paymentTypeGroup"]').attr("checked",false); 
	$("#save").show();
	$(".showimg").html("<img src='../../images/common/inputImg.png' alt='' />");
	$("#actype").val("");
	$("#id").val("");
	$("#myModalLabel").html("服务内容信息新增");
	$('#saveUpdateModal').modal('show');
}

/**
 * 翻页
 * @param pageNo 页码
 */
function goPage(pageNo){
	if(pageNo=="gopage"){
		$("#pageNo").val($("#gopage").val());
	}else{
		$("#pageNo").val(pageNo);
	}
	$("#conditionform").submit();
}

/**
 * 显示需要编辑的model
 * @param id
 */
function showEidtServiceTypeInfo(id){
	$(".form-horizontal")[0].reset();
	$('input[name="paymentTypeGroup"]').attr("checked",false); 
	var url=$("#contextPath").val()+"/service/type/getServiceTypeInfo";
	$.ajax({
    	url: url,
    	data: {id:id},
        type: "POST",
        success: function(data){
        	if(data!=null){
        		$("#save").show();
        		$("#serviceName").val(data.serviceName);
        		$("#serviceRemark").val(data.serviceRemark);
        		$("#code").val(data.code);
        		$("#skipAddress").val(data.skipAddress);
        		$("#jumpAddress").val(data.jumpAddress);
        		$("#linkUrlType").val(data.linkUrlType);
        		$("#serviceType").val(data.serviceType);
        		$("#serviceIcon").val(data.serviceIcon);
        		$("#isSignContract").val(data.isSignContract);
        		$("#id").val(data.id);
        		$("#registerStatus").val(data.registerStatus);
        		if(data.serviceStatus=="0"){
        			$("#depositType").val(data.depositType);
        			var paymentTypeArray=data.paymentType.split(",");
        			var paymentTypeGroupArrayCheck=document.getElementsByName('paymentTypeGroup');
	        		$.each(paymentTypeGroupArrayCheck,function(index,item){
	        			$.each(paymentTypeArray,function(no,obj){
	        				if(item.value==obj){
	        					$("#paymentType"+item.value+"").attr("checked",true);
	        				}
	        			})
	        		})
        		}
        		$("#myModalLabel").html("服务内容信息编辑");
        		$('#saveUpdateModal').modal('show');
        		$(".showimg").html("<img src='"+$("#visitPrefix").val()+data.serviceIcon+"' alt='' />");
                $("#serviceCategory").val(data.serviceCategory);
                $("#grayAppServiceIcon").val(data.grayAppServiceIcon);
                $(".showimgApp").html("<img src='"+$("#visitPrefix").val()+data.grayAppServiceIcon+"' alt='' />");
                $("#grayWechatServiceIcon").val(data.grayWechatServiceIcon);
                $(".showimgWechat").html("<img src='"+$("#visitPrefix").val()+data.grayWechatServiceIcon+"' alt='' />");
                $("#grayUrl").val(data.grayUrl);
        	}else{
        		alert("程序异常！");
        	}
			
        },
        error: function(){
        	layer.msg("提交失败，请检测网络", {icon: 5,end:function(){
        		
        	}});
        }
    });	
}

/**
 * 服务内容详情
 * @param id
 */
function showServiceTypeInfoDetails(id){
	$(".form-horizontal")[0].reset();
	$('input[name="paymentTypeGroup"]').attr("checked",false);
	var url=$("#contextPath").val()+"/service/type/getServiceTypeInfo";
	$.ajax({
    	url: url,
    	data: {id:id},
        type: "POST",
        success: function(data){
        	if(data!=null){
        		$("#save").hide();
        		$("#serviceName").val(data.serviceName);
        		$("#serviceRemark").val(data.serviceRemark);
        		$("#code").val(data.code);
        		$("#skipAddress").val(data.skipAddress);
        		$("#jumpAddress").val(data.jumpAddress);
        		$("#linkUrlType").val(data.linkUrlType);
        		$("#serviceType").val(data.serviceType);
        		$("#serviceIcon").val(data.serviceIcon);
        		$("#registerStatus").val(data.registerStatus);
        		$("#isSignContract").val(data.isSignContract);
        		if(data.serviceStatus=="0"){
        			$("#depositType").val(data.depositType);
        			var paymentTypeArray=data.paymentType.split(",");
        			var paymentTypeGroupArrayCheck=document.getElementsByName('paymentTypeGroup');
	        		$.each(paymentTypeGroupArrayCheck,function(index,item){
	        			$.each(paymentTypeArray,function(no,obj){
	        				if(item.value==obj){
	        					$("#paymentType"+item.value+"").attr("checked",true);
	        				}
	        			})
	        		})
        		}
        		$("#id").val(data.id);
        		$("#myModalLabel").html("服务内容信息详情");
        		$('#saveUpdateModal').modal('show');
        		$(".showimg").html("<img src='"+$("#visitPrefix").val()+data.serviceIcon+"' alt='' />");
                $("#serviceCategory").val(data.serviceCategory);
                $("#grayAppServiceIcon").val(data.grayAppServiceIcon);
                $(".showimgApp").html("<img src='"+$("#visitPrefix").val()+data.grayAppServiceIcon+"' alt='' />");
                $("#grayWechatServiceIcon").val(data.grayWechatServiceIcon);
                $(".showimgWechat").html("<img src='"+$("#visitPrefix").val()+data.grayWechatServiceIcon+"' alt='' />");
                $("#grayUrl").val(data.grayUrl);
        	}else{
        		alert("程序异常！");
        	}
			
        },
        error: function(){
        	layer.msg("提交失败，请检测网络", {icon: 5,end:function(){
        		
        	}});
        }
    });	
}

/**
 * 删除服务内容信息
 * @param id
 * @param serviceName
 */
function delServiceTypeInfo(id,serviceName){
	var url=$("#contextPath").val()+"/service/type/deleteServiceInfo";
	var serviceStatus=$("#serviceStatus").val();
	layer.confirm('您确定要删除'+serviceName+'信息吗？', {
		  btn: ['确定','取消'] //按钮
		}, function(){
			$.ajax({
		    	url: url,
		    	data: {id:id},
		        type: "POST",
		        success: function(data){
		        	if(data.flag){
		        		if("0"==serviceStatus){
		        			$("#conditionform").submit();
		                	}else{
		                	$("#conditionform").submit();
		                	}
			        	layer.alert(data.desc, {icon: 6}, function(){
			        		$("#conditionform").submit();
			        	});
		        	}else{
		        		layer.msg("删除失败！", {icon: 5});
		        	}
					
		        },
		        error: function(){
		        	layer.msg("提交失败，请检测网络", {icon: 5});
		        }
		    });	
		}, function(){
		
		});
}

/**
 * 新增或修改服务内容信息
 */
function saveUpdateServiceTypeInfo(){
	var serviceName=$("#serviceName").val();
	var serviceRemark=$("#serviceRemark").val();
	var id=$("#id").val();
	if($.trim(serviceName)==""){
		layer.msg('请输入服务名称！');
		return;
	}
	var code=$("#code").val();
	if($.trim(code)==""){
		layer.msg('请输入服务编码！');
		return;
	}
	var skipAddress=$("#skipAddress").val();
	if($.trim(skipAddress)==""){
		layer.msg('请输入服务未认证地址！');
		return;
	}
	var jumpAddress=$("#jumpAddress").val();
	if($.trim(jumpAddress)==""){
		layer.msg('请输入服务已认证地址！');
		return;
	}
	var registerStatus=$("#registerStatus").val();
	if($.trim(registerStatus)==""){
		layer.msg('请选择是否注册！');
		return;
	}
	var linkUrlType=$("#linkUrlType").val();
	if($.trim(linkUrlType)==""){
		layer.msg('请选择跳转类型！');
		return;
	}
	var serviceType=$("#serviceType").val();
	if($.trim(serviceType)==""){
		layer.msg('请选择服务类型！');
		return;
	}
	var isSignContract=$("#isSignContract").val();
	if($.trim(isSignContract)==""){
		layer.msg('请选择服务签约状态！');
		return;
	}
	var serviceIcon=$("#serviceIcon").val();
	if($.trim(serviceIcon)==""){
		layer.msg('请上传服务图片！');
		return;
	}
    var serviceCategory=$("#serviceCategory").val();
    if($.trim(serviceCategory)==""){
        layer.msg('请选择服务分类！');
        return;
    }
	var url=$("#contextPath").val()+"/service/type/saveUpdateServiceTypeInfo";
	var serviceStatus=$("#serviceStatus").val();
	var depositType="";
	var paymentType="";
	if(serviceStatus=="0"){
		depositType=$("#depositType").val();
		if($.trim(depositType)==""){
			layer.msg('请选择是否押金！');
			return;
		}
		var paymentTypeGroupArray=document.getElementsByName('paymentTypeGroup');   
		  for(var i=0; i<paymentTypeGroupArray.length; i++){    
		    if(paymentTypeGroupArray[i].checked) paymentType+=paymentTypeGroupArray[i].value+',';  //如果选中，将value添加到变量s中    
		  }
		if($.trim(paymentType)==""){
			layer.msg('请选择结算方式！');
			return;
		}
	}
	var actype=$("#actype").val();
	var organizationId=$("#organizationId").val();
	var grayUrl = $("#grayUrl").val();
    var grayAppServiceIcon = $("#grayAppServiceIcon").val();
    var grayWechatServiceIcon = $("#grayWechatServiceIcon").val();
	var roleGroup='';
	$.ajax({
    	url: url,
    	data: {id:id,serviceName:serviceName,serviceRemark:serviceRemark,serviceIcon:serviceIcon,code:code,skipAddress:skipAddress,
    		jumpAddress:jumpAddress,serviceType:serviceType,serviceStatus:serviceStatus,linkUrlType:linkUrlType,
    		actype:actype,organizationId:organizationId,roleGroup:roleGroup,registerStatus:registerStatus,depositType:depositType,paymentType:paymentType,isSignContract:isSignContract,
            grayAppServiceIcon:grayAppServiceIcon,grayWechatServiceIcon:grayWechatServiceIcon,serviceCategory:serviceCategory,grayUrl:grayUrl},
        type: "POST",
        success: function(data){
        	if(data.flag){
	        	layer.alert(data.desc, {icon: 6,end:function(){
	        		$("#conditionform").submit();
	        	}});
        	}else{
        		layer.msg(data.desc, {icon: 5,end:function(){
        			$("#conditionform").submit();
	        	}});
        	}
			
        },
        error: function(){
        	layer.msg("提交失败，请检测网络", {icon: 5,end:function(){
        		location.href=url;
        	}});
        }
    });	
}

/**
 * 服务押金细项项配置
 * @param id
 */
function showDepositItemInformationForm(id){
	$("#serviceTypeInfoId").val(id);
	myArray=new Array();
	$("#servicePz").empty();
	var url=$("#contextPath").val()+"/service/deposit/getDepositItemInformationFormList";
	$.ajax({
    	url: url,
    	data: {serviceTypeInfoId:id},
        type: "POST",
        success: function(data){
        	if(data!=null && data.length>0){
        		var html="";
        		var index=0;
        		for(var i=0;i<data.length;i++){
        				index=i+1;
        				html="<div  style='background-color:white;' id='depositItem"+index+"'><input type='hidden' id='deposId"+index+"' value='"+data[i].id+"' />";
        				html+="<label class='col-sm-2 control-label' for='deposName"+index+"' style='padding-top:0px;padding-left: 1px;'>" +
        						"<span style='color: red;'>*</span>名称：" +
        					  "</label>" +
        					  "<div class='col-sm-3'><input class='form-control' id='deposName"+index+"'  type='text' value='"+data[i].deposName+"' placeholder='请输入名称'/>" +
        					  "</div>" +
        					  "<label class='col-sm-2 control-label' for='price"+index+"' style='padding-top:0px;padding-left: 1px;'>" +
        					  		"<span style='color: red;'>*</span>金额：" +
        					  "</label>" +
        					  "<div class='col-sm-3'>" +
        					  	"<input class='form-control' id='price"+index+"' value='"+data[i].price+"'  name='price"+i+"' type='text' placeholder='请输入金额'/>" +
        					  "</div>" +
        					  "<div class='col-sm-2'>";
        				if(index==1){
        					html+="<a class='btn btn-success' href='javascript:void(0);' onclick='adddepositItemForm()'>添加</a></div></div>";
        				}else{
        					html+="<a class='btn btn-danger' href='javascript:void(0);' onclick='deleteDepositItemForm("+index+")'>删除</a></div></div>";
        				}
        				myArray.push(index);
        				$("#servicePz").append(html);
        		}
        	}else{
        		var html="";
        		myArray.push(1);
        		html="<legend >服务押金细项内容信息</legend>";
				html="<div  style='background-color:white;' id='depositItem1'><input type='hidden' id='deposId1'  />";
				html+="<label class='col-sm-2 control-label' for='deposName1' style='padding-top:0px;padding-left: 1px;'>" +
						"<span style='color: red;'>*</span>名称：" +
					  "</label>" +
					  "<div class='col-sm-3'><input class='form-control' id='deposName1'  type='text'  placeholder='请输入名称'/>" +
					  "</div>" +
					  "<label class='col-sm-2 control-label' for='price1' style='padding-top:0px;padding-left: 1px;'>" +
					  		"<span style='color: red;'>*</span>金额：" +
					  "</label>" +
					  "<div class='col-sm-3'>" +
					  	"<input class='form-control' id='price1'   name='price1' type='text' placeholder='请输入金额'/>" +
					  "</div>" +
					  "<div class='col-sm-2'>" +
					  		"<a class='btn btn-success' href='javascript:void(0);' onclick='adddepositItemForm()'>添加</a>" +
					  "</div>" +
				 "</div>";
				$("#servicePz").append(html);
        	}
			
        },
        error: function(){
        	layer.msg("请检测网络", {icon: 5,end:function(){
        		
        	}});
        }
    });	
	delArray=new Array();
	$("#myDepositItem").html("服务押金细项内容信息");
	$('#saveUpdateDepositItem').modal('show');
}

/**
 * 删除元素
 * @param index
 */
function deleteDepositItemForm(index){
	myArray.splice(myArray.indexOf(index),1);
	var deposId=$("#deposId"+index+"").val();
	if(deposId!=""){
		delArray.push(deposId);
	}
	$("#depositItem"+index+"").remove();
}

/**
 * 动态添加服务押金配置
 */
function adddepositItemForm(){
	var index=myArray[myArray.length-1];
	index+=1;
	var html="";
	html="<div  style='background-color:white;' id='depositItem"+index+"'><input type='hidden' id='deposId"+index+"' />";
		html+="<label class='col-sm-2 control-label' for='deposName"+index+"' style='padding-top:0px;padding-left: 1px;'>" +
				"<span style='color: red;'>*</span>名称：" +
			  "</label>" +
			  "<div class='col-sm-3'><input class='form-control' id='deposName"+index+"'  type='text' placeholder='请输入名称'/>" +
			  "</div>" +
			  "<label class='col-sm-2 control-label' for='price"+index+"' style='padding-top:0px;padding-left: 1px;'>" +
			  		"<span style='color: red;'>*</span>金额：" +
			  "</label>" +
			  "<div class='col-sm-3'>" +
			  	"<input class='form-control' id='price"+index+"'  name='price"+index+"' type='text' placeholder='请输入金额'/>" +
			  "</div>" +
			  "<div class='col-sm-2'>" +
			  		"<a class='btn btn-danger' href='javascript:void(0);' onclick='deleteDepositItemForm("+index+")'>删除</a>" +
			  "</div>" +
		 "</div>";
	$("#servicePz").append(html);
	myArray.push(index);
}
/**
 * 保存或修改或删除服务押金项
 */
function SaveUpdateDepositItem(){
	var myArrays="";
	var delArrays="";
	for(var i=0;i<delArray.length;i++){
		delArrays+=delArray[i]+",";
	}
	var serviceTypeInfoId=$("#serviceTypeInfoId").val();
	var data="{serviceTypeInfoId:'"+serviceTypeInfoId+"',delArrays:'"+delArrays+"'"
	for(var i=0;i<myArray.length;i++){
		var deposName=$("#deposName"+myArray[i]+"").val();
		var price=$("#price"+myArray[i]+"").val();
		var deposId=$("#deposId"+myArray[i]+"").val();
		data+=",deposName"+myArray[i]+":'"+deposName+"',price"+myArray[i]+":'"+price+"',deposId"+myArray[i]+":'"+deposId+"'"
		myArrays+=myArray[i]+",";
	}
	data+=",myArrays:'"+myArrays+"'"
	data+="}";
	var obj = eval('(' + data + ')');
	var url=$("#contextPath").val()+"/service/deposit/saveUpdateDepositItemInformationForm";
	$.ajax({
    	url: url,
    	data: obj,
        type: "POST",
        success: function(data){
        	url="/super_service/service/type/serviceTypeInfoPage?funcid="+$("#funcid").val();
        	if(data.flag){
        		layer.alert(data.desc, {icon: 6,end:function(){
        			$("#conditionform").submit();
	        	}});
        	}else{
        		layer.msg(data.desc, {icon: 5,end:function(){
            		
            	}});
        	}
        },
        error: function(){
        	layer.msg("请检测网络", {icon: 5,end:function(){
        		
        	}});
        }
    });	
	
}

/**
 * 上传图片
 * @param fileObj
 */
function selectFileImage(fileObj,type) {
	//type: 1-服务图标 2-灰度APP图片 3-灰度微信端图片
	var file = fileObj.files['0'];
	var Orientation = null;
	if (type == 2){
        $("#grayAppFileInput").val("");
	}else if (type == 3){
        $("#grayWechatFileInput").val("");
    }else {
        $("#fileInput").val("");
    }

    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;
				var mpImg = new MegaPixImage(image);
//				mpImg.render(canvas, {
//					maxWidth : 800,
//					maxHeight : 1200,
//					quality : 0.6,
//					orientation : Orientation
//				});
				base64 = canvas.toDataURL("image/png", 2);
				if (base64 != null) {
					clearBase64 = base64.substr(base64.indexOf(',') + 1)
				}

                if (type == 2){
                    $(".showimgApp").html("<img src='"+base64+"' alt='' />");
                    $("#grayAppServiceIcon").val(clearBase64);
                }else if (type == 3){
                    $(".showimgWechat").html("<img src='"+base64+"' alt='' />");
                    $("#grayWechatServiceIcon").val(clearBase64);
                }else {
                    $(".showimg").html("<img src='"+base64+"' alt='' />");
                    $("#serviceIcon").val(clearBase64);
                }

                if($("#id").val()!=""){
					$("#actype").val("1");
				}
			};
		};
		oReader.readAsDataURL(file);
	}
}

function manageServiceInfo(status){
	var typeGroupId=$("input[name='typeGroupId']:checked").val();
	if(typeGroupId==""||typeGroupId==null){
		alert("请选择服务.");
	}
	else{
		var contextPath=$("#contextPath").val();
		var funcid=$("#funcid").val();
		window.location.href=contextPath+"/service/type/serviceTypeManage?status="+status+"&serviceTypeId="+typeGroupId+"&funcid="+funcid;
	}
	
}

