<template>
	<vxe-toolbar
		ref="toolbarRef"
		:loading="state.loading"
		:refresh="{
			queryMethod: queryList,
		}"
	>
		<template #buttons>
			<el-button type="primary" @click="onUpload" v-auth="'buseiness:order:supplyFiles'">补传附件</el-button>
			<el-button type="primary" @click="onDownloadBatch" :disabled="isChecked" v-auth="'buseiness:order:downloadBatch'"
				>批量下载<span v-if="checkTable.length">({{ checkTable.length }})</span></el-button
			>
		</template>
	</vxe-toolbar>
	<vxe-table
		border
		:loading="state.loading"
		:data="state.tableData"
		:column-config="{ resizable: true }"
		:row-config="{ isCurrent: true, isHover: true, height: 30, useKey: true }"
		ref="tableRef"
		show-overflow
		:scrollY="{ enabled: true, gt: 100 }"
		:max-height="500"
		@checkbox-all="selectAllChangeEvent"
		@checkbox-change="selectChangeEvent"
	>
		<vxe-column type="checkbox" width="60" align="center"></vxe-column>
		<vxe-column field="name" title="附件名称"></vxe-column>
		<vxe-column field="type" title="附件类型"></vxe-column>
		<vxe-column field="stepName" title="所在节点"></vxe-column>
		<vxe-column field="userName" title="上传人"></vxe-column>
		<vxe-column field="creationTime" title="上传时间" width="160">
			<template #default="{ row }">
				{{ formatDate(row.creationTime, 'YYYY-mm-dd HH:MM:SS') }}
			</template>
		</vxe-column>
		<vxe-column title="操作" fixed="right" width="120" align="center">
			<template #default="{ row }">
				<el-button link type="primary" @click="onDownload(row)" title="下载" v-auth="'buseiness:order:file:download'"> 下载 </el-button>
				<el-button link type="primary" @click="onPreview(row)" title="预览" v-auth="'buseiness:order:file:preview'"> 预览 </el-button>
			</template>
		</vxe-column>
	</vxe-table>
	<el-dialog v-model="state.dialogVisible" draggable title="补传附件" destroy-on-close append-to-body @close="close" width="600px">
		<el-form :model="state.ruleForm" ref="ruleFormRef" label-width="110px" :disabled="state.dialogLoading">
			<el-form-item label="补传节点" prop="stepId" :rules="[{ required: true, message: '请选择补传节点', trigger: 'change' }]">
				<el-select v-model="state.ruleForm.stepId" placeholder="请选择补传节点" class="w100" clearable value-key="id" @change="selectStepId">
					<el-option v-for="item in traces" :key="item.id" :label="item.name" :value="item.id" />
				</el-select>
			</el-form-item>
			<el-form-item label="已有附件">
				<div class="w100">
					<div v-for="item in stepFiles" :key="item.id">
						<div class="flex-center-between w100">
							<p style="flex: 1" class="text-no-wrap" :title="item.fileName">{{ item.fileName }}</p>
							<div style="width: 100px; text-align: right">
								<el-button type="primary" link @click="onPreview(item)">预览</el-button>
								<el-button type="danger" link @click="onDelete(item)">删除</el-button>
							</div>
						</div>
					</div>
				</div>
			</el-form-item>
			<el-form-item label="补传附件" prop="files" :rules="[{ required: false, message: '请上传补传附件', trigger: 'change' }]">
				<annex-list :businessId="state.ruleForm.id" classify="办理上传" v-model="state.ruleForm.files" v-model:format="filesFormat" />
			</el-form-item>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="closeDialog" class="default-button">取 消</el-button>
				<el-button type="primary" @click="onSubmit(ruleFormRef)" :loading="state.dialogLoading">保 存</el-button>
			</span>
		</template>
	</el-dialog>
</template>
<script setup lang="ts" name="orderDetailFileList">
import { reactive, ref, onMounted, computed, defineAsyncComponent } from 'vue';
import { throttle } from '@/utils/tools';
import { orderAttachment, orderAttachmentAdd, orderStepAttachment } from '@/api/business/order';
import { formatDate } from '@/utils/formatTime';
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus';
import { fileDownloadBatch, fileDownloadByUrl } from '@/api/public/file';

const AnnexList = defineAsyncComponent(() => import('@/components/AnnexList/index.vue')); // 附件列表

