<template>
	<div class="phoneControls" v-loading="state.loading">
		<div class="infos">
			<div class="pt5" :class="state.talkTime ? '' : 'mt8'"><span>分机号：</span>{{ telStatusInfo.telsNo }}</div>
			<div class="pt5" :class="state.talkTime ? '' : 'mt8'">
				<span>状态：</span><b class="dutyOn_status">{{ currentStatusText }}</b>
			</div>
			<div class="pt5" v-if="state.talkTime">
				<span>通话时长：</span><b class="dutyOn_timer">{{ formatDuration(state.talkTime, false) }}</b>
			</div>
		</div>
		<div class="btn">
			<!-- 签出 -->
			<template v-if="telStatusInfo.isDutyOn">
				<!-- 签出可用 -->
				<div
					class="item active"
					@click="onControlClick('dutyOff')"
					v-if="activeArr.includes('dutyOff')"
					@mouseenter="onHover('dutyOffSrc', 'phoneControls/dutyOff_white.png')"
					@mouseleave="onHover('dutyOffSrc', 'phoneControls/dutyOff_blue.png')"
					title="签出"
				>
					<img :src="state.dutyOffSrc" alt="" />
					<span>签出</span>
				</div>
				<!-- 签出不可用 -->
				<div class="item disabled" v-else title="签出">
					<img :src="getImageUrl('phoneControls/dutyOff_grey.png')" alt="" />
					<span>签出</span>
				</div>
				<!-- 签出不可用 -->
			</template>
			<!-- 灰色签入不可用 -->
			<template v-else>
				<div
					class="item active"
					@click="onControlClick('dutyOn')"
					title="签入"
					@mouseenter="onHover('dutyOnSrc', 'phoneControls/dutyOn_white.png')"
					@mouseleave="onHover('dutyOnSrc', 'phoneControls/dutyOn_blue.png')"
				>
					<img :src="state.dutyOnSrc" alt="" />
					<span>签入</span>
				</div>
			</template>

			<!-- 可用挂断 -->
			<template v-if="telStatusInfo.isDutyOn && activeArr.includes('hangup')">
				<div
					class="item active"
					:class="state.active.includes('hangup') ? 'active' : ''"
					@click="onControlClick('hangup')"
					title="挂断"
					@mouseenter="onHover('hangupSrc', 'phoneControls/hangup_white.png')"
					@mouseleave="onHover('hangupSrc', 'phoneControls/hangup_blue.png')"
				>
					<img :src="state.hangupSrc" alt="" />
					<span>挂断</span>
				</div>
			</template>
			<!-- 灰色挂断 不可用 -->
			<template v-else>
				<div class="item disabled" title="挂断">
					<img :src="getImageUrl('phoneControls/hangup_grey.png')" alt="" />
					<span>挂断</span>
				</div>
			</template>

			<!-- 小休和结束休息 可用 -->
			<template v-if="telStatusInfo.isDutyOn && activeArr.includes('rest')">
				<div
					class="item active"
					@click="onControlClick('restEnd')"
					v-if="telStatusInfo.isRest === 'resting'"
					title="结束小休"
					@mouseenter="onHover('restSrc', 'phoneControls/rest_white.png')"
					@mouseleave="onHover('restSrc', 'phoneControls/rest_blue.png')"
				>
					<img :src="state.restSrc" alt="" />
					<span>结束</span>
				</div>
				<div
					class="item active"
					@click="onControlClick('rest')"
					v-else-if="telStatusInfo.isRest === 'unRest'"
					title="小休"
					@mouseenter="onHover('restSrc', 'phoneControls/rest_white.png')"
					@mouseleave="onHover('restSrc', 'phoneControls/rest_blue.png')"
				>
					<img :src="state.restSrc" alt="" />
					<span>小休</span>
				</div>
				<div class="item disabled" title="审批中" v-else-if="telStatusInfo.isRest === 'InReview'">
					<img :src="getImageUrl('phoneControls/rest_grey.png')" alt="" />
					<span>审批中</span>
				</div>
			</template>
			<!-- 灰色小休不可用 -->
			<template v-else>
				<div class="item disabled" title="小休">
					<img :src="getImageUrl('phoneControls/rest_grey.png')" alt="" />
					<span>小休</span>
				</div>
			</template>

			<!-- 保持和取消保持 可用 -->
			<template v-if="telStatusInfo.isDutyOn && activeArr.includes('hold')">
				<div
					class="item active"
					:title="telStatusInfo.isHold ? '取消保持' : '保持'"
					@click="onControlClick(telStatusInfo.isHold ? 'unHold' : 'hold')"
					@mouseenter="onHover('holdSrc', 'phoneControls/hold_white.png')"
					@mouseleave="onHover('holdSrc', 'phoneControls/hold_blue.png')"
				>
					<img :src="state.holdSrc" alt="" />
					<span>{{ telStatusInfo.isHold ? '取消保持' : '保持' }}</span>
				</div>
			</template>
			<!-- 灰色小休不可用 -->
			<template v-else>
				<div class="item disabled" title="保持">
					<img :src="getImageUrl('phoneControls/hold_grey.png')" alt="" />
					<span>保持</span>
				</div>
			</template>

			<!-- 事后处理和取消事后处理 可用-->
			<template v-if="telStatusInfo.isDutyOn && activeArr.includes('TalkingDeal')">
				<div
					class="item active"
					@click="onControlClick(telStatusInfo.isTalkingDeal ? 'unTalkingDeal' : 'TalkingDeal')"
					@mouseenter="onHover('talkingDealSrc', 'phoneControls/talkingDeal_white.png')"
					:title="telStatusInfo.isTalkingDeal ? '取消事后处理' : '事后处理'"
					@mouseleave="onHover('talkingDealSrc', 'phoneControls/talkingDeal_blue.png')"
				>
					<img :src="state.talkingDealSrc" alt="" />
					<span>{{ telStatusInfo.isTalkingDeal ? '取消事后处理' : '事后处理' }}</span>
				</div>
			</template>
			<!-- 事后处理不可用 -->
			<template v-else>
				<div class="item disabled" title="事后处理">
					<img :src="getImageUrl('phoneControls/talkingDeal_grey.png')" alt="" />
					<span>事后处理</span>
				</div>
			</template>

			<!-- 转接 可用 -->
			<template v-if="telStatusInfo.isDutyOn && activeArr.includes('transfer')">
				<div
					class="item active"
					@click="onControlClick('transfer')"
					title="保持"
					@mouseenter="onHover('transferSrc', 'phoneControls/transfer_white.png')"
					@mouseleave="onHover('transferSrc', 'phoneControls/transfer_blue.png')"
				>
					<img :src="state.transferSrc" alt="" />
					<span>转接</span>
				</div>
			</template>
			<!-- 转接不可用 -->
			<template v-else>
				<div class="item disabled" title="保持">
					<img :src="getImageUrl('phoneControls/transfer_grey.png')" alt="" />
					<span>转接</span>
				</div>
			</template>

			<!-- 三方会议 可用(两个通话 一个取消保持 一个保持 才能使用三方通话) -->
			<template v-if="telStatusInfo.isDutyOn && activeArr.includes('conference')">
				<div
					class="item active"
					@mouseenter="onHover('conferenceSrc', 'phoneControls/conference_white.png')"
					title="三方会议"
					@mouseleave="onHover('conferenceSrc', 'phoneControls/conference_blue.png')"
					@click="onControlClick( 'conference')"
				>
					<img :src="state.conferenceSrc" alt="" />
					<span>三方会议</span>
				</div>
			</template>
			<!-- 三方会议 不可用 -->
			<template v-else>
				<div class="item disabled" title="三方会议">
					<img :src="getImageUrl('phoneControls/conference_grey.png')" alt="" />
					<span>三方会议</span>
				</div>
			</template>

			<!-- 呼叫 可用-->
			<template v-if="telStatusInfo.isDutyOn && activeArr.includes('outbound')">
				<div
					class="item active"
					@mouseenter="onHover('outboundSrc', 'phoneControls/outbound_white.png')"
					title="呼叫"
					@mouseleave="onHover('outboundSrc', 'phoneControls/outbound_blue.png')"
					@click="onControlClick('outbound')"
				>
					<img :src="state.outboundSrc" alt="" />
					<span>呼叫</span>
				</div>
			</template>
			<!-- 呼叫 不可用 -->
			<template v-else>
				<div class="item disabled" title="呼叫">
					<img :src="getImageUrl('phoneControls/outbound_grey.png')" alt="" />
					<span>呼叫</span>
				</div>
			</template>
		</div>
	</div>
	<!-- 占位标签 -->
	<div class="seizeSeat-box"></div>
	<!-- 功能 -->
	<!-- 签入弹窗 -->
	<el-dialog v-model="state.dutyDialogVisible" draggable title="签入" width="500px" :show-close="false">
		<el-form :model="state.dutyForm" label-width="80px" ref="dutyFormRef">
			<el-form-item label="分机" prop="telNo" :rules="[{ required: true, message: '请选择需要签入的分机', trigger: 'change' }]">
				<el-select-v2 v-model="state.dutyForm.telNo" :options="state.telsList" placeholder="选择要签入的分机" filterable class="w100" />
			</el-form-item>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="state.dutyDialogVisible = false" class="default-button" :loading="state.loading">取 消</el-button>
				<el-button type="primary" @click="clickOnDuty(dutyFormRef)" :loading="state.loading">确 定</el-button>
			</span>
		</template>
	</el-dialog>

	<!-- 小休弹窗 -->
	<el-dialog
		v-model="state.restDialogVisible"
		ref="dialogRestRef"
		draggable
		title="小休申请"
		:width="AppConfigInfo.IsRestApproval ? '60%' : '500px'"
		@mouseup="mouseup"
		:style="'transform: ' + state.transform + ';'"
		@opend="restFormOpened"
	>
		<!-- 需要审核 -->
		<template v-if="AppConfigInfo.IsRestApproval">
			<el-form :model="state.restForm" label-width="100px" ref="restFormRef">
				<el-row :gutter="10">
					<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
						<el-form-item label="小休" prop="reason" :rules="[{ required: true, message: '请选择小休原因', trigger: 'change' }]">
							<el-select v-model="state.restForm.reason" placeholder="请选择小休原因" class="w100" clearable>
								<el-option v-for="item in state.restReasonOptions" :key="item.id" :label="item.content" :value="item.content" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
						<el-form-item label="下一环节" prop="nextStepCode" :rules="[{ required: true, message: '请选择下一环节', trigger: 'change' }]">
							<el-select v-model="state.restForm.nextStepCode" placeholder="请选择下一环节" class="w100" @change="selectNextStep">
								<el-option v-for="item in state.nextStepOptions" :key="item.key" :label="item.value" :value="item.key" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
						<el-form-item label="处理人" prop="nextHandlers" :rules="[{ required: false, message: '请选择处理人', trigger: 'change' }]">
							<el-select
								v-model="state.restForm.nextHandlers"
								multiple
								filterable
								placeholder="请选择处理人"
								class="w100"
								@change="selectHandlers"
								value-key="key"
							>
								<el-option v-for="item in state.handlerOptions" :key="item.key" :label="item.value" :value="item" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8" v-if="state.restForm.nextHandlers.length > 1">
						<el-form-item
							label="主办"
							prop="nextMainHandler"
							multiple
							filterable
							:rules="[{ required: false, message: '请选择主办', trigger: 'change' }]"
						>
							<el-select v-model="state.restForm.nextMainHandler" placeholder="请选择主办" class="w100">
								<el-option v-for="item in state.handlerMainOptions" :key="item.key" :label="item.value" :value="item.key" />
							</el-select>
						</el-form-item>
					</el-col>
					<!-- <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
						<el-form-item label="" prop="acceptSms">
							<el-checkbox v-model="state.restForm.acceptSms" label="短信通知" />
						</el-form-item>
					</el-col> -->
					<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
						<el-form-item
							label="是否发起会签"
							prop="isStartCountersign"
							:rules="[{ required: false, message: '请选择是否发起会签', trigger: 'change' }]"
						>
							<el-switch v-model="state.restForm.isStartCountersign" inline-prompt active-text="是" inactive-text="否" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<el-form-item label="办理意见" prop="opinion" :rules="[{ required: true, message: '请填写小休办理意见', trigger: 'blur' }]">
							<common-advice
								@chooseAdvice="chooseAdvice"
								v-model="state.restForm.opinion"
								placeholder="请填写小休办理意见"
								:loading="state.loading"
								:commonEnum="commonEnum.RestReason"
							/>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<el-form-item label="附件" prop="remark" :rules="[{ required: false, message: '请填写诉求内容', trigger: 'change' }]">
							<annex-list name="小休附件" businessId="" classify="小休上传"/>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
		</template>
		<!-- 不需要审核 -->
		<template v-else>
			<el-form :model="state.restForm" label-width="90px" ref="restFormRef">
				<el-row :gutter="10">
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<el-form-item label="小休" prop="reason" :rules="[{ required: true, message: '请选择小休原因', trigger: 'change' }]">
							<el-select v-model="state.restForm.reason" placeholder="请选择小休原因" class="w100" clearable>
								<el-option v-for="item in state.restReasonOptions" :key="item.id" :label="item.content" :value="item.content" />
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
		</template>

		<template #footer>
			<span class="dialog-footer">
				<el-button @click="state.restDialogVisible = false" class="default-button" :loading="state.loading">取 消</el-button>
				<el-button type="primary" @click="clickOnRest(restFormRef)" :loading="state.loading">提 交</el-button>
			</span>
		</template>
	</el-dialog>

	<!-- 转接弹窗 -->
	<el-dialog v-model="state.transferDialogVisible" draggable title="转接" width="500px">
		<el-form :model="state.transferForm" label-width="100px" ref="transferFormRef">
			<el-form-item label="转接号码" prop="telNo" :rules="[{ required: true, message: '请选择转接分机或输入外部电话', trigger: 'blur' }]">
				<el-select-v2
					v-model="state.transferForm.telNo"
					:options="state.telsList"
					placeholder="请选择转接分机或输入外部电话"
					filterable
					class="w100"
					allow-create
					default-first-option
				/>
			</el-form-item>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="state.transferDialogVisible = false" class="default-button" :loading="state.loading">取 消</el-button>
				<el-button type="primary" @click="clickOnTransfer(transferFormRef)" :loading="state.loading">确 定</el-button>
			</span>
		</template>
	</el-dialog>

	<!-- 呼叫弹窗 -->
	<el-dialog v-model="state.outboundDialogVisible" draggable title="呼叫" width="450px">
		<el-form :model="state.outboundForm" label-width="80px" ref="outboundFormRef">
			<el-form-item label="呼叫号码" prop="telNo" :rules="[{ required: true, message: '请选择或输入呼叫号码', trigger: 'blur' }]">
				<el-select-v2
					v-model="state.outboundForm.telNo"
					:options="state.telsList"
					placeholder="请选择或输入呼叫号码"
					filterable
					class="w100"
					allow-create
					default-first-option
				/>
			</el-form-item>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="state.outboundDialogVisible = false" class="default-button" :loading="state.loading">取 消</el-button>
				<el-button type="primary" @click="clickOnOutbound(outboundFormRef)" :loading="state.loading">确 定</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script setup lang="ts" name="telControl">
