<template>
	<div class="statistics-center-frequently-event-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="crTime" label="受理时间" >
					<statistical-time v-model="state.queryParams.crTime" @change="handleQuery" ref="statisticalTimeRef" :disabled="state.loading"/>
				</el-form-item>
				<el-form-item label="受理类型" prop="AcceptType">
					<el-select v-model="state.queryParams.AcceptType" placeholder="请选择受理类型" clearable class="w100" @change="handleQuery">
						<el-button @click="drawer = true" class="default-button"> <SvgIcon name="ele-Search" class="mr5" />更多查询</el-button>
					</el-select>
				</el-form-item>
				<el-form-item label="">
					<el-button type="primary" @click="handleQuery" :loading="state.loading"> <SvgIcon name="ele-Search" class="mr5" />查询 </el-button>
					<el-button @click="drawer = true" class="default-button"> <SvgIcon name="ele-Search" class="mr5" />更多查询</el-button>
				</el-form-item>
			</el-form>
			<vxe-toolbar
				ref="toolbarRef"
				:loading="state.loading"
				custom
				:refresh="{
					queryMethod: handleQuery
				}"
			>
				<template #buttons>
					<el-button type="primary" @click="onAnalysis" :disabled="isChecked">
						<SvgIcon name="ele-Document" class="mr5" />生成分析报告
					</el-button>
				</template>
			</vxe-toolbar>
			<div style="overflow: hidden; width: 100%; height: 100%; flex: 1">
				<vxe-table
					border
					:loading="state.loading"
					:data="state.tableData"
					:column-config="{ resizable: true }"
					:row-config="{ isCurrent: true, isHover: true, height: 30, useKey: true }"
					ref="tableRef"
					@checkbox-all="selectAllChangeEvent"
					@checkbox-change="selectChangeEvent"
					height="auto"
					auto-resize
					show-overflow
					:scrollY="{ enabled: true, gt: 100 }"
					id="statisticsCenterFrequentlyEvent"
					:custom-config="{ storage: true }"
					showHeaderOverflow
				>
					<vxe-column type="checkbox" width="50" align="center"></vxe-column>
					<vxe-column field="areaName" title="事发地址"></vxe-column>
					<vxe-column field="title" title="标题"></vxe-column>
					<vxe-column field="acceptType" title="受理类型"></vxe-column>
					<vxe-column field="hotspotName" title="热点分类"></vxe-column>
					<vxe-column field="sumCount" title="预警次数" width="90">
						<template #default="{ row }">
							<el-button type="primary" link @click="linkDetail(row)">
							{{row.sumCount}}
							</el-button>
						</template>
					</vxe-column>
				</vxe-table>
			</div>
			<pagination
				@pagination="queryList"
				:total="state.total"
				v-model:current-page="state.queryParams.PageIndex"
				v-model:page-size="state.queryParams.PageSize"
				:disabled="state.loading"
			/>
		</div>
		<el-dialog v-model="state.dialogVisible" width="600px" draggable title="生成分析报告" @close="close" destroy-on-close>
			<el-form :model="state.ruleForm" label-width="100px" ref="ruleFormRef">
				<el-form-item label="报告名称" prop="employee" :rules="[{ required: true, message: '请填写报告名称', trigger: 'blur' }]">
					<el-input placeholder="请填写报告名称" v-model="state.ruleForm.employee" />
				</el-form-item>
				<el-form-item label="备注" prop="remark" :rules="[{ required: false, message: '请填写备注', trigger: 'blur' }]">
					<el-input type="textarea" placeholder="请填写备注" v-model="state.ruleForm.remark" />
				</el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="state.dialogVisible = false" class="default-button">取 消</el-button>
					<el-button type="primary" @click="onSubmit(ruleFormRef)" :loading="state.loading">确 定</el-button>
				</span>
			</template>
		</el-dialog>
		<!--	更多查询	-->
		<el-drawer v-model="drawer" title="更多查询" size="500px">
			<el-form :model="state.queryParams" ref="drawerRuleFormRef" @submit.native.prevent label-width="100px">
				<el-form-item label="热点分类" prop="Hotspot">
					<el-input v-model="state.queryParams.Hotspot" placeholder="热点分类名称" clearable @keyup.enter="handleQuery" />
				</el-form-item>
				<el-form-item label="事发地址" prop="AreaCode">
					<el-cascader
						:options="areaOptions"
						filterable
						:props="{ checkStrictly: true, value: 'id', label: 'areaName', emitPath: false }"
						placeholder="请选择事发地址"
						clearable
						class="w100"
						v-model="state.queryParams.AreaCode"
						@change="handleQuery"
						ref="areaRef"
					>
					</el-cascader>
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button type="primary" @click="handleQuery" :loading="state.loading"> <SvgIcon name="ele-Search" class="mr5" />查询 </el-button>
				<el-button @click="resetQuery(drawerRuleFormRef)" class="default-button"> <SvgIcon name="ele-Refresh" class="mr5" />重置 </el-button>
			</template>
		</el-drawer>
	</div>
