<template>
	<el-dialog
		v-model="state.dialogVisible"
		:title="dialogTitle"
		draggable
		ref="dialogRef"
		width="90%"
		append-to-body
		destroy-on-close
		@close="close"
		@opened="opened"
	>
		<splitpanes Vertical>
			<pane min-size="60" max-size="60" size="60" style="max-height: calc(84vh - 111px); overflow-y: auto">
				<p class="border-title mb10">工单详情</p>
				<el-form :model="state.orderDetail" label-width="90px" v-loading="state.loading" class="show-info-form">
					<el-row :gutter="10">
						<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
							<el-form-item label="工单编码">
								{{ state.orderDetail.no }}
								<span v-if="state.orderDetail.password && userInfos.isCenter" class="ml5">({{ state.orderDetail.password }})</span>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8" v-if="state.orderDetail.receiveProvinceNo">
							<el-form-item label="省编码"> {{ state.orderDetail.receiveProvinceNo }} </el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
							<el-form-item label="来源方式"> {{ state.orderDetail.sourceChannel }} </el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
							<el-form-item label="转接来源"> {{ state.orderDetail.transferPhone }} </el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
							<el-form-item label="来电人"> {{ state.orderDetail.fromName }} </el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
							<el-form-item label="性别"> {{ state.orderDetail.fromGenderText }} </el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
							<el-form-item label="来电号码">
								{{ state.orderDetail.fromPhone }}
								<el-button
									plain
									title="工单录音文件"
									v-if="
										['ZiGong'].includes(themeConfig.appScope)
											? state.orderDetail?.recordingAbsolutePath && userInfos.isCenter
											: state.orderDetail?.recordingAbsolutePath
									"
									size="small"
									type="primary"
									class="ml8"
									@click="recordFile(state.orderDetail, 'order')"
									>工单录音</el-button
								>
								<el-button
									plain
									title="回访录音文件"
									v-if="state.visit.recordingAbsolutePath"
									size="small"
									type="primary"
									class="ml8"
									@click="recordFile(state.visit, 'visit')"
									>回访录音</el-button
								></el-form-item
							>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
							<el-form-item label="联系电话"> {{ state.orderDetail.contact }} </el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
							<el-form-item label="受理类型"> {{ state.orderDetail.acceptType }} </el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
							<el-form-item label="办理时限"> {{ state.orderDetail.timeLimit }} </el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
							<el-form-item label="热点分类"> {{ state.orderDetail.hotspotSpliceName }} </el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
							<el-form-item label="受理人"> {{ state.orderDetail.acceptorName }} </el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
							<el-form-item label="受理时间"> {{ formatDate(state.orderDetail.startTime, 'YYYY-mm-dd HH:MM:SS') }} </el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
							<el-form-item label="来电人主体"> {{ state.orderDetail.identityTypeText }} </el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
							<el-form-item label="推送分类"> {{ state.orderDetail.pushType }} </el-form-item>
						</el-col>
						<el-col>
							<el-form-item label="事发地址"> {{ state.orderDetail.fullAddress }} </el-form-item>
						</el-col>
						<el-col>
							<el-form-item label="工单标题" class="formatted-text mb5"> {{ state.orderDetail.title }} </el-form-item>
						</el-col>
						<el-col>
							<el-form-item label="受理内容" class="formatted-text mb5"> {{ state.orderDetail.content }} </el-form-item>
						</el-col>
						<el-col>
							<el-form-item label="承办意见" class="formatted-text mb5"> {{ state.orderDetail.fileOpinion }} </el-form-item>
						</el-col>
					</el-row>
				</el-form>
				<!-- 受理质检才有质检录音撰写 -->
				<template v-if="state.source === 1">
					<p class="border-title mb10 mt20">录音转写</p>
					<!-- 未转写 -->
					<template v-if="!state.qualityDetail.transferState">
						<el-empty description="无录音转写内容" :image-size="100" style="padding: 0">
							<el-button type="primary" @click="onTransfer" v-auth="'quality:index:transfer'">录音转写</el-button>
						</el-empty>
					</template>
					<!-- 转写中 -->
					<el-empty description="录音转写中，请稍后" :image-size="100" style="padding: 0" v-if="state.qualityDetail.transferState === 1"> </el-empty>
					<!-- 转写完成 -->
					<template v-if="state.qualityDetail.transferState === 2">
						<template v-if="transformContent && transformContent.length">
              <template v-if="editMode">
                <el-scrollbar class="transfer-content" v-loading="contentLoading">
                  <div v-for="(item, index) in transformContent" :key="index" class="transfer-content-item">
                    <div>
										<span>{{ item.type === 0 ? '坐席：' : '市民：' }}</span
                    ><el-input v-model="item.reviseContent"></el-input>
                    </div>
                  </div>
                </el-scrollbar>
                <el-button type="primary" @click="saveTransferContent" class="ml20">保存并应用</el-button>
              </template>
              <template v-else>
                <el-scrollbar class="transfer-content" v-loading="contentLoading">
                  <div v-for="(item, index) in transformContent" :key="index" class="transfer-content-item">
                    <div>
                      <span>{{ item.type === 0 ? '坐席：' : '市民：' }}</span>
                      <div v-html="showKeyWord(item.reviseContent, item.prohibited)" class="formatted-text"></div>
                    </div>
                  </div>
                </el-scrollbar>
                <el-button type="primary" @click="editTransferContent" class="ml20" v-auth="'quality:index:transfer:edit'">编辑转写内容</el-button>
              </template>
            </template>
            <el-empty description="无录音转写内容" :image-size="100" style="padding: 0" v-else>
            </el-empty>
					</template>
					<!-- 转写失败 -->
					<template v-if="state.qualityDetail.transferState === 3">
						<el-empty description="录音转写失败" :image-size="100" style="padding: 0"> </el-empty>
					</template>
				</template>
			</pane>
			<pane style="max-height: calc(84vh - 111px); overflow-y: auto">
				<p class="border-title">质检</p>
				<el-form :model="state.ruleForm" ref="ruleFormRef" label-width="110px" v-loading="state.loading">
					<div class="mt20 mb20">
						<el-button type="primary" class="mb10" @click="onAddItem">新增质检项</el-button>
						<!-- 表格 -->
						<el-table :data="tableData" border row-key="name" ref="multipleTableRef" @selection-change="handleSelectionChange">
							<el-table-column type="selection" width="55" align="center" :reserve-selection="true" />
							<el-table-column prop="name" label="质检项" show-overflow-tooltip align="center"></el-table-column>
							<el-table-column label="质检类型" show-overflow-tooltip align="center">
								<template #default="{ row }">
									<span> {{ row.intelligent ? '智能质检' : '人工质检' }}</span>
								</template>
							</el-table-column>
							<el-table-column prop="content" label="质检内容" show-overflow-tooltip align="center"></el-table-column>
							<el-table-column prop="grade" label="分值(分)" show-overflow-tooltip align="center"></el-table-column>
							<el-table-column label="操作" width="120" fixed="right" align="center">
								<template #default="{ row }">
									<!-- 智能质检不能编辑就和删除 -->
									<el-button link type="primary" @click="onEditItem(row)" v-if="!row.intelligent"> 编辑 </el-button>
									<el-button link type="primary" @click="onDeleteItem(row)" v-if="!row.intelligent"> 删除 </el-button>
								</template>
							</el-table-column>
						</el-table>
					</div>
					<el-row :gutter="10">
						<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
							<el-form-item label="总分："> 100 分 </el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
							<el-form-item label="当前质检得分："> {{ score }} </el-form-item>
						</el-col>
						<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
							<el-form-item label="质检评价：" prop="content" :rules="[{ required: false, message: '请填写质检评价', trigger: 'blur' }]">
								<el-input
									v-model="state.ruleForm.content"
									placeholder="请填写质检评价"
									clearable
									type="textarea"
									:autosize="{ minRows: 4, maxRows: 8 }"
								></el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</el-form>
				<div class="flex-end">
					<el-button @click="closeDialog" class="default-button">取 消</el-button>
					<el-button type="primary" @click="onSubmit(ruleFormRef)" v-waves="'light'" :loading="state.loading">确 定 </el-button>
				</div>
			</pane>
		</splitpanes>
	</el-dialog>
	<el-dialog
		v-model="state.dialogVisibleItem"
		:title="dialogTitleItem"
		draggable
		ref="dialogItemRef"
		width="600px"
		append-to-body
		destroy-on-close
		@close="closeItem"
	>
		<el-form :model="state.ruleItemForm" ref="ruleItemFormRef" label-width="100px">
			<el-form-item label="质检项" prop="name" :rules="[{ required: true, message: '请选择质检项', trigger: 'change' }]">
				<el-select v-model="state.ruleItemForm.name" placeholder="请选择质检项" class="w100" @change="changeProject">
					<el-option v-for="item in projectArray" :key="item.id" :label="item.name" :value="item.name" :disabled="item.disabled" />
				</el-select>
			</el-form-item>
			<el-form-item label="分值" prop="grade" :rules="[{ required: true, message: '请填写分值', trigger: 'blur' }]">
				<el-input-number v-model="state.ruleItemForm.grade" :precision="0" :min="1" :max="100" placeholder="请填写分值" />
				<span class="ml10">分</span>
			</el-form-item>
			<el-form-item label="质检内容" prop="content" :rules="[{ required: false, message: '请填写质检内容', trigger: 'blur' }]">
				<el-input v-model="state.ruleItemForm.content" placeholder="请填写质检内容" type="textarea" :autosize="{ minRows: 4, maxRows: 8 }"></el-input>
			</el-form-item>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="state.dialogVisibleItem = false" class="default-button">取 消</el-button>
				<el-button type="primary" @click="onSubmitItem(ruleItemFormRef)" v-waves="'light'" :loading="state.loading">确 定 </el-button>
			</span>
		</template>
	</el-dialog>
	<!-- 播放录音 -->
	<play-record ref="playRecordRef" />
