<template>
	<div class="statistics-call-container layout-pd">
		<el-card shadow="never">
			<el-form :model="state.queryParams" ref="ruleFormRef" @submit.native.prevent inline>
				<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 label="热线号码" prop="Keyword">
					<el-select v-model="state.queryParams.Keyword" placeholder="请选择热线号码" clearable @change="handleQuery">
						<el-option v-for="item in state.callForwardingSource" :value="item.dicDataValue" :key="item.dicDataValue" :label="item.dicDataName" />
					</el-select>
				</el-form-item>
				<el-form-item label-width="0">
					<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-button type="primary" @click="onDetail" :loading="state.loading"> <SvgIcon name="ele-List" class="mr5" /> 话务日期明细 </el-button>
				</el-form-item>
			</el-form>
			<el-row :gutter="20">
				<el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
					<v-chart class="chart" :option="option" :loading="state.loading" autoresize />
				</el-col>
				<el-col :xs="24" :sm="12" :md="12" :lg="4" :xl="4">
					<vxe-table
						border
						:loading="state.loading"
						:data="state.tableData1"
						:row-config="{ isCurrent: true, isHover: true,useKey:true }"
						show-footer
						:footer-method="footerMethod"
					>
						<vxe-column field="name" title=""></vxe-column>
						<vxe-column field="value" title="数量"></vxe-column>
					</vxe-table>
				</el-col>
				<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
					<v-chart class="chart1" :option="option1" :loading="state.loading" autoresize />
				</el-col>
				<el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
					<vxe-toolbar
						ref="toolbarRef"
						:loading="state.loading"
						custom
						:refresh="{
							queryMethod: handleQuery,
						}"
						:tools="[{ toolRender: { name: 'exportAll' } }]"
					>
					</vxe-toolbar>
					<div style="max-height: 60vh" class="h100">
						<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"
							height="auto"
							auto-resize
							show-overflow
							id="statisticsCallIndex"
							:custom-config="{ storage: true }"
							:params="{ exportMethod: callListExport, exportParams: requestParams }"
							show-footer
							:footer-method="footerMethod1"
						>
							<vxe-column field="hourRange" title="时段" min-width="70"></vxe-column>
							<vxe-column field="total" title="呼入数量"></vxe-column>
							<vxe-column field="answered" title="接通数量"></vxe-column>
							<vxe-column field="hanguped" title="挂断数量"></vxe-column>
						</vxe-table>
					</div>
				</el-col>
			</el-row>
		</el-card>
	</div>
</template>
<script setup lang="tsx" name="statisticsCallIndex">
import { defineAsyncComponent, onMounted, reactive, ref } from 'vue';
import { FormInstance } from 'element-plus';
import { callList, callListExport, callPeriodBase } from '@/api/statistics/call';
import { defaultDate } from '@/utils/constants';
import Other from '@/utils/other';
import { useRouter } from 'vue-router';
import XEUtils from 'xe-utils';

