<template>
	<div class="statistics-order-hotspot-are-container layout-padding">
		<div class="layout-padding-auto layout-padding-view pd20">
			<el-tabs v-model="state.queryParams.HotspotLevel" @tab-change="handleQuery">
				<el-tab-pane name="1" label="第一级别"></el-tab-pane>
				<el-tab-pane name="2" label="第二级别"></el-tab-pane>
				<el-tab-pane name="3" label="第三级别"></el-tab-pane>
				<el-tab-pane name="4" label="第四级别"></el-tab-pane>
			</el-tabs>
			<el-form :model="state.queryParams" ref="ruleFormRef" @submit.native.prevent inline class="search-form mb10">
				<el-form-item prop="crTime">
					<statistical-time v-model="state.queryParams.crTime" @change="handleQuery" ref="statisticalTimeRef" :disabled="state.loading"/>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleQuery" :loading="state.loading"> <SvgIcon name="ele-Search" class="mr5" />查询 </el-button>
					<el-button @click="resetQuery(ruleFormRef)" class="default-button" :loading="state.loading">
						<SvgIcon name="ele-Refresh" class="mr5" />重置
					</el-button>
				</el-form-item>
			</el-form>
			<div style="overflow: hidden; width: 100%; height: 100%; flex: 1">
				<vxe-grid v-bind="gridOptions" ref="tableRef">
					<template #toolbar_tools>
						<VxeButton title="导出全部" circle class="mr10" @click="exportAll"><SvgIcon name="iconfont icon-export" /></VxeButton>
					</template>
				</vxe-grid>
			</div>
		</div>
	</div>
</template>
<script setup lang="tsx" name="statisticsOrderHotspotArea">
import { onMounted, reactive, ref, defineAsyncComponent } from 'vue';
import { ElMessageBox, FormInstance } from 'element-plus';
import { defaultDate } from '@/utils/constants';
import Other from '@/utils/other';
import { statisticsOrderHot, statisticsOrderHotExport } from '@/api/statistics/order';
import { useRouter } from 'vue-router';
import { VxeButton, VxeUI } from 'vxe-pc-ui';
import { downloadFileByStream } from '@/utils/tools';
import XEUtils from 'xe-utils';

const StatisticalTime = defineAsyncComponent(() => import('@/components/StatisticalTime/index.vue')); // 日期类型选择组件

