<template>
	<div class="tels-callLog-container layout-padding">
		<div class="layout-padding-auto layout-padding-view pd20">
			<el-tabs v-model="state.queryParams.type" @tab-change="changeTba">
				<el-tab-pane name="1" label="呼入列表" :disabled="state.loading"></el-tab-pane>
				<el-tab-pane name="2" label="呼出列表" :disabled="state.loading"></el-tab-pane>
				<el-tab-pane name="3" label="未接列表" :disabled="state.loading"></el-tab-pane>
			</el-tabs>
			<el-form :model="state.queryParams" ref="ruleFormRef" @submit.native.prevent label-minWidth="100px" inline>
				<el-form-item prop="FromNo">
					<el-input v-model="state.queryParams.FromNo" placeholder="主叫号码" clearable @keyup.enter="handleQuery" class="keyword-input" />
				</el-form-item>
				<el-form-item prop="ToNo">
					<el-input v-model="state.queryParams.ToNo" placeholder="被叫号码" clearable @keyup.enter="handleQuery" class="keyword-input" />
				</el-form-item>
				<el-form-item prop="IsMissOrder" v-if="['1'].includes(state.queryParams.type)">
					<el-checkbox v-model="IsMissOrder" border @change="changeMissOrder">失联工单</el-checkbox>
				</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="drawer = true" class="default-button" :loading="state.loading">
						<SvgIcon name="ele-Search" class="mr5" />更多查询</el-button
					>
				</el-form-item>
			</el-form>
			<vxe-toolbar
				ref="toolbarRef"
				:loading="state.loading"
				custom
				:refresh="{
					queryMethod: handleQuery,
				}"
			>
			</vxe-toolbar>
			<div style="overflow: hidden; width: 100%; height: 100%; flex: 1">
				<vxe-table
					border
					:loading="state.loading"
					:data="state.tableData"
					:sort-config="{ remote: true }"
					:column-config="{ resizable: true }"
					:row-config="{ isCurrent: true, isHover: true, height: 30, useKey: true }"
					ref="tableRef"
					height="auto"
					auto-resize
					show-overflow
					:print-config="{}"
					:scrollY="{ enabled: true, gt: 100 }"
					id="telsCallLog"
					showHeaderOverflow
					:custom-config="{
						storage: true,
						checkMethod({ column }) {
							switch (state.queryParams.type) {
								case '1': //呼入列表
									return !['directionText', 'waitDuration'].includes(column.field);
								case '2': //呼出列表
									return !['mobileAreaName', 'userName', 'directionText', 'waitDuration'].includes(column.field);
								case '3': //未接列表
									return !['orderNo', 'title', 'mobileAreaName', 'userName', 'duration', 'answeredTime', 'endByText'].includes(column.field);
							}
						},
					}"
				>
					<vxe-column field="fromNo" title="主叫号码" min-width="120"></vxe-column>
					<vxe-column field="toNo" title="被叫号码" min-width="120"></vxe-column>
					<vxe-column field="orderNo" title="工单编码" width="140" :visible="['1', '2'].includes(state.queryParams.type)"></vxe-column>
					<vxe-column field="title" title="工单标题" width="200" :visible="['1', '2'].includes(state.queryParams.type)">
						<template #default="{ row }">
							<order-detail :order="{ ...row, id: row.orderId }" @updateList="queryList">{{ row.title }}</order-detail>
						</template>
					</vxe-column>
					<vxe-column field="telNo" title="响应分机" width="100"></vxe-column>
					<vxe-column field="staffNo" title="工号" width="100"></vxe-column>
					<vxe-column field="mobileAreaName" title="号码归属地" min-width="120" :visible="['1'].includes(state.queryParams.type)"></vxe-column>
					<vxe-column field="userName" title="话务员" width="120" :visible="['1'].includes(state.queryParams.type)"></vxe-column>
					<vxe-column field="groupId" title="功能组号码" width="100"></vxe-column>
					<vxe-column field="duration" title="通话时间(秒)" width="110" :visible="['1', '2'].includes(state.queryParams.type)"></vxe-column>
					<vxe-column field="endByText" title="挂断状态" width="100" :visible="['1', '2'].includes(state.queryParams.type)"></vxe-column>
					<vxe-column field="directionText" title="呼叫方向" width="100" :visible="['3'].includes(state.queryParams.type)"></vxe-column>
					<vxe-column field="beginIvrTime" title="开始时间" width="160">
						<template #default="{ row }">
							{{ formatDate(row.beginIvrTime, 'YYYY-mm-dd HH:MM:SS') }}
						</template>
					</vxe-column>
					<vxe-column field="answeredTime" title="接通时间" width="160" :visible="['1', '2'].includes(state.queryParams.type)">
						<template #default="{ row }">
							{{ formatDate(row.answeredTime, 'YYYY-mm-dd HH:MM:SS') }}
						</template>
					</vxe-column>
					<vxe-column field="endTime" title="挂断时间" width="160">
						<template #default="{ row }">
							{{ formatDate(row.endTime, 'YYYY-mm-dd HH:MM:SS') }}
						</template>
					</vxe-column>
					<vxe-column field="waitDuration" title="等待时长(秒)" width="120" :visible="['3'].includes(state.queryParams.type)"></vxe-column>
					<vxe-column title="操作" fixed="right" width="240" align="center" v-if="['1', '2'].includes(state.queryParams.type)">
						<template #default="{ row }">
							<el-button
								link
								type="primary"
								@click="onCreate(row)"
								title="创建失联工单"
								v-auth="'tels:callLog:connectOrder'"
								v-if="!row.orderId && row.callState !== 0"
							>
								失联工单
							</el-button>
							<el-button type="primary" @click="onPlaySoundRecording(row)" title="播放录音" link v-if="row.audioFile">播放录音</el-button>
							<el-button link type="primary" @click="onDownload(row)" title="下载录音" v-if="row.audioFile"> 下载录音 </el-button>
						</template>
					</vxe-column>
					<vxe-column title="操作" fixed="right" width="160" align="center" v-else>
						<template #default="{ row }">
							<el-button type="primary" @click="onPlaySoundRecording(row)" title="播放录音" link v-if="row.audioFile">播放录音</el-button>
							<el-button link type="primary" @click="onDownload(row)" title="下载录音" v-if="row.audioFile"> 下载录音 </el-button>
						</template>
					</vxe-column>
				</vxe-table>
			</div>
			<div class="flex-end">
				<el-pagination
					layout="prev, pager, next"
					:total="state.total"
					@current-change="handleCurrentChange"
					:page-size="state.queryParams.PageSize"
					:current-page="state.queryParams.PageIndex"
				/>
			</div>
			<el-drawer v-model="drawer" title="更多查询" size="500px">
				<el-form :model="state.queryParams" ref="drawerRuleFormRef" @submit.native.prevent label-width="100px">
					<el-form-item prop="TelNo" label="响应分机">
						<el-input v-model="state.queryParams.TelNo" placeholder="响应分机" clearable @keyup.enter="handleQuery" />
					</el-form-item>
					<el-form-item prop="crTime" 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"
						/>
					</el-form-item>
					<el-form-item prop="Direction" v-show="['3'].includes(state.queryParams.type)" label="电话方向">
						<el-select v-model="state.queryParams.Direction" placeholder="电话方向" clearable class="w100" @change="handleQuery">
							<el-option v-for="item in state.callDirectionOption" :value="item.key" :key="item.key" :label="item.value" />
						</el-select>
					</el-form-item>
					<el-form-item prop="EndBy" v-show="['4'].includes(state.queryParams.type)" label="挂断状态">
						<el-select v-model="state.queryParams.EndBy" placeholder="挂断状态" clearable class="w100" @change="handleQuery">
							<el-option v-for="item in state.endByOptions" :value="item.key" :key="item.key" :label="item.value" />
						</el-select>
					</el-form-item>
					<el-form-item prop="UserName" v-show="['1'].includes(state.queryParams.type)" label="话务员名称">
						<el-input v-model="state.queryParams.UserName" placeholder="话务员名称" clearable @keyup.enter="handleQuery" />
					</el-form-item>
					<el-form-item prop="OrderNo" v-show="['0', '1'].includes(state.queryParams.type)" label="工单编码">
						<el-input v-model="state.queryParams.OrderNo" placeholder="工单编码" clearable @keyup.enter="handleQuery" />
					</el-form-item>
					<el-form-item prop="Title" v-show="['0', '1'].includes(state.queryParams.type)" label="工单标题">
						<el-input v-model="state.queryParams.Title" placeholder="工单标题" clearable @keyup.enter="handleQuery" />
					</el-form-item>
					<el-form-item prop="WaitDurationStart" v-show="['3'].includes(state.queryParams.type)" label="等待时长">
						<el-row :gutter="10">
							<el-col :span="12">
								<el-input placeholder="等待时长开始" v-model.number="state.queryParams.WaitDurationStart" clearable />
							</el-col>
							<el-col :span="12">
								<el-input placeholder="等待时长结束" v-model.number="state.queryParams.WaitDurationEnd" clearable />
							</el-col>
						</el-row>
					</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>
		<!-- 播放录音 -->
		<play-record ref="playRecordRef" />
	</div>
