<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="0" label="全部" :disabled="state.loading"></el-tab-pane>
				<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-tab-pane name="4" label="智能应答" :disabled="state.loading"></el-tab-pane>
				<el-tab-pane name="5" label="呼入白名单" :disabled="state.loading"></el-tab-pane>
				<el-tab-pane name="6" label="呼入黑名单" :disabled="state.loading"></el-tab-pane>
			</el-tabs>
			<el-form :model="state.queryParams" ref="ruleFormRef" @submit.native.prevent inline>
				<el-form-item prop="CPN" label="主叫号码">
					<el-input v-model="state.queryParams.CPN" placeholder="主叫号码" clearable @keyup.enter="handleQuery" class="keyword-input" />
				</el-form-item>
				<el-form-item prop="CDPN" label="被叫号码">
					<el-input v-model="state.queryParams.CDPN" placeholder="被叫号码" clearable @keyup.enter="handleQuery" class="keyword-input" />
				</el-form-item>
				<el-form-item prop="IsSensitiveWord" v-if="['1', '2'].includes(state.queryParams.type)">
					<el-checkbox v-model="IsSensitiveWord" border @change="changeIsSensitiveWord">是否敏感通话</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,
				}"
				:tools="[{ toolRender: { name: 'exportCurrent' } }, { toolRender: { name: 'exportAll' } }]"
			>
				<template #buttons>
					<el-button
						type="primary"
						@click="onTransferOrder"
						:disabled="isChecked"
						:loading="state.loading"
						v-auth="'tels:callLog:recordTransfer'"
						v-if="['1', '2', '4'].includes(state.queryParams.type)"
					>录音转写</el-button
					>
				</template>
			</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 '0': //全部
									return !['checkbox', 'transliterationStateText', 'sensitiveText'].includes(column.field);
								case '1': //呼入已接
									return !['onStateText', 'callDirectionText'].includes(column.field);
								case '2': //呼出已接
									return ![
										'order.no',
										'order.title',
										'mobileAreaName',
										'onStateText',
										'callDirectionText',
										'beginIvrTime',
										'endIvrTime',
										'beginQueueTime',
										'endQueueTime',
										'beginRingTime',
										'endRingTimg',
									].includes(column.field);
								case '3': //未接
									return ![
										'checkbox',
										'order.no',
										'order.title',
										'onStateText',
										'transliterationStateText',
										'sensitiveText',
										'answeredTime',
										'duration',
										'endByText',
									].includes(column.field);
								case '4': //智能应答
									return ![
										'userName',
										'onStateText',
										'callDirectionText',
										'beginQueueTime',
										'endQueueTime',
										'beginRingTime',
										'endRingTimg',
										'sensitiveText',
										'telNo',
									].includes(column.field);
								case '5': //呼入白名单
									return !['checkbox', 'order.no', 'order.title', 'callDirectionText', 'transliterationStateText', 'sensitiveText'].includes(
										column.field
									);
								case '6': //呼入黑名单
									return ![
										'checkbox',
										'order.no',
										'order.title',
										'userName',
										'callDirectionText',
										'transliterationStateText',
										'sensitiveText',
										'onStateText',
										'beginIvrTime',
										'endIvrTime',
										'beginQueueTime',
										'endQueueTime',
										'beginRingTime',
										'endRingTimg',
										'answeredTime',
									].includes(column.field);
							}
						},
					}"
					:checkbox-config="checkboxConfig"
					@checkbox-all="selectAllChangeEvent"
					@checkbox-change="selectChangeEvent"
					:params="{ exportMethod: callLogPagedExport, exportParams: requestParams }"
				>
					<vxe-column
						type="checkbox"
						width="50"
						align="center"
						field="checkbox"
						:visible="['1', '2', '4'].includes(state.queryParams.type)"
					></vxe-column>
					<vxe-column field="cpn" title="主叫号码" min-width="120"></vxe-column>
					<vxe-column field="cdpn" title="被叫号码" min-width="120"></vxe-column>
					<vxe-column field="order.no" title="工单编码" width="140" :visible="['0', '1','4'].includes(state.queryParams.type)"></vxe-column>
					<vxe-column field="order.title" title="工单标题" width="200" :visible="['0', '1','4'].includes(state.queryParams.type)">
						<template #default="{ row }">
							<order-detail :order="row.order" @updateList="queryList">{{ row.order?.title }}</order-detail>
						</template>
					</vxe-column>
					<vxe-column field="telNo" title="响应分机" width="100" :visible="['0', '1', '2', '3', '5'].includes(state.queryParams.type)"></vxe-column>
					<vxe-column field="gateway" title="中继号码" width="100"></vxe-column>
					<vxe-column
						field="mobileAreaName"
						title="号码归属地"
						min-width="120"
						:visible="['0', '1', '3', '4', '5', '6'].includes(state.queryParams.type)"
					></vxe-column>
					<vxe-column field="userName" title="话务员" width="120" :visible="['0', '1', '2', '3', '5'].includes(state.queryParams.type)"></vxe-column>
					<vxe-column
						field="duration"
						title="通话时间(秒)"
						width="110"
						:visible="['0', '1', '2', '4', '5', '6'].includes(state.queryParams.type)"
					></vxe-column>
					<vxe-column field="onStateText" title="通话结果" width="100" :visible="['0', '5'].includes(state.queryParams.type)"></vxe-column>
					<vxe-column field="callDirectionText" title="电话方向" width="100" :visible="['0', '3'].includes(state.queryParams.type)"></vxe-column>
					<vxe-column
						field="endByText"
						title="挂机类型"
						width="100"
						:visible="['0', '1', '2', '4', '5', '6'].includes(state.queryParams.type)"
					></vxe-column>
					<vxe-column
						field="transliterationStateText"
						title="录音转写状态"
						width="110"
						:visible="['1', '2', '4'].includes(state.queryParams.type)"
					></vxe-column>
					<vxe-column field="sensitiveText" title="敏感词" width="110" :visible="['1', '2'].includes(state.queryParams.type)"></vxe-column>
					<vxe-column field="beginIvrTime" title="ivr开始时间" width="160" :visible="['0', '1', '3', '4', '5'].includes(state.queryParams.type)">
						<template #default="{ row }">
							{{ formatDate(row.beginIvrTime, 'YYYY-mm-dd HH:MM:SS') }}
						</template>
					</vxe-column>
					<vxe-column field="endIvrTime" title="ivr结束时间" width="160" :visible="['0', '1', '3', '4', '5'].includes(state.queryParams.type)">
						<template #default="{ row }">
							{{ formatDate(row.endIvrTime, 'YYYY-mm-dd HH:MM:SS') }}
						</template>
					</vxe-column>
					<vxe-column field="beginQueueTime" title="队列开始时间" width="160" :visible="['0', '1', '3', '5'].includes(state.queryParams.type)">
						<template #default="{ row }">
							{{ formatDate(row.beginQueueTime, 'YYYY-mm-dd HH:MM:SS') }}
						</template>
					</vxe-column>
					<vxe-column field="endQueueTime" title="队列结束时间" width="160" :visible="['0', '1', '3', '5'].includes(state.queryParams.type)">
						<template #default="{ row }">
							{{ formatDate(row.endQueueTime, 'YYYY-mm-dd HH:MM:SS') }}
						</template>
					</vxe-column>
					<vxe-column field="beginRingTime" title="开始振铃时间" width="160" :visible="['0', '1', '3', '5'].includes(state.queryParams.type)">
						<template #default="{ row }">
							{{ formatDate(row.beginRingTime, 'YYYY-mm-dd HH:MM:SS') }}
						</template>
					</vxe-column>
					<vxe-column field="endRingTimg" title="结束振铃时间" width="160" :visible="['0', '1', '3', '5'].includes(state.queryParams.type)">
						<template #default="{ row }">
							{{ formatDate(row.endRingTimg, 'YYYY-mm-dd HH:MM:SS') }}
						</template>
					</vxe-column>
					<vxe-column field="createdTime" title="开始时间" width="160">
						<template #default="{ row }">
							{{ formatDate(row.createdTime, 'YYYY-mm-dd HH:MM:SS') }}
						</template>
					</vxe-column>
					<vxe-column field="answeredTime" title="接通时间" width="160" :visible="['0', '1', '2', '4', '5'].includes(state.queryParams.type)">
						<template #default="{ row }">
							{{ formatDate(row.answeredTime, 'YYYY-mm-dd HH:MM:SS') }}
						</template>
					</vxe-column>
					<vxe-column field="overTime" title="挂断结束时间" width="160">
						<template #default="{ row }">
							{{ formatDate(row.overTime, 'YYYY-mm-dd HH:MM:SS') }}
						</template>
					</vxe-column>
					<vxe-column title="操作" fixed="right" width="160" align="center" v-if="['0', '2', '5'].includes(state.queryParams.type)">
						<template #default="{ row }">
							<el-button type="primary" @click="onPlaySoundRecording(row)" title="播放录音" link v-if="row.recordingAbsolutePath && row.otherAccept"
							>播放录音</el-button
							>
							<el-button link type="primary" @click="onDownload(row)" title="下载录音" v-if="row.recordingAbsolutePath && row.otherAccept">
								下载录音
							</el-button>
						</template>
					</vxe-column>
					<vxe-column title="操作" fixed="right" width="310" align="center" v-if="['1'].includes(state.queryParams.type)">
						<template #default="{ row }">
							<el-button link type="primary" @click="onCreate(row)" title="创建失联工单" v-auth="'tels:callLog:connectOrder'" v-if="!row.externalId">
								失联工单
							</el-button>
							<el-button link type="primary" @click="onConnect(row)" title="关联业务" v-auth="'tels:callLog:connect'" v-if="!row.externalId">
								关联业务
							</el-button>
							<el-button type="primary" @click="onPlaySoundRecording(row)" title="播放录音" link v-if="row.recordingAbsolutePath && row.otherAccept"
							>播放录音</el-button
							>
							<el-button link type="primary" @click="onDownload(row)" title="下载录音" v-if="row.recordingAbsolutePath && row.otherAccept">
								下载录音
							</el-button>
						</template>
					</vxe-column>
					<vxe-column title="操作" fixed="right" width="220" align="center" v-if="['4'].includes(state.queryParams.type)">
						<template #default="{ row }">
							<el-button type="primary" @click="onPlaySoundRecording(row)" title="播放录音" link v-if="row.recordingAbsolutePath && row.otherAccept"
							>播放录音</el-button
							>
							<el-button link type="primary" @click="onDownload(row)" title="下载录音" v-if="row.recordingAbsolutePath && row.otherAccept">
								下载录音
							</el-button>
							<el-button
								link
								type="primary"
								@click="transferOrder(row)"
								title="转写工单"
								v-auth="'tels:callLog:transferOrder'"
							>
								转工单
							</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>
		<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="SensitiveWord" label="敏感词" v-show="['1', '2'].includes(state.queryParams.type)">
					<el-input v-model="state.queryParams.SensitiveWord" placeholder="敏感词" clearable @keyup.enter="handleQuery" />
				</el-form-item>
				<el-form-item prop="TelNo" label="响应分机" v-show="['0', '1', '2', '3', '5', '6'].includes(state.queryParams.type)">
					<el-input v-model="state.queryParams.TelNo" placeholder="响应分机" clearable @keyup.enter="handleQuery" />
				</el-form-item>
				<el-form-item prop="UserName" label="话务员名称" v-show="['0', '1', '2', '3', '5'].includes(state.queryParams.type)">
					<el-input v-model="state.queryParams.UserName" placeholder="话务员名称" clearable @keyup.enter="handleQuery" />
				</el-form-item>
				<el-form-item prop="gateway" label="中继号码" v-show="['4', '6'].includes(state.queryParams.type)">
					<el-input v-model="state.queryParams.gateway" placeholder="中继号码" clearable @keyup.enter="handleQuery" />
				</el-form-item>
				<el-form-item prop="CallDirection" label="电话方向" v-show="['0', '3'].includes(state.queryParams.type)">
					<el-select v-model="state.queryParams.CallDirection" placeholder="电话方向" clearable class="w100" @change="handleQuery">
						<el-option v-for="item in state.callDirection" :value="item.key" :key="item.key" :label="item.value" />
					</el-select>
				</el-form-item>
				<el-form-item prop="OnState" label="通话结果" v-show="['0'].includes(state.queryParams.type)">
					<el-select v-model="state.queryParams.OnState" placeholder="通话结果" clearable class="w100" @change="handleQuery">
						<el-option v-for="item in state.onState" :value="item.key" :key="item.key" :label="item.value" />
					</el-select>
				</el-form-item>
				<el-form-item prop="EndBy" label="挂机类型" v-show="['4'].includes(state.queryParams.type)">
					<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="beginIvrTime" v-show="['0', '1', '3', '4', '5'].includes(state.queryParams.type)" label="ivr开始">
					<el-date-picker
						v-model="state.queryParams.beginIvrTime"
						type="datetimerange"
						unlink-panels
						range-separator="至"
						start-placeholder="ivr开始开始时间"
						end-placeholder="ivr开始结束时间"
						:shortcuts="shortcuts"
						@change="handleQuery"
						value-format="YYYY-MM-DD[T]HH:mm:ss"
						:default-time="defaultTimeStartEnd"
					/>
				</el-form-item>
				<el-form-item prop="endIvrTime" v-show="['0', '1', '3', '4', '5'].includes(state.queryParams.type)" label="ivr结束">
					<el-date-picker
						v-model="state.queryParams.endIvrTime"
						type="datetimerange"
						unlink-panels
						range-separator="至"
						start-placeholder="ivr结束开始时间"
						end-placeholder="ivr结束结束时间"
						:shortcuts="shortcuts"
						@change="handleQuery"
						value-format="YYYY-MM-DD[T]HH:mm:ss"
						:default-time="defaultTimeStartEnd"
					/>
				</el-form-item>
				<el-form-item prop="beginQueueTime" v-show="['0', '1', '3', '5'].includes(state.queryParams.type)" label="队列开始">
					<el-date-picker
						v-model="state.queryParams.beginQueueTime"
						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="endQueueTime" v-show="['0', '1', '3', '5'].includes(state.queryParams.type)" label="队列结束">
					<el-date-picker
						v-model="state.queryParams.endQueueTime"
						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="beginRingTime" v-show="['0', '1', '3', '5'].includes(state.queryParams.type)" label="振铃开始">
					<el-date-picker
						v-model="state.queryParams.beginRingTime"
						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="endRingTime" v-show="['0', '1', '3', '5'].includes(state.queryParams.type)" label="振铃结束">
					<el-date-picker
						v-model="state.queryParams.endRingTime"
						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="callTime" label="开始时间">
					<el-date-picker
						v-model="state.queryParams.callTime"
						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="answeredTime" v-show="['0', '1', '2', '4', '5'].includes(state.queryParams.type)" label="接通时间">
					<el-date-picker
						v-model="state.queryParams.answeredTime"
						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="overTime" label="挂断时间">
					<el-date-picker
						v-model="state.queryParams.overTime"
						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="OrderNo" label="工单编码" v-show="['0', '1'].includes(state.queryParams.type)">
					<el-input v-model="state.queryParams.OrderNo" placeholder="工单编码" clearable @keyup.enter="handleQuery" />
				</el-form-item>
				<el-form-item prop="Title" label="工单标题" v-show="['0', '1'].includes(state.queryParams.type)">
					<el-input v-model="state.queryParams.Title" placeholder="工单标题" clearable @keyup.enter="handleQuery" />
				</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>
		<!-- 播放录音 -->
		<play-record ref="playRecordRef" />
		<!-- 业务关联 -->
		<connect-business ref="connectBusinessRef" @updateList="queryList" />
	</div>
