<template>
	<div class="statistics-call-detail-seats-date-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 label="工单编码" prop="No">
					<el-input v-model="state.queryParams.No" placeholder="工单编码" clearable @keyup.enter="handleQuery" class="keyword-input" />
				</el-form-item>
				<el-form-item label="主叫号码" prop="FromNo">
					<el-input v-model="state.queryParams.FromNo" placeholder="主叫号码" clearable @keyup.enter="handleQuery" class="keyword-input" />
				</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"> <SvgIcon name="ele-Search" class="mr5" />更多查询</el-button>
				</el-form-item>
			</el-form>
			<vxe-toolbar
				ref="toolbarRef"
				:loading="state.loading"
				custom
				:refresh="{
					queryMethod: queryList,
				}"
				:tools="[{ toolRender: { name: 'exportCurrent' } }, { toolRender: { name: 'exportAll' } }]"
			>
			</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"
					height="auto"
					auto-resize
					show-overflow
					:scrollY="{ enabled: true, gt: 100 }"
					id="statisticsCallDetailSeatsDate"
					:custom-config="{ storage: true }"
					:params="{ exportMethod: callDateSimpleDetailExport, exportParams: requestParams }"
					showHeaderOverflow
				>
					<vxe-column field="orderNo" title="工单编码" width="140"></vxe-column>
					<vxe-column field="title" title="工单标题" width="200">
						<template #default="{ row }">
							<order-detail :order="{ ...row, id: row.orderId }" @updateList="queryList">{{ row.orderTitle }}</order-detail>
						</template>
					</vxe-column>
					<vxe-column field="fromNo" title="主叫号码" width="120"></vxe-column>
					<vxe-column field="toNo" title="被叫号码" width="120"></vxe-column>
					<vxe-column field="telNo" title="响应分机" width="120"></vxe-column>
					<vxe-column field="endByTxt" title="挂断状态" width="120"></vxe-column>
					<vxe-column field="userName" title="话务员" width="120"></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">
						<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="duration" title="通话时间(秒)" width="120"></vxe-column>
					<vxe-column title="操作" fixed="right" width="160" align="center" :show-overflow="false">
						<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>
			<pagination
				@pagination="queryList"
				:total="state.total"
				v-model:current-page="state.queryParams.PageIndex"
				v-model:page-size="state.queryParams.PageSize"
				:disabled="state.loading"
			/>
		</div>
		<!-- 播放录音 -->
		<play-record ref="playRecordRef" />
		<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="ToNo" label="被叫号码">
					<el-input v-model="state.queryParams.ToNo" placeholder="被叫号码" clearable @keyup.enter="handleQuery" />
				</el-form-item>
				<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="EndBy" label="挂断状态">
					<el-select v-model="state.queryParams.EndBy" placeholder="挂断状态" clearable class="w100" @change="handleQuery">
						<el-option v-for="item in EndByOptions" :value="item.key" :key="item.key" :label="item.value" />
					</el-select>
				</el-form-item>
				<el-form-item prop="hrTime" label="呼入时间">
					<el-date-picker
						v-model="state.queryParams.hrTime"
						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>
			<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="statisticsCallDetailSeatsDate">
import { defineAsyncComponent, onMounted, reactive, ref } from 'vue';
import { ElMessageBox, FormInstance } from 'element-plus';
import { callDateSimpleDetail, callDateSimpleDetailBase, callDateSimpleDetailExport } from '@/api/statistics/call';
import { useRoute } from 'vue-router';
import { formatDate } from '@/utils/formatTime';
import { fileDownload } from '@/api/public/file';
import { downloadFileBySrc, downloadFileByStream } from '@/utils/tools';
import { useThemeConfig } from '@/stores/themeConfig';
import { storeToRefs } from 'pinia';
import { defaultTimeStartEnd, shortcuts } from '@/utils/constants';

const PlayRecord = defineAsyncComponent(() => import('@/components/PlayRecord/index.vue')); // 播放录音
const OrderDetail = defineAsyncComponent(() => import('@/components/OrderDetail/index.vue')); // 工单详情
const pagination = defineAsyncComponent(() => import('@/components/ProTable/components/Pagination.vue')); // 分页
// 定义变量内容
const ruleFormRef = ref<RefType>(); // 表单ref
const state = reactive<any>({
	queryParams: {
		PageIndex: 1,
		PageSize: 20,
	},
	tableData: [], //表单
	loading: false, // 加载
	total: 0, // 总数
	callForwardingSource: [],
	totalCount: {},
});
/** 搜索按钮操作 */
const handleQuery = () => {
	state.queryParams.PageIndex = 1;
	queryList();
};
/** 重置按钮操作 */
const drawer = ref(false);
const drawerRuleFormRef = ref();
const resetQuery = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	ruleFormRef.value?.resetFields();
	queryList();
};
/** 获取列表 */
const requestParams = ref<EmptyObjectType>({});
const route = useRoute();
const routeQueryParams = route.query;
const queryList = async () => {
	state.loading = true;
	try {
		requestParams.value = {
			StartTime: routeQueryParams.StartTime,
			EndTime: routeQueryParams.EndTime,
			FieldName: routeQueryParams.FieldName,
			...state.queryParams,
		};
		const { result } = await callDateSimpleDetail(requestParams.value);
		state.tableData = result?.items ?? [];
		state.total = result.total ?? 0;
		state.loading = false;
	} catch (e) {
		state.loading = false;
		console.log(e);
	}
};
// 播放录音
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(() => {
			switch (themeConfig.value.appScope) {
				case 'YiBin':
					fileDownload({ path: themeConfig.value.recordDownLoadPrefix + row.audioFile })
						.then((res: any) => {
							downloadFileByStream(res, row.audioFile);
						})
						.catch(() => {});
					break;
				case 'ZiGong':
				case 'LuZhou':
					downloadFileBySrc(themeConfig.value.recordPrefix + row.audioFile, row.audioFile);
					break;
			}
		})
		.catch(() => {});
};
// 获取基础数据
const EndByOptions = ref<EmptyArrayType>([])
const getBaseData = async () => {
	try {
		const { result} = await callDateSimpleDetailBase();
		EndByOptions.value = result.endBy;
	}catch (e){
		console.log(e)
	}
};
const toolbarRef = ref<RefType>();
const tableRef = ref<RefType>();
onMounted(() => {
	queryList();
	if (tableRef.value && toolbarRef.value) {
		tableRef.value.connect(toolbarRef.value);
	}
	getBaseData();
});
</script>