const StatisticalTime = defineAsyncComponent(() => import('@/components/StatisticalTime/index.vue')); // 日期类型选择组件
// 定义变量内容
const ruleFormRef = ref<RefType>(); // 表单ref
const state = reactive<any>({
	queryParams: {
		// 查询条件
		Keyword: null, // 关键词
		crTime: defaultDate, //
		StartTime: null,
		EndTime: null,
	},
	tableData: [], //表单
	tableData1: [],
	loading: false, // 加载
	total: 0, // 总数
	callForwardingSource: [],
});
// 计算合计
const footerMethod = ({ columns, data }) => {
	return [
		columns.map((column: any, columnIndex: number) => {
			if (columnIndex === 0) {
				return '合计';
			}
			if (['value'].includes(column.property)) {
				return XEUtils.sum(data, column.property);
			}
		}),
	];
};
// 计算合计
const footerMethod1 = ({ columns, data }) => {
	return [
		columns.map((column: any, columnIndex: number) => {
			if (columnIndex === 0) {
				return '合计';
			}
			if (['answered', 'total', 'hanguped'].includes(column.property)) {
				return XEUtils.sum(data, column.property);
			}
		}),
	];
};
/** 搜索按钮操作 */
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');
	callList(requestParams.value)
		.then((res: any) => {
			state.tableData = res.result;

			const xData = state.tableData.map((item: any) => item.hourRange);
			const inData = state.tableData.map((item: any) => item.total);
			const connectData = state.tableData.map((item: any) => item.answered);
			const hangupData = state.tableData.map((item: any) => item.hanguped);
			setOption1({
				xData,
				inData,
				connectData,
				hangupData,
			});

			const allConnectNum = state.tableData.reduce((pre: any, cur: any) => {
				pre += cur.answered;
				return pre;
			}, 0);
			const allHangupNum = state.tableData.reduce((pre: any, cur: any) => {
				pre += cur.hanguped;
				return pre;
			}, 0);
			state.tableData1 = state.tableData.length
				? [
						{ value: allConnectNum, name: '接通' },
						{ value: allHangupNum, name: '挂断' },
				  ]
				: [];
			const dataTable = state.tableData.length
				? [
						{ value: allConnectNum, name: '接通' },
						{ value: allHangupNum, name: '挂断' },
				  ]
				: [
						{ value: null, name: '接通' },
						{ value: null, name: '挂断' },
				  ];
			setOption(dataTable);
			state.loading = false;
		})
		.catch(() => {
			state.loading = false;
		});
};
/** 重置按钮操作 */
const statisticalTimeRef = ref<RefType>();
const resetQuery = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	statisticalTimeRef.value.reset();
	queryList();
};
const option = ref<any>({});
const option1 = ref<any>({});
// 呼入总体分析图
const setOption = (data: any) => {
	option.value = {
		title: {
			text: '呼入总体分析图',
			left: 'center',
		},
		tooltip: {
			formatter: '{b0}: {c0} ({d}%)',
		},
		legend: [
			{
				left: 'left',
				top: '40',
				orient: 'vertical',
				data: ['接通', '挂断'],
			},
		],
		grid: {
			containLabel: true,
		},
		series: [
			{
				type: 'pie',
				radius: ['0%', '40%'],
				label: {
					show: true,
					overflow: 'none',
					formatter: function (params: any) {
						if (params.name !== '') {
							return `${params.name}:${params.data.value}（${params.percent}%）`;
						}
					},
				},
				data: data,
			},
		],
	};
};
// 呼入数量分析图
const setOption1 = (data: any) => {
	option1.value = {
		title: {
			text: '呼入数量分析图',
			left: 'center',
		},
		tooltip: {
			trigger: 'axis',
		},
		legend: {
			data: ['呼入数量', '接通数量', '挂断数量'],
			top: 30,
		},
		grid: {
			left: '13%',
			right: '4%',
			top: '20%',
		},
		xAxis: {
			type: 'category',
			boundaryGap: false,
			data: data.xData,
		},
		yAxis: {
			type: 'value',
		},
		series: [
			{
				name: '呼入数量',
				type: 'line',
				data: data.inData,
			},
			{
				name: '接通数量',
				type: 'line',
				data: data.connectData,
			},
			{
				name: '挂断数量',
				type: 'line',
				data: data.hangupData,
			},
		],
	};
};
// 获取基础信息
const getBaseInfo = async () => {
	try {
		const { result } = await callPeriodBase();
		state.callForwardingSource = result.callForwardingSource ?? [];
	} catch (e) {
		console.log(e);
	}
};
// 话务日期明细
const router = useRouter();
const onDetail = () => {
	router.push({
		name: 'statisticsCallDetailIndex',
	});
};
const toolbarRef = ref<RefType>();
const tableRef = ref<RefType>();
onMounted(() => {
	queryList();
	if (tableRef.value && toolbarRef.value) {
		tableRef.value.connect(toolbarRef.value);
	}
	getBaseInfo();
});
</script>
<style lang="scss" scoped>
.chart,
.chart1 {
	height: 60vh;
	margin-top: 10px;
}
</style>
