/**
 * 水果类统计支出js
 */
$(function(){
	getOrgdeptListInfo();
	var orgid = localStorage.getItem(getQueryVariable("JSONID")+"orgid");
	if(orgid.length>2){
		$("#addBtn").show();
		$("#xd").show();
	}else{
		$("#sd").show();
		$("#so").show();
	}
	
	getTypeList();
	loadYears("year","zzy_sg")
	loadYears("baseyear")
	loadYears("baseEdityear")
	initTable();
})

/**
 * 查询水果分类
 */
var dataList = [];
function getTypeList(){
	$.ajax({
		type:"Post",
		url:"../fruit/getTypeAllList.service",
		dataType:"json",
		success:function(data){
			var str = '';
			dataList = data.list;
			$.each(data.list,function(i,item){
				str += '<option value="'+item.id+'">'+item.name+'</option>';
			})
			$("#typeId").html(str)
			 var config = {
	            '.chosen-select': {},
	            '.chosen-select-deselect': {
	                allow_single_deselect: true
	            },
	            '.chosen-select-no-single': {
	                disable_search_threshold: 10
	            },
	            '.chosen-select-no-results': {
	                no_results_text: '没有更多数据'
	            },
	      }
	       for (var selector in config) {
	            $(selector).chosen(config[selector]);
	            var width = "100%"
	            $('.chosen-container-single').attr("style", "width:"+width)
	        }
	         $('#typeId').val($('#typeId').val()).trigger('chosen:updated');
		}
	});
}


function getOrgdeptListInfo(){
	$.ajax({
		type:"Post",
		url:"../organization/getOrgdeptListInfo.service",
		dataType:"json",
		success:function(data){
			var str = '<option value="">全部区县</option>';
			$.each(data.list,function(i,item){
				if(item.id.length>2){
					str += '<option value="'+item.id+'">'+item.text+'</option>';
				}
			})
			$("#orgdeptId").html(str)
			 var config = {
	            '.chosen-select': {},
	            '.chosen-select-deselect': {
	                allow_single_deselect: true
	            },
	            '.chosen-select-no-single': {
	                disable_search_threshold: 10
	            },
	            '.chosen-select-no-results': {
	                no_results_text: '没有更多数据'
	            },
	      }
	       for (var selector in config) {
	            $(selector).chosen(config[selector]);
	            var width = "100%"
	            $('.chosen-container-single').attr("style", "width:"+width)
	        }
	         $('#orgdeptId').val($('#orgdeptId').val()).trigger('chosen:updated');
		}
	});
}
/**
 * 新增录入
 */
function addBtn(){
	$("#hiddenid").val("");
	var str ='';
	$.each(dataList,function(i,item){
		str +='<div class="form-group fruitInfo">'
		str +='	<label class="col-sm-3 control-label" style="text-align: center;">'+item.name+'</label>'
		str +='	<div class="col-sm-4">'
		str +='		<input id="'+item.id+'bzmj" name="money" class="form-control money" data-name="'+item.name+'播种面积" type="text" aria-required="true" >'
		str +='	</div>'
		str +='	<div class="col-sm-4">'
		str +='		<input id="'+item.id+'zcl" name="money" class="form-control money" data-name="'+item.name+'总产量" type="text" aria-required="true" >'
		str +='	</div>'
		str +='</div>'
	})
	$("#fruitHtml").html(str);	
	$("#baseModal").modal("show");
}

function saveAddBtn(){
	var flag = true
	$("input[name=money]").each(function(i,item){
		var value = item.value;
		if(value!=""&&!moneycheck.test(value)){
			flag = false
			showModal("请输入正确的"+item.getAttribute("data-name")+"数字")
			return;
		}
		
	})
	if(!flag){
		return;
	}
	var dataJson=[]
	$.each(dataList,function(i,item){
		var bzmj = $("#"+item.id+"bzmj").val()
		var zcl = $("#"+item.id+"zcl").val()
		bzmj=bzmj==""?"0.0":bzmj;
		zcl=zcl==""?"0.0":zcl;
		var da = {
			id:"",
			typeId:item.id,
			year:$("#baseyear").val(),
			typeName:item.name,
			bzmj:bzmj,
			zcl:zcl
		}
		dataJson.push(da)
	})
	
	$.ajax({
		type:"Post",
		url:"../sg/saveAddSgInfo.service",
		data:JSON.stringify(dataJson),
		dataType:"json",
		contentType : 'application/json',
		success:function(data){ 
			if(data.success=="true"){
				showModal(data.message);
				$("#baseModal").modal("hide");
				reLoadTable();
			}else{
				showModal(data.message);
				return;
			}
		}
	});	
	
}

/**
 * 编辑修改
 */
function edit(id){
	var rowdata = jQuery("#table_list_1").jqGrid("getRowData", id);
	$("#hiddenid").val(id);
	$("#baseyear").val(rowdata.year)
	$("#typeId").val(rowdata.typeId);
	$("#bzmj").val(rowdata.bzmj);
	$("#zcl").val(rowdata.zcl);
	$("#baseEditModal").modal("show");
}
/**
 * 保存信息
 */
