<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 pb1">
					<el-form label-width="100px">
						<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 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 pb1">
					<el-form label-width="100px">
						<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="onCall">录音文件</el-button>
									<!-- <el-popover :width="480" trigger="hover">
                        <template #reference>
                          <el-button link type="primary" class="ml5" title="播放录音"><SvgIcon name="ele-Headset" size="16px" /></el-button>
                        </template>
                        <AudioPlayer ref="AudioPlayerRef" :url="state.ruleForm.url" />
                      </el-popover> -->
								</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.callAddress }} </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-checkbox-group v-model="checkedCities" :min="0" :max="1" class="ml10">
										<el-checkbox v-for="city in cities" :key="city.value" :label="city.value">{{ city.label }}</el-checkbox>
									</el-checkbox-group>
									<el-button plain title="呼叫" size="small" type="primary" class="ml8" @click="onCall">外呼</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 pb1">
					<el-form label-width="120px" ref="ruleFormRef" :model="state.ruleForm" label-position="left">
						<el-row :gutter="10">
							<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-button type="primary" class="ml5" title="查看回访记录" link v-if="visitCount > 0">查看回访记录</el-button>
								</el-form-item>
							</el-col>
							<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
								<el-form-item label="回访标签">
									<el-checkbox v-model="state.ruleForm.isPutThrough" :disabled="disabled">未接通</el-checkbox>
								</el-form-item>
							</el-col>
						</el-row>

						<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}.voiceEvaluate`"
										:rules="[{ required: !state.ruleForm.isPutThrough, message: '请选择语音评价', trigger: 'change' }]"
									>
										<el-radio-group v-model="item.voiceEvaluate" :disabled="disabled">
											<el-radio :label="item.key" v-for="item in viceEvaluate" :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}.seatEvaluate`"
										:rules="[{ required: !state.ruleForm.isPutThrough, message: '请选择话务员评价', trigger: 'change' }]"
									>
										<el-radio-group v-model="item.seatEvaluate" :disabled="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="话务员回访内容"
										:prop="`visitDetails.${index}.visitContent`"
										:rules="[{ required: !state.ruleForm.isPutThrough, 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%"
											:disabled="disabled"
										/>
									</el-form-item>
								</el-col>
							</template>
							<!-- 部门评价 -->
							<template v-if="item.visitTarget === 20">
								<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
									<el-divider content-position="left"
										><span class="font18 bold">{{ item.visitOrgName }}</span></el-divider
									>
								</el-col>
								<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
									<el-form-item
										label="部门办件结果"
										:prop="`visitDetails.${index}.orgProcessingResults`"
										:rules="[{ required: !state.ruleForm.isPutThrough, message: '请选择部门办件结果', trigger: 'change' }]"
									>
										<el-select
											v-model="item.orgProcessingResults"
											placeholder="请选择部门办件结果"
											class="w100"
											value-key="dicDataValue"
											:disabled="disabled"
                      @change="(val) => {
													item.orgProcessingResults.name = val.dicDataName;
													item.orgProcessingResults.id = 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">
									<el-form-item
										label="不满意原因"
										:prop="`visitDetails.${index}.orgNoSatisfiedReason`"
										:rules="[{ required: !state.ruleForm.isPutThrough, message: '请选择不满意原因', trigger: 'change' }]"
									>
										<el-select
											v-model="item.orgNoSatisfiedReason"
											placeholder="请选择不满意原因"
											class="w100"
											value-key="dicDataValue"
											:disabled="disabled"
                      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: !state.ruleForm.isPutThrough, message: '请选择部门办件态度', trigger: 'change' }]"
									>
										<el-select
											v-model="item.orgHandledAttitude"
											placeholder="请选择部门办件态度"
											class="w100"
											value-key="dicDataValue"
											:disabled="disabled"
                      @change="(val) => {
													item.orgHandledAttitude.name = val.dicDataName;
													item.orgHandledAttitude.id = 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: !state.ruleForm.isPutThrough, 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%"
											:disabled="disabled"
										/>
									</el-form-item>
								</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="onCancel" class="default-button">关 闭</el-button>
			</span>
		</template>
		<template #footer v-else>
			<span class="dialog-footer">
				<el-button @click="onCancel" class="default-button">取 消</el-button>
				<el-button type="primary" @click="onSubmit(ruleFormRef)" :loading="state.loading">保存</el-button>
			</span>
		</template>
	</el-dialog>
</template>
<script setup lang="ts" name="orderFollowUpDetail">
import { computed, defineAsyncComponent, reactive, ref } from 'vue';
import { ElMessage, FormInstance } from 'element-plus';
import { VoiceInterfaceObject } from '/@/utils/PhoneScript';
import { commonEnum } from '/@/utils/constants';
import { visitDetailBaseData } from '/@/api/business/followUp';
import { storeToRefs } from 'pinia';
import { useUserInfo } from '/@/stores/userInfo';
import { formatDate } from '/@/utils/formatTime';
import { visitOrder } from '/@/api/business/followUp';

const storesUserInfo = useUserInfo();
const { userInfos } = storeToRefs(storesUserInfo); // 用户信息
// 引入组件
const CommonAdvice = defineAsyncComponent(() => import('/@/components/CommonAdvice/index.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: {}, // 工单详情
});
const ruleFormRef = ref<RefType>();
const checkedCities = ref([]);
const cities = [
	{ label: '加0', value: '+0' },
	{ label: '去0', value: '-0' },
];
const againCount = ref<number>(0); // 重办次数
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) => {
	try {
		const res = await visitDetailBaseData(id);
		againCount.value = res.result?.againCount ?? 0;
		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.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.name,
            dicDataValue: i.orgProcessingResults.id
          }
        }
        if(i.orgNoSatisfiedReason){
          i.orgNoSatisfiedReason = i.orgNoSatisfiedReason.map((item:any)=>{
            return {
              ...item,
              dicDataName: item.name,
              dicDataValue: item.id
            }
          });
        }else{
          i.orgNoSatisfiedReason = [];
        }
        if(i.orgHandledAttitude){
          i.orgHandledAttitude= {
            ...i.orgHandledAttitude,
            dicDataName: i.orgHandledAttitude.name,
            dicDataValue: i.orgHandledAttitude.id
          }
        }
      }
    }
	} catch (error) {
		console.log(error);
	}
};
// 打开弹窗
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;
	state.ruleForm = {};
};
// 取消
const onCancel = () => {
	closeDialog();
};
// 呼叫
const dialOut = (phoneNumber: string) => {
	VoiceInterfaceObject.DialOut(phoneNumber);
};
const onCall = () => {
	if (checkedCities.value && checkedCities.value.length > 0) {
		let phoneNumber = state.orderDetail.fromPhone;
		if (checkedCities.value[0] === '+0') {
			// 呼叫外部电话 +0
			dialOut('0' + phoneNumber);
		} else if (checkedCities.value[0] === '-0') {
			// 去掉电话号码的第一个字符如果它是'0'
			phoneNumber = phoneNumber.charAt(0) === '0' ? phoneNumber.substring(1) : phoneNumber;
			dialOut(phoneNumber);
		}
	} else {
		// 呼叫外部电话
		dialOut(state.orderDetail.fromPhone);
	}
};
// 选择不满意原因
const selectReason = (val:any,index:number|string)=>{
  state.ruleForm.visitDetails[index].orgNoSatisfiedReason = val.map((item:any)=>{
    return {
      ...item,
      name: item.dicDataName,
      id: 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;
	}
	.el-form-item {
		margin-bottom: 0 !important;
	}
}
</style>
