/**
 * 订餐管理>统计
 * 2018/4/20 by liufang
 */
$(function () {
	var ERROK = 200;
	var contextPath=$("#contextPath").val()
	var table;
	var orgList = [];
	var startTime;
	var timeArr =[]
	var tpl = {
			"yearTpl": '<%for(var i=0;i<yearList.length;i++){%>\
					<option value="<%=yearList[i]%>-"><%=yearList[i]%>年</option>\
				<%}%>',
			"otherTpl": '<%for(var i=0;i<list.length;i++){%>\
					<option value="<%=list[i].value%>"><%=list[i].key%></option>\
				<%}%>'	
	}
	template.config("escape", false);
	var mealManage = {
		init: function () {
			layui.use("layer",function(){})
			this.render();
			this.bindEvent();
		},
		render: function () {
			var _this = this;
			this.getStartTime(function(){
			
				_this.renderDinnerTable();//订餐统计table
			});
		},
		bindEvent: function () {
			var _this = this;
			
			//查询
			$('#conditionform  .search-btn').on('click', function () {
				var type = $("#conditionform .type").val();
				if(type==1){
					_this.renderDinnerTable();
				}else if(type==2){
					_this.renderGradeTable();
				}else if(type==3){
					_this.renderPartTable();
				}else if(type==4){
					_this.renderPersonTable();
				}
//				if($("#conditionform .dateType").val()==1){
//					_this.againRenderTableYear();
//				}else{
//					_this.againRenderTableTime();
//				}
			});
			//导出
			$('#conditionform  .set-btn').on('click', function () {
				_this.exportAjax();
			});
			//校区改变，重新获取时间
			$("#orgId").on("change",function(){
				setTimeout(function(){
					_this.getStartTime(function(){
						_this.renderDinnerTable();//订餐统计table
					});
				},100)
			})
			// 模糊搜索
			_this.search_fuzzy()
		},
		// 模糊搜索事件
		search_fuzzy: function(){
			$('body').on("input",'#orgId',function(event){
				var _this = $(this)
				cjqt.search_fuzzy.event_input(_this,'org__id','org__span',contextPath,'/admin/templ/getOrgListByName')
			});
			$('body').on("focus",'#orgId',function(event){
				var _this = $(this)
				cjqt.search_fuzzy.event_focus(_this,'org__id','org__span',contextPath,'/admin/templ/getOrgListByName')
			});
			$('body').on('blur','#orgId',function(event) {
				var _this = $(this)
				cjqt.search_fuzzy.event_blur(_this,'org__id')
			});
			$('body').on('click','.select_wrap>.org__span', function(event) {
				event.preventDefault();
				event.stopPropagation();
				/* Act on the event */
				var _this = $(this)
				cjqt.search_fuzzy.event_click(_this,'org__id','#orgId')
			});
		},
		yearChange: function(){
			var _this = this;
			$(".dateType").on("change",function(){
				var type = $(this).val();
				if(type ==1){//年
					//开始年份到当前年份
					_this.getTimeList(type)
					
				}else if(type==2){//季度
					//开始季度到当前季度
					_this.getTimeList(type)
				}else if(type==3){//月
					_this.getTimeList(type)
					//开始月份到当前月份
				}
			})
		},
		/**
		 * 获取时间段的年份、季度、月,并渲染
		 * @param type 
		 * @param callback
		 */
		getTimeList: function(type,callback){
			var _this = this;
			timeArr = [];
			if(type==1){
				var start = new Date(startTime).getFullYear();
				var end =  new Date().getFullYear();
				while(start<=end){
					timeArr.push(start);
					start++;
				};
				$(".year-and-time").html(template.render(tpl.yearTpl)({yearList: timeArr}))
			}else if(type==2){
				var start = new Date(startTime);  
				var end = new Date();
//				
				while(start <= end){  
				   var quarter =_this.getQuarterStartMonth(start.getMonth()).quarter  ;
				   var month = _this.getQuarterStartMonth(start.getMonth()).quarterStartMonth;
				   
				   timeArr.push({
					   key: start.getFullYear()+"年"+quarter+"季",
					   value: start.getFullYear()+"-"+quarter,
				   });
				   start.setMonth(month);  
				   
			   }  ;
			   var endQuarter = _this.getQuarterStartMonth(end.getMonth()).quarter
			   timeArr.push({
				   key: end.getFullYear()+"年"+quarter+"季",
				   value: end.getFullYear()+"-"+quarter
			   });
			   console.log(timeArr);
			   timeArr = _this.uniq(timeArr);
			   console.log(timeArr);
			   $(".year-and-time").html(template.render(tpl.otherTpl)({list: timeArr}))
			}else if(type==3){
				var start = new Date(startTime);  
				var end = new Date();
				
				while(start <= end){  
				   var month = start.getMonth();  
				   timeArr.push({
					   key: start.getFullYear()+"年"+(month+1)+"月",
					   value: start.getFullYear()+"-"+(month+1)
				   })
				   start.setMonth(month+1);  
			   }    
				console.log(timeArr);
				$(".year-and-time").html(template.render(tpl.otherTpl)({list: timeArr}))
			};
//			  
			
		},
		
		/**
		 * 获得本季度的月份和月份
		 * @param nowMonth 当前月
		 * 
		 */ 
		getQuarterStartMonth: function (nowMonth){ 
			var quarterStartMonth = 0; 
			var quarter ;
			if(nowMonth<3){ 
				quarterStartMonth = 3; 
				quarter = 1;
			} 
			if(2<nowMonth && nowMonth<6){ 
				quarterStartMonth = 6; 
				quarter = 2;
			} 
			if(5<nowMonth && nowMonth<9){ 
				quarterStartMonth = 9; 
				quarter = 3;
			} 
			if(nowMonth>8){ 
				quarterStartMonth = 12; 
				quarter = 4;
			} 
			return {
				quarterStartMonth: quarterStartMonth,
				quarter: quarter
			}; 
		} ,
		//数组去重
		uniq: function (arr){
			var result = [];
			var obj = {};
			for(var i =0; i<arr.length; i++){
				if(!obj[arr[i].key]){
				   result.push(arr[i]);
			       obj[arr[i].key] = true;
			    }
			}
			return result; 
		},

		//订餐统计table
		renderDinnerTable: function () {
			var _this = this;
			layui.use('table', function () {
				table = layui.table;

				//方法级渲染
				table.render({
					elem: '#LAY_table_user',
					url: $("#contextPath").val() + "/admin/dinner/getDataStatistics"
					,method: "post"
					 ,skin: 'nob' //行边框风格
			    		  ,even: true //开启隔行背景
			    		  ,size: 'lg' //小尺寸的表格
					,cols: [
						[ {
							   field:'index', 
							   title: '序号', 
							   width: '80',
							   templet: '#indexTpl'
						 },{
							field: 'totalNum',
							title: '总份数',
							minWidth: 200
						}, {
                            field: 'rate',
                            title: '订餐率',
                            minWidth: 120
                           
                        },{
							field: 'groupFood',
							title: '组合',
							minWidth: 200
						}, {
							field: 'soupFood',
							title: '工作餐',
							minWidth: 200
						}, {
							field: 'bigRice',
							title: '大份米饭',
							minWidth: 200
						}, {
							field: 'smallRice',
							title: '小份米饭',
							minWidth: 200
							
                        },{
							field: 'roll',
							title: '花卷',
							minWidth: 120
							
						},{
							field: 'buns',
							title: '馒头',
							minWidth: 120
							
						},{
							field: 'fruitFood',
							title: '会议餐',
							minWidth: 200
							
						},{
							field: 'singleFood',
							title: '单品',
							minWidth: 120
						
						}]
					],
					id: 'testReload',
					page: true,
					response: {
						statusName: 'code' //数据状态的字段名称，默认：code
							,
						statusCode: 200 //成功的状态码，默认：0
							,
						countName: "count" //数据总数的字段名称，默认：count
							,
						dataName: "data" //数据列表的字段名称，默认：data
					},
					request: {
					    pageName: 'pageNo' //页码的参数名称，默认：page
					    ,limitName: 'pageSize' //每页数据量的参数名，默认：limit
					  },
					  where:{
						  type: $("#conditionform .type").val(),
						  dateType: $("#conditionform .dateType").val(),
						  year: $("#conditionform .year-and-time").val().split("-")[0],
						  time: $("#conditionform .year-and-time").val().split("-")[1],
						  orgId: $("#conditionform  #orgId").attr('org__id'),
						  operationType: 1
					  },
					done: function (res, curr, count) {
						
					}
				});
				
			});
			
		},
		/*重新渲染table */
		againRenderTableYear: function(){
			table.reload('testReload', {
				where: {
					type: $("#conditionform .type").val(),
					dateType: $("#conditionform .dateType").val(),
					year: $("#conditionform .year-and-time").val(),
					time: '',
					orgId: $("#conditionform  #orgId").attr('org__id'),
					operationType: 1
				} ,
				  page: {
				    curr: 1 //重新从第 1 页开始
				  }
			}); 
		},
		againRenderTableTime: function(){
			table.reload('testReload', {
				where: {
					type: $("#conditionform .type").val(),
					dateType: $("#conditionform .dateType").val(),
					year: $("#conditionform .year-and-time").val().split("-")[0],
					time: $("#conditionform .year-and-time").val().split("-")[1],
					orgId: $("#conditionform  #orgId").attr('org__id'),
					operationType: 1
				} ,
				  page: {
				    curr: 1 //重新从第 1 页开始
				  }
			}); 
		},
		//评价统计table
		renderGradeTable: function(){
			var _this = this;
//			layui.use('table', function () {
//				table = layui.table;

				//方法级渲染
				table.render({
					elem: '#LAY_table_user',
					url: $("#contextPath").val() + "/admin/dinner/getDataStatistics"
					,method: "post"
					 ,skin: 'nob' //行边框风格
			    		  ,even: true //开启隔行背景
			    		  ,size: 'lg' //小尺寸的表格
					,cols: [
						[ {
							   field:'index', 
							   title: '序号', 
							   minWidth: 80,
							   templet: '#indexTpl'
						 },{
							field: 'starStr',
							title: '评价统计'
						
						}, {
                            field: 'sumCount',
                            title: '订单数'
                           
                           
                        }, {
                            field: 'rate',
                            title: '占比'
                           
                           
                        }]
					],
					id: 'testReload',
					page: true,
					response: {
						statusName: 'code' //数据状态的字段名称，默认：code
							,
						statusCode: 200 //成功的状态码，默认：0
							,
						countName: "count" //数据总数的字段名称，默认：count
							,
						dataName: "data" //数据列表的字段名称，默认：data
					},
					request: {
					    pageName: 'pageNo' //页码的参数名称，默认：page
					    ,limitName: 'pageSize' //每页数据量的参数名，默认：limit
					  },
				   where:{
					  type: $("#conditionform .type").val(),
					  dateType: $("#conditionform .dateType").val(),
					  year: $("#conditionform .year-and-time").val().split("-")[0],
					  time: $("#conditionform .year-and-time").val().split("-")[1],
					  orgId: $("#conditionform  #orgId").attr('org__id'),
					  operationType: 1
				   },
					done: function (res, curr, count) {
						
					}
				});
				//查询
//				$('#conditionform  .search-btn').on('click', function () {
////					_this.againRenderTable();
//				});
//			});
		},
		//部门统计table
		renderPartTable: function(){
			var _this = this;
//			layui.use('table', function () {
//				table = layui.table;

				//方法级渲染
				table.render({
					elem: '#LAY_table_user',
					url: $("#contextPath").val() + "/admin/dinner/getDataStatistics"
					,method: "post"
					 ,skin: 'nob' //行边框风格
			    		  ,even: true //开启隔行背景
			    		  ,size: 'lg' //小尺寸的表格
					,cols: [
						[ {
							   field:'index', 
							   title: '序号', 
							   width: '80',
							   templet: '#indexTpl'
						 },{
							field: 'dept',
							title: '部门',
							minWidth: 200
						}, {
                            field: 'totalNum',
                            title: '餐品份数',
                            minWidth: 120
                           
                        },{
							field: 'groupFood',
							title: '组合',
							minWidth: 200
						}, {
							field: 'soupFood',
							title: '工作餐',
							minWidth: 200
						}, {
							field: 'bigRice',
							title: '大份米饭',
							minWidth: 200
						}, {
							field: 'smallRice',
							title: '小份米饭',
							minWidth: 200
							
                        },{
							field: 'roll',
							title: '花卷',
							minWidth: 120
							
						},{
							field: 'buns',
							title: '馒头',
							minWidth: 120
							
						},{
							field: 'fruitFood',
							title: '会议餐',
							minWidth: 200
							
						},{
							field: 'singleFood',
							title: '单品',
							minWidth: 120
						
						}]
					],
					id: 'testReload',
					page: true,
					response: {
						statusName: 'code' //数据状态的字段名称，默认：code
							,
						statusCode: 200 //成功的状态码，默认：0
							,
						countName: "count" //数据总数的字段名称，默认：count
							,
						dataName: "data" //数据列表的字段名称，默认：data
					},
					request: {
					    pageName: 'pageNo' //页码的参数名称，默认：page
					    ,limitName: 'pageSize' //每页数据量的参数名，默认：limit
					  },
					  where:{
						  type: $("#conditionform .type").val(),
						  dateType: $("#conditionform .dateType").val(),
						  year: $("#conditionform .year-and-time").val().split("-")[0],
						  time: $("#conditionform .year-and-time").val().split("-")[1],
						  orgId: $("#conditionform  #orgId").attr('org__id'),
						  operationType: 1
					   },
					done: function (res, curr, count) {
						
					}
				});
				//查询
//				$('#conditionform  .search-btn').on('click', function () {
////					_this.againRenderTable();
//				});
//			});
		},
		//个人统计table
		renderPersonTable: function(){
			var _this = this;
//			layui.use('table', function () {
//				table = layui.table;

				//方法级渲染
				table.render({
					elem: '#LAY_table_user',
					url: $("#contextPath").val() + "/admin/dinner/getDataStatistics"
					,method: "post"
					 ,skin: 'nob' //行边框风格
			    		  ,even: true //开启隔行背景
			    		  ,size: 'lg' //小尺寸的表格
					,cols: [
						[ {
							   field:'index', 
							   title: '序号', 
							  
							   templet: '#indexTpl'
						 },{
							field: 'loginName',
							title: '手机号码'
						
						}, {
                            field: 'userName',
                            title: '姓名'
                           
                           
                        }, {
                            field: 'dept',
                            title: '部门'
                           
                           
                        }, {
                            field: 'sumCount',
                            title: '餐品份数'
                           
                          
                        }]
					],
					id: 'testReload',
					page: true,
					response: {
						statusName: 'code' //数据状态的字段名称，默认：code
							,
						statusCode: 200 //成功的状态码，默认：0
							,
						countName: "count" //数据总数的字段名称，默认：count
							,
						dataName: "data" //数据列表的字段名称，默认：data
					},
					request: {
					    pageName: 'pageNo' //页码的参数名称，默认：page
					    ,limitName: 'pageSize' //每页数据量的参数名，默认：limit
					  },
					  where:{
						  type: $("#conditionform .type").val(),
						  dateType: $("#conditionform .dateType").val(),
						  year: $("#conditionform .year-and-time").val().split("-")[0],
						  time: $("#conditionform .year-and-time").val().split("-")[1],
						  orgId: $("#conditionform  #orgId").attr('org__id'),
						  operationType: 1
					   },
					done: function (res, curr, count) {
						
					}
				});
				//查询
//				$('#conditionform  .search-btn').on('click', function () {
////					_this.againRenderTable();
//				});
//			});
		},
		// 获取最开始订餐时间
		getStartTime: function(callback){
			var _this = this;
			$.ajax({
                type: "post",
                url: contextPath + "/admin/dinner/getTopCreateTime",
                data:{
                	orgId: $("#orgId").attr('org__id')
                },
                success: function (data) {
                    
                    if (data.code == ERROK) {
                    	if(!!data.data){
                    		$(".layui-form").show();
                    		startTime = data.data;
//                        	startTime = "2016-10-01";
                        	_this.yearChange();
                        	$(".dateType").val(3);
                        	_this.getTimeList(3);
                        	$(".year-and-time").val(timeArr[timeArr.length-1].value);
                        	callback && callback(data.data);
                    	}else{
                    		$(".layui-form").hide();
//                    		layer.msg('该校区下暂时没有数据！')
                    	}
                    
                    } else {
                        layer.msg(data.msg)
                    }
                },
                error: function (error) {
                    layer.msg('error')
                }
            });
		},
		//导出
		exportAjax: function(){
			var _this = this;
			$.ajax({
                type: "post",
                url: contextPath + "/admin/dinner/getDataStatistics",
                data:{
                  type: $("#conditionform .type").val(),
				  dateType: $("#conditionform .dateType").val(),
				  year: $("#conditionform .year-and-time").val().split("-")[0],
				  time: $("#conditionform .year-and-time").val().split("-")[1],
				  orgId: $("#conditionform  #orgId").attr('org__id'),
				  operationType: 2
                },
                success: function (data) {
                    
                    if (data.code == ERROK) {
//                    	location.href = data.data;
                    	location.href =  $("#contextPath").val() + "/upload/OrderDataExcel.xls";
                    } else {
                        layer.msg(data.msg)
                    }
                },
                error: function (error) {
                    layer.msg('error')
                }
            });
		}
	};
	mealManage.init();
})