<template>
	<div class="phoneControls" v-loading="state.loading">
		<div class="infos">
			<div class="pt10" :class="state.time ? '' : 'mt8'"><span>分机号：</span>{{ telStatusInfo.telsNo }}</div>
			<div class="pt5" :class="state.time ? '' : 'mt8'">
				<span>状态：</span><b class="dutyOn_status">{{ currentStatusText }}</b>
			</div>
			<div class="pt5" v-if="state.time">
				<span>通话时长：</span><b class="dutyOn_timer">{{ formatDuration(state.time, 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')">
				<!-- 多个挂断 -->
				<el-popover
					:width="130 * telStatusInfo.onCallArr.length"
					:offset="0"
					v-model:visible="state.showHangupList"
					:show-arrow="false"
					trigger="hover"
					popper-class="hangup-popover"
					v-if="telStatusInfo.onCallArr.length > 1"
				>
					<template #reference>
						<div
							class="item active"
							:class="state.active.includes('hangup') ? 'active' : ''"
							@mouseenter="onHover('hangupSrc', 'phoneControls/hangup_white.png')"
							@mouseleave="onHover('hangupSrc', 'phoneControls/hangup_blue.png')"
						>
							<img :src="state.hangupSrc" alt="" />
							<span>挂断（{{ telStatusInfo.onCallArr.length }}）</span>
						</div>
					</template>
					<div class="hangup-container">
						<div class="hangup-item" v-for="(item, index) in telStatusInfo.onCallArr" :key="index">
							<p class="hangup-item-name">{{ state.callTypes[item.callType] }}</p>
							<p class="hangup-item-phoneNumber">{{ item.from }}</p>
							<button class="hangup-item-button" @click="hangupOne(item)">挂断</button>
						</div>
					</div>
				</el-popover>
				<!-- 单个挂断 -->
				<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')"
					v-else
				>
					<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')">
				<!-- 多个保持 -->
				<template v-if="telStatusInfo.onHoldArr.length > 1">
					<el-popover
						:width="130 * telStatusInfo.onHoldArr.length"
						:offset="0"
						v-model:visible="state.showHoldList"
						:show-arrow="false"
						trigger="hover"
						popper-class="hangup-popover"
					>
						<template #reference>
							<div
								class="item active"
								@mouseenter="onHover('holdSrc', 'phoneControls/hold_white.png')"
								@mouseleave="onHover('holdSrc', 'phoneControls/hold_blue.png')"
							>
								<img :src="state.holdSrc" alt="" />
								<span>保持（{{ telStatusInfo.onHoldArr.length }}）</span>
							</div>
						</template>
						<div class="hangup-container">
							<div class="hangup-item" v-for="(item, index) in telStatusInfo.onHoldArr" :key="index">
								<p class="hangup-item-name">{{ state.callTypes[item.callType] }}</p>
								<p class="hangup-item-phoneNumber">{{ item.to }}</p>
								<button class="hangup-item-button" @click="holdItem(item)">{{ item.isHold ? '取消保持' : '保持' }}</button>
							</div>
						</div>
					</el-popover>
				</template>
				<template v-else>
					<div
						class="item active"
						:title="telStatusInfo.onHoldArr[0]?.isHold ? '取消保持' : '保持'"
						@click="onControlClick(telStatusInfo.onHoldArr[0]?.isHold ? 'unHold' : 'hold')"
						@mouseenter="onHover('holdSrc', 'phoneControls/hold_white.png')"
						@mouseleave="onHover('holdSrc', 'phoneControls/hold_blue.png')"
					>
						<img :src="state.holdSrc" alt="" />
						<span>{{ telStatusInfo.onHoldArr[0]?.isHold ? '取消保持' : '保持' }}</span>
					</div>
				</template>
			</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('mute')">
				<div
					class="item active"
					@click="onControlClick(telStatusInfo.isMute ? 'unMute' : 'mute')"
					@mouseenter="onHover('muteSrc', 'phoneControls/mute_white.png')"
					:title="telStatusInfo.isMute ? '取消静音' : '静音'"
					@mouseleave="onHover('muteSrc', 'phoneControls/mute_blue.png')"
				>
					<img :src="state.muteSrc" alt="" />
					<span>{{ telStatusInfo.isMute ? '取消静音' : '静音' }}</span>
				</div>
			</template>
			<!-- 静音不可用 -->
			<template v-else>
				<div class="item disabled" title="保持">
					<img :src="getImageUrl('phoneControls/mute_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(telStatusInfo.isMeeting ? 'conferenceEnd' : 'conference') &&
					telStatusInfo.onHoldArr.length === 2 &&
					telStatusInfo.onHoldArr.filter((item) => item.isHold) &&
					telStatusInfo.onHoldArr.filter((item) => !item.isHold)
				"
			>
				<div
					class="item active"
					@mouseenter="onHover('conferenceSrc', 'phoneControls/conference_white.png')"
					:title="telStatusInfo.isMeeting ? '结束会议' : '三方会议'"
					@mouseleave="onHover('conferenceSrc', 'phoneControls/conference_blue.png')"
					@click="onControlClick('conference')"
				>
					<img :src="state.conferenceSrc" alt="" />
					<span>{{ telStatusInfo.isMeeting ? '结束会议' : '三方会议' }}</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>

			<!-- 呼叫转移 可用 -->
			<template v-if="telStatusInfo.isDutyOn && activeArr.includes('callForwarding')">
				<div
					class="item active"
					title="呼叫转移"
					@mouseenter="onHover('callForwardingSrc', 'phoneControls/callForwarding_white.png')"
					@mouseleave="onHover('callForwardingSrc', 'phoneControls/callForwarding_blue.png')"
					@click="onControlClick('callForwarding')"
				>
					<img :src="state.callForwardingSrc" alt="" />
					<span>呼叫转移</span>
				</div>
			</template>
			<!-- 呼叫转移 不可用 -->
			<template v-else>
				<div class="item disabled" title="呼叫转移">
					<img :src="getImageUrl('phoneControls/callForwarding_grey.png')" alt="" />
					<span>呼叫转移</span>
				</div>
			</template>

			<!-- 评价 可用 -->
			<template v-if="telStatusInfo.isDutyOn && activeArr.includes('evaluate')">
				<div
					class="item active"
					@mouseenter="onHover('evaluateSrc', 'phoneControls/evaluate_white.png')"
					title="评价"
					@mouseleave="onHover('evaluateSrc', 'phoneControls/evaluate_blue.png')"
					@click="onControlClick('evaluate')"
				>
					<img :src="state.evaluateSrc" alt="" />
					<span>评价</span>
				</div>
			</template>
			<!-- 评价 不可用 -->
			<template v-else>
				<div class="item disabled" title="评价">
					<img :src="getImageUrl('phoneControls/evaluate_grey.png')" alt="" />
					<span>评价</span>
				</div>
			</template>
		</div>
	</div>
	<!-- 占位标签 -->
	<div class="seizeSeat-box"></div>
	<!-- 功能 -->
	<!-- 签入 -->
	<el-dialog v-model="state.showDutyDialog" draggable title="签入" width="500px">
		<el-form :model="state.dutyForm" label-width="80px" ref="dutyFormRef">
			<el-form-item label="分机" prop="telNo" :rules="[{ required: true, message: '请选择需要签入的分机', trigger: 'change' }]">
				<el-select v-model="state.dutyForm.telNo" placeholder="请选择需要签入的分机" class="w100">
					<el-option v-for="item in state.telsList" :key="item.id" :label="item.no" :value="item.no" />
				</el-select>
			</el-form-item>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="state.showDutyDialog = false" class="default-button" :loading="state.loading">取 消</el-button>
				<el-button type="primary" @click="clickOnDuty" :loading="state.loading">确 定</el-button>
			</span>
		</template>
	</el-dialog>

	<!-- 小休弹窗 -->
	<el-dialog
		v-model="state.showRestDialog"
		ref="dialogRestRef"
		draggable
		title="小休申请"
		:width="AppConfigInfo.isRestApproval ? '60%' : '500px'"
		@mouseup="mouseup"
		:style="'transform: ' + state.transform + ';'"
	>
		<!-- 需要审核 -->
		<template v-if="AppConfigInfo.isRestApproval">
			<el-form :model="state.restForm" label-width="90px" 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="selectHanders"
								value-key="key"
							>
								<el-option v-for="item in state.handerOptions" :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.handerMainOptions" :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="24" :md="24" :lg="24" :xl="24">
						<el-form-item label="办理意见" prop="opinion" :rules="[{ required: true, message: '请填写小休办理意见', trigger: 'blur' }]">
							<Comment
								@chooseComment="chooseComment"
								v-model="state.restForm.opinion"
								:loading="state.loading"
								placeholder="请填写小休办理意见"
								: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' }]">
							<Upload :fileList="state.fileList" />
						</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.showRestDialog = false" class="default-button" :loading="state.loading">取 消</el-button>
				<el-button type="primary" @click="clickOnRest" :loading="state.loading">提 交</el-button>
			</span>
		</template>
	</el-dialog>

	<!-- 转接 -->
	<el-dialog v-model="state.showTransferDialog" draggable title="转接" width="500px">
		<el-form :model="state.transferForm" label-width="80px" ref="transferFormRef">
			<el-form-item label="线路" prop="way" :rules="[{ required: true, message: '请选择线路', trigger: 'change' }]">
				<el-radio-group v-model="state.transferForm.way">
					<el-radio label="inside">内线</el-radio>
					<el-radio label="external">外线</el-radio>
				</el-radio-group>
			</el-form-item>
			<el-form-item
				label="转接号码"
				prop="telNo"
				:rules="[{ required: true, message: '请输入内线号码', trigger: 'blur' }]"
				v-if="state.transferForm.way === 'inside'"
			>
				<el-select v-model="state.transferForm.telNo" placeholder="请选择转接分机" class="w100" filterable clearable>
					<el-option v-for="item in state.telsList" :key="item.id" :label="item.no" :value="item.no" />
				</el-select>
			</el-form-item>
			<el-form-item
				label="转接号码"
				prop="outerNo"
				:rules="[{ required: true, message: '请输入外线号码', trigger: 'blur' }]"
				v-if="state.transferForm.way === 'external'"
			>
				<el-select
					v-model="state.transferForm.outerNo"
					placeholder="请选择转接分机或输入外部电话"
					class="w100"
					filterable
					allow-create
					default-first-option
					clearable
				>
					<el-option v-for="item in state.telsList" :key="item.id" :label="item.no" :value="item.no" />
				</el-select>
			</el-form-item>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="state.showTransferDialog = false" class="default-button" :loading="state.loading">取 消</el-button>
				<el-button type="primary" @click="clickOnTransfer" :loading="state.loading">确 定</el-button>
			</span>
		</template>
	</el-dialog>

	<!-- 呼叫 -->
	<el-dialog v-model="state.showOutboundDialog" draggable title="呼叫" width="450px">
		<el-form :model="state.outboundForm" label-width="80px" ref="outboundFormRef">
			<el-form-item label="线路" prop="way" :rules="[{ required: true, message: '请选择线路', trigger: 'change' }]">
				<el-radio-group v-model="state.outboundForm.way">
					<el-radio label="inside">内线</el-radio>
					<el-radio label="external">外线</el-radio>
				</el-radio-group>
			</el-form-item>
			<el-form-item
				label="呼叫号码"
				prop="telNo"
				:rules="[{ required: true, message: '请输入内线号码', trigger: ['blur', 'change'] }]"
				v-if="state.outboundForm.way === 'inside'"
			>
				<el-select v-model="state.outboundForm.telNo" placeholder="请选择呼叫分机" class="w100" filterable clearable>
					<el-option v-for="item in state.telsList" :key="item.id" :label="item.no" :value="item.no" />
				</el-select>
			</el-form-item>
			<el-form-item
				label="外线号码"
				prop="outerNo"
				:rules="[{ required: true, message: '请输入外线号码', trigger: 'blur' }]"
				v-if="state.outboundForm.way === 'external'"
			>
				<el-select
					v-model="state.outboundForm.outerNo"
					placeholder="请选择呼叫分机或输入外部电话"
					class="w100"
					filterable
					allow-create
					default-first-option
					clearable
				>
					<el-option v-for="item in state.telsList" :key="item.id" :label="item.no" :value="item.no" />
				</el-select>
			</el-form-item>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="state.showOutboundDialog = false" class="default-button" :loading="state.loading">取 消</el-button>
				<el-button type="primary" @click="clickOnOutbound" :loading="state.loading">确 定</el-button>
			</span>
		</template>
	</el-dialog>

	<!-- 呼叫转移 -->
	<el-dialog v-model="state.showCallForwardingDialog" draggable title="呼叫转移" width="500px">
		<el-form :model="state.callForwardingForm" label-width="100px" ref="callForwardingFormRef">
			<el-form-item prop="way">
				<template #label>
					<div class="flex-center-align">
						<el-popover :width="360" trigger="hover">
							<template #reference>
								<SvgIcon name="ele-QuestionFilled" color="var(--el-color-info)" class="mr5" />
							</template>
							<div>
								<p>1.全转：所有来电全部转移；</p>
								<p>2.遇忙转：来电时，当前话机忙时来电转移；</p>
								<p>3.无应答转：来电时，当前话机无人接听时来电转移。</p>
							</div>
						</el-popover>
						转移方式
					</div>
				</template>
				<el-radio-group v-model="state.callForwardingForm.way">
					<el-radio label="quanzhuan">全转</el-radio>
					<el-radio label="yumang">遇忙转</el-radio>
					<el-radio label="wuyingda">无应答转</el-radio>
				</el-radio-group>
			</el-form-item>
			<el-form-item label="转移号码" prop="phoneNo" :rules="[{ required: true, message: '请输入呼叫转移号码', trigger: 'blur' }]">
				<el-input v-model="state.callForwardingForm.phoneNo" placeholder="请输入呼叫转移号码" clearable></el-input>
			</el-form-item>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="state.showCallForwardingDialog = false" class="default-button" :loading="state.loading">取 消</el-button>
				<el-button type="primary" @click="clickOnCallForwarding" :loading="state.loading">确 定</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script setup lang="ts" name="telControl">
import { reactive, ref, computed, watch, onUnmounted, defineAsyncComponent } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessageBox, ElNotification, ElMessage } from 'element-plus';
import { storeToRefs } from 'pinia';
import { useTelStatus } from '/@/stores/telStatus';
import { useAppConfig } from '/@/stores/appConfig';
import { getImageUrl } from '/@/utils/tools';
import { getTelsList } from '/@/api/device/phone';
import signalR from '/@/utils/signalR';
import { formatDuration } from '/@/utils/formatTime';
import { commonEnum } from '/@/utils/tools';
import { Local } from '/@/utils/storage';
import other from '/@/utils/other';
import {
	onDuty,
	offDuty,
	telRest,
	telUnrest,
	telHold,
	telUnHold,
	telMute,
	telUnMute,
	visitorToTel,
	telToOuter,
	telToTel,
	visitorToOuter,
	meeting,
	hangupApi,
	restFlowStart,
	evaluateCall,
} from '/@/api/login/user';
import { TelStates, RestStates } from '/@/stores/interface';
import { workflowStepOptions } from '/@/api/system/workflow';
import { commonList } from '/@/api/business/commonP';
import { auth } from '/@/utils/authFunction';

// 引入组件
const Comment = defineAsyncComponent(() => import('/@/views/business/order/components/Order-comment.vue'));
const Upload = defineAsyncComponent(() => import('/@/components/Upload/index.vue'));

const state = reactive<any>({
	active: <EmptyArrayType>[], // 当前选中
	currentStatus: '', //当前通话状态
	showDutyDialog: false, //签入选分机弹窗
	dutyForm: {
		telNo: '', //分机号
	},
	telsList: <EmptyArrayType>[], // 分机列表
	loading: false,
	showHangupList: false, //是否展示挂断列表
	showRestDialog: false, //小休弹窗
	restForm: {
		//小休表单
		opinion: '',
		nextStepCode: '',
		nextHandlers: [],
		acceptSms: false,
		nextMainHandler: '',
		reason: '',
	},
	handerMainOptions: [], // 主办
	showTransferDialog: false, // 转接弹窗
	transferForm: {
		//转接表单
		way: 'inside',
		telNo: '',
		outerNo: '',
	},
	showOutboundDialog: false, //外呼弹窗
	outboundForm: {
		// 外呼表单
		way: 'inside',
		telNo: '',
		outerNo: '',
	},
	showCallForwardingDialog: false, // 呼叫转移弹窗
	callForwardingForm: {
		// 呼叫转移表单
		phoneNo: '',
		way: 'quanzhuan',
	},
	showHoldList: false, // 是否展示保持列表
	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'), //保持图片
	muteSrc: getImageUrl('phoneControls/mute_blue.png'), //静音图片
	transferSrc: getImageUrl('phoneControls/transfer_blue.png'), //转接图片
	conferenceSrc: getImageUrl('phoneControls/conference_blue.png'), //三方会议图片
	outboundSrc: getImageUrl('phoneControls/outbound_blue.png'), //外呼图片
	callForwardingSrc: getImageUrl('phoneControls/callForwarding_blue.png'), //呼叫转移图片
	evaluateSrc: getImageUrl('phoneControls/evaluate_blue.png'), //评价图片
	callTypes: {
		// 通话类型
		0: '坐席',
		1: '坐席',
		2: '市民',
		3: '市民',
	},
	time: 0, // 毫秒数 记录通话时长
	timer: null as any, // 计时器
	restReasonOptions: [], // 小休原因
	nextStepOptions: [], // 下一个环节
	handerOptions: [], // 处理人
	handleId: '', // 流程处理ID
  transform: 'translate(0px, 0px)',
	fileList: [], // 文件上传列表
});
const usetelStatusStore = useTelStatus();
const { telStatusInfo } = storeToRefs(usetelStatusStore);
const appConfigStore = useAppConfig();
const { AppConfigInfo } = storeToRefs(appConfigStore);
const dutyFormRef = ref<RefType>(); //签入
const restFormRef = ref<RefType>(); //小休
const transferFormRef = ref<RefType>(); // 转接
const outboundFormRef = ref<RefType>(); //外呼
const callForwardingFormRef = ref<RefType>(); //呼叫转移
const dialogRestRef = ref<RefType>(); // 小休申请弹窗
const router = useRouter();
//  signalR 初始化signalr
signalR.init();

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

// 如果当前是已经签入状态 监听消息事件
if (telStatusInfo.value.isDutyOn) {
	if (
		['onCall', 'oneCallHold', 'onMute', 'onConference', 'oneHoldOneCall'].includes(telStatusInfo.value.phoneControlState) &&
		telStatusInfo.value.onCallArr.length >= 1
	) {
		//如果当前状态是通话中  刷新继续计时
		// 开始计时
		startTime();
	}
	signalR.start();
	signalR.SR.on('Ring', (data: any) => {
		// 接收来电消息
		console.log(data, '来电消息');
		data.isHold = false; // 默认保持为false
		telStatusInfo.value.onCallArr.push(data);
		// 拨打电话通话数 = 保持数量
		telStatusInfo.value.onHoldArr = telStatusInfo.value.onCallArr;
		// 将状态存入Pina
		usetelStatusStore.setHoldState(telStatusInfo.value.onHoldArr);
		usetelStatusStore.setCallState(telStatusInfo.value.onCallArr);
		// 设置电话控件状态
		usetelStatusStore.setPhoneControlState(TelStates.ring);
		// 跳转到录入工单页面
		router.push({
			name: 'orderAdd',
			params: {
				createBy: 'tel',
				telNo: data.from,
				callId: data.id,
				transfer: '12315',
				tagsViewName: '工单受理',
			},
		});
	});
	signalR.SR.on('Answered', (data: any) => {
		//接收接听消息
		console.log(data, '接听消息');
		// 设置电话状态
		usetelStatusStore.setPhoneControlState(TelStates.onCall);
		if (telStatusInfo.value.onCallArr.length === 1) {
			// 开始计时
			startTime();
		}
	});
	signalR.SR.on('Bye', (data: any) => {
		// 接收挂断消息
		console.log(data, '挂断消息');
		// 设置电话状态
		usetelStatusStore.setPhoneControlState(TelStates.dutyOn);
		// 挂断从挂断列表中移除
		telStatusInfo.value.onCallArr = telStatusInfo.value.onCallArr.filter((item: any) => item.id != data.id);
		// 如果保持也有 直接去除保持列表中的数据
		telStatusInfo.value.onHoldArr = telStatusInfo.value.onHoldArr.filter((item: any) => item.id != data.id);

		// 将状态存入Pina
		usetelStatusStore.setHoldState(telStatusInfo.value.onHoldArr);
		usetelStatusStore.setCallState(telStatusInfo.value.onCallArr);

		if (telStatusInfo.value.onCallArr.length === 0) {
			// 关闭定时器
			removeTimer();
		}
	});
	signalR.SR.on('RestApplyPass', (data: any) => {
		// 小休审批通过消息
		console.log(data, '小休审批通过消息');
		// 设置电话状态小休中
		ElNotification({
			title: '成功',
			message: '小休审批通过，开始小休',
			type: 'success',
		});
		usetelStatusStore.setPhoneControlState(TelStates.rest);
		usetelStatusStore.setRest(RestStates.resting);
	});
}
// 设置当前可用的按钮
const activeArr = computed(() => {
	const switchCases = {
		dutyOff: ['dutyOn'], // 签出状态
		dutyOn: ['dutyOff', 'rest', 'outbound', 'callForwarding'], // 已签入无通话状态
		rest: ['rest', 'callForwarding'], // 小休中状态
		ring: ['hangup'], //振铃中
		onCall: ['hangup', 'hold', 'mute', 'transfer', 'evaluate'], // 单个通话中
		oneCallHold: ['hangup', 'hold', 'mute', 'transfer', 'outbound', 'evaluate'], // 单个保持中
		oneHoldOneCall: ['hangup', 'hold', 'mute', 'transfer', 'conference'], // 通话一保持通话二通话中（可用三方通话）
		onMute: ['hangup', 'hold', 'mute', 'transfer', 'conference', 'evaluate'], // 通话静音中
		onConference: ['hangup', 'hold', 'mute', 'transfer', 'conference', 'evaluate'], // 三方会议中
	};
	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: '振铃中',
		onCall: '通话中',
		oneCallHold: '通话保持',
		onMute: '静音',
		onConference: '会议中',
	};
	return statusMap[telStatusInfo.value.phoneControlState] || '';
});
// 查询所有分机
const getTelsLists = () => {
	getTelsList().then((res: any) => {
		state.telsList = res?.result ?? [];
	});
};
// 鼠标移入移出改变图标
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 'mute': //静音
			if (!auth('public:seat:mute')) ElMessage.error('抱歉，您没有静音权限！');
			else onMute();
			break;
		case 'unMute': // 取消静音
			if (!auth('public:seat:unMute')) ElMessage.error('抱歉，您没有取消静音权限！');
			else unMute();
			break;
		case 'transfer': //转接
			if (!auth('999110')) ElMessage.error('抱歉，您没有转接权限！');
			else onTransfer();
			break;
		case 'conference': //三方会议
			if (!auth('public:seat:meeting')) ElMessage.error('抱歉，您没有三方会议权限！');
			else onConference();
			break;
		case 'conferenceEnd': //结束三方会议
			if (!auth('public:seat:meeting')) ElMessage.error('抱歉，您没有结束三方会议权限！');
			else onConferenceEnd();
			break;
		case 'outbound': //呼叫
			if (!auth('999111')) ElMessage.error('抱歉，您没有呼叫权限！');
			else onOutbound();
			break;
		case 'callForwarding': //呼叫转移
			if (!auth('999104')) ElMessage.error('抱歉，您没有呼叫转移权限！');
			else onCallForwarding();
			break;
		case 'evaluate': //评价
			if (!auth('public:seat:evaluate')) ElMessage.error('抱歉，您没有评价权限！');
			else onEvaluate();
			break;
		default:
			break;
	}
};
//签入
const onDutyFn = () => {
	dutyFormRef.value?.resetFields();
	// 获取所有分机列表
	getTelsLists();
	state.showDutyDialog = true;
};
// 确认签入
const clickOnDuty = () => {
	dutyFormRef.value.validate((valid: boolean) => {
		if (valid) {
			state.loading = true;
			onDuty(state.dutyForm.telNo)
				.then(() => {
					// 设置分机号
					usetelStatusStore.setTelsNo(state.dutyForm.telNo);
					// 设置签入状态
					usetelStatusStore.setDutyState(true);
					// 设置电话状态
					usetelStatusStore.setPhoneControlState(TelStates.dutyOn);
					// 开启 signalr 链接
					signalR.start();
					signalR.SR.on('Ring', (data: any) => {
						// 接收来电消息
						console.log(data, '来电消息');
						data.isHold = false; // 默认保持为false
						telStatusInfo.value.onCallArr.push(data);
						// 拨打电话通话数 = 保持数量
						telStatusInfo.value.onHoldArr = telStatusInfo.value.onCallArr;
						// 将状态存入Pina
						// 将状态存入Pina
						usetelStatusStore.setHoldState(telStatusInfo.value.onHoldArr);
						usetelStatusStore.setCallState(telStatusInfo.value.onCallArr);
						// 设置电话状态
						usetelStatusStore.setPhoneControlState(TelStates.ring);
						// 跳转到录入工单页面
						router.push({
							name: 'orderAdd',
							params: {
								createBy: 'tel',
								telNo: data.from,
								callId: data.id,
								transfer: '12315',
								tagsViewName: '工单受理',
							},
						});
					});
					signalR.SR.on('Bye', (data: any) => {
						// 接收挂断消息
						console.log(data, '挂断消息');
						// 设置电话状态
						usetelStatusStore.setPhoneControlState(TelStates.dutyOn);

						// 挂断从挂断列表中移除
						telStatusInfo.value.onCallArr = telStatusInfo.value.onCallArr.filter((item: any) => item.id != data.id);
						// 如果保持也有 直接去除保持列表中的数据
						telStatusInfo.value.onHoldArr = telStatusInfo.value.onHoldArr.filter((item: any) => item.id != data.id);

						// 将状态存入Pina
						usetelStatusStore.setHoldState(telStatusInfo.value.onHoldArr);
						usetelStatusStore.setCallState(telStatusInfo.value.onCallArr);
						if (telStatusInfo.value.onCallArr.length === 0) {
							// 关闭定时器
							removeTimer();
						}
					});
					signalR.SR.on('Answered', (data: any) => {
						//接收接听消息
						console.log(data, '接听消息');
						// 设置电话状态
						usetelStatusStore.setPhoneControlState(TelStates.onCall);

						if (telStatusInfo.value.onCallArr.length === 1) {
							// 开始计时
							startTime();
						}
					});
					signalR.SR.on('RestApplyPass', (data: any) => {
						// 小休审批通过消息
						console.log(data, '小休审批通过消息');
						ElNotification({
							title: '成功',
							message: '小休审批通过，开始小休',
							type: 'success',
						});
						// 设置电话状态小休中
						usetelStatusStore.setPhoneControlState(TelStates.rest);
						usetelStatusStore.setRest(RestStates.resting);
					});
					ElNotification({
						title: '成功',
						message: '签入成功',
						type: 'success',
					});
					//  重置表单
					dutyFormRef.value?.resetFields();
					state.showDutyDialog = false;
					state.loading = false;
				})
				.catch((err: any) => {
					console.log(err, '签入出现错误');
					state.showDutyDialog = false;
					state.loading = false;
				});
		}
	});
};
// 签出
const offDutyFn = () => {
	ElMessageBox.confirm(`确定要签出，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			state.loading = true;
			offDuty()
				.then(() => {
					ElNotification({
						title: '成功',
						message: '签出成功',
						type: 'success',
					});
					signalR.SR.off('Ring');
					signalR.SR.off('Answered');
					signalR.SR.off('Bye');
					signalR.SR.off('RestApplyPass');
					// 断开链接
					signalR.stop();
					// 重置所有状态
					usetelStatusStore.resetState();
					state.loading = false;
				})
				.catch(() => {
					state.loading = false;
				});
		})
		.catch(() => {});
};
// 挂断
const onHangup = () => {
	ElMessageBox.confirm(`确定要挂断，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			state.loading = true;
			hangupApi(telStatusInfo.value.onCallArr[0])
				.then(() => {
					ElNotification({
						title: '成功',
						message: '挂断成功',
						type: 'success',
					});
					// 设置话机状态 设置为签入状态
					usetelStatusStore.setPhoneControlState(TelStates.dutyOn);
					// 清空当前的通话数组
					usetelStatusStore.setCallState([]);
					// 关闭定时器
					removeTimer();
					state.loading = false;
				})
				.catch((err: any) => {
					console.log(err);
					state.loading = false;
				});
		})
		.catch(() => {});
};
// 挂断其中一个
const hangupOne = (value: any) => {
	ElMessageBox.confirm(`确定要挂断，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			state.loading = true;
			hangupApi(value)
				.then(() => {
					ElNotification({
						title: '成功',
						message: '挂断成功',
						type: 'success',
					});
					// state.showHangupList = false;
					console.log(telStatusInfo.value.onCallArr, telStatusInfo.value.onHoldArr, value.id);
					// 挂断从挂断列表中移除
					telStatusInfo.value.onCallArr = telStatusInfo.value.onCallArr.filter((item: any) => item.id != value.id);
					// 如果保持也有 直接去除保持列表中的数据
					telStatusInfo.value.onHoldArr = telStatusInfo.value.onHoldArr.filter((item: any) => item.id != value.id);

					// 将状态存入Pina
					usetelStatusStore.setHoldState(telStatusInfo.value.onHoldArr);
					usetelStatusStore.setCallState(telStatusInfo.value.onCallArr);

					if (telStatusInfo.value.onCallArr.length === 0) {
						// 没有通话 关闭定时器
						removeTimer();
					}
					state.loading = false;
					console.log(telStatusInfo.value.onCallArr, telStatusInfo.value.onHoldArr, 'newArr');
				})
				.catch(() => {
					state.loading = false;
				});
		})
		.catch(() => {});
};
// 小休
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({ typecode: commonEnum.RestReason });
	state.restReasonOptions = response.result;
	state.showRestDialog = true;
};
// 小休流程选择下一个环节
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.handerOptions = res.result ?? [];
	} catch (error) {
		console.log(error);
	}
};
// 小休选择处理人
const selectHanders = () => {
	restFormRef.value?.resetFields('nextMainHandler');
};
// 主办从处理人中选择
state.handerMainOptions = computed(() => {
	return state.restForm.nextHandlers;
});
// 确定小休
const clickOnRest = () => {
	restFormRef.value.validate((valid: boolean) => {
		if (valid) {
			ElMessageBox.confirm(`确认提交?`, '提示', {
				confirmButtonText: '确认',
				cancelButtonText: '取消',
				type: 'warning',
				draggable: true,
				cancelButtonClass: 'default-button',
				autofocus: false,
			})
				.then(() => {
					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;
							}
						}
						telRest(submitObj)
							.then(() => {
								ElNotification({
									title: '成功',
									message: '申请小休成功',
									type: 'success',
								});
								// 设置休息状态 审核中
								usetelStatusStore.setRest(RestStates.InReview);
								state.showRestDialog = false;
								state.loading = false;
							})
							.catch(() => {
								state.loading = false;
							});
					} else {
						//不需要审核直接开始小休
						telRest(state.restForm)
							.then(() => {
								ElNotification({
									title: '成功',
									message: '小休开始',
									type: 'success',
								});
								state.showRestDialog = false;
								// 设置休息状态 小休中
								usetelStatusStore.setRest(RestStates.resting);
								// 设置话机状态 开始休息设置为小休状态
								usetelStatusStore.setPhoneControlState(TelStates.rest);
								state.loading = false;
							})
							.catch(() => {
								state.loading = false;
							});
					}
				})
				.catch(() => {});
		}
	});
};
// 设置抽屉
const mouseup = () => {
	state.transform = dialogRestRef.value.dialogContentRef.$el.style.transform;
};
// 选择常用意见 填入填写框
const chooseComment = (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;
			telUnrest()
				.then(() => {
					ElNotification({
						title: '成功',
						message: '小休结束',
						type: 'success',
					});
					// 设置休息状态 设置未正常状态
					usetelStatusStore.setRest(RestStates.unRest);
					// 设置话机状态 结束休息改为签入状态
					usetelStatusStore.setPhoneControlState(TelStates.dutyOn);
					state.loading = false;
				})
				.catch(() => {
					state.loading = false;
				});
		})
		.catch(() => {});
};
// 单个通话保持
const onHold = () => {
	ElMessageBox.confirm(`确定要保持，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			state.loading = true;
			telHold(telStatusInfo.value.onCallArr[0].id)
				.then(() => {
					ElNotification({
						title: '成功',
						message: '保持开始',
						type: 'success',
					});
					// 把当前保持添加进保持列表
					telStatusInfo.value.onHoldArr = telStatusInfo.value.onCallArr;
					telStatusInfo.value.onHoldArr[0].isHold = true;
					console.log(telStatusInfo.value.onHoldArr);
					// 将状态存入Pina
					usetelStatusStore.setHoldState(telStatusInfo.value.onHoldArr);

					// 设置电话状态  单个通话保持
					usetelStatusStore.setPhoneControlState(TelStates.oneCallHold);
					state.loading = false;
				})
				.catch(() => {
					state.loading = false;
				});
		})
		.catch(() => {});
};
// 取消保持
const onUnHold = () => {
	ElMessageBox.confirm(`确定要取消保持，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			state.loading = true;
			telUnHold(telStatusInfo.value.onCallArr[0].id)
				.then(() => {
					ElNotification({
						title: '成功',
						message: '取消保持',
						type: 'success',
					});
					// 设置保持状态
					telStatusInfo.value.onHoldArr[0].isHold = false;
					usetelStatusStore.setHoldState(telStatusInfo.value.onHoldArr);
					// 设置电话状态  取消单个保持为通话中
					usetelStatusStore.setPhoneControlState(TelStates.onCall);
					state.loading = false;
				})
				.catch(() => {
					state.loading = false;
				});
		})
		.catch(() => {});
};
// 保持或者取消保持其中一个
const holdItem = (item: any) => {
	ElMessageBox.confirm(`确定要${item.isHold ? '取消保持' : '保持'}，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			console.log(item);
			if (item.isHold) {
				// 取消保持
				state.loading = true;
				telUnHold(item.id)
					.then(() => {
						ElNotification({
							title: '成功',
							message: '取消保持',
							type: 'success',
						});
						// 设置保持状态
						for (let i of telStatusInfo.value.onHoldArr) {
							if (i.id === item.id) {
								i.isHold = false;
							}
						}
						console.log(telStatusInfo.value.onHoldArr);
						usetelStatusStore.setHoldState(telStatusInfo.value.onHoldArr);
						// 判断两个通话 一个保持 一个通话中
						if (
							telStatusInfo.value.onHoldArr.length === 2 &&
							telStatusInfo.value.onHoldArr.filter((item: any) => !item.isHold) &&
							telStatusInfo.value.onHoldArr.filter((item: any) => !item.isHold)
						) {
							// 设置电话状态 // 通话一保持通话二通话中（可用三方通话）
							usetelStatusStore.setPhoneControlState(TelStates.oneHoldOneCall);
						}
						state.loading = false;
					})
					.catch(() => {
						state.loading = false;
					});
			} else {
				//保持
				state.loading = true;
				telHold(item.id)
					.then(() => {
						ElNotification({
							title: '成功',
							message: '保持开始',
							type: 'success',
						});
						// 设置保持状态
						for (let i of telStatusInfo.value.onHoldArr) {
							if (i.id === item.id) {
								i.isHold = true;
							}
						}
						console.log(telStatusInfo.value.onHoldArr);
						usetelStatusStore.setHoldState(telStatusInfo.value.onHoldArr);
						// 判断两个通话 一个保持 一个通话中
						if (
							telStatusInfo.value.onHoldArr.length === 2 &&
							telStatusInfo.value.onHoldArr.filter((item: any) => !item.isHold) &&
							telStatusInfo.value.onHoldArr.filter((item: any) => !item.isHold)
						) {
							// 设置电话状态 // 通话一保持通话二通话中（可用三方通话）
							usetelStatusStore.setPhoneControlState(TelStates.oneHoldOneCall);
						}
						state.loading = false;
					})
					.catch(() => {
						state.loading = false;
					});
			}
		})
		.catch(() => {});
};
// 静音
const onMute = () => {
	ElMessageBox.confirm(`确定要静音，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			state.loading = true;
			telMute()
				.then(() => {
					ElNotification({
						title: '成功',
						message: '静音开始',
						type: 'success',
					});
					// 设置静音状态
					usetelStatusStore.setMute(true);
					// 设置话机状态 静音修改为静音状态
					usetelStatusStore.setPhoneControlState(TelStates.onMute);
					state.loading = false;
				})
				.catch(() => {
					state.loading = false;
				});
		})
		.catch(() => {});
};
// 取消静音
const unMute = () => {
	ElMessageBox.confirm(`确定要取消静音，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			state.loading = true;
			telUnMute()
				.then(() => {
					ElNotification({
						title: '成功',
						message: '静音结束',
						type: 'success',
					});
					// 设置静音状态
					usetelStatusStore.setMute(false);
					// 设置话机状态 取消静音修改为通话状态
					usetelStatusStore.setPhoneControlState(TelStates.onCall);
					state.loading = false;
				})
				.catch(() => {
					state.loading = false;
				});
		})
		.catch(() => {});
};
// 转接
const onTransfer = () => {
	// 转接分为咨询转接和盲转
	// 只有一条通话线路时 保持当前通话且不存在多通电话的情况下 盲转
	if (telStatusInfo.value.onHoldArr.length === 1) {
		//  重置表单
		transferFormRef.value?.resetFields();
		state.showTransferDialog = true;
	} else {
		// 咨询转 当前已存在通话一、通话二的情况下，点击【转接】按钮，直接将通话一转接给通话二
	}
};
// 确认转接
const clickOnTransfer = () => {
	transferFormRef.value.validate((valid: boolean) => {
		if (valid) {
			if (state.transferForm.way === 'inside') {
				// 内线
				visitorToTel({ telNo: state.transferForm }).then(() => {
					ElNotification({
						title: '成功',
						message: '转接成功',
						type: 'success',
					});
					state.showTransferDialog = false;
				});
			} else if (state.transferForm.way === 'external') {
				// 外线
				visitorToOuter({ outerNo: state.transferForm }).then(() => {
					ElNotification({
						title: '成功',
						message: '转接成功',
						type: 'success',
					});
					state.showTransferDialog = false;
				});
			}
		}
	});
};
// 三方会议开始
const onConference = () => {
	state.loading = true;
	meeting({ telNo: telStatusInfo.value.telsNo })
		.then(() => {
			ElNotification({
				title: '成功',
				message: '三方会议开始',
				type: 'success',
			});
			// 设置三方会议状态
			usetelStatusStore.setMetTing(true);
			// 设置话机状态 取消静音修改为会议状态
			usetelStatusStore.setPhoneControlState(TelStates.onConference);
			state.loading = false;
		})
		.catch(() => {
			state.loading = false;
		});
};
// 确定要结束三方会议
const onConferenceEnd = () => {
	ElMessageBox.confirm(`确定确定要结束三方会议，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			// 设置三方会议状态
			usetelStatusStore.setMetTing(false);
			// 设置话机状态 取消静音修改为通话状态
			usetelStatusStore.setPhoneControlState(TelStates.onCall);
		})
		.catch(() => {});
};
// 外呼
const onOutbound = () => {
	//  重置表单
	outboundFormRef.value?.resetFields();
	state.showOutboundDialog = true;
};
// 外呼保存
const clickOnOutbound = () => {
	outboundFormRef.value.validate((valid: boolean) => {
		console.log(state.outboundForm, valid);
		if (valid) {
			state.loading = true;
			if (state.outboundForm.way === 'inside') {
				// 呼叫分机
				telToTel({ telNo: state.outboundForm.telNo })
					.then(() => {
						ElNotification({
							title: '成功',
							message: '外呼成功',
							type: 'success',
						});
						state.showOutboundDialog = false;
						state.loading = false;
					})
					.catch(() => {
						state.loading = false;
					});
			} else {
				// 呼叫外部电话
				telToOuter({ outerNo: state.outboundForm.outerNo })
					.then(() => {
						ElNotification({
							title: '成功',
							message: '外呼成功',
							type: 'success',
						});
						state.showOutboundDialog = false;
						state.loading = false;
					})
					.catch(() => {
						state.loading = false;
					});
			}
		}
	});
};
// 呼叫转移
const onCallForwarding = () => {
	//  重置表单
	callForwardingFormRef.value?.resetFields();
	state.showCallForwardingDialog = true;
};
// 呼叫转移保存
const clickOnCallForwarding = () => {
	callForwardingFormRef.value.validate((valid: boolean) => {
		if (valid) {
			state.loading = true;
			visitorToOuter(state.callForwardingForm)
				.then(() => {
					ElNotification({
						title: '成功',
						message: '呼叫转移成功',
						type: 'success',
					});
					state.loading = false;
				})
				.catch(() => {
					state.loading = false;
				});
		}
	});
};
// 评价
const onEvaluate = () => {
	ElMessageBox.confirm(`确定确定要开始评价，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			state.loading = true;
			evaluateCall(state.callForwardingForm)
				.then(() => {
					ElNotification({
						title: '成功',
						message: '开启评价成功',
						type: 'success',
					});
					state.loading = false;
				})
				.catch(() => {
					state.loading = false;
				});
		})
		.catch(() => {});
};
// 监听电话状态变化
watch(
	() => telStatusInfo.value.phoneControlState,
	(newVal, oldVal) => {
		console.log(`状态改变了：${oldVal}=====>${newVal}`);
	}
);
// 清理定时器
onUnmounted(() => {
	removeTimer();
});
</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: 15px;
			}

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

			&.disabled {
				cursor: not-allowed;
				overflow: hidden;
				// &:hover{
				//     background-color:var(--hotline-bg-main-color);
				// }
			}
		}

		.active {
			&:hover {
				color: var(--hotline-color-white);
				background-image: url('../../../assets/images/phoneControls/active.png');
				background-repeat: no-repeat;
				background-size: 100% 100%;
			}
		}
	}
}
</style>
<style lang="scss">
.el-popover.hangup-popover {
	background: var(--el-color-primary);
	border-radius: 16px;
	opacity: 0.9;
	box-shadow: 0 1px 8px 0 rgba(0, 15, 49, 0.1);
	border: 1px solid var(--el-color-primary);
	padding: 15px;

	.hangup-container {
		display: flex;
		flex-wrap: nowrap;
		color: var(--hotline-color-white);
		font-size: var(--el-font-size-small);

		.hangup-item {
			text-align: center;
			width: 130px;
			border-right: 1px solid var(--el-border-color-darker);

			&:last-child {
				border-right: 0;
			}

			&-phoneNumber {
				padding-top: 4px;
			}

			&-button {
				background: linear-gradient(0deg, #e3e3e3, #ffffff);
				border-radius: 8px;
				color: var(--el-color-primary);
				outline: none;
				padding: 5px 15px;
				border: none;
				margin-top: 6px;
				font-weight: bold;
				cursor: pointer;
			}
		}
	}
}
</style>