import { reactive, ref, computed, defineAsyncComponent, onMounted, onBeforeMount } from 'vue';
import { ElMessageBox, ElNotification, ElMessage, FormInstance } from 'element-plus';
import { storeToRefs } from 'pinia';
import { useTelStatus, TelStates, RestStates } from '/@/stores/telStatus';
import { useUserInfo } from '/@/stores/userInfo';
import { useAppConfig } from '/@/stores/appConfig';
import { debounce, getImageUrl } from '/@/utils/tools';
import { formatDuration } from '/@/utils/formatTime';
import { commonEnum } from '/@/utils/constants';
import other from '/@/utils/other';
import mittBus from '/@/utils/mitt';
import { workflowStepOptions } from '/@/api/system/workflow';
import { restFlowStart, restFlowDel, restFlowStartWex, getTelList } from '/@/api/public/wex';
import { commonList } from '/@/api/system/commonAdvice';
import { auth } from '/@/utils/authFunction';
import { VoiceInterfaceObject } from '/@/utils/PhoneScript';
import { WebsocketInterface } from '/@/utils/websocket';
import signalR from '/@/utils/signalR';
import { Local } from '/@/utils/storage';
import {getGroup} from '/@/api/tels/group';

// 引入组件
const CommonAdvice = defineAsyncComponent(() => import('/@/components/CommonAdvice/index.vue')); // 常用意见
const AnnexList = defineAsyncComponent(() => import('/@/components/AnnexList/index.vue'));