</template>
<script setup lang="ts" name="qualityInspection">
import { defineAsyncComponent, reactive, ref, watch } from 'vue';
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus';
import { formatDate, formatDuration } from '@/utils/formatTime';
import { templateList } from '@/api/quality/template';
import Other from '@/utils/other';
import { qualityUpdate, qualityDetail, qualityRecordTransfer, qualityContentUpdate } from '@/api/quality';
import { useThemeConfig } from '@/stores/themeConfig';
import { storeToRefs } from 'pinia';
import { useUserInfo } from '@/stores/userInfo';
import { Splitpanes, Pane } from 'splitpanes';
import 'splitpanes/dist/splitpanes.css';
import { useAppConfig } from '@/stores/appConfig';

// 引入组件
const PlayRecord = defineAsyncComponent(() => import('@/components/PlayRecord/index.vue')); // 播放录音
// 定义子组件向父组件传值/事件
const emit = defineEmits(['updateList']);
const state = reactive<any>({
	dialogVisible: false, // 弹窗显示隐藏
	ruleForm: {
		name: '', // 违禁词
		classify: '', // 违禁词分类
		type: '', // 违禁词属性
	},
	loading: false, // 确定按钮loading
	orderDetail: {}, // 工单详情
	visit: {}, // 回访详情
	dialogVisibleItem: false,
	ruleItemForm: {
		second: 0,
		name: '', // 质检时间点
		grade: 1, // 分值
		content: '', // 质检内容
	},
	source: 1, // 来源
	qualityDetail: {},
});
const dialogTitle = ref<string>('受理质检');
const dialogTitleItem = ref<string>('新增质检项');
const projectArray = ref<EmptyArrayType>([]); // 质检项数组
const tableData = ref<EmptyArrayType>([]); // 表格数据
const qualityId = ref<string>(''); // 质检ID
// 打开弹窗
const openDialog = (row: any, source?: string | number | undefined) => {
	qualityId.value = row.id;
	state.source = source;
	score.value = 100;
	state.loading = true;
	state.dialogVisible = true;
	getQualityDetail(row.id, source);
};
// 转写内容
const transformContent = ref<EmptyArrayType>([]);
// 编辑模式
const editMode = ref<boolean>(false);
// 获取质检详情
const getQualityDetail = async (id: string, source?: string | number | undefined) => {
	try {
		if (source) {
			state.source = source;
			const [temRes, qualityRes] = await Promise.all([
				templateList({ IsEnable: 1, Grouping: source, PageIndex: 1, PageSize: 999 }),
				qualityDetail(id),
			]);
			projectArray.value = temRes.result?.items[0]?.templateDetails ?? [];
			state.qualityDetail = qualityRes.result;
			tableData.value = qualityRes.result?.qualityDetails ?? [];
			multipleSelection.value = tableData.value.filter((v: any) => v.check === true);
			state.orderDetail = qualityRes.result?.order ?? {};
			state.visit = qualityRes.result?.visit ?? {};
			transformContent.value = Other.deepClone(qualityRes.result.transfer);
			state.loading = false;
			switch (source) {
				case 1:
					dialogTitle.value = '受理质检';
					break;
				case 2:
					dialogTitle.value = '派单质检';
					break;
				case 3:
					dialogTitle.value = '回访质检';
					break;
			}
		}
	} catch (e) {
		console.log(e);
	}
};
const opened = () => {
	// 回显选中表格
	if (state.dialogVisible) {
		multipleSelection.value.forEach((v: any) => {
			multipleTableRef.value?.toggleRowSelection(v, true);
		});
	}
};
// 表格多选
const multipleTableRef = ref<RefType>();
const multipleSelection = ref<EmptyArrayType>([]);
const handleSelectionChange = (val: any[]) => {
	multipleSelection.value = val;
	multipleSelection.value.forEach((v: any) => {
		v.check = true;
	});
};
// 计算当前得分
const score = ref(100);
watch(
	() => multipleSelection.value,
	(newVal) => {
		let total = 100;
		for (let i of newVal) {
			total -= i.grade;
		}
		score.value = total;
	}
);
watch(
	() => score.value,
	(newVal) => {
		if (newVal <= 0) {
			ElMessage.warning('质检得分不能小于0分');
		}
	}
);
// 关闭弹窗
const closeDialog = () => {
	state.dialogVisible = false;
};
const ruleFormRef = ref<FormInstance>();
const close = () => {
	ruleFormRef.value?.clearValidate();
	ruleFormRef.value?.resetFields();
};
const closeItem = () => {
	ruleItemFormRef.value?.clearValidate();
	ruleItemFormRef.value?.resetFields();
};
// 查看录音文件
const playRecordRef = ref<RefType>();
const storesThemeConfig = useThemeConfig();
const { themeConfig } = storeToRefs(storesThemeConfig);
const storesUserInfo = useUserInfo();
const { userInfos } = storeToRefs(storesUserInfo); // 用户信息
const appConfigStore = useAppConfig();
const { AppConfigInfo } = storeToRefs(appConfigStore); // 系统配置信息
const recordFile = (obj: any, type: string) => {
	switch (type) {
		case 'order':
			playRecordRef.value.playRecord(obj.callId);
			break;
		case 'visit':
			playRecordRef.value.playRecord(AppConfigInfo.value.recordPrefix + obj.recordingAbsolutePath);
			break;
	}
};
// 新增质检项内容
const onAddItem = () => {
	dialogTitleItem.value = '新增质检项';
	state.ruleItemForm = {
		second: 0,
		name: '', // 质检时间点
		grade: 1, // 分值
		content: '', // 质检内容
	};
	state.dialogVisibleItem = true;
	getEnableAcceptType();
};
// 选择质检项
const changeProject = (val: any) => {
	const item = projectArray.value.filter((v: any) => v.name === val)[0];
	state.ruleItemForm.grade = item.grade;
	state.ruleItemForm.content = item.content;
	getEnableAcceptType();
};
// 编辑质检内容
const onEditItem = (row: any) => {
	dialogTitleItem.value = '编辑质检项';
	state.ruleItemForm = Other.deepClone(row);
	state.ruleItemForm.value = formatDuration(state.ruleItemForm.second, false, true);
	state.ruleItemForm.endValue = formatDuration(state.ruleItemForm.endSecond, false, true);
	state.dialogVisibleItem = true;
	getEnableAcceptType();
};
// 质检项保存
const ruleItemFormRef = ref<RefType>();
const onSubmitItem = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate((valid: boolean) => {
		if (!valid) return;
		state.loading = true;
		if (dialogTitleItem.value === '新增质检项') {
			const data = Other.deepClone(state.ruleItemForm);
			tableData.value.push(data);
			state.loading = false;
			state.dialogVisibleItem = false;
		} else {
			const newArray = <EmptyArrayType>[];
			for (let i of tableData.value) {
				if (i.name === state.ruleItemForm.name) {
					newArray.push({
						...i,
						...state.ruleItemForm,
					});
				} else {
					newArray.push(i);
				}
			}
			tableData.value = newArray;
			state.loading = false;
			state.dialogVisibleItem = false;
		}
	});
};
// 删除质检项内容
const onDeleteItem = (row: any) => {
	ElMessageBox.confirm(`您确定要删除：【${row.name}】质检项，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			tableData.value = tableData.value.filter((v: any) => v.name !== row.name);
			setTimeout(() => {
				getEnableAcceptType();
			}, 100);
		})
		.catch(() => {});
};
// 获取可用的数组
const getEnableAcceptType = () => {
	if (tableData.value.length) {
		const array = tableData.value.map((v: any) => v.name);
		projectArray.value.forEach((v: any) => {
			v.disabled = array.includes(v.name);
		});
	} else {
		projectArray.value.forEach((v: any) => {
			v.disabled = false;
		});
	}
};
// 录音转写
const onTransfer = () => {
  ElMessageBox.confirm(`您确定要创建录音转写任务，是否继续?`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
    draggable: true,
    cancelButtonClass: 'default-button',
    autofocus: false,
  })
      .then(() => {
        state.loading = true;
        qualityRecordTransfer([{ id: qualityId.value }])
            .then(() => {
              ElMessage.success('转写任务创建成功');
              getQualityDetail(qualityId.value, state.source);
              emit('updateList');
            })
            .catch((err) => {
              console.log(err);
            });
      })
      .catch(() => {});
};
// 高亮关键词
const showKeyWord = (val: string[], keywordString: string) => {
	if (!keywordString) return val;
	const keywordArr = keywordString.split(',');
	let str: any = val;
	if (keywordArr && keywordArr.length) {
		// 2.定制关键词对应正则
		keywordArr.forEach((e) => {
			let regStr = '' + `(${e})`;
			let reg = new RegExp(regStr, 'g');
			// 3.正则替换，关键词飘红
			str = str.replace(reg, '<span class="color-danger font-bold"">' + e + '</span>');
		});
	}
	return str;
};
// 编辑转写内容
const editTransferContent = () => {
	editMode.value = !editMode.value;
};
// 修改录音转写内容保存
const contentLoading = ref(false);
const saveTransferContent = () => {
	const request = {
		id: qualityId.value,
		transfer: transformContent.value,
	};
  contentLoading.value = true;
	qualityContentUpdate(request)
		.then(() => {
			ElMessage.success('保存成功');
			editMode.value = !editMode.value;
      contentLoading.value = false;
		})
		.catch((err) => {
			console.log(err);
      contentLoading.value = false;
		});
};
// 保存
const onSubmit = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate((valid: boolean) => {
		if (!valid) return;
		if (score.value <= 0) {
			ElMessage.warning('质检得分不能小于0分');
			return;
		}
		const qualityDetails = tableData.value.map((v: any) => {
			return {
				...v,
				check: multipleSelection.value.includes(v),
			};
		});
		state.loading = true;
		const request = {
			orderId: state.orderDetail.id, // 工单id
			mode: '人工质检', // 质检模式
			grade: score.value, // 质检得分
			content: state.ruleForm.content, // 质检评价
			source: state.source, // 来源
			qualityDetails: qualityDetails, // 质检详情
			id: qualityId.value, // 质检id
		};
		qualityUpdate(request)
			.then(() => {
				ElMessage.success('质检成功');
				emit('updateList');
				state.loading = false;
				state.dialogVisible = false;
			})
			.catch(() => {
				state.loading = false;
				state.dialogVisible = false;
				emit('updateList');
			});
	});
};
defineExpose({
	openDialog,
	closeDialog,
});
</script>
<style scoped lang="scss">
.transfer-content {
	border: var(--el-border);
	padding: 10px;
	margin: 10px 20px;
	max-height: 300px;
	overflow: auto;
	&-item {
		margin-bottom: 5px;
		div {
			display: flex;
			align-items: center;
			width: 100%;
			span {
				width: 50px;
			}
		}
		&:last-child {
			margin-bottom: 0;
		}
	}
}
</style>
