<template>
	<div class="statistics-order-hotspot-count-container layout-padding">
		<div class="layout-padding-auto layout-padding-view pd20">
			<el-form :model="state.queryParams" ref="ruleFormRef" @submit.native.prevent inline>
				<el-form-item prop="dateType" label="时间单位">
					<el-segmented
						v-model="state.queryParams.dateType"
						:options="[
									{ label: '年', value: 'year' },
									{ label: '月', value: 'month' },
									{ label: '日', value: 'date' },
									{ label: '自定义', value: 'daterange' },
								]"
						@change="handleQuery"
						:disabled="state.loading"
					/>
				</el-form-item>
				<el-form-item prop="crTime" v-if="state.queryParams.dateType === 'daterange'" label="时间">
					<el-date-picker
						v-model="state.queryParams.crTime"
						type="datetimerange"
						unlink-panels
						range-separator="至"
						start-placeholder="开始时间"
						end-placeholder="结束时间"
						:shortcuts="shortcuts"
						@change="handleQuery"
						value-format="YYYY-MM-DD[T]HH:mm:ss"
						:default-time="defaultTimeStartEnd"
						:clearable="false"
						:editable="false"
					/>
				</el-form-item>
				<el-form-item prop="hbTime" v-if="state.queryParams.dateType === 'daterange'" label="环比时间段">
					<el-date-picker
						v-model="state.queryParams.hbTime"
						type="datetimerange"
						unlink-panels
						range-separator="至"
						start-placeholder="开始时间"
						end-placeholder="结束时间"
						:shortcuts="shortcuts"
						@change="handleQuery"
						value-format="YYYY-MM-DD[T]HH:mm:ss"
						:default-time="defaultTimeStartEnd"
						:clearable="false"
						:editable="false"
					/>
				</el-form-item>
				<el-form-item prop="time" v-else label="时间">
					<el-date-picker
						v-model="state.queryParams.time"
						:type="state.queryParams.dateType"
						placeholder="选择时间"
						@change="handleQuery"
						:value-format="valueFormat"
						:clearable="false"
						:editable="false"
					/>
				</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>
			<vxe-toolbar
			ref="toolbarRef"
			:loading="state.loading"
			custom
			:refresh="{
			queryMethod: handleQuery,
			}"
			:tools="[{ toolRender: { name: 'exportAll' } }]"
			>
			</vxe-toolbar>
			<div style="overflow: hidden; width: 100%; height: 100%; flex: 1">
				<vxe-table
					border
					:loading="state.loading"
					:data="tableData"
					:column-config="{ resizable: true }"
					:row-config="{ isCurrent: true, isHover: true, height: 30,useKey:true }"
					ref="tableRef"
					height="auto"
					auto-resize
					show-overflow
					:scrollY="{ enabled: true, gt: 0 }"
					id="statisticsOrderHotspotCount"
					:custom-config="{ storage: true }"
					:params="{ exportMethod: departmentHotExport, exportParams: requestParams }"
					showHeaderOverflow
					show-footer
					:footer-method="footerMethod"
					:tree-config="treeConfig"
				>
					<vxe-column field="name" title="热点名称"  tree-node></vxe-column>
					<vxe-column field="num" title="工单数"></vxe-column>
					<vxe-column field="chainNum" title="环比工单数"></vxe-column>
					<vxe-column field="chainRate" title="日环比"></vxe-column>
				</vxe-table>
			</div>
		</div>
	</div>
</template>
<script setup lang="tsx" name="statisticsOrderHotspotCount">
import { computed, onMounted, reactive, ref } from 'vue';
import { FormInstance } from 'element-plus';
import { departmentHot, departmentHotExport } from '@/api/statistics/order';
import { defaultDateTime, defaultTimeStartEnd, shortcuts } from '@/utils/constants';
import dayjs from 'dayjs';
import XEUtils from 'xe-utils';

