<template>
	<div class="statistics-center-frequently-event-container layout-padding">
		<div class="layout-padding-auto layout-padding-view pd20">
			<ProTable
				ref="proTableRef"
				:columns="columns"
				:data="state.tableData"
				@updateTable="queryList"
				:loading="state.loading"
				:total="state.total"
				v-model:page-index="state.queryParams.PageIndex"
				v-model:page-size="state.queryParams.PageSize"
			>
				<template #table-search>
					<el-form :model="state.queryParams" ref="ruleFormRef" @submit.native.prevent inline>
						<el-form-item label="受理时间" prop="crTime">
							<el-date-picker
								v-model="state.queryParams.crTime"
								type="daterange"
								unlink-panels
								range-separator="至"
								start-placeholder="开始时间"
								end-placeholder="结束时间"
								:shortcuts="shortcuts"
								@change="handleQuery"
								value-format="YYYY-MM-DD"
								:clearable="false"
							/>
						</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>
				</template>
				<template #tableHeader="scope">
					<el-button type="primary" @click="onAnalysis" :disabled="!scope.isSelected">
						<SvgIcon name="ele-Document" class="mr5" />生成分析报告
					</el-button>
				</template>
			</ProTable>
		</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 { onMounted, reactive, ref } from 'vue';
import { ElMessageBox, FormInstance } from 'element-plus';
import { defaultDate, shortcuts } 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 proTableRef = ref<RefType>(); // 表格ref
// 表格配置项
const columns = ref<any[]>([
	{ type: 'selection', fixed: 'left', width: 40, align: 'center' },
	{ prop: 'areaName', label: '事发地址' },
	{ prop: 'title', label: '标题' },
	{ prop: 'acceptType', label: '受理类型' },
	{ prop: 'hotspotName', label: '热点分类' },
	{
		prop: 'sumCount',
		label: '预警次数',
		render: (scope) => {
			return (
				<el-button type="primary" link onClick={() => linkDetail(scope.row)}>
					{scope.row.sumCount}
				</el-button>
			);
		},
	},
]);
// 定义变量内容
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 resetQuery = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	ruleFormRef.value?.resetFields();
	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: proTableRef.value.selectedList,
		};
		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);
onMounted(() => {
	getBaseData();
	queryList();
});
</script>
<style scoped lang="scss">
.statistics-center-frequently-event-container {
	.arrow {
		transition: transform var(--el-transition-duration);
		cursor: pointer;
	}
	.arrow.is-reverse {
		transform: rotateZ(-180deg);
	}
}
</style>