const state = reactive<any>({
	active: <EmptyArrayType>[], // 当前选中
	currentStatus: '', //当前通话状态
	dutyDialogVisible: false, //签入选分机弹窗
	dutyForm: {
		//签入选分机表单
		telNo: null, //分机号
	},
	telsList: <EmptyArrayType>[], // 分机列表
	loading: false,
	showHangupList: false, //是否展示挂断列表
	restDialogVisible: false, //小休弹窗
	restForm: {
		//小休表单
		opinion: '', //小休原因
		nextStepCode: '', //下一步
		nextHandlers: [], //下一步处理人
		acceptSms: false, //是否接收短信
		nextMainHandler: '', //下一步主办人
		reason: '', //小休原因
		expiredTime: '', //期满时间
		isStartCountersign: false, //是否发起会签
	},
	handlerMainOptions: [], // 主办
	transferDialogVisible: false, // 转接弹窗
	transferForm: {
		//转接表单
		telNo: null,
	},
	outboundDialogVisible: false, //外呼弹窗
	outboundForm: {
		// 外呼表单
		telNo: null, //外呼号码
	},
	talkTime: 0, //通话时长
	talkTimer: null, //通话时长定时器
	dutyOnSrc: getImageUrl('phoneControls/dutyOn_blue.png'), //签入图片
	dutyOffSrc: getImageUrl('phoneControls/dutyOff_blue.png'), //签出图片
	hangupSrc: getImageUrl('phoneControls/hangup_blue.png'), //挂断图片
	restSrc: getImageUrl('phoneControls/rest_blue.png'), //小休图片
	holdSrc: getImageUrl('phoneControls/hold_blue.png'), //保持图片
	talkingDealSrc: getImageUrl('phoneControls/talkingDeal_blue.png'), //时候处理图片
	transferSrc: getImageUrl('phoneControls/transfer_blue.png'), //转接图片
	conferenceSrc: getImageUrl('phoneControls/conference_blue.png'), //三方会议图片
	outboundSrc: getImageUrl('phoneControls/outbound_blue.png'), //外呼图片
	evaluateSrc: getImageUrl('phoneControls/evaluate_blue.png'), //评价图片
	restReasonOptions: [], // 小休原因
	nextStepOptions: [], // 下一个环节
	handlerOptions: [], // 处理人
	handleId: '', // 流程处理ID
	transform: 'translate(0px, 0px)',
	fileList: [], // 文件上传列表
	metingDialogVisible: false, // 三方会议弹窗
	metingForm: {
		// 三方会议表单
		metingId: '', // 三方会议ID
		phoneNo: '', // 三方会议号码
	},
  groupName:'', //坐席组名称
});

