/**
 * 2018/4/20 by liufang
 */
$(function() {
	$.ajaxSetup({
	  async: false
	});
	var ERROK = 200;
	var contextPath = $("#contextPath").val()
	var table;
	var _dataArr = []; //当前数据集合
	var _jiduArr = []; //当前数据集合


	var initObj = {
		init: function() {
			this.initChart()
			this.rendertable();
			this.getjiduArr()
			this.bindEvent();
		},
		bindEvent: function() {
			var _this = this;
			layui.use('laydate', function() {
				var laydate = layui.laydate;
				laydate.render({
					elem: '#beginTime_1', 
					type: 'year',
					value: new Date().getFullYear()
				});
				laydate.render({
					elem: '#beginTime_3', 
					type: 'month'
				});
				laydate.render({
					elem: '#beginTime_4', 
				});
				laydate.render({
					elem: '#endTime' 
				});
			});
			//重置
			$(".set-btn").on("click", function() {
				var $orgId = $("#conditionform  .single-orgid");
				var $dom = $("#conditionform input,#conditionform select")
				_this.init_reset()
				$("#beginTime_1").show()
				if($orgId.length){
					$dom.val("").removeAttr('com__id dep__id')
				}else{
					$dom.val("").removeAttr('org__id com__id dep__id')
				}
				_this.againRenderTable({type:1});
			});
			//查询
			$('#conditionform  .search-btn').on('click', function() {
				_this.againRenderTable();
			});
			// 统计周期
			$('#conditionform  .status').on('change', function(event) {
				event.preventDefault();
				/* Act on the event */
				var value = this.value
				_this.init_reset()
				if(value == 1){
					$("#beginTime_1").show()
				}else if(value == 2){
					$("#beginTime_2").show()
					$('.jidu_div').show()
				}else if(value == 3){
					$("#beginTime_3").show()
				}else if(value == 4){
					$("#beginTime_4").show()
					$('.endTime_wrap').show()
				}else{
					$("#beginTime_1").show()
				}
			});
			// 字段选择展示柱形体
			$('.optionSelect').on('change', function(event) {
				event.preventDefault();
				/* Act on the event */
				var value = this.value
				var name = _this.searchKey(value)
				var itemArr = []
				var orgNameArr = []
				_dataArr.forEach(function(item,index,arr){
					itemArr.push(item[value] || "0")
					orgNameArr.push(item.orgName || '')
				})
				myChart.setOption({
				    yAxis: {
				        type: 'category',
				        data: orgNameArr.reverse()
				    },
				    legend: {
				        data: [name]
				    },
				    series: [
				        {
				            name: name,
				            type: 'bar',
				            data: itemArr.reverse()
				        },
				    ]
				})
			});
			//导出
			$("#excelFile").on("click", function() {
				var $orgId = $("#conditionform  .single-orgid");
				var orgId;
				if($orgId.length){
					orgId = $orgId.attr('org__id')
				}else{
					orgId = $('.default-select#orgId').attr('org__id')
				}
				console.log(orgId)
				_this.exportOrderAjax(orgId);
			});
			//季度事件
			// $('body').on("input",'#beginTime_2',function(event){
			// 	var _this = $(this)
			// 	var html = ''
			// 	// 先清空
			// 	_this.attr('jidu__Data', '')
			// 	if (_jiduArr.length) {
			// 		_this.parent().find('.jidu_wrap').show()
			// 		$.each(_jiduArr, function (index, el) {
			// 			html += '<span class="jidu_item" id="' + el["year"]+ '-' + el["jidu"] + '">'
			// 			html += el['year'] + '年' + el['jidu'] + '季度'
			// 			html += '</span>'
			// 		});
			// 		_this.parent().find('.jidu_wrap').empty().append(html)
			// 	} else {
			// 		_this.parent().find('.jidu_wrap').empty().hide()
			// 	}
			// });
			$('body').on("click",'#beginTime_2',function(event){
				var _this = $(this)
				var html = ''
				if (_jiduArr.length) {
					_this.parent().find('.jidu_wrap').show()
					$.each(_jiduArr, function (index, el) {
						console.log(el)
						html += '<span class="jidu_item" id="' + el["year"]+ '-' + el["jidu"] + '">'
						html += el['year'] + '年' + el['jidu'] + '季度'
						html += '</span>'
					});
					_this.parent().find('.jidu_wrap').empty().append(html)
				} else {
					_this.parent().find('.jidu_wrap').empty().hide()
				}
			});
			$('body').on('blur','#beginTime_2',function(event) {
				var _this = $(this)
				// 如果值或者attrName不存在则都清空
				// 清除定时器检
				if (typeof (delayClock) != "undefined") {
					clearTimeout(delayClock);
				}
				// 如果值或者attrName不存在则都清空
				closeClock = setTimeout(function () {
					var name = _this.val()
					var id = _this.attr('jidu__Data')
					if (!(name && id)) {
						_this.val('')
						_this.removeAttr('value')
						_this.attr('jidu__Data', '')
					}
					$('.jidu_wrap').empty().hide()
				}, 200)
			});
			$('body').on('click','.jidu_item', function(event) {
				event.preventDefault();
				event.stopPropagation();
				/* Act on the event */
				var _this = $(this)
				var _Id = _this[0].id
				var _Name = _this[0].innerText
				_this.parent('.jidu_wrap').parent().find('#beginTime_2').val(_Name).attr('jidu__Data',_Id)
				_this.parent('.jidu_wrap').empty().hide()
			});
			// 模糊搜索
			_this.search_fuzzy()
		},
		init_reset: function(){
			$(".beginTimeClass").hide()
			$('#beginTime_1').val('')
			$('#beginTime_2').val('')
			$('#beginTime_3').val('')
			$('#beginTime_4').val('')
			$('#endTime').val('')
			$('.endTime_wrap').hide()
			$('.jidu_div').hide()
		},
		getjiduArr: function(){
			var date = new Date()
			var year = date.getFullYear()
			var month = date.getMonth() + 1
			var temArr = []
			var flag = 1
			while (2018 <= year){
				var jidu = ''
				// 如果是第一次进来循环对应的次数
				if(flag){
					if([1,2,3].indexOf(month) >= -1){
					  	jidu = 1
					}else if([4,5,6].indexOf(month) >= -1){
					  	jidu = 2
					}else if([7,8,9].indexOf(month) >= -1){
					  	jidu = 3
					}else if([10,11,12].indexOf(month) >= -1){
					  	jidu = 4
					}
					for (var i = jidu - 1; i >= 0; i--) {
						var tmpobj = {}
					  	tmpobj.year = year
					  	tmpobj.jidu = (function(num){return num})(i) + 1
					  	temArr.push(tmpobj)
					}
					flag = 0
				}else{
					for (var i = 4 - 1; i >= 0; i--) {
						var tmpobj = {}
					  	tmpobj.year = year
					  	tmpobj.jidu = (function(num){return num})(i) + 1
					  	temArr.push(tmpobj) 
					}
				}
				year--;
			}
			_jiduArr = temArr
		},
		// 模糊搜索事件
		search_fuzzy: function(){
			var _this = this
			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'
			});
			var option_2 = $.extend(true,{},default_option,{
				org_target:'.d-orgid#orgId'
			});
			 
			

			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_2,{type:1})
		},
		rendertable: function() {
			var newDate = new Date;
 			var currentYear = newDate.getFullYear()
			var _this = this;
			var $orgId = $("#conditionform  .single-orgid");
			if($orgId.length){
				var orgId = $orgId.attr('org__id') || ''
			}else{
				var orgId = $("#conditionform  #orgId").attr('org__id') || ''
			}
			layui.use('table', function() {
				table = layui.table;
				//方法级渲染
				table.render({
					elem: '#LAY_table_user',
					url: $("#contextPath").val() + "/admin/dinner/place/getMeetStatistics",
					where: {
						orgId: orgId,
						dateType: '1',
						date: currentYear,
					},
					method: "post",
					skin: 'nob', //行边框风格
					even: true,//开启隔行背景
					size: 'lg', //小尺寸的表格
					cols: [
						[{
							field: 'index',
							title: '序号',
							width: '80',
							fixed: 'left',
							templet: '#indexTpl'
						},{
							field: 'orgName',
							title: '项目名称',
							minWidth: 200
						},{
							field: 'dateInfo',
							title: '统计时间',
							minWidth: 150,
						},{
							field: 'reportnum',
							title: '预定会议室次数',
							minWidth: 150,
							templet: function(data) {
								if(data.reportnum){
									return data.reportnum
								}else{
									return '0'
								}
							}
						},{
							field: 'usetime',
							title: '使用时长',
							minWidth: 150,
							templet: function(data) {
								if(data.usetime){
									return data.usetime
								}else{
									return '0'
								}
							}
						},{
							field: 'usemoney',
							title: '预定会议室费用',
							minWidth: 150,
							templet: function(data) {
								if(data.usemoney){
									return data.usemoney
								}else{
									return '0'
								}
							}
						},{
							field: 'freenum',
							title: '减免时长使用数',
							minWidth: 150,
							align: 'center',
							templet: function(data) {
								if(data.freenum){
									return data.freenum
								}else{
									return '0'
								}
							}
						},{
							field: 'freemoney',
							title: '减免时长扣减费用',
							minWidth: 150,
							templet: function(data) {
								if(data.freemoney){
									return data.freemoney
								}else{
									return '0'
								}
							}
						},{
							field: 'servicesmoney',
							title: '附加服务费用',
							minWidth: 150,
							templet: function(data) {
								if(data.servicesmoney){
									return data.servicesmoney
								}else{
									return '0'
								}
							}
						},{
							field: 'amount',
							title: '费用总计',
							minWidth: 150,
							templet: function(data) {
								if(data.amount){
									return data.amount
								}else{
									return '0'
								}
							}
						}]
					],
					id: 'testReload',
					page: true,
					response: {
						statusName: 'code' //数据状态的字段名称，默认：code
							,
						statusCode: 200 //成功的状态码，默认：0
							,
						countName: "count" //数据总数的字段名称，默认：count
							,
						dataName: "data" //数据列表的字段名称，默认：data
					},
					request: {
						pageName: 'pageNo' //页码的参数名称，默认：page
							,
						limitName: 'pageSize' //每页数据量的参数名，默认：limit
					},
					done: function(res, curr, count) {
						$('.optionSelect').val('')
						if(res && res.code == 200){
							_dataArr = res.data || []
							var itemArr = []
							var orgNameArr = []
							var length = _dataArr.length || 0
							var page_length = $('.layui-laypage-limits select').eq(0).val() || 10
							for (var i = (page_length - length) - 1; i >= 0; i--) {
								_dataArr.push({})
							}
							_dataArr.forEach(function(item,index,arr){
								itemArr.push(item.reportnum || '0')
								orgNameArr.push(item.orgName || '')
							})
							myChart.setOption({
							    yAxis: {
							        type: 'category',
							        data: orgNameArr.reverse()
							    },
							    legend: {
							        data: ['预定会议室次数']
							    },
							    series: [
							        {
							            name: '预定会议室次数',
							            type: 'bar',
							            data: itemArr.reverse()
							        },
							    ]
							})
						}
					}
				});
			});
		},
		/*重新渲染table*/
		againRenderTable: function(option) {
			var obj = $.extend(true, {}, option);
			var type =  obj.type || ''
			var $orgId = $("#conditionform  .single-orgid");
			if($orgId.length){
				var orgId = $orgId.attr('org__id')
			}else{
				var orgId = $("#conditionform  #orgId").attr('org__id')
			}
			var dateType = $("#conditionform .status").val() 
			if(dateType == 1){
				var date = $("#conditionform #beginTime_1").val()
			}else if(dateType == 2){
				var dateTmp = $("#conditionform #beginTime_2").attr('jidu__Data')
				var date = dateTmp.substr(0, 4)
				var endDate =  dateTmp.substr(5,date.length)
			}else if(dateType == 3){
				var dateTmp = $("#conditionform #beginTime_3").val()
				var date = dateTmp.substr(0, 4)
				var endDate =  dateTmp.substr(5,date.length)
			}else if(dateType == 4){
				var date = $("#conditionform #beginTime_4").val()
				var endDate =  $("#conditionform #endTime").val()
			}
			var newDate = new Date;
 			var currentYear = newDate.getFullYear()
			if(type == 1){
				table.reload('testReload', {
					where: {
						orgId: '',
						dateType: '1',
						date: currentYear,
						endDate: endDate, 
					},
					page: {
						curr: 1 //重新从第 1 页开始
					}
				});
			}else{
				table.reload('testReload', {
					where: {
						orgId: orgId,
						dateType: date?dateType:'1',
						date: date?date:currentYear,
						endDate: endDate
					},
					page: {
						curr: 1 //重新从第 1 页开始
					}
				});
			}
		},
		// 图表
		initChart:function(){
			var dom = document.getElementById("echarts");
			myChart = echarts.init(dom);
			option = null;
			option = {
			    title: {
			        text: '会议室概况统计表',
			        subtext: '数据来源于本平台'
			    },
			    tooltip: {
			        trigger: 'axis',
			        axisPointer: {
			            type: 'shadow'
			        }
			    },
			    legend: {
			        data: ['预定会议室次数']
			    },
			    grid: {
			        left: '3%',
			        right: '4%',
			        bottom: '3%',
			        containLabel: true
			    },
			    xAxis: {
			        type: 'value',
			        boundaryGap: [0, 0.01]
			    },
			    yAxis: {
			        type: 'category',
			        data:  ['','','','','','','','','','']
			    },
			    series: [
			        {
			            name: '预定会议室次数',
			            type: 'bar',
			            data: [0, 0, 0, 0, 0, 0, 0, 0 ,0, 0],
			            itemStyle:{
			            	color:'#158DF6'
			            }
			        },
			    ]
			};
			if (option && typeof option === "object") {
			    myChart.setOption(option, true);
			}
		},
		searchKey:function(key){
			var value = '';
			switch (key){
				case 'reportnum':
				value = '预定会议室次数'
				break;
				case 'usetime':
				value = '使用时长'
				break;
				case 'usemoney':
				value = '预定会议室费用'
				break;
				case 'freenum':
				value = '减免时长使用数'
				break;
				case 'freemoney':
				value = '减免时长扣减费用'
				break;
				case 'servicesmoney':
				value = '附加服务费用'
				break;
				case 'amount':
				value = '费用总计'
				break;
			}
			return value
		},
		/**
		 * 导入用户请求
		 * @param orgId 项目id
		 * @param callback
		 */
		exportOrderAjax: function(orgId, callback) {
            var _this = this;
            
            var dateType = $("#conditionform .status").val() 
			if(dateType == 1){
				var date = $("#conditionform #beginTime_1").val()
			}else if(dateType == 2){
				var dateTmp = $("#conditionform #beginTime_2").attr('jidu__Data')
				var date = dateTmp.substr(0, 4)
				var endDate =  dateTmp.substr(5,date.length)
			}else if(dateType == 3){
				var dateTmp = $("#conditionform #beginTime_3").val()
				var date = dateTmp.substr(0, 4)
				var endDate =  dateTmp.substr(5,date.length)
			}else if(dateType == 4){
				var date = $("#conditionform #beginTime_4").val()
				var endDate =  $("#conditionform #endTime").val()
			}
			
			var newDate = new Date;
 			var currentYear = newDate.getFullYear()


            $.ajax({
                type: "post",
                url: contextPath + "/admin/dinner/place/exportMeetStatistics",
                data: {
                    orgId: orgId || '',
					dateType: date?dateType:'1',
					date: date?date:currentYear,
					endDate: endDate
                },
                success: function(data) {
                    if (data.code == ERROK) {
                        location.href = $("#contextPath").val() + "/upload/MeetingDataExcel.xls";
                        callback && callback();
                    } else {
                        layer.msg(data.msg)
                    }
                },
                error: function(error) {
                    layer.msg('ervirtualArchIdror')
                }
            });
        },
	};
	initObj.init();
})