</template>

<script lang="tsx" setup name="callLog">
import { defineAsyncComponent, onMounted, reactive, ref, onActivated, onBeforeUnmount, computed } from 'vue';
import type { FormInstance } from 'element-plus';
import { ElMessage, ElMessageBox } from 'element-plus';
import { downloadFileByStream } from '@/utils/tools';
import { callBaseData, callLogPaged, callLogTranscription, callLogPagedExport } from '@/api/tels/callLog';
import { formatDate } from '@/utils/formatTime';
import { defaultTimeStartEnd, shortcuts } from '@/utils/constants';
import { useRouter } from 'vue-router';
import { fileDownload } from '@/api/public/file';
import mittBus from '@/utils/mitt';
import Other from '@/utils/other';
import { Local } from '@/utils/storage';
import { useThemeConfig } from '@/stores/themeConfig';
import { storeToRefs } from 'pinia';

// 引入组件
const PlayRecord = defineAsyncComponent(() => import('@/components/PlayRecord/index.vue')); // 播放录音
const ConnectBusiness = defineAsyncComponent(() => import('@/views/tels/callLog/components/Connect-business.vue')); // 关联工单还是回访
const OrderDetail = defineAsyncComponent(() => import('@/components/OrderDetail/index.vue')); // 工单详情
const pagination = defineAsyncComponent(() => import('@/components/ProTable/components/Pagination.vue')); // 分页