// 定义变量内容
const ruleFormRef = ref<RefType>(); // 表单ref
const state = reactive<any>({
	queryParams: {
		// 查询条件
		HotspotLevel: '1',
		crTime: defaultDate, //
		StartTime: null,
		EndTime: null,
	},
	tableData: [], //表单
	loading: false, // 加载
	total: 0, // 总数
	callForwardingSource: [],
});
const handleQuery = () => {
	// state.queryParams.PageIndex = 1;
	queryList();
};
const requestParams = ref<EmptyObjectType>({});
const gridOptions = reactive<any>({
	loading: false,
	border: true,
	showOverflow: true,
	printConfig: {},
	columnConfig: {
		resizable: true,
	},
	scrollY: {
		enabled: true,
		gt: 100
	},
	toolbarConfig: {
		zoom: true,
		custom: true,
		refresh: {
			queryMethod: () => {
				queryList();
			},
		},
		slots: {
			tools: 'toolbar_tools',
		},
	},
	showFooter: true,
	footerMethod: ({ columns, data }) => {
		return [
			columns.map((column: any, columnIndex: number) => {
				if (columnIndex === 0) {
					return '合计';
				}
				return XEUtils.sum(data, column.property);
			}),
		];
	},
	showHeaderOverflow: true,
	customConfig: {
		storage: true
	},
	id: 'statisticsOrderHotspotArea',
	rowConfig: { isHover: true, height: 30,isCurrent:true,useKey:true },
	height: 'auto',
	columns: [],
	data: [],
});
/** 获取列表 */
const queryList = async () => {
	state.loading = true;
	gridOptions.loading = true;
	try {
		requestParams.value = Other.deepClone(state.queryParams);
		requestParams.value.StartTime = state.queryParams.crTime === null ? null : state.queryParams.crTime[0];
		requestParams.value.EndTime = state.queryParams.crTime === null ? null : state.queryParams.crTime[1];
		Reflect.deleteProperty(requestParams.value, 'crTime');
		const { result } = await statisticsOrderHot(requestParams.value);
		let columns = result.areaList.map((item: any) => {
			return {
				key: item.id,
				dataKey: item.id,
				title: item.areaName,
				minWidth: 100,
				align: 'center',
				field: item.id,
				sortable:true,
				slots: {
					default (scope:any) {
						return (
							<>
								{scope.row.HotspotName1 !== '合计' ? (
									<el-button type="primary" link onClick={() => linkDetail(scope)}>
										{scope.row[item.id] ? scope.row[item.id] : 0}
									</el-button>
								) : (
									<span>{scope.row[item.id]}</span>
								)}
							</>
						);
					}
				}
			};
		});
		let tableData = result.data;
		tableData.map((item: any) => {
			// 取第一级名称
			item.HotspotName1 = item.HotspotName?.split('-')[0] ?? '';
			// 取第二级名称
			item.HotspotName2 = item.HotspotName?.split('-')[1] ?? '';
			// 取第三级名称
			item.HotspotName3 = item.HotspotName?.split('-')[2] ?? '';
			// 取第四级名称
			item.HotspotName4 = item.HotspotName?.split('-')[3] ?? '';
			return { ...item };
		});
		switch (state.queryParams.HotspotLevel) {
			case '1':
				// 分类级别
				columns.unshift({
					key: 'HotspotName1',
					dataKey: 'HotspotName1',
					title: `一级热点`,
					field: 'HotspotName1',
					width: 150,
					align: 'center',
				});
				break;
			case '2':
				columns.unshift(
					{
						key: 'HotspotName1',
						dataKey: 'HotspotName1',
						title: `一级热点`,
						field: 'HotspotName1',
						width: 150,
						align: 'center',
					},
					{
						key: 'HotspotName2',
						dataKey: 'HotspotName2',
						title: `二级热点`,
						width: 150,
						align: 'center',
						field: 'HotspotName2',
					}
				);
				break;
			case '3':
				columns.unshift(
					{
						key: 'HotspotName1',
						dataKey: 'HotspotName1',
						title: `一级热点`,
						width: 150,
						align: 'center',
						field: 'HotspotName1',
					},
					{
						key: 'HotspotName2',
						dataKey: 'HotspotName2',
						title: `二级热点`,
						width: 150,
						align: 'center',
						field: 'HotspotName2',
					},
					{
						key: 'HotspotName3',
						dataKey: 'HotspotName3',
						title: `三级热点`,
						width: 150,
						align: 'center',
						field: 'HotspotName3',
					}
				);
				break;
			case '4':
				columns.unshift(
					{
						key: 'HotspotName1',
						dataKey: 'HotspotName1',
						title: `一级热点`,
						width: 150,
						align: 'center',
						field: 'HotspotName1',
					},
					{
						key: 'HotspotName2',
						dataKey: 'HotspotName2',
						field: 'HotspotName2',
						title: `二级热点`,
						width: 150,
						align: 'center',
					},
					{
						key: 'HotspotName3',
						dataKey: 'HotspotName3',
						field: 'HotspotName3',
						title: `三级热点`,
						width: 150,
						align: 'center',
					},
					{
						key: 'HotspotName4',
						dataKey: 'HotspotName4',
						field: 'HotspotName4',
						title: `四级热点`,
						width: 150,
						align: 'center',
					}
				);
				break;
			default:
				break;
		}

		// 计算横轴小计
		tableData = result.data.map((item: any) => {
			let subtotal = 0;
			for (let i of result.areaList) {
				const itemI = item[i.id] ?? 0;
				subtotal += itemI;
			}
			return {
				...item,
				subtotal,
			};
		});
		columns.push({
			align: 'center',
			key: 'subtotal',
			dataKey: 'subtotal',
			title: '小计',
			field: 'subtotal',
			width: 100,
			sortable:true
		});
		if (result.data.length) {
			tableData = tableData.filter((item) => item.HotspotName1); // 筛选掉空对象
		}
		gridOptions.data = tableData;
		gridOptions.columns = columns;
		state.loading = false;
		gridOptions.loading = false;
	} catch (e) {
		state.loading = false;
		gridOptions.loading = false;
		console.log(e);
	}
};
/** 重置按钮操作 */
const statisticalTimeRef = ref<RefType>();
const resetQuery = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	statisticalTimeRef.value.reset();
	queryList();
};
// 查看列表明细
const router = useRouter();
const linkDetail = (data:any) => {
	router.push({
		path: '/statistics/order/detailHotspotArea',
		query: {
			AreaCode: data.column.field,
			HotspotId: data.row.HotspotId,
			StartTime: requestParams.value.StartTime,
			EndTime: requestParams.value.EndTime,
			type: 'hotspotArea',
			tagsViewName:`${data.row.HotspotName}-${data.column.title}`
		},
	});
};
// 导出
const tableRef = ref();
const exportAll = () => {
	const columns = tableRef.value.getColumns();
	ElMessageBox.confirm(`您确定要导出全部数据，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			const AddColumnName = columns
				.map((item: any) => item.title)
				.filter((item: any) => !['一级热点', '二级热点', '三级热点', '四级热点'].includes(item));
			AddColumnName.unshift('热点分类');
			const specialRequest = {
				...requestParams.value,
				AddColumnName,
			};
			VxeUI.modal.message({
				content: `导出中，请稍等`,
				status: 'loading',
				id: 'exportAll',
				duration: -1,
			});
			statisticsOrderHotExport(specialRequest)
				.then((res: any) => {
					downloadFileByStream(res);
					VxeUI.modal.close('exportAll');
					VxeUI.modal.message({
						content: `导出成功`,
						status: 'success',
					});
				})
				.catch((e) => {
					console.log(`导出失败:${e}`);
					VxeUI.modal.close('exportAll');
					VxeUI.modal.message({
						content: `导出失败`,
						status: 'error',
					});
				});
		})
		.catch(() => {});
};
onMounted(() => {
	queryList();
});
</script>