function saveBtn(){
	var id = $("#hiddenid").val();
	var year = $("#baseyear").val();
	var typeId = $("#typeId").val();
	
	var bzmj = $("#bzmj").val();
	if(bzmj!=""&&!moneycheck.test(bzmj)){
		showModal("请输入正确的数字");
		return ;
	}
	var zcl = $("#zcl").val();
	if(zcl!=""&&!moneycheck.test(zcl)){
		showModal("请输入正确的数字");
		return ;
	}
	bzmj=bzmj==""?"0.0":bzmj;
	zcl=zcl==""?"0.0":zcl;
	$.ajax({
		type:"Post",
		url:"../sg/saveRecord.service",
		data:{ 
			id:id,
			year:year,
			typeId:typeId,
			bzmj:bzmj,
			zcl:zcl,
			typeName:$('.chosen-single span').html()
		},
		dataType:"json",
		success:function(data){
			if(data.success=="true"){
				if(id==""){
					loadYears("year","zzy_sg")
				}
				$("#baseEditModal").modal("hide");
				showModal(data.message);
				reLoadTable();
			}else{
				showModal(data.message);
				return;
			}
		}
	});
}
/**
 * 删除信息
 */
function deleteInfo(id){
	modalComfirm("确定删除该条信息吗",function(res){
		if(res){
			$.ajax({
				type:"Post",
				url:"../sg/deleteRecord.service",
				data:{ 
					id:id
				},
				dataType:"json",
				success:function(data){
					if(data.success=="true"){
						showModal(data.message);
						reLoadTable();
					}else{
						showModal(data.message);
						return;
					}
				}
			});
		}
	})
}

/* 重新加载表格 */
function reLoadTable() {
	$("#table_list_1").jqGrid('setGridParam', {
		url : "../sg/getRecordList.service",
		postData : {
			'year' : $("#year").val(),
			'orgid':$("#orgdeptId").val()
		}, //发送数据 
		page : 1
	}).trigger("reloadGrid"); //重新载入  
}
	
/* 初始化表格 */
function initTable() {
	$.jgrid.defaults.styleUI = 'Bootstrap';
	$("#table_list_1").jqGrid({
		url : "../sg/getRecordList.service",
		loadBeforeSend: function(xhr){
			xhr.setRequestHeader("token",getQueryVariable("JSONID"));
        },
		datatype : "json",
		height : 500,
		autowidth : true,
		shrinkToFit : true,
		rowNum : 50,
		rowList : [ 50, 100, 150 ],
		jsonReader : {
			root : "list",
			page : "currPage",
			total : "totalpages", //   很重要 定义了 后台分页参数的名字。
			records : "count",
			repeatitems : false,
			id : "id"
		},
		colNames : [ '操作', '部门','年度', '水果', '播种面积(亩)','总产量(吨)','1','1'],
		colModel : [
			{  name : 'caozuo',width: 25,align:'center',formatter :cLink,sortable:false },
			{  name : 'orgname',index : 'orgname',width: 80,sortable:false},
			{  name : 'year',index : 'year',width: 80,sortable:false},
			{  name : 'typeName',index : 'typeName',width: 80,sortable:false},
			{  name : 'bzmj',index : 'bzmj',width: 80,sortable:false,formatter:function(c,p,o){if(c==0){return ""}else{return c}}},
			{  name : 'zcl',index : 'zcl',width: 80,sortable:false,formatter:function(c,p,o){if(c==0){return ""}else{return c}}},
			{  name : 'typeId',index : 'typeId',width: 80,sortable:false,hidden:true},
			{  name : 'orgid',index : 'orgid',width: 140,sortable:false,hidden:true}
		],
		pager : "#pager_list_1",
		viewrecords : true,
		multiselect : false,
		caption : "",
		hidegrid : false,
		footerrow: true,
		gridComplete: function() {
			$.ajax({
				type : "post",
				url : "../sg/getSumHj.service",
				data : {
					'year':$("#year").val(),
					'orgid':$("#orgdeptId").val()
				},
				dataType : "json",
				success : function(data) {
					$('#table_list_1').footerData("set", { "orgname": "合计：", "year": "<font>播种总面积(亩)<font>",
						"typeName": "<font>" + parseFloat(data.bzmj).toFixed(2) + "<font>",
						"bzmj": "<font>总产量(吨)<font>",
						"zcl": "<font>" + parseFloat(data.zcl).toFixed(2) + "<font>"});
				}
			});
				
		 }
	});
	$(window).bind('resize', function() {
		var width = $('.jqGrid_wrapper').width();
		$('#table_list_1').setGridWidth(width);
	});
}

/* 表格操作事件 */
function cLink(cellvalue, options, rowObject){  
	return "<a title='编辑' onclick='edit(\"" + options.rowId + "\")'><span  class='glyphicon glyphicon-pencil'></span></a>&nbsp&nbsp<a title='删除' onclick='deleteInfo(\""+options.rowId+"\")'><span style='color:red' class='glyphicon glyphicon-remove'></span></a>";
}

/**
 * 导出
 */
function exportData(){
	$.ajax({
		type : "post",
		url : "../sg/exprotRecord.service",
		data : {
			'year':$("#year").val()
		},
		dataType : "json",
		success : function(data) {
			if (data.success == "true") {
				showModal("导出成功:<a href='../" + data.data + "'>点击下载</a>");
			} else {
				showModal(data.message);
			}
		}
	});
}
/**
 * 导入
 */
function showImport(){
	$("#fileElement").val('');
	$('#modalImport').modal("show");
}
/**
 * 导入文件
 */
function importData() {
	var form = new FormData(document.getElementById("fom")); //获取from表单
	var fileElement = $("#fileElement").val();
	if (fileElement == "") {
		showModal("请选择导入文件"); //提示框
		return;
	}
	$('#modalImport').modal("hide");
	$.ajax({
		type : "Post",
		url : "../sg/importData.service",
		data : form,
		processData : false,
		contentType : false,
		dataType : "json",
		success : function(data) {
			showModal(data.message);
			if (data.success == "true") {
				reLoadTable();
			}
		}
	});
}