const useTelStatusStore = useTelStatus();
const { telStatusInfo } = storeToRefs(useTelStatusStore); // 电话状态
const appConfigStore = useAppConfig();
const { AppConfigInfo } = storeToRefs(appConfigStore); // 系统配置信息
const storesUserInfo = useUserInfo();
const { userInfos } = storeToRefs(storesUserInfo); // 用户信息

// 开始计时
const startTime = debounce(() => {
	let talkTime = Local.get('talkTime');
	if (talkTime) {
		state.talkTime = Number(talkTime);
		state.talkTimer = setInterval(() => {
			state.talkTime++;
			Local.set('talkTime', String(state.talkTime));
		}, 1000);
	} else {
		state.talkTimer = setInterval(() => {
			state.talkTime++;
			Local.set('talkTime', String(state.talkTime));
		}, 1000);
	}
}, 1000);
// 结束计时
const removeTimer = debounce(() => {
	state.talkTime = 0;
	Local.remove('talkTime');
	clearInterval(state.talkTimer);
}, 1000);

// 小休审批通过消息
const RestApplyPassFn = (data: any) => {
	ElNotification({
		title: '成功',
		message: '小休审批通过，开始小休',
		type: 'success',
	});
	VoiceInterfaceObject.SetBusy(data); //设置忙碌
};
// 链接websocket
const initWebsocket = () => {
	if (!userInfos.value.staffNo) {
		ElMessage.warning('账号暂无工号,请设置工号后重新登录后重试');
		return;
	}
	let telNo: string | number;
  let groupName:string|number = '';
	if (telStatusInfo.value.isDutyOn) {
		// 如果已签入
		telNo = telStatusInfo.value.telsNo;
    groupName = telStatusInfo.value.groupName;
	} else {
		// 如果未签入
		telNo = state.dutyForm.telNo;
    groupName = state.groupName;
	}
	// 设置变量
	VoiceInterfaceObject.SetSendModel({
		GongHao: userInfos.value.staffNo,
		FenJi: telNo,
		DepartmentID: 'Default',
		AgentGroupName: groupName,
	});
	// 初始化参数
	const wsParams = {
		url: import.meta.env.VITE_WEX_SOCKET_URL,
		IsReConnect: true, //是否重连
		reConnectTime: 40, //重连间隔
		IsKeepAlive: true, //是否发送心跳
		KeepAliveTime: 30, //30秒发送1次
		KeepAliveData: JSON.stringify(VoiceInterfaceObject.GetSendModel('keeplive')), //心跳
		onOpen: async () => {
			//登录语音系统
			VoiceInterfaceObject.Login();
      VoiceInterfaceObject.GetOnUserState(); //获取用户状态
		},
		onMessage: (e: any) => {
			// 收到消息调用方法
			let str: string = e.data; // 收到的消息
			const methodsName = str.split('(')[0]; // 方法名
			const parsers = str.split('(')[1].split(')')[0]; // 参数
			VoiceInterfaceObject[methodsName](JSON.parse(parsers));
		},
		onClose: () => {
			console.info('链接关闭了');
		},
		onError: (e: any) => {
			console.info('链接出错', e);
		},
	};
	//初始化WebSocket
	WebsocketInterface(wsParams);
	return Promise.resolve();
};

