;
layui.config({
	base: "../../../admin/js/layuiPlugins/"
}).use(['form', 'layer', 'jquery', 'laypage', 'element', 'table', 'laydate', 'laytpl', 'cascade'], function() {
	var form = layui.form,
		layer = layui.layer,
		laytpl = layui.laytpl,
		laypage = layui.laypage,
		$ = layui.jquery,
		table = layui.table,
		element = layui.element,
		laydate = layui.laydate,
		cascade = layui.cascade;
	//自定义验证
	form.verify({
		namelength: [
			/^.{0,18}$/,
			"长度限制在0-18个字符噢"
		]
	});

	var vm = function(obj) {
		var _this = this;
		_this.dataId = obj.dataId || 'dataListId'; //数据表ID
		_this.elem = obj.elem || 'dataListBox'; //数据表容器
		_this.toolbar = obj.toolbar || '';
		_this.url = obj.url || ''; //数据表接口URL
		_this.page = obj.page; //分页
		_this.limit = obj.limit;
		_this.cols = obj.cols || []; //表头
		_this.done = obj.done || ''; //表头
		_this.formObj = {}; //当前表单对象
		_this.searchParameter = {}; //搜索参数
		_this.config = {};
		_this.where = obj.where;
		_this.config.dateTime = obj.dateTime;
		_this.dateTime = {
			year: 365 * 1 * 24 * 3600 * 1000,
			month: 30 * 1 * 24 * 3600 * 1000,
			day: 24 * 3600 * 1000,
		}
		_this.main();
	};
	//入口函数
	vm.prototype.main = function() {
		var _this = this;
		laydate.render({
			elem: '#test6',
			range: true,
			btns: ['now','confirm'],
			done: function(value, date, endDate) {
				if (date.month < 10) {
					date.month = '0' + date.month
				}
				if (date.date < 10) {
					date.date = '0' + date.date
				}
				if (endDate.month < 10) {
					endDate.month = '0' + endDate.month
				}
				if (endDate.date < 10) {
					endDate.date = '0' + endDate.date
				}
				rankTableVm.searchParameter.timeType = '';
				rankTableVm.searchParameter.beginTime = date.year + '-' + date.month + '-' + date.date;
				rankTableVm.searchParameter.endTime = endDate.year + '-' + endDate.month + '-' + endDate.date;
				rankTableVm.reload();
			}
		});
		laydate.render({
			elem: '#test7',
			range: true,
			btns: ['now','confirm'],
			done: function(value, date, endDate) {
				if (date.month < 10) {
					date.month = '0' + date.month
				}
				if (date.date < 10) {
					date.date = '0' + date.date
				}
				if (endDate.month < 10) {
					endDate.month = '0' + endDate.month
				}
				if (endDate.date < 10) {
					endDate.date = '0' + endDate.date
				}
				singleGoodsTableVm.searchParameter.timeType = '';
				singleGoodsTableVm.searchParameter.beginTime = date.year + '-' + date.month + '-' + date.date;
				singleGoodsTableVm.searchParameter.endTime = endDate.year + '-' + endDate.month + '-' + endDate.date;
				_this.lineChartShow();
				_this.totalShow();
				singleGoodsTableVm.reload();
			}
		});
		//监听一级Tab切换
		element.on('tab(tabBrief)', function(obj) {
			console.log('12', obj)

			switch (obj.index) {
				case 0:
					$('#rankBtn button').eq(0).removeClass('layui-btn-primary').siblings().addClass('layui-btn-primary');
					rankTableVm.reload();
					break;
				case 1:
					$('#singleGoodsBtn button').eq(0).removeClass('layui-btn-primary').siblings().addClass('layui-btn-primary');
					singleGoodsTableVm.searchParameter.timeType = 1
					_this.lineChartShow();
					_this.totalShow();
					singleGoodsTableVm.reload();
					break;
			}
		});
		_this.initializationData();
	};
	//初始化表格
	vm.prototype.initializationData = function() {
		var _this = this;
		_this.dataListObj = table.render({
			id: _this.dataId,
			elem: _this.elem,
			toolbar: _this.toolbar,
			defaultToolbar: ['filter'],
			url: _this.url,
			page: _this.page,
			cols: _this.cols,
			done: _this.done,
			where: $.extend(_this.where, _this.searchParameter),
			limit: _this.limit,
		});
	};
	//重新加载数据表
	vm.prototype.reload = function() {
		var _this = this;
		_this.dataListObj = table.reload(_this.dataId, { //执行重载数据表
			where: _this.searchParameter,
			page: {
				curr: 1
			}
		});
	};
	//初始化组件
	vm.prototype.initializationModule = function(obj) {
		var _this = this;
		$.ajax({
			url: obj.url,
			data: obj.data,
			success: function(res) {
				var html = '<option value="">' + obj.prompt + '</option>';
				for (var i in res.data) {
					html += '<option value="' + res.data[i].id + '">' + res.data[i].name +
						'</option>';
				}
				$(obj.elem).html(html);
				form.render();
			}
		});
	};
	//初始化事件监听
	vm.prototype.eventMonitor = function(id) {
		var _this = this;
		//监听搜索表单事件
		if (typeof(_this.formEvent) == "object") {
			for (let i = 0; i < _this.formEvent.length; i++) {
				form.on('submit(' + _this.formEvent[i] + ')', function(obj) {
					_this.formInfoSearch(_this.formEvent[i], obj);
					return false;
				});
			}
		}
		//监听类别切换事件
		if (typeof(_this.tabEvent) == "object") {
			for (let i = 0; i < _this.tabEvent.length; i++) {
				form.on('submit(' + _this.tabEvent[i] + ')', function(obj) {
					_this.tabInfoSearch(_this.tabEvent[i], obj);
					return false;
				});
			}
		}
		return _this;
	};
	//搜索处理函数
	vm.prototype.formInfoSearch = function(id, obj) {
		var _this = this;
		$(obj.elem).removeClass('layui-btn-primary').siblings().addClass('layui-btn-primary');
		if (obj.elem.name == 4) {
			return false
		}
		obj.field.timeType = obj.elem.name || 1;
		_this.searchParameter = obj.field;
		if (_this.dataId == "singleGoodsTableData") {
			_this.lineChartShow();
			_this.totalShow();
		}
		_this.reload();
	};
	vm.prototype.tabInfoSearch = function(id, obj) {
		var _this = this;
		console.log(_this)
		$(obj.elem).removeClass('layui-btn-primary').siblings().addClass('layui-btn-primary');
		obj.field.timeType = 1;
		_this.searchParameter = obj.field;
		if (id == 'goods') {
			table.reload(tableId, {
				url: 'goodsTableUrl',
				cols: [
					[{
						type: 'numbers',
						title: '排名',
						width: 80
					}, {
						field: 'name',
						title: '商品名称'
					}, {
						field: 'buyers',
						title: '支付买家数',
						align: 'center'
					}, {
						field: 'orders',
						title: '支付订单数',
						align: 'center'
					}, {
						field: 'dealAmount',
						title: '成交金额（元）',
						align: 'center'
					}]
				]
			})
		} else if (id == 'seller') {
			table.reload(tableId, {
				url: 'sellerTableUrl',
				cols: [
					[{
						type: 'numbers',
						title: '排名',
						width: 80
					}, {
						field: 'name',
						title: '商户名称'
					}, {
						field: 'buyers',
						title: '支付买家数',
						align: 'center'
					}, {
						field: 'orders',
						title: '支付订单数',
						align: 'center'
					}, {
						field: 'dealAmount',
						title: '成交金额（元）',
						align: 'center'
					}]
				]
			});
		}

	};

	//jquer事件绑定
	vm.prototype.$event = function() {
		var _this = this;
		//监听头部工具栏
		table.on('toolbar(' + _this.dataId + ')', function(obj) {
			switch (obj.event) {
				case 'export':
					_this.dataExport();
					break;
			};
		});
	};
	//数据导出处理函数
	vm.prototype.dataExport = function() {
		var _this = this;
		_this.downloadParameter = '?';
		for (var i in _this.dataListObj.config.where) {
			_this.downloadParameter += "&" + i + '=' + _this.dataListObj.config.where[i];
		}
		_this.startDownload();
	};
	//启动下载
	vm.prototype.startDownload = function() {
		var _this = this;
		window.open(window.hywa.config.href + window.hywa.config.port[_this.dataDownload] + _this.downloadParameter);
	};

	vm.prototype.lineChartShow = function() {
		var _this = this;
		$.ajax({
			url: "singleOrderVolumeUrl",
			data: {
				timeType: singleGoodsTableVm.searchParameter.timeType,
				beginTime: singleGoodsTableVm.searchParameter.beginTime,
				endTime: singleGoodsTableVm.searchParameter.endTime,
			},
			success: function(res) {
				console.log(res)
				if (res.code == 0) {
					let seriesData1 = [],
						seriesData2 = [],
						xAxisData = []
					for (let i = 0; i < res.data.length; i++) {
						xAxisData.push(res.data[i].time);
						seriesData1.push(res.data[i].orders);
						seriesData2.push(res.data[i].rateOfIncrease);
					}
					_this.lineChart = echarts.init(document.getElementById('goodsChart'));
					var option = {
						color: ['#1E9FFF', '#e34c4c'],
						tooltip: {
							trigger: 'axis',
						},
						color: ['#5FB878', '#1E9FFF'],
						legend: {
							data: ['下单量', '增长率']
						},
						grid: {
							left: '2%',
							right: '1%',
							bottom: '2%',
							top: '20%',
							containLabel: true
						},
						xAxis: [{
							type: 'category',
							data: xAxisData,
							axisPointer: {
								type: 'shadow'
							},
							axisLine: {
								show: false
							},
							axisTick: {
								show: false
							}
						}],
						yAxis: [{
								type: 'value',
								name: '下单量',
								axisLabel: {
									formatter: '{value}'
								},
								axisLine: {
									show: false
								},
								axisTick: {
									show: false
								}
							},
							{
								type: 'value',
								name: '增长率',
								axisLabel: {
									formatter: '{value}'
								},
								axisLine: {
									show: false
								},
								axisTick: {
									show: false
								}
							}
						],
						series: [{
								name: '下单量',
								type: 'bar',
								barMaxWidth: 35,
								barGap: 0,
								data: seriesData1,
								itemStyle: {
									normal: {
										barBorderRadius: 20,
									},
								},
							},
							{
								name: '增长率',
								type: 'line',
								yAxisIndex: 1,
								data: seriesData2,
								smooth: true
							}
						]
					};
					_this.lineChart.setOption(option);
					window.addEventListener("resize", () => {
						_this.lineChart.resize();
					});
				}

			}
		});
	};

	vm.prototype.totalShow = function() {
		var _this = this;
		$.ajax({
			type: 'get',
			url: "singleGoodsTotalUrl",
			data: {
				timeType: singleGoodsTableVm.searchParameter.timeType,
				beginTime: singleGoodsTableVm.searchParameter.beginTime,
				endTime: singleGoodsTableVm.searchParameter.endTime,
			},
			success: function(res) {
				console.log(res)
				typeTpl({
					elem: ".goodsTotal",
					tpl: totalTpl,
					data: res.data[0]
				});
			},
		})

	};

	//模板引擎
	function typeTpl(obj) {
		laytpl(obj.tpl.innerHTML).render(obj.data, function(html) {
			$(obj.elem).html(html);
		});
	}

	// 排行榜
	let tableId = "rankTableData"
	var rankTableVm = new vm({
		dataId: 'rankTableData',
		elem: '#rankTableData',
		url: 'goodsTableUrl',
		page: true,
		where: {
			beginTime: '',
			endTime: '',
			timeType: 1,
		},
		cols: [
			[{
				type: 'numbers',
				title: '排名',
				width: 80
			}, {
				field: 'name',
				title: '商品名称'
			}, {
				field: 'buyers',
				title: '支付买家数',
				align: 'center'
			}, {
				field: 'orders',
				title: '支付订单数',
				align: 'center'
			}, {
				field: 'dealAmount',
				title: '成交金额（元）',
				align: 'center'
			}]
		]
	});
	//初始化事件监听
	rankTableVm.formEvent = ['day', 'month', 'week', 'range'];
	rankTableVm.tabEvent = ['goods', 'seller'];
	rankTableVm.eventMonitor();
	rankTableVm.$event();

	// 单品分析
	var singleGoodsTableVm = new vm({
		dataId: 'singleGoodsTableData',
		elem: '#singleGoodsTableData',
		url: 'singleGoodsTableUrl',
		page: true,
		where: {
			beginTime: '',
			endTime: '',
			timeType: 1,
		},
		cols: [
			[{
				field: 'productName',
				title: '农产品名称',
				align: 'center'
			}, {
				field: 'avgPrice',
				title: '成交价格（元）',
				align: 'center'
			}, {
				field: 'usersNumber',
				title: '支付人数',
				align: 'center'
			}, {
				field: 'ordersNumber',
				title: '支付订单数',
				align: 'center'
			}, {
				field: 'amount',
				title: '成交金额（元）',
				align: 'center'
			}]
		]
	});
	//初始化事件监听
	singleGoodsTableVm.formEvent = ['day1', 'month1', 'week1', 'range1'];
	singleGoodsTableVm.eventMonitor();
	singleGoodsTableVm.$event();

});
