;
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个字符噢"
		]
	});
	//监听一级Tab切换
	element.on('tab(productTabBrief)', function(obj) {
		switch (obj.index) {
			case 0:
				tableVm.reload();
				break;
		}
	});
	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 = {
			timeType: '1'
		}; //搜索参数
		_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;
		var ins1 = laydate.render({
			elem: '#test6',
			range: true,
			btns: [],
			change: function(value, date, endDate) {
				let arr = value.split(" ");
				if (((new Date(arr[2]) - new Date(arr[0])) / (24 * 60 * 60 * 1000) + 1) > 30) {
					ins1.hint("最大只能选择30天");
					return;
				}
				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
				}
				_this.searchParameter.timeType = '';
				_this.searchParameter.beginTime = date.year + '-' + date.month + '-' + date.date;
				_this.searchParameter.endTime = endDate.year + '-' + endDate.month + '-' + endDate.date;
				_this.barChartShow();
				_this.pieChartShow();
			}
		});
		_this.initializationData();
		_this.barChartShow();
		_this.pieChartShow();
	};
	//初始化表格
	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,
			even: true,
			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.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;
				});
			}
		}
		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.id == 4) {
			return false
		}
		obj.field.timeType = obj.elem.id || 1;
		_this.searchParameter = obj.field;
		_this.barChartShow();
		_this.pieChartShow();
	};

	//渲染时间选择器
	vm.prototype.showTimeSelect = function(obj) {
		laydate.render({
			elem: obj.elem,
			type: "month",
			value: ((new Date().getMonth() + 1) < 10) ? new Date().getFullYear() + '-0' + (new Date().getMonth() + 1) : new Date()
				.getFullYear() + '-' + (new Date().getMonth() + 1)
		});
	};
	//jquer事件绑定
	vm.prototype.$event = function() {
		var _this = this;
		$(_this.dataExportBtn).on("click", function(e) {
			_this.dataExport();
		});
	};
	//数据导出处理函数
	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.barChartShow = function() {
		var _this = this;
		$.ajax({
			url: "viewsVolumeUrl",
			data: {
				timeType: _this.searchParameter.timeType,
				beginTime: _this.searchParameter.beginTime,
				endTime: _this.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].views);
						seriesData2.push(res.data[i].orders);
					}
					_this.barChart = echarts.init(document.getElementById('viewsChart'));
					var option = {
						tooltip: {
							trigger: 'axis'
						},
						color: ['#5FB878', '#1E9FFF'],
						legend: {
							data: ['浏览量', '下单量']
						},
						grid: {
							left: '1%',
							right: '3%',
							bottom: '8%',
							top: '15%',
							containLabel: true
						},
						calculable: true,
						xAxis: [{
							type: 'category',
							data: xAxisData,
							axisLabel: {
								interval: 0, //横轴信息全部显示
								rotate: 30, //-30度角倾斜显示    
							}
						}],
						yAxis: [{
							type: 'value'
						}],
						dataZoom: [{
							type: 'slider',
							filterMode: 'none',
							height: 20,
							bottom: 5,
							borderColor: 'transparent',
							backgroundColor: '#e2e2e2',
							handleSize: 20,
							handleStyle: {
								shadowBlur: 6,
								shadowOffsetX: 1,
								shadowOffsetY: 2,
								shadowColor: '#aaa'
							}
						}, {
							type: 'inside',
							filterMode: 'none'
						}],
						series: [{
								name: '浏览量',
								type: 'bar',
								barMaxWidth: 40,
								barGap: 0,
								data: seriesData1
							},
							{
								name: '下单量',
								type: 'bar',
								barMaxWidth: 40,
								data: seriesData2
							}
						]
					};
					_this.barChart.setOption(option);
					window.addEventListener("resize", () => {
						_this.barChart.resize();
					});
				}

			}
		});
	};

	vm.prototype.pieChartShow = function() {
		var _this = this;
		$.ajax({
			url: "visitorTableUrl",
			data: {
				timeType: _this.searchParameter.timeType,
				beginTime: _this.searchParameter.beginTime,
				endTime: _this.searchParameter.endTime,
			},
			success: function(res) {
				let tableData = [{
					customerType: '新客户',
					customerVisits: res.data[0].newCustomerVisits,
					customerPercent: res.data[0].newCustomerPercent
				}, {
					customerType: '老客户',
					customerVisits: res.data[0].oldCustomerVisits,
					customerPercent: res.data[0].oldCustomerPercent
				}];
				table.reload(tableId, {
					data: tableData,
				});
				if (res.code == 0) {
					_this.pieChart = echarts.init(document.getElementById('visitorChart'));
					var option = {
						backgroundColor: '#ffffff',
						tooltip: {
							trigger: 'item',
							formatter: "{a} <br/>{b} : {c} ({d}%)"
						},
						color: ['#009688', '#5FB878', '#1E9FFF', '#01AAED', '#2F4056', '#393D49'],
						series: [{
							name: '客户类型',
							type: 'pie',
							radius: '55%',
							center: ["50%", "50%"],
							radius: ["45%", "80%"],

							data: [{
									value: res.data[0].newCustomerVisits,
									name: '新客户'
								},
								{
									value: res.data[0].oldCustomerVisits,
									name: '老客户'
								}
							],
							itemStyle: {
								emphasis: {
									shadowBlur: 10,
									shadowOffsetX: 0,
									shadowColor: 'rgba(0, 0, 0, 0.5)'
								}
							},
							itemStyle: {
								normal: {
									label: {
										show: true,
										formatter: '{b} : {c} ({d}%)'
									},
									borderColor: '#ffffff',
									borderWidth: 10,
								},
								labelLine: {
									show: true
								}
							}
						}]
					};
					_this.pieChart.setOption(option);
					window.addEventListener("resize", () => {
						_this.pieChart.resize();
					});
				}
			}
		});
	};


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


	// 表格列表
	let tableId = "tableData";
	var tableVm = new vm({
		dataId: 'tableData',
		elem: '#tableData',
		data: [],
		page: false,
		cols: [
			[{
				field: 'customerType',
				title: '客户类型'
			}, {
				field: 'customerVisits',
				title: '访问数',
				align: 'center'
			}, {
				field: 'customerPercent',
				title: '占比',
				align: 'center'
			}]
		]
	});
	//初始化事件监听
	tableVm.formEvent = ['tableSearch'];
	tableVm.formEvent = ['day', 'month', 'week', 'range'];
	tableVm.eventMonitor();
	tableVm.$event();

});
