<template>
	<el-dialog
		v-model="state.dialogVisible"
		draggable
		:title="dialogTitle"
		ref="dialogRef"
		width="50%"
		append-to-body
		@mouseup="mouseup"
		:style="'transform: ' + state.transform + ';'"
		@close="close"
	>
		<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>{{ dayjs(state.orderDetail.startTime).format('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 v-if="state.orderDetail?.acceptorStaffNo">[{{ state.orderDetail?.acceptorStaffNo }}]</span></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="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="mb5"> {{ state.orderDetail.actualOpinion }} </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">
								<el-form-item label="来电号码" class="mb5">
									{{ state.orderDetail.fromPhone }}
									<el-button
										plain
										title="录音文件"
										size="small"
										type="primary"
										class="ml8"
										@click="recordFile(state.recordingFileUrl)"
										v-if="state.recordingFileUrl"
										>录音文件</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="onCall(state.orderDetail.contact)">外呼</el-button>
								</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">
						<el-row :gutter="10">
							<!-- 详情 -->
							<template v-if="disabled">
								<el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
									<el-form-item label="当前回访人">
										{{ state.orderVisitModel.employeeName }}
									</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="回访标签">
										<span v-if="state.ruleForm.isPutThrough !== null">{{ state.ruleForm.isPutThrough ? '已接通' : '未接通' }}</span>
									</el-form-item>
								</el-col>
								<el-row v-for="item in state.ruleForm.visitDetails" :key="item.id" :gutter="10">
									<!-- 务员评价 -->
									<template v-if="item.visitTarget === 10">
										<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
											<el-form-item label="话务员评价">
												<el-radio-group v-model="item.seatEvaluate" disabled>
													<el-radio :label="item.key" v-for="item in seatEvaluate" :key="item.key">{{ item.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="话务员回访内容">
												{{ 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"> {{ item.visitOrgName }} </el-text>
										</el-divider>
										<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">
											<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">
											<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>
							</template>
							<!-- 编辑 -->
							<template v-else>
								<el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
									<el-form-item label="当前回访人">
										{{ userInfos.name }}
									</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">
											<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
												<el-form-item
													label="话务员评价"
													:prop="`visitDetails.${index}.seatEvaluate`"
													:rules="[{ required: notGetThrough, message: '请选择话务员评价', trigger: 'change' }]"
												>
													<el-radio-group v-model="item.seatEvaluate">
														<el-radio :label="item.key" v-for="item in seatEvaluate" :key="item.key">{{ item.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: notGetThrough, message: '请填写话务员回访内容', trigger: 'blur' }]"
												>
													<common-advice
														@chooseAdvice="chooseAdvice($event, index)"
														v-model="item.visitContent"
														placeholder="请填写话务员回访内容"
														:loading="state.loading"
														:commonEnum="commonEnum.Seat"
														: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>
											<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
												<el-form-item
													label="部门办件结果"
													:prop="`visitDetails.${index}.orgProcessingResults`"
													:rules="[{ required: notGetThrough, 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;
															}
														"
													>
														<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="12" :xl="12" v-if="['1', '2'].includes(item.orgProcessingResults?.key)">
												<el-form-item
													label="不满意原因"
													:prop="`visitDetails.${index}.orgNoSatisfiedReason`"
													:rules="[{ required: notGetThrough, 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)"
													>
														<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">
												<el-form-item
													label="部门办件态度"
													:prop="`visitDetails.${index}.orgHandledAttitude`"
													:rules="[{ required: notGetThrough, 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 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="24" :xl="24">
												<el-form-item
													label="部门回访内容"
													:prop="`visitDetails.${index}.visitContent`"
													:rules="[{ required: notGetThrough, message: '请填写部门回访内容', trigger: 'blur' }]"
												>
													<common-advice
														@chooseAdvice="chooseAdvice($event, index)"
														v-model="item.visitContent"
														placeholder="请填写部门回访内容"
														:loading="state.loading"
														:commonEnum="commonEnum.Seat"
														:minRows="5"
														:maxRows="10"
														drawerWidth="40%"
													/>
												</el-form-item>
											</el-col>
										</template>
									</el-row>
								</el-col>
							</template>
						</el-row>
					</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>
				<el-button type="primary" @click="onSubmit(ruleFormRef)" :loading="state.loading">保存</el-button>
			</span>
		</template>
	</el-dialog>
	<!-- 播放录音 -->
	<play-record ref="playRecordRef" />
</template>
<script setup lang="ts" name="orderFollowUpDetail">
import { computed, defineAsyncComponent, reactive, ref, watch } from 'vue';
import { ElButton, ElMessage, FormInstance } from 'element-plus';
import { commonEnum } from '@/utils/constants';
import { storeToRefs } from 'pinia';
import { useUserInfo } from '@/stores/userInfo';
import { ola } from '@/utils/ola_api';
import dayjs from 'dayjs';
import { visitDetailBaseData, visitOrder } from '@/api/business/visit';

// 引入组件
const CommonAdvice = defineAsyncComponent(() => import('@/components/CommonAdvice/index.vue')); // 常用意见
const PlayRecord = defineAsyncComponent(() => import('@/views/tels/callLog/component/Play-record.vue')); // 播放录音
// 定义子组件向父组件传值/事件
const emit = defineEmits(['updateList']);
// 定义变量内容
const state = reactive<any>({
	collapseArr: ['1', '2', '3'], // 折叠面板
	dialogVisible: false, // 是否显示弹窗
	loading: false, // 是否显示加载
	transform: 'translate(0px, 0px)', // 附件弹窗位置
	ruleForm: {
		isPutThrough: false, //未接通
		visitDetails: {},
	},
	orderDetail: {}, // 工单详情
	orderVisitModel: {}, // 回访详情
	recordingFileUrl: '', // 录音文件
});
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 getBaseData = async (id: string) => {
	state.loading = true;
	try {
		const res = await visitDetailBaseData(id);
		visitCount.value = res.result?.visitCount ?? 0;
		seatEvaluate.value = res.result?.seatEvaluate ?? [];
		viceEvaluate.value = res.result?.viceEvaluate ?? [];
		dissatisfiedReason.value = res.result?.dissatisfiedReason ?? [];
		visitManner.value = res.result?.visitManner ?? [];
		visitSatisfaction.value = res.result?.visitSatisfaction ?? [];
		visitId.value = res.result?.orderVisitModel?.id ?? '';
		state.orderDetail = res.result?.orderVisitModel?.order ?? {};
		state.orderVisitModel = res.result?.orderVisitModel ?? {};
		state.recordingFileUrl = res.result?.recordingFileUrl ?? '';
		if (res.result?.orderVisitModel?.isPutThrough !== null) {
			state.ruleForm.isPutThrough = !res.result?.orderVisitModel?.isPutThrough ?? false;
		} else {
			state.ruleForm.isPutThrough = false;
		}
		state.ruleForm.visitDetails = res.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 openDialog = (row: any, type: string = '回访') => {
	getBaseData(row.id);
	dialogTitle.value = type;
	state.dialogVisible = true;
};
const disabled = computed(() => {
	return 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 = (url: string) => {
	playRecordRef.value.openDialog(url);
};
// 呼叫
const onCall = (phoneNumber: string) => {
	ola.dial(phoneNumber);
};
// 选择不满意原因
const selectReason = (val: any, index: number | string) => {
	state.ruleForm.visitDetails[index].orgNoSatisfiedReason = val.map((item: any) => {
		return {
			...item,
			value: item.dicDataName,
			key: item.dicDataValue,
		};
	});
};
const close = () => {
	ruleFormRef.value?.clearValidate();
	ruleFormRef.value?.resetFields();
};
// 提交
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,
		};
		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;
};
defineExpose({
	openDialog,
	closeDialog,
});
</script>

<style lang="scss" scoped>
.collapse-box {
	: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">
.demo-tabs-form {
	.title {
		font-size: var(--el-font-size-medium);
		padding: 10px 15px 20px 15px;
	}
}
</style>
