<template>
	<div class="statistics-call-telephonist-container layout-pd">
		<!-- 搜索  -->
		<el-card shadow="never">
			<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="queryList"
						value-format="YYYY-MM-DD"
            :clearable="false"
					/>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="queryList" :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>
		</el-card>
		<el-card shadow="never">
			<ProTable
				ref="proTableRef"
				:columns="columns"
				:data="state.tableData"
				@updateTable="queryList"
				:loading="state.loading"
				:pagination="false"
				show-summary
				border
				row-key="orgId"
				@sort-change="sortChange"
				:summary-method="getSummaries"
			>
				<template #name="{ row }">
					<span
						>{{ row.name }} <span v-if="row.staffNo">({{ row.staffNo }})</span></span
					>
				</template>
			</ProTable>
		</el-card>
	</div>
</template>
<script setup lang="tsx" name="statisticsCallTelephonist">
import { onMounted, reactive, ref } from 'vue';
import { ElButton, FormInstance } from 'element-plus';
import { throttle } from '@/utils/tools';
import { callAgent } from '@/api/statistics/call';
import { shortcuts } from '@/utils/constants';
import dayjs from 'dayjs';
import { formatDuration, formatDurationDay } from '@/utils/formatTime';

const proTableRef = ref<RefType>(); // 表格ref
// 表格配置项
const columns = ref<any[]>([
	{ type: 'index', fixed: 'left', width: 55, label: '序号', align: 'center' },
	{
		prop: 'name',
		label: '坐席工号',
		align: 'center',
		minWidth: 120,
		render: (scope) => (
			<span>
				{scope.row.name} {scope.row.staffNo ? <span>({scope.row.telNo})</span> : ''}{' '}
			</span>
		),
	},
	{ prop: 'inTotal', label: '呼入总量', align: 'center', sortable: 'custom', minWidth: 120 },
	{ prop: 'inAnswered', label: '接通总量', align: 'center', sortable: 'custom', minWidth: 120 },
	{ prop: 'inHangupImmediate', label: '呼入秒挂', align: 'center', sortable: 'custom', minWidth: 120 },
	{ prop: 'inHanguped', label: '呼入超时未接', align: 'center', sortable: 'custom', minWidth: 140 },
	{
		prop: 'inAnsweredRate',
		label: '接通率',
		align: 'center',
		sortable: 'custom',
		render: (scope) => <span>{scope.row.inAnsweredRate}%</span>,
		minWidth: 120,
	},
	{ prop: 'outDurationAvg', label: '呼入平均时长', align: 'center', sortable: 'custom', minWidth: 140 },
	{ prop: 'inAvailableAnswer', label: '有效接通量', align: 'center', sortable: 'custom', minWidth: 120 },
	{ prop: 'inHangupImmediateWhenAnswered', label: '接通秒挂', align: 'center', sortable: 'custom', minWidth: 120 },
	{
		prop: 'inAnsweredRate',
		label: '有效接通率',
		align: 'center',
		sortable: 'custom',
		render: (scope) => <span>{scope.row.inAnsweredRate}%</span>,
		minWidth: 120,
	},
	{ prop: 'outTotal', label: '呼出总量', align: 'center', sortable: 'custom', minWidth: 120 },
	{ prop: 'outAnswered', label: '呼出接通量', align: 'center', sortable: 'custom', minWidth: 120 },
	{
		prop: 'outAnsweredRate',
		label: '呼出接通率',
		align: 'center',
		render: (scope) => <span>{scope.row.outAnsweredRate}%</span>,
		minWidth: 120,
	},
	{
		prop: 'outDurationAvg',
		label: '呼出平均时长',
		align: 'center',
		minWidth: 140,
	},
	{
		prop: 'loginDuration',
		label: '登录时长',
		align: 'center',
		minWidth: 200,
		render: (scope) => <span>{formatDurationDay(scope.row.loginDuration)}</span>,
	},
	{
		prop: 'restDuration',
		label: '小休时长',
		align: 'center',
		minWidth: 200,
		render: (scope) => <span>{formatDurationDay(scope.row.restDuration)}</span>,
	},
	{ prop: 'workRate', label: '工作效率', align: 'center', minWidth: 120, render: (scope) => <span>{scope.row.workRate}%</span> },
]);
// 定义变量内容
const ruleFormRef = ref<RefType>(); // 表单ref
const state = reactive({
	queryParams: {
		// 查询条件
		PageIndex: 1,
		PageSize: 10,
		Keyword: null, // 关键词
		crTime: [dayjs().startOf('day').format('YYYY-MM-DD'), dayjs().endOf('day').format('YYYY-MM-DD')], // 时间默认今天开始到今天结束
	},
	tableData: [], //表单
	loading: false, // 加载
	total: 0, // 总数
});
/** 获取列表 */
const queryList = throttle(() => {
	state.loading = true;
	let StartTime = null;
	let EndTime = null;
	if (state.queryParams?.crTime) {
		StartTime = state.queryParams?.crTime[0];
		EndTime = state.queryParams?.crTime[1];
	}
	const request = {
		StartTime,
		EndTime,
		SortField: state.queryParams.SortField,
		SortRule: state.queryParams.SortRule,
	};
	callAgent(request)
		.then((res: any) => {
			state.tableData = res.result;
			state.loading = false;
		})
		.catch(() => {
			state.loading = false;
		});
}, 300);
// 排序
const sortChange = (val: any) => {
	state.queryParams.SortField = val.prop;
	// 0 升序 1 降序
	state.queryParams.SortRule = val.order ? (val.order == 'descending' ? 1 : 0) : null;
	queryList();
};
/** 重置按钮操作 */
const resetQuery = throttle((formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	queryList();
}, 300);
// 合计
const getSummaries = (param: any) => {
	const { columns, data } = param;
	const sums: string[] = [];
	columns.forEach((column: { property: string }, index: number) => {
		if (index === 0) {
			sums[index] = '合计';
			return;
		}
		const values = data.map((item: { [x: string]: any }) => Number(item[column.property]));
		if (['inAnsweredRate', 'outAnsweredRate', 'inAvailableAnswer', 'outDurationAvg', 'workRate'].includes(column.property)) {
			//百分比不能计算
			sums[index] = '';
			return '';
		} else if (['loginDuration', 'restDuration'].includes(column.property)) {
			sums[index] = formatDurationDay(
				values.reduce((prev: any, curr: any) => {
					const value = Number(curr);
					if (!Number.isNaN(value)) {
						return prev + curr;
					} else {
						return prev;
					}
				}, 0)
			);
		} else if (!values.every((value: unknown) => Number.isNaN(value))) {
			sums[index] = `${values.reduce((prev: any, curr: any) => {
				const value = Number(curr);
				if (!Number.isNaN(value)) {
					return prev + curr;
				} else {
					return prev;
				}
			}, 0)}`;
		} else {
			sums[index] = ' ';
		}
	});
	return sums;
	/*const { columns } = param;
  const sums: string[] = [];
  columns.forEach((column: { property: string }, index: number) => {
    switch (column.property) {
      case 'name':
        sums[index] = state.totalCount?.name;
        break;
      case 'num':
        sums[index] = state.totalCount?.num;
        break;
      case 'chainNum':
        sums[index] = state.totalCount?.chainNum;
        break;
      case 'chainRate':
        sums[index] = state.totalCount?.chainRate;
        break;
      default:
        sums[index] = '';
        break;
    }
  });
  return sums;*/
};
onMounted(() => {
	queryList();
});
</script>
