<template>
	<el-dialog
		v-model="state.dialogVisible"
		:title="dialogTitle"
		draggable
		ref="dialogRef"
		width="50%"
		append-to-body
		destroy-on-close
		@close="close"
		@opened="opened"
	>
		<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="
											['ZiGong'].includes(themeConfig.appScope)
												? state.orderDetail?.recordingAbsolutePath && userInfos.isCenter
												: state.orderDetail?.recordingAbsolutePath
										"
							size="small"
							type="primary"
							class="ml8"
							@click="recordFile(state.ruleForm?.order, 'order')"
							>工单录音</el-button
						>
						<el-button
							plain
							title="回访录音文件"
							v-if="state.ruleForm?.visit?.recordingAbsolutePath"
							size="small"
							type="primary"
							class="ml8"
							@click="recordFile(state.ruleForm?.visit, 'visit')"
							>回访录音</el-button
						>
					</el-form-item>
				</el-col>
				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
					<el-form-item label="受理人："> {{ state.orderDetail?.acceptorName }}</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" v-if="!viewMode">新增扣分项</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" :selectable="selectable" />
					<el-table-column label="开始扣分时间点" show-overflow-tooltip align="center" min-width="120">
						<template #default="{ row }">
							{{ formatDuration(row.second, false, true) }}
						</template>
					</el-table-column>
					<el-table-column label="结束扣分时间点" show-overflow-tooltip align="center" min-width="120">
						<template #default="{ row }">
							{{ formatDuration(row.endSecond, false, true) }}
						</template>
					</el-table-column>
					<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" v-if="!viewMode">
						<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="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: false, message: '请填写质检评价', trigger: 'blur' }]">
						<el-input
							v-model="state.ruleForm.content"
							placeholder="请填写质检评价"
							clearable
							type="textarea"
							:autosize="{ minRows: 4, maxRows: 8 }"
							:disabled="viewMode"
						></el-input>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<template #footer>
			<span class="dialog-footer" v-if="!viewMode">
				<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: false, message: '请选择开始扣分时间点', trigger: 'change' }]"
				label-width="140px"
			>
				<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="endValue"
				:rules="[{ required: false, message: '请选择结束扣分时间点', trigger: 'change' }]"
				label-width="140px"
			>
				<el-time-picker
					v-model="state.ruleItemForm.endValue"
					placeholder="请选择结束扣分时间点"
					@change="selectSecondEnd"
					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 { reactive, ref, watch, defineAsyncComponent } from 'vue';
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus';
import { formatDate, formatDuration } from '@/utils/formatTime';
import Other from '@/utils/other';
import { qualityUpdate, qualityDetail } from '@/api/quality';
import { templateList } from '@/api/quality/template';
import { useThemeConfig } from '@/stores/themeConfig';
import { storeToRefs } from 'pinia';
import { useUserInfo } from '@/stores/userInfo';

// 引入组件
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: {},
	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 viewMode = ref<boolean>(false); // 是否查看
// 打开弹窗
const openDialog = async (row: any, source: string | number | undefined, isView?: boolean) => {
	score.value = 100;
	try {
		const { result } = await qualityDetail(row.id);
		state.ruleForm = result ?? {};
		tableData.value = result.qualityDetails ?? [];
		multipleSelection.value = tableData.value.filter((v: any) => v.check === true);
		state.orderDetail = row.order ?? {};
		qualityId.value = row.id;
		state.source = source;
		viewMode.value = isView ?? false;
		const response = await templateList({ IsEnable: 1, Grouping: source, PageIndex: 1, PageSize: 1000 });
		projectArray.value = response.result?.items[0]?.templateDetails ?? [];
		switch (source) {
			case 1:
				dialogTitle.value = viewMode.value ? '查看受理质检' : '编辑受理质检';
				break;
			case 2:
				dialogTitle.value = viewMode.value ? '查看派单质检' : '编辑派单质检';
				break;
			case 3:
				dialogTitle.value = viewMode.value ? '查看回访质检' : '编辑回访质检';
				break;
		}
		state.dialogVisible = true;
	} 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 selectable = () => {
	return !viewMode.value;
};
// 计算当前得分
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 recordFile = (obj: any, type: string) => {
	switch (type) {
		case 'order':
			playRecordRef.value.playRecord(obj.callId);
			break;
		case 'visit':
			playRecordRef.value.playRecord(themeConfig.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 formatSecond = (val: string) => {
	if (!val) return 0;
	const minute = Number(val.split(':')[0]);
	const second = Number(val.split(':')[1]);
	return (minute * 60 + second) * 1000;
};
// 选择开始扣分时间点
const selectSecond = (val: any) => {
	state.ruleItemForm.second = formatSecond(val);
};
// 选择结束扣分时间点
const selectSecondEnd = (val: any) => {
	state.ruleItemForm.endSecond = 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);
		});
	} else {
		projectArray.value.forEach((v: any) => {
			v.disabled = 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>