</template>
<script setup lang="tsx" name="statisticsCenterFrequentlyEvent">
import { computed, defineAsyncComponent, onMounted, reactive, ref } from 'vue';
import { ElMessageBox, FormInstance } from 'element-plus';
import { defaultDate } from '@/utils/constants';
import { treeArea } from '@/api/auxiliary/area';
import { centerAddAnalysisReport, departmentHighFrequencyEvent } from '@/api/statistics/center';
import { useRouter } from 'vue-router';
import Other from '@/utils/other';
import { throttle } from '@/utils/tools';
import { returnBase } from '@/api/business/return';
import mittBus from '@/utils/mitt';


const StatisticalTime = defineAsyncComponent(() => import('@/components/StatisticalTime/index.vue')); // 日期类型选择组件
const pagination = defineAsyncComponent(() => import('@/components/ProTable/components/Pagination.vue')); // 分页
// 定义变量内容
const state = reactive<any>({
	queryParams: {
		// 查询条件
		AreaCode: null, // 事发地址
		AcceptType: null, // 受理类型
		Hotspot: null, // 热点分类
		crTime: defaultDate,
		StartTime: null,
		EndTime: null,
		PageIndex: 1,
		PageSize: 20,
	},
	tableData: [], //表单
	loading: false, // 加载
	total: 0, // 总数
	dialogVisible: false, // 弹框
	ruleForm: {
		employee: null,
		remark: null,
	},
});
// 基础信息
const acceptTypeOptions = ref([]); // 受理类型
const areaOptions = ref([]); // 事发地址
const getBaseData = async () => {
	const [acceptType, area] = await Promise.all([returnBase(), treeArea()]);
	acceptTypeOptions.value = acceptType.result?.acceptTypeOptions;
	areaOptions.value = area.result ?? [];
};
/** 搜索按钮操作 */
const handleQuery = () => {
	state.queryParams.PageIndex = 1;
	queryList();
};
/** 获取列表 */
const requestParams = ref<EmptyObjectType>({});
const queryList = () => {
	state.loading = true;
	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');
	departmentHighFrequencyEvent(requestParams.value)
		.then((res: any) => {
			state.tableData = res.result?.items ?? [];
			state.total = res.result?.total ?? 0;
			state.loading = false;
		})
		.catch(() => {
			state.loading = false;
		});
};
/** 重置按钮操作 */
const drawerRuleFormRef = ref();
const ruleFormRef = ref<RefType>(); // 表单ref
const drawer = ref(false);
const statisticalTimeRef = ref<RefType>();
const resetQuery = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	ruleFormRef.value?.resetFields();
	statisticalTimeRef.value.reset();
	queryList();
};
// 查看详情
const router = useRouter();
const linkDetail = (row: any) => {
	const StartTime = state.queryParams.crTime === null ? null : state.queryParams.crTime[0];
	const EndTime = state.queryParams.crTime === null ? null : state.queryParams.crTime[1];
	router.push({
		path: '/statistics/center/detailEventFrequently',
		query: {
			StartTime,
			EndTime,
			HotspotId: row.hotspotId,
			AreaCode: row.areaCode,
			AcceptTypeCode: row.acceptTypeCode,
			id: row.id,
			type:'event',
			tagsViewName:'高频事件统计明细'
		},
	});
};
// 生成分析报告
const onAnalysis = () => {
	state.dialogVisible = true;
};
const close = () => {
	ruleFormRef.value?.clearValidate();
	ruleFormRef.value?.resetFields();
};
const onSubmit = throttle((formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate((valid: boolean) => {
		if (!valid) return;
		const request = {
			analysisName: state.ruleForm.employee,
			remark: state.ruleForm.remark,
			startTime: state.queryParams.crTime === null ? null : state.queryParams.crTime[0],
			endTime: state.queryParams.crTime === null ? null : state.queryParams.crTime[1],
			analysisList: checkTable.value,
		};
		centerAddAnalysisReport(request)
			.then(() => {
				state.dialogVisible = false;
				ElMessageBox.confirm('分析报告已提交，可进入【报告管理】进行查看和下载', '提示', {
					autofocus: false,
					draggable: true,
					type: 'success',
					showClose: false,
					distinguishCancelAndClose: true,
					confirmButtonText: '查看报告',
					cancelButtonText: '我知道了',
				})
					.then(() => {
						mittBus.emit('clearCache', 'statisticsCenterReportManage');
						queryList();
						router.push({
							path: '/statistics/center/reportManage',
						});
					})
					.catch(() => {
						queryList();
					});
			})
			.catch(() => {
				state.dialogVisible = false;
			});
	});
}, 300);
const tableRef = ref<RefType>();
const checkTable = ref<EmptyArrayType>([]);
const selectAllChangeEvent = ({ checked }) => {
	if (tableRef.value) {
		const records = tableRef.value.getCheckboxRecords();
		checkTable.value = records;
		console.log(checked ? '所有勾选事件' : '所有取消事件', records);
	}
};

const selectChangeEvent = ({ checked }) => {
	if (tableRef.value) {
		const records = tableRef.value.getCheckboxRecords();
		checkTable.value = records;
		console.log(checked ? '勾选事件' : '取消事件', records);
	}
};
const isChecked = computed(() => {
	return !Boolean(checkTable.value.length);
});
const toolbarRef = ref<RefType>();
onMounted(() => {
	queryList();
	if (tableRef.value && toolbarRef.value) {
		tableRef.value.connect(toolbarRef.value);
	}
	getBaseData();
});
</script>