// 定义变量内容
const ruleFormRef = ref<RefType>(); // 表单ref
const state = reactive({
	queryParams: {
		// 查询条件
		dateType: 'date', // 关键词
		time: dayjs(new Date()).format('YYYY-MM-DD'), // 时间默认今天
		crTime: defaultDateTime, // 时间默认今天开始到今天结束
		hbTime: defaultDateTime, // 时间默认今天开始到今天结束
	},
	loading: false, // 加载
});
const valueFormat = computed(() => {
	return state.queryParams.dateType === 'date' ? 'YYYY-MM-DD' : state.queryParams.dateType === 'month' ? 'YYYY-MM' : 'YYYY';
});
// 设置当前时间的映射值
const getType = computed(() => {
	const statusMap: any = {
		date: '1',
		year: '3',
		month: '2',
		daterange: '0',
	};
	return statusMap[state.queryParams.dateType] || '';
});
const tableData = ref<EmptyArrayType>([]);
/** 搜索按钮操作 */
const handleQuery = () => {
	// state.queryParams.PageIndex = 1;
	tableData.value = [];
	queryList();
};
/** 获取列表 */
const requestParams = ref<EmptyObjectType>({});
const queryList = () => {
	state.loading = true;
	let StartTime: any = null;
	let EndTime: any = null;
	let ChainStartTime: any = null;
	let ChainEndTime: any = null;
	switch (state.queryParams.dateType) {
		case 'date':
			StartTime = dayjs(state.queryParams.time).startOf('date').format('YYYY-MM-DD');
			EndTime = dayjs(state.queryParams.time).endOf('date').format('YYYY-MM-DD');
			break;
		case 'month':
			StartTime = dayjs(state.queryParams.time).startOf('month').format('YYYY-MM-DD');
			EndTime = dayjs(state.queryParams.time).endOf('month').format('YYYY-MM-DD');
			break;
		case 'year':
			StartTime = dayjs(state.queryParams.time).startOf('year').format('YYYY-MM-DD');
			EndTime = dayjs(state.queryParams.time).endOf('year').format('YYYY-MM-DD');
			break;
		case 'daterange':
			StartTime = state.queryParams?.crTime[0];
			EndTime = state.queryParams?.crTime[1];
			ChainStartTime = state.queryParams?.hbTime[0];
			ChainEndTime = state.queryParams?.hbTime[1];
			break;
	}
	requestParams.value = {
		Type: getType.value,
		StartTime,
		EndTime,
		ChainStartTime,
		ChainEndTime,
	};
	departmentHot(requestParams.value)
		.then((res: any) => {
			tableData.value = [...res.result.list];
			state.loading = false;
		})
		.catch(() => {
			state.loading = false;
		});
};
/** 重置按钮操作 */
const resetQuery = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	queryList();
};
const treeConfig = reactive({
	transform: true,
	rowField: 'id',
	parentField: 'parentId',
	lazy: true,
	hasChild: 'sublevel',
	loadMethod({ row }) {
		// 异步加载子节点
		return fetchChildListApi(row);
	},
});
const fetchChildListApi = (row: any) => {
	return new Promise((resolve) => {
		let StartTime: any = null;
		let EndTime: any = null;
		let ChainStartTime: any = null;
		let ChainEndTime: any = null;
		switch (state.queryParams.dateType) {
			case 'date':
				StartTime = dayjs(state.queryParams.time).startOf('date').format('YYYY-MM-DD');
				EndTime = dayjs(state.queryParams.time).endOf('date').format('YYYY-MM-DD');
				break;
			case 'month':
				StartTime = dayjs(state.queryParams.time).startOf('month').format('YYYY-MM-DD');
				EndTime = dayjs(state.queryParams.time).endOf('month').format('YYYY-MM-DD');
				break;
			case 'year':
				StartTime = dayjs(state.queryParams.time).startOf('year').format('YYYY-MM-DD');
				EndTime = dayjs(state.queryParams.time).endOf('year').format('YYYY-MM-DD');
				break;
			case 'daterange':
				StartTime = state.queryParams?.crTime[0];
				EndTime = state.queryParams?.crTime[1];
				ChainStartTime = state.queryParams?.hbTime[0];
				ChainEndTime = state.queryParams?.hbTime[1];
				break;
		}
		const request = {
			Type: getType.value,
			StartTime,
			EndTime,
			ChainStartTime,
			ChainEndTime,
			Id: row.id,
		};
		departmentHot(request)
			.then((res: any) => {
				resolve([...res.result.list]);
			})
			.catch(() => {});
	});
};
// 计算合计
const footerMethod = ({ columns, data }) => {
	return [
		columns.map((column: any, columnIndex: number) => {
			if (columnIndex === 0) {
				return '合计';
			}
			if (['num'].includes(column.property)) {
				return XEUtils.sum(data, column.property);
			}
			return null;
		}),
	];
};
const toolbarRef = ref<RefType>();
const tableRef = ref<RefType>();
onMounted(() => {
	queryList();
	if (tableRef.value && toolbarRef.value) {
		tableRef.value.connect(toolbarRef.value);
	}
});
</script>
