/**
 * 空调加时报表
 * 2018/4/20 by liufang
 */

var userType = '';
var companyArr = []; // 运营中心列表
var companyId = '';
var orgArr = []; // 项目列表

$(function(){
	var ERROK = 200;
	template.config("escape", false);
	var contextPath =  $("#contextPath").val();
	var table;
	var tpl = {
			"freeTpl": '<div class="dialog-wp">\
				<div class="mask"></div>\
				<div class="dialog dialog-free-con">\
					<div class="title-wp">\
						<span>空调加时费用明细</span>\
						<span class="close-btn"></button>\
					</div>\
					<div class="company-wp">\
						<span><%=virName%></span>\
					</div>\
					<div class="room-wp">\
						<span>房间号:<%=roomNo%></span>\
					</div>\
					<div class="info-wp">\
						<div class="info-wp-left">\
							<span class="info-title-name">时间:<%=queryDate%></span>\
							<span class="info-title-name">订单数:<%=billNum%></span>\
							<span class="info-title-name">总金额:<%=totalFree%></span>\
						</div>\
						<div class="info-wp-right">\
						<span class="dialog-export-btn">导出到Excel</span>\
						</div>\
					</div>\
					<div class="dialog-free-wp">\
						<div class="free-con">\
							<table class="layui-hide" id="LAY_table_free" lay-filter="user"></table>  \
						</div>\
					</div>\
				</div>\
			</div>	'
	}
	var appSend = {
			init: function(){
				userType = $("#userType").val();
				this.render();
				this.bindEvent();
			},
			render: function(){
				this.rendertable();
			},
			bindEvent: function(){
				var _this = this;
				layui.use('laydate', function(){
					  var laydate = layui.laydate;
//					  var
					  //执行一个laydate实例
					  laydate.render({
					    elem: '#reportTime' ,//提交开始时间
				    	type: 'month',
				    	value: new Date().getFullYear()+"-"+(new Date().getMonth()>8 ? (new Date().getMonth()+1):("0"+(new Date().getMonth()+1)))
					  });


					});
				//重置
				$(".set-btn").on("click",function(){
					var strTime = new Date().getFullYear()+"-"+(new Date().getMonth()>8 ? (new Date().getMonth()+1):("0"+(new Date().getMonth()+1)));
					$("#conditionform .companyName").val("");
					$("#conditionform #reportTime").val(strTime);

					let contextPath = window.location.hostname === 'localhost' ? '//wx.palmnest.com/super_cloud' : "/super_cloud"
					if (userType == 1 || userType == 2|| userType == 6) {
						$('#comdId').val(companyArr[0].label).attr('comd__id', companyArr[0].value).attr('meetCode', companyArr[0].meetCode);
						companyId = $("#conditionform #comdId").attr('comd__id');
						_this.setOrgData(contextPath);
					} else {
						companyId = localStorage.getItem("companyId")
						_this.setOrgData(contextPath);
					}
				});
				//导出excel
				$(".export-btn").on("click",function(){
					_this.exportAirAjax();
				});

				let contextPath = window.location.hostname === 'localhost' ? '//wx.palmnest.com/super_cloud' : "/super_cloud"
				if (userType == 1 || userType == 2|| userType == 6) {
					_this.getCompanyList({}, contextPath)
					$('body').on("focus", '#comdId', function (event) {
						_this.setOrgCompanyData($('#comdId'), 'comd__id', 'comd__span' , companyArr);
					});
					$('body').on('blur', '#comdId', function (event) {
						var _that = $(this)
						cjqt.search_fuzzy.event_blur(_that, 'comd__id')
					});
					$('body').on('click', '.select_wrap>.comd__span', function (event) {
						event.preventDefault();
						event.stopPropagation();
						/* Act on the event */
						var _that = $(this)
						cjqt.search_fuzzy.event_click(_that, 'comd__id', '#comdId')
						companyId = $("#conditionform #comdId").attr('comd__id')
						_this.setOrgData(contextPath);
					});
					$('body').on("input",'#comdId',function(event){ // input内容变化执行
						_this.setFuzzyFilter($('#comdId').val(), companyArr, backData => {
							_this.setOrgCompanyData($('#comdId'), 'comd__id', 'comd__span' , backData);
						})
					});
				} else {
					companyId = localStorage.getItem("companyId")
					_this.setOrgData(contextPath);
				}
			},
			setOrgData: function(contextPath) {
				var _this = this;
				_this.getOrgList({
					pageNo: 1,
					pageSize: 9999,
					"conditions[companyId]": companyId
				}, contextPath)
				$('body').on("focus", '#orgId', function (event) {
					_this.setOrgCompanyData($('#orgId'), 'org__id', 'org__span' , orgArr);
				});
				$('body').on('blur', '#orgId', function (event) {
					var _that = $(this)
					cjqt.search_fuzzy.event_blur(_that, 'org__id')
				});
				$('body').on('click', '.select_wrap>.org__span', function (event) {
					event.preventDefault();
					event.stopPropagation();
					/* Act on the event */
					var _that = $(this)
					cjqt.search_fuzzy.event_click(_that, 'org__id', '#orgId')
				});
				$('body').on("input",'#orgId',function(event){
					_this.setFuzzyFilter($('#orgId').val(), orgArr, backData => {
						_this.setOrgCompanyData($('#orgId'), 'org__id', 'org__span' , backData);
					})
				});
			},
			// 获取运营中心数据
			getCompanyList: function (obj, contextPath) {
				var _this = this;
				companyArr = [];
				$.ajax({
					url: contextPath + '/api/organisation/company/getselectlist',
					type: "POST",
					dataType: "json",
					data: obj,
					success: function (data) {
						if (data.code == 200 && data.data) {
							companyArr = data.data;
							_this.setInputData($('#comdId'), 'comd__id', 'comd__span' , companyArr);
							companyId = $("#conditionform #comdId").attr('comd__id')
							_this.setOrgData(contextPath);
						} else {
							layer.msg(data.msg);
						}
					}
				});
			},
			// 获取项目数据
			getOrgList(obj, contextPath) {
				var _this = this;
				orgArr = [];
				$.ajax({
					url: contextPath + '/api/organisation/organization/getselectlist',
					type: "POST",
					dataType: "json",
					data: obj,
					success: function (data) {
						if (data.code == 200 && data.data) {
							orgArr = data.data;
							_this.setInputData($('#orgId'), 'org__id', 'org__span', orgArr);
						} else {
							layer.msg(data.msg);
						}
					}
				});
			},
			setInputData: function(_this, attrName, liClassName, dataArr) {
				// 先清空
				_this.attr(attrName, '')
				var html = ''
				if (dataArr.length) {
					_this.val(dataArr[0].label).attr(attrName, dataArr[0].value).attr('meetCode', dataArr[0].meetCode);
					if (attrName == 'org__id') {
						$('#conditionform  .search-btn').click();
					}
					$.each(dataArr, function (index, el) {
						var meetCode = el.meetCode || ''
						html += '<span class="' + liClassName + '" id="' + el.value + '" meetCode="' + meetCode + '">'
						html += el.label
						html += '</span>'
					});
					_this.parent().find('.select_wrap').empty().append(html);
				} else {
					_this.val('').attr(attrName, '').attr('meetCode', '');
					_this.parent().find('.select_wrap').empty().hide()
				}
			},
			setOrgCompanyData: function(_this, attrName, liClassName, dataArr) {
				var html = ''
				if (dataArr.length) {
					_this.parent().find('.select_wrap').show()
					$.each(dataArr, function (index, el) {
						var meetCode = el.meetCode || ''
						html += '<span class="' + liClassName + '" id="' + el.value + '" meetCode="' + meetCode + '">'
						html += el.label
						html += '</span>'
					});
					_this.parent().find('.select_wrap').empty().append(html)
				} else {
					_this.parent().find('.select_wrap').empty().hide()
				}
			},
			setFuzzyFilter: function (strLabel, dataArr, backData) {
				const fuzzyArr = dataArr; // 内容省略
				const objArr = [];
				fuzzyArr.forEach(item => {
					if (item.label.includes(strLabel)) {
						objArr.push(item);
					}
				});
				backData(objArr);
			},
			rendertable: function(){
				var _this = this;
				layui.use('table', function(){
					   table = layui.table;

					  //方法级渲染
					  table.render({
					    elem: '#LAY_table_user'
				    	 ,skin: 'nob' //行边框风格
			    		  ,even: true //开启隔行背景
			    		  ,size: 'lg' //小尺寸的表格
					    ,cols: [[
					      {
				    		   field:'billId',
				    		   title: '序号',
//				    		   width: 80,
				    		   templet: '#indexTpl',
				    	  },{
				    		  field:'virtualName',
				    		  title: '企业名称',

			    		  },{
			    			  field:'roomNames',
			    			  title: '房间号',
//		    			  },{
//		    				  field:'fullName',
//		    				  title: '企业账号',

	    				  },{
		    				  field:'billNo',
		    				  title: '订单数',
//		    				  minWidth:200
	    				  },{
		    				  field:'applyTime',
		    				  title: '统计时间',
//		    				  minWidth:120

	    				  },{
	    					  field:'freeTotal',
	    					  title: '空调加时费用总计',
//	    					  minWidth:120,
//	    					  templet: function(data){
//		    						 return "<span data-id="+data.billId+" class='check-blue-btn check-detail'>"+data.freeTotal+"<span>"
//	    					  }
	  					  },{
							  field:'id',
							  title: '操作',
							  fixed: "right",
							  minWidth: 150,
							  templet: function(data){
								  var str = '';
    							  str+= "<span data-virtualid="+data.virtualId+" data-reporttime="+data.applyTime+" class='check-blue-btn  check-btn'>费用明细<span>"
	    						 return str;
	    					  }
						  }
						  ]]
						    ,id: 'testReload'
						    ,page: true,

						    method: 'post',
						    response: {
						    	  statusName: 'code' //数据状态的字段名称，默认：code
						    	  ,statusCode: 200 //成功的状态码，默认：0
						    	  ,countName: "count"//数据总数的字段名称，默认：count
						    	  ,dataName: "data" //数据列表的字段名称，默认：data
						    	}   ,
						    	where:{
						    		reportTime: new Date().getFullYear()+"-"+(new Date().getMonth()>8 ? (new Date().getMonth()+1):("0"+(new Date().getMonth()+1)))
						    	},
					    	request: {
					    	    pageName: 'pageNo' //页码的参数名称，默认：page
					    	    ,limitName: 'pageSize' //每页数据量的参数名，默认：limit
					    	  }	,
						    done: function(res, curr, count){
						        //如果是异步请求数据方式，res即为你接口返回的信息。
						    	//查看费用明细
						    	$(".check-btn").on("click",function(){
						    		var reportTime = $(this).data("reporttime");
						    		var virtualId = $(this).data("virtualid");
									_this.getDetailListDataAjax(reportTime,virtualId)


						    	})
						      }
					  });
					  //查询
					  $('#conditionform  .search-btn').on('click', function(){
						  var org_Id = $("#conditionform #orgId").attr('org__id');
						  if (!org_Id&&userType!=1&&userType!=2) {
							  layer.msg('请选择项目')
							  return;
						  }
						  _this.againRenderTable();
					  });
					});
			},
			/*重新渲染table*/
			againRenderTable: function(){
				table.reload('testReload', {
					url:contextPath + "/air/reportList",
					where: {
						orgId: $("#conditionform #orgId").attr('org__id'),
						reportTime: $("#conditionform #reportTime").val(),
						companyName: $("#conditionform .companyName").val(),
					} ,
					  page: {
					    curr: 1 //重新从第 1 页开始
					  }
				});
			},

			/**
			 * 导出订单汇总请求
			 * @param orgId 项目id
			 * @param callback
			 */
			exportAirAjax: function(){
				var _this = this;
				$.ajax({
	                type: "post",
	                url: contextPath + "/air/exportReportList",
	                data:{
	                	orgId: $("#conditionform #orgId").attr('org__id'),
	                	reportTime: $("#conditionform #reportTime").val(),
						companyName: $("#conditionform .companyName").val()
	                },
	                success: function (data) {

	                    if (data.code == ERROK) {
//	                    	location.href = data.data;
	                    	location.href =  $("#contextPath").val() + "/upload/AirAddTime.xls";
	                    } else {
	                        layer.msg(data.msg)
	                    }
	                },
	                error: function (error) {
	                    layer.msg('error')
	                }
	            });
			},
			//获得空调加时费用明细汇总数据
			getDetailListDataAjax: function(reportTime,virtualId){
				var _this = this;
				$.ajax({
	                type: "post",
	                url: contextPath + "/air/getDetailListData",
	                data:{
	                	reportTime: reportTime,
						virtualId: virtualId,
						pageNo:1,
						pageSize:20
	                },
	                success: function (data) {
	                    if (data.code == ERROK) {
							_this.showFreeDetailDialog(data.data,reportTime,virtualId)
	                    } else {
	                        layer.msg(data.msg)
	                    }
	                },
	                error: function (error) {
	                    layer.msg('error')
	                }
	            });
			},
				//导出
			exportAjax: function (reportTime,virtualId) {
				var _this = this;
				$.ajax({
					type: "post",
					url: contextPath + "/air/exportDetailList",
					data: {
						pageNo: 1,
						pageSize: 10000,
						reportTime: reportTime,
						virtualId:virtualId ,

					},
					success: function (data) {
						if (data.code == ERROK) {
							// location.href = data.data;
							location.href = $("#contextPath").val() + "/upload/AddTimeDetailList.xls";
						} else {
							layer.msg(data.msg)
						}
					},
					error: function (error) {
						layer.msg('error')
					}
				});
			},
			/**
			 * 查看费用明细
			 * @param reportTime 月份
			 * @param virtualId 企业id
			 */
			showFreeDetailDialog: function(data,reportTime,virtualId){
				var _this = this;
				$("body").append(template.render(tpl.freeTpl)(data));
				//关闭弹窗
				$(".close-btn").on("click",function(){
					$(".dialog-wp").remove();
				});
				//下载Excel
				$(".dialog-export-btn").on("click",function(){
					var str = "确定导出报表数据吗?";
					layer.confirm(str, {
						btn: ['确定', '取消']
					}, function (index, layero) {
						layer.close(index); //如果设定了yes回调，需进行手工关闭
						_this.exportAjax(reportTime,virtualId);
					}, function (index) {});
				});

				_this.renderFreeDetailTable(reportTime,virtualId)
			},
			/**
			 * 渲染table
			 * @param reportTime 月份
			 * @param virtualId 企业id
			 */
			renderFreeDetailTable: function(reportTime,virtualId){
				var _this = this;
				var freeTable;
				layui.use('table', function(){
					freeTable = layui.table;

					  //方法级渲染
					freeTable.render({
					    elem: '#LAY_table_free'
					    ,url:contextPath + "/air/reportDetailList"
					    ,skin:"nob"
					    ,cols: [[
					      {
				    		  field:'code',
				    		  title: '订单号',
				    		  width:180
			    		  },{
		    				  field:'billSource',
		    				  title: '订单来源',
//		    				  minWidth:50,
		    				  templet: function(data){
	    						  if(data.billSource == 1){
	    							  return "空调加时"
	    						  }else if(data.billSource == 2){
	    							  return '预定会议室'
	    						  }
	    					  }
	    				  },{
		    				  field:'roomNames',
		    				  title: '申请房号',
//		    				  minWidth:50
	    				  },{
		    				  field:'applyArea',
		    				  title: '申请面积',
//		    				  minWidth:100
	    				  },{
		    				  field:'useDisplayTime',
		    				  title: '使用时间',
		    				  width: 230
	    				  },{
		    				  field:'useLengthTime',
		    				  title: '使用时长(小时)',
		    				  width:160
	    				  },{
		    				  field:'priceDisplay',
		    				  title: '单价',
		    				  width:180
	    				  },{
		    				  field:'applyUser',
		    				  title: '申请人',
//		    				  minWidth:50
	    				  },{
		    				  field:'freeTotal',
		    				  title: '订单金额',
//		    				  minWidth:50
	    				  }
						  ]]
						    ,id: 'testReloaddialog'
						    ,page: true,
						    method: 'post',
						    even: true,
						    where:{
						    	reportTime: reportTime,
						    	virtualId: virtualId
						    },
						    response: {
						    	  statusName: 'code' //数据状态的字段名称，默认：code
						    	  ,statusCode: 200 //成功的状态码，默认：0
						    	  ,countName: "count"//数据总数的字段名称，默认：count
						    	  ,dataName: "data" //数据列表的字段名称，默认：data
						    	}   ,
					    	request: {
					    	    pageName: 'pageNo' //页码的参数名称，默认：page
					    	    ,limitName: 'pageSize' //每页数据量的参数名，默认：limit
					    	  }	,

					  })
					});
			}
	};
	appSend.init();
})
