<template>
	<el-dialog
		v-model="state.dialogVisible"
		draggable
		:title="dialogTitle"
		ref="dialogRef"
		@mouseup="mouseup"
		:style="'transform: ' + state.transform + ';'"
		@close="close"
		destroy-on-close
		modal-class="modal_class"
		class="visit_dialog_no_modal"
		:modal="false"
	>
		<el-collapse v-model="state.collapseArr" class="collapse-box" v-loading="state.loading">
			<!-- 工单信息 -->
			<el-collapse-item name="1">
				<template #title>
					<p class="pl20">
						<b class="font14">工单信息</b>
					</p>
				</template>
				<div class="collapse-container">
					<el-form label-width="100px" class="show-info-form">
						<el-row :gutter="10">
							<el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
								<el-form-item label="工单编码" class="mb5"> {{ state.orderDetail.no }} </el-form-item>
							</el-col>
							<el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
								<el-form-item label="受理时间" class="mb5">
									<span>{{ formatDate(state.orderDetail.startTime, 'YYYY-mm-dd HH:MM:SS') }}</span></el-form-item
								>
							</el-col>
							<el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
								<el-form-item label="受理人" class="mb5">
									<span>{{ state.orderDetail?.acceptorName }}</span>
								</el-form-item>
							</el-col>
							<el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
								<el-form-item label="来源渠道" class="mb5"> {{ state.orderDetail.sourceChannel }} </el-form-item>
							</el-col>
							<el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
								<el-form-item label="受理类型" class="mb5"> {{ state.orderDetail.acceptType }} </el-form-item>
							</el-col>
							<el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
								<el-form-item label="热点分类" class="mb5"> {{ state.orderDetail.hotspotName }} </el-form-item>
							</el-col>
							<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
								<el-form-item label="工单标题" class="mb5"> {{ state.orderDetail.title }} </el-form-item>
							</el-col>
							<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
								<el-form-item label="工单内容" class="formatted-text mb5"> {{ state.orderDetail.content }} </el-form-item>
							</el-col>
							<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
								<el-form-item label="办理结果" class="formatted-text mb5"> {{ state.orderDetail.fileOpinion }} </el-form-item>
							</el-col>
						</el-row>
					</el-form>
				</div>
			</el-collapse-item>
			<el-collapse-item name="2">
				<template #title>
					<p class="pl20">
						<b class="font14">来电人信息</b>
					</p>
				</template>
				<div class="collapse-container">
					<el-form label-width="100px" class="show-info-form">
						<el-row :gutter="10">
							<el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
								<el-form-item label="来电人姓名"> {{ state.orderDetail.fromName }} </el-form-item>
							</el-col>
							<el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12" v-if="state.orderDetail.fromPhone">
								<el-form-item label="来电号码" class="mb5">
									{{ state.orderDetail.fromPhone }}
									<el-button
										plain
										title="人工回访录音"
										size="small"
										type="primary"
										class="ml8"
										@click="recordFile"
										v-if="['ZiGong'].includes(themeConfig.appScope) ? state.recordingAbsolutePath && userInfos.isCenter : state.recordingAbsolutePath"
										>人工回访录音</el-button
									>
								</el-form-item>
							</el-col>
							<el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
								<el-form-item label="来电人性别" class="mb5"> {{ state.orderDetail.fromGenderText }} </el-form-item>
							</el-col>
							<el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
								<el-form-item label="联系电话">
									{{ state.orderDetail.contact }}
									<el-button plain title="呼叫" size="small" type="primary" class="ml8" @click="callPhone(state.orderDetail.contact)" v-if="!disabled"
										>外呼</el-button
									>
									<el-checkbox-group
										v-model="prefixOptions"
										:max="1"
										v-if="['ZiGong', 'LuZhou'].includes(themeConfig.appScope) && !disabled"
										class="checkbox ml5"
									>
										<el-checkbox value="add">加0</el-checkbox>
										<el-checkbox value="remove">减0</el-checkbox>
									</el-checkbox-group>
								</el-form-item>
							</el-col>
							<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
								<el-form-item label="联系地址"> {{ state.orderDetail.address }} </el-form-item>
							</el-col>
						</el-row>
					</el-form>
				</div>
			</el-collapse-item>
			<el-collapse-item name="3">
				<template #title>
					<p class="pl20">
						<b class="font14">回访信息</b>
					</p>
				</template>
				<div class="collapse-container">
					<el-form label-width="120px" ref="ruleFormRef" :model="state.ruleForm" label-position="left">
						<!-- 详情 -->
						<template v-if="disabled">
							<el-row :gutter="10" class="show-info-form">
								<el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
									<el-form-item label="当前回访人">
										{{ state.orderVisitModel.employeeName }}
										<el-button plain title="智能回访录音" size="small" type="primary" class="ml8" @click="onSmartRecord" v-if="state.smartRecord"
											>智能回访录音
										</el-button>
										<el-button
											plain
											title="人工回访录音"
											size="small"
											type="primary"
											class="ml8"
											@click="recordFile"
											v-if="
												['ZiGong'].includes(themeConfig.appScope) ? state.recordingAbsolutePath && userInfos.isCenter : state.recordingAbsolutePath
											"
											>人工回访录音</el-button
										>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12" v-if="visitCount">
									<el-form-item label="当前工单已回访次数" label-width="140px"> {{ visitCount }}次 </el-form-item>
								</el-col>
								<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
									<el-form-item label="回访时间"> {{ formatDate(state.orderVisitModel.visitTime, 'YYYY-mm-dd HH:MM:SS') }} </el-form-item>
								</el-col>
								<!--								<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
									<el-form-item label="回访标签">
										<span v-if="state.ruleForm.isPutThrough !== null">{{ state.ruleForm.isPutThrough ? '已接通' : '未接通' }}</span>
									</el-form-item>
								</el-col>-->
								<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
									<el-row v-for="item in state.ruleForm.visitDetails" :key="item.id" :gutter="10">
										<!-- 务员评价 -->
										<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" v-if="['ZiGong'].includes(themeConfig.appScope) && item.visitTarget === 10">
											<el-form-item label="语音评价"> {{ item.voiceEvaluateText }} </el-form-item>
										</el-col>
										<template v-if="item.visitTarget === 10 && isTelSource">
											<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
												<el-form-item label="话务员评价">
													{{ item.seatEvaluateText }}
												</el-form-item>
											</el-col>
											<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
												<el-form-item label="话务员回访内容">
													{{ item.visitContent }}
												</el-form-item>
											</el-col>
										</template>
										<!-- 部门评价 -->
										<template v-if="item.visitTarget === 20">
											<el-divider content-position="left">
												<el-text tag="b" size="large" type="primary"> {{ item.visitOrgName }} </el-text>
											</el-divider>
											<template v-if="['YiBin'].includes(themeConfig.appScope)">
												<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
													<el-form-item label="部门是否联系">
														{{ item.isContact === null ? '' : item.isContact === true ? '是' : '否' }}
													</el-form-item>
												</el-col>
												<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
													<el-form-item label="处理结果">
														{{ item.volved === null ? '' : item.volved === true ? '已得到解决' : '未得到解决' }}
													</el-form-item>
												</el-col>
												<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" v-if="item.volveConent">
													<el-form-item label="备注" class="formatted-text mb5">
														{{ item.volveConent }}
													</el-form-item>
												</el-col>
											</template>
											<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
												<el-form-item label="部门办件结果">
													{{ item.orgProcessingResults?.dicDataName }}
												</el-form-item>
											</el-col>
											<!-- 不满意才会选择不满意原因 -->
											<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" v-if="item.orgNoSatisfiedReason && item.orgNoSatisfiedReason.length && item.orgProcessingResults?.value === '不满意'">
												<el-form-item label="不满意原因">
													{{ item.orgNoSatisfiedReason.map((item) => item.dicDataName).join(',') }}
												</el-form-item>
											</el-col>
											<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" v-if="['ZiGong'].includes(themeConfig.appScope)">
												<el-form-item label="部门办件态度">
													{{ item.orgHandledAttitude?.dicDataName }}
												</el-form-item>
											</el-col>
											<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
												<el-form-item label="部门回访内容">
													{{ item.visitContent }}
												</el-form-item>
											</el-col>
										</template>
									</el-row>
								</el-col>
								<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" v-if="state.orderVisitModel.orgJudge || state.orderVisitModel.seatJudge">
									<el-form-item label="扭转满意度">
										<el-tag v-if="state.orderVisitModel.orgJudge" class="mr10">扭转部门满意度</el-tag>
										<el-tag v-if="state.orderVisitModel.seatJudge">扭转坐席满意度</el-tag>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" v-if="state.orderVisitModel.judgeStateText">
									<el-form-item label="评判结果">
										<span>{{ state.orderVisitModel.judgeStateText }}</span>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" v-if="state.orderVisitModel.judgeContent">
									<el-form-item label="评判内容" class="formatted-text mb5">
										<span>{{ state.orderVisitModel.judgeContent }}</span>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" v-if="['ZiGong'].includes(themeConfig.appScope)">
									<el-form-item label="历史回访记录" class="w100">
										<div class="w100">
											<vxe-table
												border
												:loading="state.loading"
												:data="state.histories"
												:column-config="{ resizable: true }"
												:row-config="{ isCurrent: true, isHover: true, height: 30, useKey: true }"
												show-overflow
												:scrollY="{ enabled: true, gt: 100 }"
												max-height="300px"
											>
												<vxe-column field="voiceEvaluateTxt" title="语音评价" width="110"></vxe-column>
												<vxe-column field="seatEvaluateTxt" title="话务员评价" width="110"></vxe-column>
												<vxe-column field="visitOrgName" title="部门名称" width="140"></vxe-column>
												<vxe-column field="orgProcessingResultsValue" title="部门办件结果" width="110"></vxe-column>
												<vxe-column field="orgHandledAttitudeValue" title="部门办件态度" width="110"></vxe-column>
												<vxe-column field="visitContent" title="部门评价内容" width="110"></vxe-column>
												<vxe-column field="visitTime" title="回访时间" width="160">
													<template #default="{ row }">
														{{ formatDate(row.visitTime, 'YYYY-mm-dd HH:MM:SS') }}
													</template>
												</vxe-column>
												<vxe-column title="回访录音" fixed="right" width="90" align="center">
													<template #default="{ row }">
														<el-button link type="primary" @click="onPlayRecord(row)" title="回访录音" v-if="row.callId"> 回访录音 </el-button>
													</template>
												</vxe-column>
											</vxe-table>
										</div>
									</el-form-item>
								</el-col>
							</el-row>
						</template>
						<!-- 编辑 -->
						<template v-else>
							<el-row :gutter="10">
								<el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
									<el-form-item label="当前回访人">
										{{ userInfos.name }}
										<el-button plain title="智能回访录音" size="small" type="primary" class="ml8" @click="onSmartRecord" v-if="state.smartRecord"
											>智能回访录音
										</el-button>
										<el-button
											plain
											title="人工回访录音"
											size="small"
											type="primary"
											class="ml8"
											@click="recordFile"
											v-if="
												['ZiGong'].includes(themeConfig.appScope) ? state.recordingAbsolutePath && userInfos.isCenter : state.recordingAbsolutePath
											"
											>人工回访录音</el-button
										>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
									<el-form-item label="当前工单已回访次数" label-width="140px"> {{ visitCount }}次 </el-form-item>
								</el-col>
								<!--								<el-col :span="24">
										<el-form-item label="回访标签" prop="isPutThrough" :rules="[{ required: false, message: '请选择回访标签', trigger: 'change' }]">
											<el-checkbox v-model="state.ruleForm.isPutThrough">未接通</el-checkbox>
										</el-form-item>
									</el-col>-->
								<el-col :span="24">
									<el-row v-for="(item, index) in state.ruleForm.visitDetails" :key="item.id" :gutter="10">
										<!-- 务员评价 -->
										<template v-if="item.visitTarget === 10 && isTelSource">
											<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" v-if="['ZiGong'].includes(themeConfig.appScope)">
												<el-form-item
													label="语音评价"
													:prop="`visitDetails.${index}.voiceEvaluate`"
													:rules="[{ required: true, message: '请选择语音评价', trigger: 'change' }]"
												>
													<el-radio-group v-model="item.voiceEvaluate" disabled>
														<el-radio v-for="items in viceEvaluate" :key="items.key" :label="items.value" :value="items.key">{{
															items.value
														}}</el-radio>
													</el-radio-group>
												</el-form-item>
											</el-col>
											<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
												<el-form-item
													label="话务员评价"
													:prop="`visitDetails.${index}.seatEvaluate`"
													:rules="[{ required: true, message: '请选择话务员评价', trigger: 'change' }]"
												>
													<el-radio-group v-model="item.seatEvaluate">
														<el-radio v-for="items in seatEvaluate" :key="items.key" :label="items.value" :value="items.key">{{
															items.value
														}}</el-radio>
													</el-radio-group>
												</el-form-item>
											</el-col>
											<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
												<el-form-item
													label="话务员回访内容"
													:prop="`visitDetails.${index}.visitContent`"
													:rules="[{ required: true, message: '请填写话务员回访内容', trigger: 'blur' }]"
												>
													<common-advice
														@chooseAdvice="chooseAdvice($event, index)"
														v-model="item.visitContent"
														placeholder="请填写话务员回访内容"
														:loading="state.loading"
														:commonEnum="commonEnum.ReturnVisit"
														:minRows="5"
														:maxRows="10"
														drawerWidth="40%"
													/>
												</el-form-item>
											</el-col>
										</template>
										<!-- 部门评价 -->
										<template v-if="item.visitTarget === 20">
											<el-divider content-position="left">
												<el-text tag="b" size="large"> {{ item.visitOrgName }} </el-text>
											</el-divider>
											<template v-if="['YiBin'].includes(themeConfig.appScope)">
												<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
													<el-form-item
														label="部门是否联系"
														:prop="`visitDetails.${index}.isContact`"
														:rules="[{ required: true, message: '请选择部门是否联系', trigger: 'change' }]"
													>
														<el-radio-group v-model="item.isContact">
															<el-radio :value="true">是</el-radio>
															<el-radio :value="false">否</el-radio>
														</el-radio-group>
													</el-form-item>
												</el-col>
												<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
													<el-form-item
														label="处理结果"
														:prop="`visitDetails.${index}.volved`"
														:rules="[{ required: true, message: '请选择处理结果', trigger: 'change' }]"
													>
														<el-radio-group v-model="item.volved">
															<el-radio :value="true">已得到解决</el-radio>
															<el-radio :value="false">未得到解决</el-radio>
														</el-radio-group>
													</el-form-item>
												</el-col>
												<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" v-if="item.volved === false">
													<el-form-item
														label=""
														:prop="`visitDetails.${index}.volveConent`"
														:rules="[{ required: false, message: '请填写备注', trigger: 'blur' }]"
													>
														<common-advice
															@chooseAdvice="chooseAdvice($event, index)"
															v-model="item.volveConent"
															placeholder="请填写备注"
															:loading="state.loading"
															:commonEnum="commonEnum.ReturnVisit"
															:minRows="5"
															:maxRows="10"
															drawerWidth="40%"
														/>
													</el-form-item>
												</el-col>
											</template>
											<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
												<el-form-item
													label="部门办件结果"
													:prop="`visitDetails.${index}.orgProcessingResults`"
													:rules="[{ required: true, message: '请选择部门办件结果', trigger: 'change' }]"
												>
													<el-select
														v-model="item.orgProcessingResults"
														placeholder="请选择部门办件结果"
														class="w100"
														value-key="dicDataValue"
														@change="
															(val) => {
																item.orgProcessingResults.value = val?.dicDataName;
																item.orgProcessingResults.key = val?.dicDataValue;
																item.orgNoSatisfiedReason = [];
															}
														"
													>
														<el-option v-for="items in visitSatisfaction" :key="items.dicDataValue" :label="items.dicDataName" :value="items" />
													</el-select>
												</el-form-item>
											</el-col>
											<!-- 不满意才会选择不满意原因 -->
											<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" v-if="['1', '2'].includes(item.orgProcessingResults?.key)">
												<el-form-item
													label="不满意原因"
													:prop="`visitDetails.${index}.orgNoSatisfiedReason`"
													:rules="[{ required: true, message: '请选择不满意原因', trigger: 'change' }]"
												>
													<el-select
														v-model="item.orgNoSatisfiedReason"
														placeholder="请选择不满意原因"
														class="w100"
														value-key="dicDataValue"
														multiple
														collapse-tags
														collapse-tags-tooltip
														@change="selectReason($event, index)"
														clearable
													>
														<el-option v-for="items in dissatisfiedReason" :key="items.dicDataValue" :label="items.dicDataName" :value="items" />
													</el-select>
												</el-form-item>
											</el-col>
											<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" v-if="['ZiGong'].includes(themeConfig.appScope)">
												<el-form-item
													label="部门办件态度"
													:prop="`visitDetails.${index}.orgHandledAttitude`"
													:rules="[{ required: true, message: '请选择部门办件态度', trigger: 'change' }]"
												>
													<el-select
														v-model="item.orgHandledAttitude"
														placeholder="请选择部门办件态度"
														class="w100"
														value-key="dicDataValue"
														@change="
															(val) => {
																item.orgHandledAttitude.value = val.dicDataName;
																item.orgHandledAttitude.key = val.dicDataValue;
															}
														"
													>
														<el-option v-for="items in visitManner" :key="items.dicDataValue" :label="items.dicDataName" :value="items" />
													</el-select>
												</el-form-item>
											</el-col>
											<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
												<el-form-item
													label="部门回访内容"
													:prop="`visitDetails.${index}.visitContent`"
													:rules="[{ required: true, message: '请填写部门回访内容', trigger: 'blur' }]"
												>
													<common-advice
														@chooseAdvice="chooseAdvice($event, index)"
														v-model="item.visitContent"
														d
														placeholder="请填写部门回访内容"
														:loading="state.loading"
														:commonEnum="commonEnum.ReturnVisit"
														:minRows="5"
														:maxRows="10"
														drawerWidth="40%"
													/>
												</el-form-item>
											</el-col>
										</template>
									</el-row>
								</el-col>
								<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
									<el-form-item label="扭转满意度" prop="orgJudge" :rules="[{ required: false, message: '请选择扭转满意度', trigger: 'change' }]">
										<el-checkbox v-model="state.ruleForm.orgJudge">扭转部门满意度</el-checkbox>
										<el-checkbox v-model="state.ruleForm.seatJudge">扭转坐席满意度</el-checkbox>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" v-if="['ZiGong'].includes(themeConfig.appScope)">
									<el-form-item label="历史回访记录">
										<div class="w100">
											<vxe-table
												border
												:loading="state.loading"
												:data="state.histories"
												:column-config="{ resizable: true }"
												:row-config="{ isCurrent: true, isHover: true, height: 30, useKey: true }"
												show-overflow
												:scrollY="{ enabled: true, gt: 100 }"
												max-height="300px"
											>
												<vxe-column field="voiceEvaluateTxt" title="语音评价" width="110"></vxe-column>
												<vxe-column field="seatEvaluateTxt" title="话务员评价" width="110"></vxe-column>
												<vxe-column field="visitOrgName" title="部门名称" width="140"></vxe-column>
												<vxe-column field="orgProcessingResultsValue" title="部门办件结果" width="110"></vxe-column>
												<vxe-column field="orgHandledAttitudeValue" title="部门办件态度" width="110"></vxe-column>
												<vxe-column field="visitContent" title="部门评价内容" width="110"></vxe-column>
												<vxe-column field="visitTime" title="回访时间" width="160">
													<template #default="{ row }">
														{{ formatDate(row.visitTime, 'YYYY-mm-dd HH:MM:SS') }}
													</template>
												</vxe-column>
												<vxe-column title="回访录音" fixed="right" width="90" align="center">
													<template #default="{ row }">
														<el-button link type="primary" @click="onPlayRecord(row)" title="回访录音" v-if="row.callId"> 回访录音 </el-button>
													</template>
												</vxe-column>
											</vxe-table>
										</div>
									</el-form-item>
								</el-col>
							</el-row>
						</template>
					</el-form>
				</div>
			</el-collapse-item>
		</el-collapse>
		<template #footer v-if="disabled">
			<span class="dialog-footer">
				<el-button @click="closeDialog" class="default-button">关 闭</el-button>
			</span>
		</template>
		<template #footer v-else>
			<span class="dialog-footer">
				<el-button @click="closeDialog" class="default-button">取 消</el-button>
				<template v-if="['ZiGong', 'LuZhou'].includes(themeConfig.appScope)" v-auth="'business:visit:notConnected'">
					<el-popconfirm title="您确定将当前回访设置为未接通？" @confirm="notConnected" width="260">
						<template #reference>
							<el-button type="primary" :loading="state.loading">设为未接通</el-button>
						</template>
					</el-popconfirm>
				</template>
				<el-button
					type="primary"
					@click="onRedo"
					:loading="state.loading"
					v-auth="'business:visit:redo'"
					v-if="['ZiGong', 'LuZhou'].includes(themeConfig.appScope)"
					>重办</el-button
				>
				<el-button type="primary" @click="onSubmit(ruleFormRef)" :loading="state.loading">保存</el-button>
			</span>
		</template>
	</el-dialog>
	<!-- 播放录音 -->
	<play-record ref="playRecordRef" />
	<!-- 回访重办 -->
	<visit-redo ref="visitRedoRef" @updateList="onRedoSuccess" />
