<template>
	<el-dialog v-model="state.dialogVisible" :title="dialogTitle" draggable ref="dialogRef" width="50%" append-to-body destroy-on-close @close="close">
		<el-form :model="state.ruleForm" ref="ruleFormRef" label-width="110px">
			<el-row :gutter="10">
				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
					<el-form-item label="工单编码："> {{ state.orderDetail.no }} </el-form-item>
				</el-col>
				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
					<el-form-item label="来电号码：">
						{{ state.orderDetail.fromPhone }}
						<el-button
							plain
							title="工单录音文件"
							v-if="state.orderDetail.recordingFileUrl"
							size="small"
							type="primary"
							class="ml8"
							@click="recordFile(state.orderDetail.recordingFileUrl)"
							>工单录音</el-button
						>
						<el-button
							plain
							title="回访录音文件"
							v-if="state.visit.recordingFileUrl"
							size="small"
							type="primary"
							class="ml8"
							@click="recordFile(state.visit.recordingFileUrl)"
							>回访录音</el-button
						>
					</el-form-item>
				</el-col>
				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
					<el-form-item label="受理人：">
						<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="12" :md="12" :lg="12" :xl="12">
					<el-form-item label="受理时间："> {{ formatDate(state.orderDetail?.startTime, 'YYYY-mm-dd HH:MM:SS') }} </el-form-item>
				</el-col>
			</el-row>
			<el-divider content-position="left">
				<el-text tag="b" size="large"> 质检内容 </el-text>
			</el-divider>
			<div class="mt20 mb20">
				<el-button type="primary" class="mb10" @click="onAddItem">新增扣分项</el-button>
				<!-- 表格 -->
				<el-table :data="tableData" border row-key="name">
					<el-table-column label="扣分时间点" show-overflow-tooltip align="center">
						<template #default="{ row }">
							{{ formatDuration(row.second, false) }}
						</template>
					</el-table-column>
					<el-table-column prop="name" label="扣分项" show-overflow-tooltip align="center"></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)"> 编辑 </el-button>
							<el-button link type="primary" @click="onDeleteItem(row)"> 删除 </el-button>
						</template>
					</el-table-column>
				</el-table>
			</div>
			<el-row :gutter="10">
				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
					<el-form-item label="总分："> 100 分 </el-form-item>
				</el-col>
				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
					<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: true, 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>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="closeDialog" class="default-button">取 消</el-button>
				<el-button type="primary" @click="onSubmit(ruleFormRef)" v-waves="'light'" :loading="state.loading">确 定 </el-button>
			</span>
		</template>
	</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="value" :rules="[{ required: true, message: '请输入扣分时间点', trigger: 'change' }]">
				<el-time-picker
					v-model="state.ruleItemForm.value"
					placeholder="请选择扣分时间点"
					@change="selectSecond"
					value-format="mm:ss"
					format="mm:ss"
					:picker-options="{
						selectableRange: '00:00:00 - 00:59:59',
					}"
					popper-class="noneMinute"
				/>
			</el-form-item>
			<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 { computed, defineAsyncComponent, reactive, ref, watch } from 'vue';
import { ElInput, 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 } from '/@/api/quality';

// 引入组件
const PlayRecord = defineAsyncComponent(() => import('/@/views/tels/callLog/component/Play-record.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, // 来源
});
const dialogTitle = ref<string>('受理质检');
const dialogTitleItem = ref<string>('新增扣分项');
const projectArray = ref<EmptyArrayType>([]); // 质检项数组
const tableData = ref<EmptyArrayType>([]); // 表格数据
const qualityId = ref<string>(''); // 质检ID
// 打开弹窗
const openDialog = async (row: any, source?: string | number | undefined) => {
	qualityId.value = row.id;
	if (source) {
		state.source = source;
		const [temRes, qualityRes] = await Promise.all([
			templateList({ IsEnable: 1, Grouping: source, PageIndex: 1, PageSize: 999 }),
			qualityDetail(row.id),
		]);
		projectArray.value = temRes.result?.items[0]?.templateDetails ?? [];
		tableData.value = qualityRes.result?.qualityDetails ?? [];
		console.log(qualityRes, '123', tableData.value);
		state.orderDetail = qualityRes.result?.order ?? {};
		state.visit = qualityRes.result?.visit ?? {};
		switch (source) {
			case 1:
				dialogTitle.value = '受理质检';
				break;
			case 2:
				dialogTitle.value = '派单质检';
				break;
			case 3:
				dialogTitle.value = '回访质检';
				break;
		}
	}

	state.dialogVisible = true;
};
// 计算当前得分
const score = computed(() => {
	let score = 0;
	if (tableData.value.length) {
		tableData.value.forEach((v: any) => {
			score += v.grade;
		});
	}
	return 100 - score;
});
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 recordFile = (url: string) => {
	playRecordRef.value.openDialog(url);
};
// 新增质检项内容
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);
	state.dialogVisibleItem = true;
	getEnableAcceptType();
};
// 分秒计算成秒
const formatSecond = (val: string) => {
	if (!val) return 0;
	const minute = Number(val.split(':')[0]);
	const second = Number(val.split(':')[1]);
	return minute * 60 + second;
};
// 选择扣分时间点
const selectSecond = (val: any) => {
	state.ruleItemForm.second = formatSecond(val);
};
// 扣分项保存
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);
			getEnableAcceptType();
		})
		.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);
		});
	}
};
// 保存
const onSubmit = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate((valid: boolean) => {
		if (!valid) return;
		state.loading = true;
		const request = {
			orderId: state.orderDetail.id, // 工单id
			mode: '人工质检', // 质检模式
			grade: score.value, // 质检得分
			content: state.ruleForm.content, // 质检评价
			source: state.source, // 来源
			qualityDetails: tableData.value, // 质检详情
			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>