</template>

<script lang="tsx" setup name="callLog">
import { defineAsyncComponent, onMounted, reactive, ref, onActivated, onBeforeUnmount } from 'vue';
import type { FormInstance } from 'element-plus';
import { ElMessageBox } from 'element-plus';
import { downloadFileBySrc, getNeedArr } from '@/utils/tools';
import { formatDate } from '@/utils/formatTime';
import { defaultTimeStartEnd, shortcuts } from '@/utils/constants';
import { useRouter } from 'vue-router';
import mittBus from '@/utils/mitt';
import Other from '@/utils/other';
import { getCallCenterCallRecord, getCallCenterCallRecordBaseData } from '@/api/callCenter';
import { useThemeConfig } from '@/stores/themeConfig';
import { storeToRefs } from 'pinia';

// 引入组件
const PlayRecord = defineAsyncComponent(() => import('@/components/PlayRecord/index.vue')); // 播放录音
const OrderDetail = defineAsyncComponent(() => import('@/components/OrderDetail/index.vue')); // 工单详情

// 表格配置项
// 定义变量内容
const state = reactive<any>({
	queryParams: {
		PageIndex: 1, // 当前页
		PageSize: 20, // 每页条数
		type: '1', // 默认呼入列表
		IsConnected: null, // 接通状态
		FromNo: null, // 主叫
		ToNo: null, // 被叫
		UserName: null, // 话务员名称
		TelNo: null, // 分机号
		EndBy: null, //挂断
		Direction: null, // 通话方向
		crTime: [], // 时间
		CallStartTimeStart: null,
		CallStartTimeEnd: null,
		WaitDurationStart: null,
		WaitDurationEnd: null,
		IsMissOrder: null,
	},
	tableData: [], // 列表数据
	loading: false, // 加载
	total: 0, // 总条数
	callDirection: [],
	onState: [],
	endByOptions: [],
});
const ruleFormRef = ref<FormInstance>(); // 表单ref
const changeTba = () => {
	ruleFormRef.value?.resetFields();
	drawerRuleFormRef.value?.resetFields();
	handleQuery();
};
// 手动查询，将页码设置为1
const handleQuery = () => {
	state.queryParams.PageIndex = 1;
	queryIndex.value = 0;
	queryList(true);
};
// 改变页码
const queryIndex = ref(0); // 数据批次
const totalTable = ref([]); // 数据总数
const handleCurrentChange = (val: number) => {
	state.queryParams.PageIndex = val;
	// 判断当前页是否是数据的最后一页
	if (val === Math.ceil(state.total / state.queryParams.PageSize)) {
		queryList();
	} else {
		state.tableData = getNeedArr(totalTable.value, state.queryParams.PageSize)[state.queryParams.PageIndex - 1]; //当前页的表格数据
	}
};
/** 通话记录列表 */
const requestParams = ref<EmptyObjectType>({});
const queryList = async (isQuery: boolean = false) => {
	state.loading = true;
	requestParams.value = Other.deepClone(state.queryParams);
	requestParams.value.CallStartTimeStart = state.queryParams.crTime === null ? null : state.queryParams.crTime[0];
	requestParams.value.CallStartTimeEnd = state.queryParams.crTime === null ? null : state.queryParams.crTime[1];
	Reflect.deleteProperty(requestParams.value, 'crTime'); // 通话开始和结束时间段
	requestParams.value.QueryIndex = queryIndex.value; // 数据批次
	state.loading = true;
	getCallCenterCallRecord(requestParams.value)
		.then((response: any) => {
			if (isQuery) {
				// 如果是查询
				totalTable.value = []; // 先清空
				totalTable.value = response?.result;
				state.total = totalTable.value.length;
				state.tableData = getNeedArr(totalTable.value, state.queryParams.PageSize)[state.queryParams.PageIndex - 1]; //当前页的表格数据
				queryIndex.value = 1;
			} else {
				if (response?.result.length) queryIndex.value++;
				totalTable.value = totalTable.value.concat(response?.result);
				state.total = totalTable.value.length;
				state.tableData = getNeedArr(totalTable.value, state.queryParams.PageSize)[state.queryParams.PageIndex - 1]; //当前页的表格数据
			}
			state.loading = false;
			tableRef.value.clearCheckboxRow();
		})
		.catch(() => {
			state.loading = false;
			tableRef.value.clearCheckboxRow();
		});
};
// 失联工单
const IsMissOrder = ref(false);
const changeMissOrder = (val: any) => {
	if (!val) state.queryParams.IsMissOrder = null;
	else state.queryParams.IsMissOrder = val;
	handleQuery();
};
/** 重置按钮操作 */
const drawer = ref(false);
const drawerRuleFormRef = ref();
const resetQuery = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	queryIndex.value = 0;
	ruleFormRef.value?.resetFields();
	IsMissOrder.value = false;
	queryList(true);
};
// 播放录音
const playRecordRef = ref<RefType>();
const storesThemeConfig = useThemeConfig();
const { themeConfig } = storeToRefs(storesThemeConfig);
const onPlaySoundRecording = (val: any) => {
	playRecordRef.value.playRecord(val.id);
};
// 下载录音
const onDownload = (row: any) => {
	ElMessageBox.confirm(`您确定要下载此录音吗？`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			downloadFileBySrc(themeConfig.value.recordPrefix + row.audioFile, row.audioFile);
		})
		.catch(() => {});
};
// 失联工单
const router = useRouter();
const onCreate = (row: any) => {
	router.push({
		name: 'orderAccept',
		query: {
			createBy: 'tel',
			fromTel: row.fromNo,
			callId: row.callNo,
			transfer: row.toNo,
			telArea: '',
		},
	});
};
// 基础信息
const getBaseData = async () => {
	try {
		const { result } = await getCallCenterCallRecordBaseData();
		state.callDirectionOption = result.direction;
		state.endByOptions = result.endBy;
	} catch (e) {
		console.log(e);
	}
};
onMounted(() => {
	getBaseData();
	queryList();
	if (tableRef.value && toolbarRef.value) {
		tableRef.value.connect(toolbarRef.value);
	}
});
const toolbarRef = ref<RefType>();
const tableRef = ref<RefType>();
onActivated(() => {
	mittBus.on('clearCachePage', () => {
		//清除缓存
		handleQuery();
	});
});
onBeforeUnmount(() => {
	mittBus.off('clearCachePage');
});
</script>