</template>
<script setup lang="tsx" name="orderFollowUpDetail">
import { computed, defineAsyncComponent, reactive, ref } from 'vue';
import { ElMessage, FormInstance } from 'element-plus';
import { commonEnum, getNowDateTime } from '@/utils/constants';
import { storeToRefs } from 'pinia';
import { useUserInfo } from '@/stores/userInfo';
import { visitDetailBaseData, visitOrder, visitSetUnconnected } from '@/api/business/visit';
import mittBus from '@/utils/mitt';
import { callCenterOutbound } from '@/utils/callCenter';
import { useThemeConfig } from '@/stores/themeConfig';
import { formatDate } from '@/utils/formatTime';
import { specialApplyBase } from '@/api/business/special';
import { submitLog } from '@/api/public/log';
import { Local } from '@/utils/storage';

// 引入组件
const CommonAdvice = defineAsyncComponent(() => import('@/components/CommonAdvice/index.vue')); // 常用意见
const PlayRecord = defineAsyncComponent(() => import('@/components/PlayRecord/index.vue')); // 播放录音
const VisitRedo = defineAsyncComponent(() => import('@/views/business/visit/components/Visit-redo.vue')); // 回访重办
// 定义子组件向父组件传值/事件
const emit = defineEmits(['updateList']);
// 定义变量内容
const state = reactive<any>({
	collapseArr: ['1', '2', '3'], // 折叠面板
	dialogVisible: false, // 是否显示弹窗
	loading: false, // 是否显示加载
	transform: 'translate(0px, 0px)', // 附件弹窗位置
	smartRecord: null,
	ruleForm: {
		visitDetails: {},
		orgJudge: false, // 扭转部门满意度
		seatJudge: false, // 扭转坐席满意度
	},
	orderDetail: {}, // 工单详情
	orderVisitModel: {}, // 回访详情
	recordingAbsolutePath: '', // 录音文件
	histories: [], //回访记录列表
});
const ruleFormRef = ref<RefType>();
const storesUserInfo = useUserInfo();
const { userInfos } = storeToRefs(storesUserInfo); // 用户信息
const visitCount = ref<number>(0); // 回访次数
const seatEvaluate = ref<EmptyArrayType>(); // 话务员评价
const viceEvaluate = ref<EmptyArrayType>(); // 语音评价
const dissatisfiedReason = ref<EmptyArrayType>(); // 不满意原因
const visitManner = ref<EmptyArrayType>(); // 部门办件态度
const visitSatisfaction = ref<EmptyArrayType>(); // 部门办件结果
const visitId = ref<string>(''); // 回访id
const dialogTitle = ref<string>('回访'); // 弹窗标题
const aiVisitVoiceBaseUrl = ref(''); // 智能回访录音前缀
const storesThemeConfig = useThemeConfig();
const { themeConfig } = storeToRefs(storesThemeConfig);
const getBaseData = async (id: string) => {
	state.loading = true;
	try {
		const { result } = await visitDetailBaseData(id);
		visitCount.value = result?.visitCount ?? 0;
		seatEvaluate.value = result?.seatEvaluate ?? [];
		viceEvaluate.value = result?.viceEvaluate ?? [];
		dissatisfiedReason.value = result?.dissatisfiedReason ?? [];
		visitManner.value = result?.visitManner ?? [];
		visitSatisfaction.value = result?.visitSatisfaction ?? [];
		visitId.value = result?.orderVisitModel?.id ?? '';
		state.orderDetail = result?.orderVisitModel?.order ?? {};
		state.orderVisitModel = result?.orderVisitModel ?? {};
		state.recordingAbsolutePath = result?.recordingAbsolutePath ?? '';
		state.smartRecord = result?.orderVisitModel.recordUrl ?? '';
		aiVisitVoiceBaseUrl.value = result.aiVisitVoiceBaseUrl;
		state.histories = result?.histories ?? []; // 回访记录列表
		/*	if (result?.orderVisitModel?.isPutThrough !== null) {
			state.ruleForm.isPutThrough = !result?.orderVisitModel?.isPutThrough ?? false;
		} else {
			state.ruleForm.isPutThrough = false;
		}*/
		state.ruleForm.visitDetails = result?.orderVisitModel?.orderVisitDetails ?? {};
		for (let i of state.ruleForm.visitDetails) {
			if (i.visitTarget === 20) {
				if (i.orgProcessingResults) {
					i.orgProcessingResults = {
						...i.orgProcessingResults,
						dicDataName: i.orgProcessingResults.value,
						dicDataValue: i.orgProcessingResults.key,
					};
				}
				if (i.orgNoSatisfiedReason) {
					i.orgNoSatisfiedReason = i.orgNoSatisfiedReason.map((item: any) => {
						return {
							...item,
							dicDataName: item.value,
							dicDataValue: item.key,
						};
					});
				} else {
					i.orgNoSatisfiedReason = [];
				}
				if (i.orgHandledAttitude) {
					i.orgHandledAttitude = {
						...i.orgHandledAttitude,
						dicDataName: i.orgHandledAttitude.value,
						dicDataValue: i.orgHandledAttitude.key,
					};
				}
			}
		}
		state.loading = false;
	} catch (error) {
		console.log(error);
		state.loading = false;
	}
};
/*const notGetThrough = ref(false);
watch(
	() => state.ruleForm.isPutThrough,
	(val) => {
		notGetThrough.value = !val;
	},
	{ immediate: true, deep: true }
);*/
// 判断当前工单是否是电话来源
const isTelSource = computed(() => {
	return state.orderDetail?.sourceChannelCode === 'RGDH';
});
// 记录日志
const submitLogFn = async (request: any) => {
	try {
		await submitLog(request);
		Local.remove('telNo');
	} catch (error) {
		console.log(`${getNowDateTime()}：日志记录失败,${error}`);
	}
};
// 打开弹窗
const callId = ref<string>('');
const openDialog = (row: any, type: string = '回访') => {
	callId.value = '';
	mittBus.on('outboundConnect', (data) => {
		console.log(data, '外呼已经接通辣');
		if (data.callNumber === state.orderDetail.contact) callId.value = data.callId;
		const request = {
			creationTime: new Date(),
			name: `回访外呼已经接通`,
			remark: JSON.stringify(data),
			executeUrl: themeConfig.value.callCenterSocketUrl,
		};
		submitLogFn(request);
	});
	if (!row.id || !row) {
		ElMessage.warning('传入回访ID不正确');
		return;
	}
	state.dialogVisible = true;
	getBaseData(row.id);
	dialogTitle.value = type;
};
const disabled = computed(() => {
	return ['回访明细', '回访详情'].includes(dialogTitle.value);
});
// 设置抽屉
const dialogRef = ref<RefType>(); // 弹窗ref
const mouseup = () => {
	state.transform = dialogRef.value.dialogContentRef.$el.style.transform;
};
// 关闭弹窗
const closeDialog = () => {
	state.dialogVisible = false;
};
// 查看人工回访录音文件
const playRecordRef = ref<RefType>();
const recordFile = () => {
	playRecordRef.value.playRecord(state.orderVisitModel.callId);
};
// 查看智能回访录音
const onSmartRecord = () => {
	playRecordRef.value.playRecordPath(aiVisitVoiceBaseUrl.value + state.smartRecord);
};
// 呼叫
const prefixOptions = ref<EmptyArrayType>([]);
const callPhone = (phoneNumber: string) => {
	let finalNumber = phoneNumber;
	// 处理加0
	if (prefixOptions.value.includes('add')) {
		finalNumber = '0' + finalNumber;
	}
	// 处理减0
	if (prefixOptions.value.includes('remove')) {
		finalNumber = finalNumber.startsWith('0') ? finalNumber.slice(1) : finalNumber;
	}
	// 移除号码中的非数字字符
	finalNumber = finalNumber.replace(/\D/g, '');
	if (['YiBin'].includes(themeConfig.value.appScope)) {
		callCenterOutbound(phoneNumber);
	} else {
		callCenterOutbound(finalNumber);
	}
};
// 选择不满意原因
const selectReason = (val: any, index: number | string) => {
	state.ruleForm.visitDetails[index].orgNoSatisfiedReason = val.map((item: any) => {
		return {
			...item,
			value: item.dicDataName,
			key: item.dicDataValue,
		};
	});
	console.log(state.ruleForm.visitDetails[index].orgNoSatisfiedReason);
};
const close = () => {
	ruleFormRef.value?.clearValidate();
	ruleFormRef.value?.resetFields();
	callId.value = '';
	mittBus.off('outboundConnect');
};
// 提交
const onSubmit = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate((valid: boolean) => {
		if (!valid) return;
		state.loading = true;
		let request = {
			...state.ruleForm,
			// isPutThrough: !state.ruleForm.isPutThrough,
			...state.visitDetails,
			id: visitId.value,
		};
		if (callId.value) {
			request.callId = callId.value;
		}
		visitOrder(request)
			.then(() => {
				ElMessage.success('操作成功');
				state.loading = false;
				closeDialog();
				emit('updateList');
			})
			.catch(() => {
				state.loading = false;
			});
	});
};
// 选中常用意见
const chooseAdvice = (item: any, index: number | string) => {
	if (state.ruleForm.visitDetails[index].visitContent === null) {
		state.ruleForm.visitDetails[index].visitContent = '';
	}
	state.ruleForm.visitDetails[index].visitContent += item.content;
};
// 重办
const visitRedoRef = ref<RefType>();
const onRedo = async () => {
	state.loading = true;
	try {
		const { result } = await specialApplyBase(state.orderDetail.workflowId);
		if (result.isTerminate) {
			ElMessage.warning('该工单已终止，无法重办');
			state.loading = false;
			return;
		}
		visitRedoRef.value.openDialog(state.orderDetail);
		state.loading = false;
	} catch (e) {
		console.log(e);
		state.loading = false;
	}
};
// 重办成功
const onRedoSuccess = () => {
	closeDialog();
	emit('updateList');
};
// 设为未接通
const notConnected = () => {
	state.loading = true;
	visitSetUnconnected({ id: visitId.value })
		.then(() => {
			state.loading = false;
			ElMessage.success('设置未接通成功');
			closeDialog();
			emit('updateList');
		})
		.catch(() => {
			state.loading = false;
		});
};
// 回访历史播放录音
const onPlayRecord = (row: any) => {
	playRecordRef.value.playRecord(row.callId);
};
defineExpose({
	openDialog,
	closeDialog,
});
</script>

<style lang="scss" scoped>
.collapse-box {
	.el-radio {
		margin-right: 10px;
	}
	:deep(.el-collapse-item__header) {
		background-color: var(--hotline-bg-main-color);
		height: 40px;
		border-radius: var(--el-border-radius-base);
	}
	:deep(.el-collapse-item__content) {
		padding-bottom: 10px !important;
	}
	.collapse-container {
		padding: 10px;
		.plug-container {
			border: var(--el-border);
			border-radius: var(--el-border-radius-base);
			margin-bottom: 15px;
			&:last-child {
				margin-bottom: 0;
			}
			.plug-container-title {
				padding: 10px 15px;
				font-weight: bold;
				border-bottom: var(--el-border);
				font-size: var(--el-font-size-medium);
			}
		}
	}
}
</style>
<style lang="scss" scoped>
.demo-tabs-form {
	.title {
		font-size: var(--el-font-size-medium);
		padding: 10px 15px 20px 15px;
	}
}
.checkbox {
	:deep(.el-checkbox) {
		margin-right: 5px;
	}
}
</style>
<style lang="scss">
.visit_dialog_no_modal {
	pointer-events: auto;
	margin: 0 !important;
	position: absolute;
	bottom: 5vh;
	left: 25%;
}
</style>