//  signalR 初始化signalr
signalR.init();
// 监听消息
const signalRStart = () => {
	// 加入分组
	signalR.joinGroup('CallCenter');
	signalR.SR.on('Send', (data: any) => {
		// 加入分组成功
		console.log(data, '加入分组成功');
	});
	signalR.SR.on('RestApplyPass', (data: any) => {
		// 小休审批通过消息
		console.log(data, '小休审批通过消息');
		RestApplyPassFn(data);
	});
};
// 检查用户状态
// 设置当前可用的按钮
const activeArr = computed(() => {
	const switchCases: any = {
		dutyOff: ['dutyOn'], // 签出状态
		dutyOn: ['dutyOff', 'rest', 'outbound', 'callForwarding'], // 已签入无通话状态
		rest: ['rest', 'callForwarding'], // 小休中状态
		ring: ['hangup'], //振铃中
		onCall: ['hangup', 'hold', 'transfer', 'evaluate'], // 单个通话中
		onHold: ['hangup', 'hold', 'transfer', 'evaluate'], // 保持中
		onTalkingDeal: ['dutyOff', 'rest', 'outbound', 'callForwarding', 'TalkingDeal'], // 事后处理中
    onTransferSuccess:['hangup','conference'], // 转接成功
		onConference: ['hangup'], // 三方会议中 只能挂断
	};
	let arr = <EmptyArrayType>[];
	if (telStatusInfo.value.phoneControlState in switchCases) {
		arr = switchCases[telStatusInfo.value.phoneControlState];
	}
	return arr;
});
// 设置当前状态的值
const currentStatusText = computed(() => {
	const statusMap: any = {
		dutyOff: '签出',
		dutyOn: '空闲',
		rest: '小休中',
		ring: '振铃中',
		onHold: '保持中',
		onCall: '通话中',
		onTalkingDeal: '事后处理',
		onConference: '会议中',
    onTransferSuccess:'转接成功'
	};
	return statusMap[telStatusInfo.value.phoneControlState] || '';
});
// 查询所有分机
const getTelsLists = async (object?: object) => {
  state.loading = true;
	try {
		const res: any = await getTelList(object);
		state.telsList = res?.data ?? [];
		state.telsList = state.telsList.map((item: any) => ({
			value: item.device,
			label: item.device,
			...item,
		}));
    state.loading = false;
		return Promise.resolve(state.telsList);
	} catch (err) {
		console.log(err);
    state.loading = false;
	}
};
// 鼠标移入移出改变图标
const onHover = (val: string, path: string) => {
	state[val] = getImageUrl(path);
};
// 点击事件
const onControlClick = (val: string) => {
	switch (val) {
		case 'dutyOn': //签入
			if (!auth('public:seat:dutyOn')) ElMessage.error('抱歉，您没有签入权限！');
			else onDutyFn();
			break;
		case 'dutyOff': //签出
			if (!auth('public:seat:dutyOff')) ElMessage.error('抱歉，您没有签出权限！');
			else offDutyFn();
			break;
		case 'hangup': //挂断
			if (!auth('public:seat:hangup')) ElMessage.error('抱歉，您没有挂断权限！');
			else onHangup();
			break;
		case 'rest': //小休
			if (!auth('public:seat:rest')) ElMessage.error('抱歉，您没有小休权限！');
			else onRest();
			break;
		case 'restEnd': //结束小休
			if (!auth('public:seat:restEnd')) ElMessage.error('抱歉，您没有结束小休权限！');
			else onRestEnd();
			break;
		case 'hold': //保持
			if (!auth('public:seat:hold')) ElMessage.error('抱歉，您没有保持权限！');
			else onHold();
			break;
		case 'unHold': //取消保持
			if (!auth('public:seat:unHold')) ElMessage.error('抱歉，您没有取消保持权限！');
			else onUnHold();
			break;
		case 'TalkingDeal': //事后处理
			if (!auth('public:seat:TalkingDeal')) ElMessage.error('抱歉，您没有事后处理权限！');
			else onTalkingDeal();
			break;
		case 'unTalkingDeal': // 取消事后处理
			if (!auth('public:seat:unTalkingDeal')) ElMessage.error('抱歉，您没有取消事后处理权限！');
			else unTalkingDeal();
			break;
		case 'transfer': //转接
			if (!auth('public:seat:transfer')) ElMessage.error('抱歉，您没有转接权限！');
			else onTransfer();
			break;
    case 'conference': //三方会议
      if (!auth('public:seat:meeting')) ElMessage.error('抱歉，您没有三方会议权限！');
      else onConference();
      break;
		case 'outbound': //外呼
			if (!auth('public:seat:outbound')) ElMessage.error('抱歉，您没有呼叫权限！');
			else onOutbound();
			break;
		default:
			break;
	}
};
//签入
const dutyFormRef = ref<RefType>();
const onDutyFn = async () => {
	dutyFormRef.value?.resetFields();
	// 获取所有分机列表（未签入的）
	const list = await getTelsLists({ sigin: 0 });
	const isDefaultTelNo = list.some((item: any) => item.value === userInfos.value.defaultTelNo);
	if (isDefaultTelNo) {
		// 如果默认分机号是空闲的，就默认选中
		state.dutyForm.telNo = userInfos.value.defaultTelNo;
	}
	state.dutyDialogVisible = true;
};
// 确认签入
const clickOnDuty = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate((valid: boolean) => {
		if (!valid) return;
		state.loading = true;
		// {telNo:state.dutyForm.telNo}
    getGroup(state.dutyForm.telNo).then((res:any)=>{// 获取坐席分组
      state.groupName = res.result.groupName ?? '';
      state.loading = false;
      state.dutyDialogVisible = false;
      initWebsocket(); //开启消息监听
    })
	});
};
// 签出
const offDutyFn = () => {
	ElMessageBox.confirm(`确定要签出，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			state.loading = true;
			VoiceInterfaceObject.LogOut(); // 退出语音系统
			// 重置所有状态
			useTelStatusStore.resetState();
			state.loading = false;
		})
		.catch(() => {
			state.loading = false;
		});
};
// 挂断
const onHangup = () => {
	ElMessageBox.confirm(`确定要挂断，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			VoiceInterfaceObject.HangUp(); // 挂断
		})
		.catch(() => {});
};
// 小休
const restFormRef = ref<RefType>(); //小休表单
const onRest = async () => {
	if (AppConfigInfo.value.IsRestApproval) {
		// 如果小休需要审核
		// 查询流程节点参数
		const res: any = await restFlowStart();
		state.nextStepOptions = res.result.steps;
		state.handleId = res.result.id;
	}
	//  重置表单
	restFormRef.value?.resetFields();
	// 查询小休原因
	const response: any = await commonList({ commonType: commonEnum.RestReason });
	state.restReasonOptions = response.result;
	state.restDialogVisible = true;
};
// 打开弹窗清空表单
const restFormOpened = () => {
	restFormRef.value?.resetFields();
	restFormRef.value?.clearValidate();
};
// 小休流程选择下一个环节
const selectNextStep = (val: any) => {
	const next = state.nextStepOptions.find((item: any) => item.key === val);
	getNextStepOption(state.handleId, next.key);
};
// 查询流程下一节点参数
const getNextStepOption = async (DefineId: string, Code: string) => {
	try {
		const res: any = await workflowStepOptions({ DefineId, Code });
		state.handlerOptions = res.result ?? [];
	} catch (error) {
		console.log(error);
	}
};
// 小休选择处理人
const selectHandlers = () => {
	restFormRef.value?.resetFields('nextMainHandler');
};
// 主办从处理人中选择
state.handlerMainOptions = computed(() => {
	return state.restForm.nextHandlers;
});
// 确定小休(示忙)
const clickOnRest = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate((valid: boolean) => {
		if (!valid) return;
		state.loading = true;
		if (AppConfigInfo.value.IsRestApproval) {
			//如果需要审核
			state.restForm.additions = state.fileList;
			let submitObj = other.deepClone(state.restForm);
			if (submitObj.nextHandlers && submitObj.nextHandlers.length) {
				submitObj.nextHandlers = submitObj.nextHandlers.map((item: any) => {
					return {
						id: item.key,
						name: item.value,
					};
				});
				if (submitObj.nextHandlers.length === 1) {
					submitObj.nextMainHandler = submitObj.nextHandlers[0].id;
				}
			}
			restFlowStartWex(submitObj)
				.then(() => {
					ElNotification({
						title: '成功',
						message: '申请小休成功',
						type: 'success',
					});
					// 设置休息状态 审核中
					useTelStatusStore.setRest(RestStates.InReview);
					state.restDialogVisible = false;
					state.loading = false;
				})
				.catch(() => {
					restFlowDel().then(() => {
						state.loading = false;
						state.restDialogVisible = false;
					});
				});
		} else {
			//不需要审核直接开始小休
			VoiceInterfaceObject.SetBusy(state.restForm.reason); //设置忙碌
			state.restDialogVisible = false;
			state.loading = false;
		}
	});
};
// 设置抽屉
const dialogRestRef = ref<RefType>(); // 小休申请弹窗
const mouseup = () => {
	state.transform = dialogRestRef.value.dialogContentRef.$el.style.transform;
};
// 选择常用意见 填入填写框
const chooseAdvice = (item: any) => {
	state.restForm.opinion += item.content;
};
// 小休结束
const onRestEnd = () => {
	ElMessageBox.confirm(`确定要结束小休，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			state.loading = true;
			VoiceInterfaceObject.SetIdle(); //设置空闲
			state.loading = false;
		})
		.catch(() => {});
};
// 通话保持
const onHold = () => {
	ElMessageBox.confirm(`确定要保持，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			state.loading = true;
			VoiceInterfaceObject.KeepInTouch();
			state.loading = false;
		})
		.catch(() => {});
};
// 取消保持
const onUnHold = () => {
	ElMessageBox.confirm(`确定要取消保持，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			state.loading = true;
			VoiceInterfaceObject.KeepCancelInTouch();
			state.loading = false;
		})
		.catch(() => {});
};
// 事后处理
const onTalkingDeal = () => {
	ElMessageBox.confirm(`确定要事后处理，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			state.loading = true;
			// 设置事后处理
			useTelStatusStore.setTalkingDeal(true);
			// 设置话机状态 设置为事后处理中
			useTelStatusStore.setPhoneControlState(TelStates.onTalkingDeal);
			state.loading = false;
		})
		.catch(() => {});
};
// 取消事后处理
const unTalkingDeal = () => {
	ElMessageBox.confirm(`确定要取消事后处理，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			state.loading = true;
			// 设置事后处理
			useTelStatusStore.setTalkingDeal(false);
			// 设置话机状态 取消时候处理修改为空闲状态
			useTelStatusStore.setPhoneControlState(TelStates.dutyOn);
			VoiceInterfaceObject.EndTalkingDeal(); //结束事后处理
			state.loading = false;
		})
		.catch(() => {});
};
// 打开转接弹窗
const transferFormRef = ref<RefType>(); // 转接表单
const onTransfer = () => {
	//  重置表单
	transferFormRef.value?.resetFields();
	// 获取所有分机列表
	getTelsLists().then(()=>{
    state.transferDialogVisible = true;
  })
};
// 确认转接
const clickOnTransfer = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate((valid: boolean) => {
		if (!valid) return;
		VoiceInterfaceObject.TeleSwitch(state.transferForm.telNo);
		state.transferDialogVisible = false;
	});
};
// 三方会议开始
const onConference = () => {
  ElMessageBox.confirm(`确定确定要开启三方会议，是否继续?`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
    draggable: true,
    cancelButtonClass: 'default-button',
    autofocus: false,
  })
      .then(() => {
          VoiceInterfaceObject.Dtmf('0'); // 开启dtmf 三方通话
      })
      .catch(() => {});
};
// 外呼
const outboundFormRef = ref<RefType>(); //外呼
const onOutbound = () => {
	//  重置表单
	outboundFormRef.value?.resetFields();
	// 获取所有分机列表
	getTelsLists().then(()=>{
    state.outboundDialogVisible = true;
  })
};
// 外呼保存
const clickOnOutbound = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate((valid: boolean) => {
		if (!valid) return;
		state.loading = true;
		setTimeout(() => {
			VoiceInterfaceObject.DialOut(state.outboundForm.telNo);
			state.outboundDialogVisible = false;
			state.loading = false;
		}, 300);
	});
};
onMounted(() => {
	signalRStart(); //开启消息监听
	if (telStatusInfo.value.telsNo) {
		// 有分机号
		initWebsocket(); // 初始化websocket
	}
	mittBus.on('startTalkTime', (message:string) => { // 开始计时
		startTime();
	});
	mittBus.on('endTalkTime', () => { // 结束计时
		removeTimer();
	});
});
onBeforeMount(() => {
	mittBus.off('startTalkTime'); // 移除监听
	mittBus.off('endTalkTime'); // 移除监听
	signalR.leaveGroup('CallCenter'); // 离开分组
});
</script>

<style scoped lang="scss">
.seizeSeat-box {
	display: none;
}
.phoneControls {
	display: flex;
	flex: 1;
	background-color: var(--el-color-white) !important;
	box-shadow: 0 1px 8px 0 rgba(0, 15, 49, 0.1);
	border-bottom-left-radius: 90px;
	border-bottom-right-radius: 90px;
	padding: 0 18px 0 40px;
	color: var(--hotline-color-text-main);
	height: 100%;

	.infos {
		text-align: left;
		width: 140px;

		.dutyOn_status {
			color: var(--el-color-primary);
			font-weight: normal;
		}

		.dutyOn_timer {
			color: var(--el-color-danger);
			font-weight: normal;
		}

		span {
			display: inline-block;
			width: 80px;
			text-align: right;
		}
	}

	// 按钮列表
	.btn {
		display: flex;
		width: calc(100% - 120px);
		justify-content: space-between;

		.item {
			text-align: center;
			cursor: pointer;
			width: 100%;
			user-select: none;
			height: calc(100% + 20px);
			img {
				display: block;
				margin: 0 auto;
				padding-top: 10px;
			}

			span {
				margin-top: 5px;
				display: inline-block;
			}

			&.disabled {
				cursor: not-allowed;
				overflow: hidden;
			}
		}

		.active {
			&:hover {
				color: var(--hotline-color-white);
				background-image: url('/@/assets/images/phoneControls/active.png');
				background-repeat: no-repeat;
				background-size: 100% 100%;
			}
		}
	}
}
</style>