const props = defineProps({
	orderId: {
		type: String,
		default: '',
	},
	workflowId: {
		type: String,
		default: '',
	},
});
const state = reactive<any>({
	tableData: [], // 附件
	loading: false,
	dialogVisible: false,
	dialogLoading: false,
	ruleForm: {
		files: [],
		stepId: null,
		orderId: null,
	},
});
/** 获取列表 */
const queryList = throttle(async () => {
	state.loading = true;
	try {
		const { result } = await orderAttachment(props.orderId);
		state.tableData = result;
		state.loading = false;
		tableRef.value?.clearCheckboxRow();
		checkTable.value = [];
	} catch (error: any) {
		console.log(error);
		state.loading = false;
	}
}, 300);
// 下载
const onDownload = (row: any) => {
	const id = row.additions;
	if (!id) {
		ElMessage.error('附件不存在');
		return;
	}
	// 确定是否下载
	ElMessageBox.confirm(`确定要下载附件 ${row.fileName} 吗？`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
	})
		.then(() => {
			fileDownloadByUrl({
				Source: 'hotline',
				Id: row.additions,
			}).then((res: any) => {
				let blob: Blob = new Blob([res.data], { type: res.data.type }); // 创建blob 设置blob文件类型 data 设置为后端返回的文件(例如mp3,jpeg) type:这里设置后端返回的类型 为 mp3
				let down: HTMLAnchorElement = document.createElement('a'); // 创建A标签
				let href: string = window.URL.createObjectURL(blob); // 创建下载的链接
				down.href = href; // 下载地址
				down.download = row.fileName; // 下载文件名
				document.body.appendChild(down);
				down.click(); // 模拟点击A标签
				document.body.removeChild(down); // 下载完成移除元素
				window.URL.revokeObjectURL(href); // 释放blob对象
			});
		})
		.catch(() => {});
};
// 预览
const onPreview = (row: any) => {
	const path = row.path;
	if (!path) {
		ElMessage.error('附件不存在');
		return;
	}
	// 判断后缀是图片 不是图片提示不支持预览
	if (
		![
			'jpg',
			'jpeg',
			'png',
			'gif',
			'bmp',
			'tiff',
			'tif',
			'webp',
			'heif',
			'heic',
			'svg',
			'ai',
			'eps',
			'JPG',
			'JPEG',
			'PNG',
			'GIF',
			'BMP',
			'TIFF',
			'TIF',
			'WEBP',
			'HEIF',
			'HEIC',
			'SVG',
			'AI',
			'EPS',
		].includes(row.type)
	) {
		ElMessage.warning('仅支持图片预览');
		return;
	}
	// 确定是否下载
	const url = import.meta.env.VITE_API_UPLOAD_URL + path;
	window.open(url);
};

// 批量下载
const onDownloadBatch = () => {
	const ids = checkTable.value.map((item) => item.additions);
	// 确定是否下载
	ElMessageBox.confirm(`确定要批量下载选中的附件？`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
	})
		.then(() => {
			fileDownloadBatch({
				Source: 'hotline',
				ids,
			}).then((res: any) => {
				let blob: Blob = new Blob([res.data], { type: res.data.type }); // 创建blob 设置blob文件类型 data 设置为后端返回的文件(例如mp3,jpeg) type:这里设置后端返回的类型 为 mp3
				let down: HTMLAnchorElement = document.createElement('a'); // 创建A标签
				let href: string = window.URL.createObjectURL(blob); // 创建下载的链接
				down.href = href; // 下载地址
				// 时间戳+文件名
				down.download = new Date().getTime() + '附件.zip'; // 下载文件名
				document.body.appendChild(down);
				down.click(); // 模拟点击A标签
				document.body.removeChild(down); // 下载完成移除元素
				window.URL.revokeObjectURL(href); // 释放blob对象
				queryList();
			});
		})
		.catch(() => {});
};
const toolbarRef = ref<RefType>();
const tableRef = ref<RefType>();
const checkTable = ref<EmptyArrayType>([]);
const selectAllChangeEvent = ({ checked }) => {
	if (tableRef.value) {
		const records = tableRef.value.getCheckboxRecords();
		checkTable.value = records;
		console.log(checked ? '所有勾选事件' : '所有取消事件', records);
	}
};

const selectChangeEvent = ({ checked }) => {
	if (tableRef.value) {
		const records = tableRef.value.getCheckboxRecords();
		checkTable.value = records;
		console.log(checked ? '勾选事件' : '取消事件', records);
	}
};
const isChecked = computed(() => {
	return !checkTable.value.length;
});
// 上传
const traces = ref<EmptyArrayType>([]); // 补充节点
const onUpload = () => {
	if (!props.workflowId) {
		ElMessage.warning('工单暂未开启流程，无法补传附件');
		return;
	}
	state.dialogVisible = true;
	state.dialogLoading = true;
	orderStepAttachment(props.workflowId)
		.then((res) => {
			traces.value = res.result.traces;
			state.dialogLoading = false;
		})
		.catch(() => {
			state.dialogLoading = false;
		});
};
const filesFormat = ref<EmptyArrayType>([]); // 附件列表格式化
const stepFiles = ref<EmptyArrayType>([]); // 节点附件
// 选择补传节点
const selectStepId = (val: any) => {
	stepFiles.value = [];
	if (val) {
		const item = traces.value.find((item) => item.id === val);
		if (item.files) {
			stepFiles.value = item.files;
		} else {
			stepFiles.value = [];
		}
	}
};
const ruleFormRef = ref<RefType>();
// 关闭补传附件
const closeDialog = () => {
	state.dialogVisible = false;
};
// 删除
const onDelete = (row: any) => {
	// 确定是否下载
	ElMessageBox.confirm(`确定要删除附件 ${row.fileName} 吗？`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
	})
		.then(() => {
			// 删除本地附件
			stepFiles.value = stepFiles.value.filter((item: any) => item.additions != row.additions);
		})
		.catch(() => {});
};
const close = () => {
	ruleFormRef.value?.resetFields();
	ruleFormRef.value?.resetFields();
	stepFiles.value = [];
	traces.value = [];
};
// 保存
const onSubmit = throttle(async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate((valid: boolean) => {
		if (!valid) return;
		state.dialogLoading = true;
		const files = stepFiles.value.concat(filesFormat.value);
		const request = {
			orderId: props.orderId,
			stepId: state.ruleForm.stepId,
			files,
		};
		orderAttachmentAdd(request)
			.then(() => {
				ElMessage({
					message: '修改成功',
					type: 'success',
				});
				state.dialogLoading = false;
				closeDialog();
				queryList();
			})
			.catch(() => {
				queryList();
				// 新增失败
				state.dialogLoading = false;
				closeDialog();
			});
	});
}, 300);
onMounted(() => {
	queryList();
	if (tableRef.value && toolbarRef.value) {
		tableRef.value.connect(toolbarRef.value);
	}
});
</script>