// 定义变量内容
const state = reactive<any>({
	queryParams: {
		PageIndex: 1, // 当前页
		PageSize: 20, // 每页条数
		type: '0',
		StaffNo: null, // 分机号
		CPN: null, // 主叫号码
		CDPN: null, // 被叫号码
		TelNo: null, // 响应分机
		CallDirection: null, // 呼叫类型
		UserName: null, // 话务员名称
		gateway: null, //中继号码
		OnState: null, // 结果
		IsAiAnswered: null, // 是否智能应答
		callTime: [], // 通话时间
		answeredTime: [], // 接通时间
		overTime: [], // 挂断时间段
		beginIvrTime: [], // ivr开始时间段
		endIvrTime: [], // ivr结束时间段
		beginQueueTime: [], // 队列开始时间段
		endQueueTime: [], // 队列结束时间段
		beginRingTime: [], // 振铃开始时间段
		endRingTime: [], // 振铃结束时间段
		CallTimeStart: null, // 通话开始时间
		CallTimeEnd: null, // 通话结束时间
		OverTimeStart: null, // 挂断开始时间
		OverTimeEnd: null, // 挂断结束时间
		AnsweredTimeStart: null, // 接通开始时间
		AnsweredTimeEnd: null, // 接通结束时间
		BeginIvrTimeStart: null, // ivr开始开始时间
		BeginIvrTimeEnd: null, // ivr开始结束时间
		EndIvrTimeStart: null, // ivr结束开始时间
		EndIvrTimeEnd: null, // ivr结束结束时间
		BeginQueueTimeStart: null, // 队列开始开始时间
		BeginQueueTimeEnd: null, // 队列开始结束时间
		EndQueueTimeStart: null, // 队列结束开始时间
		EndQueueTimeEnd: null, // 队列结束结束时间
		BeginRingTimeStart: null, // 振铃开始开始时间
		BeginRingTimeEnd: null, // 振铃开始结束时间
		EndRingTimeStart: null, // 振铃结束开始时间
		EndRingTimeEnd: null, // 振铃结束结束时间
		SensitiveWord: null, // 敏感词
		IsSensitiveWord: null, // 是否敏感通话
	},
	tableData: [], // 列表数据
	loading: false, // 加载
	total: 0, // 总条数
	callDirection: [],
	onState: [],
	endByOptions: [],
});
const ruleFormRef = ref<FormInstance>(); // 表单ref
const changeTba = () => {
	ruleFormRef.value?.resetFields();
	handleQuery();
};
// 手动查询，将页码设置为1
const handleQuery = () => {
	state.queryParams.PageIndex = 1;
	queryList();
};
/** 通话记录列表 */
const requestParams = ref<EmptyObjectType>({});
const queryList = async () => {
	state.loading = true;
	try {
		requestParams.value = Other.deepClone(state.queryParams);
		requestParams.value.CallTimeStart = state.queryParams.callTime === null ? null : state.queryParams.callTime[0];
		requestParams.value.CallTimeEnd = state.queryParams.callTime === null ? null : state.queryParams.callTime[1];
		Reflect.deleteProperty(requestParams.value, 'callTime'); // 通话开始和结束时间段
		requestParams.value.AnsweredTimeStart = state.queryParams.answeredTime === null ? null : state.queryParams.answeredTime[0];
		requestParams.value.AnsweredTimeEnd = state.queryParams.answeredTime === null ? null : state.queryParams.answeredTime[1];
		Reflect.deleteProperty(requestParams.value, 'answeredTime'); //接通开始和结束时间段
		requestParams.value.OverTimeStart = state.queryParams.overTime === null ? null : state.queryParams.overTime[0];
		requestParams.value.OverTimeEnd = state.queryParams.overTime === null ? null : state.queryParams.overTime[1];
		Reflect.deleteProperty(requestParams.value, 'overTime'); //挂断开始和结束时间段
		requestParams.value.BeginIvrTimeStart = state.queryParams.beginIvrTime === null ? null : state.queryParams.beginIvrTime[0];
		requestParams.value.BeginIvrTimeEnd = state.queryParams.beginIvrTime === null ? null : state.queryParams.beginIvrTime[1];
		Reflect.deleteProperty(requestParams.value, 'beginIvrTime'); //IVR开始时间段
		requestParams.value.EndIvrTimeStart = state.queryParams.endIvrTime === null ? null : state.queryParams.endIvrTime[0];
		requestParams.value.EndIvrTimeEnd = state.queryParams.endIvrTime === null ? null : state.queryParams.endIvrTime[1];
		Reflect.deleteProperty(requestParams.value, 'endIvrTime'); //IVR结束时间段
		requestParams.value.BeginQueueTimeStart = state.queryParams.beginQueueTime === null ? null : state.queryParams.beginQueueTime[0];
		requestParams.value.BeginQueueTimeEnd = state.queryParams.beginQueueTime === null ? null : state.queryParams.beginQueueTime[1];
		Reflect.deleteProperty(requestParams.value, 'beginQueueTime'); //队列开始时间段
		requestParams.value.EndQueueTimeStart = state.queryParams.endQueueTime === null ? null : state.queryParams.endQueueTime[0];
		requestParams.value.EndQueueTimeEnd = state.queryParams.endQueueTime === null ? null : state.queryParams.endQueueTime[1];
		Reflect.deleteProperty(requestParams.value, 'endQueueTime'); //队列结束时间段
		requestParams.value.BeginRingTimeStart = state.queryParams.beginRingTime === null ? null : state.queryParams.beginRingTime[0];
		requestParams.value.BeginRingTimeEnd = state.queryParams.beginRingTime === null ? null : state.queryParams.beginRingTime[1];
		Reflect.deleteProperty(requestParams.value, 'beginRingTime'); //振铃开始和结束时间段
		requestParams.value.EndRingTimeStart = state.queryParams.endRingTime === null ? null : state.queryParams.endRingTime[0];
		requestParams.value.EndRingTimeEnd = state.queryParams.endRingTime === null ? null : state.queryParams.endRingTime[1];
		Reflect.deleteProperty(requestParams.value, 'endRingTime'); //振铃结束时间段
		Reflect.deleteProperty(requestParams.value, 'type'); // 删除无用的参数
		switch (state.queryParams.type) {
			case '0': // 全部
				requestParams.value.IsAiAnswered = false;
				break;
			case '1': // 呼入已接
				requestParams.value.CallDirection = 0;
				requestParams.value.OnState = 1;
				requestParams.value.IsAiAnswered = false;
				break;
			case '2': // 呼出已接
				requestParams.value.CallDirection = 1;
				requestParams.value.OnState = 1;
				requestParams.value.IsAiAnswered = false;
				break;
			case '3': // 未接
				requestParams.value.OnState = 2;
				break;
			case '4': // 智能应答
				requestParams.value.IsAiAnswered = true;
				requestParams.value.OnState = 1;
				requestParams.value.CallDirection = 0;
				break;
			case '5': // 呼入白名单
				requestParams.value.PhoneTypes = 1; // 呼入VIP
				requestParams.value.CallDirection = 0; // 来电
				requestParams.value.IsAiAnswered = false;
				break;
			case '6': // 呼入黑名单
				requestParams.value.PhoneTypes = 2; // 呼入黑名单
				requestParams.value.IsAiAnswered = false;
				break;
			default:
				break;
		}
		const response = await callLogPaged(requestParams.value);
		state.tableData = response.result?.items ?? [];
		state.total = response.result?.total ?? 0;
		state.loading = false;
		tableRef.value.clearCheckboxRow()
	} catch (e) {
		state.loading = false;
		console.log(e);
		tableRef.value.clearCheckboxRow();
	}
};
// 是否敏感通话
const IsSensitiveWord = ref(false);
const changeIsSensitiveWord = (val: any) => {
	if (!val) state.queryParams.IsSensitiveWord = null;
	else state.queryParams.IsSensitiveWord = val;
	handleQuery();
};
/** 重置按钮操作 */
const drawer = ref(false);
const drawerRuleFormRef = ref();
const resetQuery = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	ruleFormRef.value?.resetFields();
	IsSensitiveWord.value = false;
	queryList();
};
// 播放录音
const playRecordRef = ref<RefType>();
const storesThemeConfig = useThemeConfig();
const { themeConfig } = storeToRefs(storesThemeConfig);
const onPlaySoundRecording = (val: any) => {
	playRecordRef.value.playRecord(val.otherAccept);
};
// 下载录音（因为天润无法配置跨域所以需要后端代理请求一次）
const onDownload = (row: any) => {
	ElMessageBox.confirm(`您确定要下载此录音吗？`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			fileDownload({ path: themeConfig.value.recordDownLoadPrefix + row.recordingAbsolutePath }).then((res: any) => {
				downloadFileByStream(res, row.recordingFileName);
			});
		})
		.catch(() => {});
};
// 关联业务
const connectBusinessRef = ref<RefType>();
const onConnect = (row: any) => {
	connectBusinessRef.value.openDialog(row);
};
// 失联工单
const router = useRouter();
const onCreate = (row: any) => {
	router.push({
		name: 'orderAccept',
		query: {
			createBy: 'tel',
			fromTel: row.cpn,
			callId: row.otherAccept,
			transfer: row.gateway,
			telArea: '',
		},
	});
};
// 创建转写任务
const onTransferOrder = () => {
	const ids = checkTable.value.map((item: any) => item.otherAccept);
	ElMessageBox.confirm(`您确定录音转写选中的录音吗？`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			state.loading = true;
			callLogTranscription({ ids })
				.then(() => {
					ElMessage({
						message: '转写任务创建成功',
						type: 'success',
					});
					queryList();

				})
				.catch((e) => {
					console.log(e);
					state.loading = false;
					tableRef.value.clearCheckboxRow();
				});
		})
		.catch(() => {
		});
};
// 转写工单
const transferOrder = (row: any) => {
	router.push({
		name: 'orderAccept',
		query: {
			createBy: 'transfer',
			fromTel: row.cpn,
			callId: row.otherAccept,
			transfer: row.gateway,
			telArea: '',
		},
	});
	Local.set(`${row.otherAccept}`, row.transliterationContent);
};
// 基础信息
const getBaseData = async () => {
	const response = await callBaseData();
	state.callDirection = response.result.callDirection;
	state.onState = response.result.onState;
	state.endByOptions = response.result.endBy;
};
const tableRef = ref<RefType>();
const checkTable = ref<EmptyArrayType>([]);
const selectAllChangeEvent = ({ checked }) => {
	if (tableRef.value) {
		const records = tableRef.value.getCheckboxRecords();
		checkTable.value = records;
		console.log(checked ? '所有勾选事件' : '所有取消事件', records);
	}
};

const selectChangeEvent = ({ checked }) => {
	if (tableRef.value) {
		const records = tableRef.value.getCheckboxRecords();
		checkTable.value = records;
		console.log(checked ? '勾选事件' : '取消事件', records);
	}
};
const isChecked = computed(() => {
	return !Boolean(checkTable.value.length);
});
const checkboxConfig = reactive<any>({
	// labelField: 'id',
	// 未转写和转写失败才能选择
	checkMethod: ({ row }) => {
		return [0, 3].includes(row.transliterationState);
	},
});
const toolbarRef = ref<RefType>();
onMounted(() => {
	getBaseData();
	queryList();
	if (tableRef.value && toolbarRef.value) {
		tableRef.value.connect(toolbarRef.value);
	}
});
onActivated(() => {
	mittBus.on('clearCachePage', () => {
		//清除缓存
		handleQuery();
	});
});
onBeforeUnmount(() => {
	mittBus.off('clearCachePage');
});
</script>
