<template>
	<el-dialog v-model="state.dialogVisible" width="50%" draggable title="录音上传">
		<el-upload
			class="upload-demo"
			v-model:file-list="fileList"
			:action="action"
			:multiple="true"
			:accept="fileTypeAccept"
			:on-exceed="handleExceed"
			ref="uploadListRef"
			name="fileData"
			:on-change="handleChangeFile"
			:on-success="updateSuccess"
			:disabled="uploadingDisabled"
			:on-error="onUploadError"
			:limit="fileLimit"
			:on-remove="handRemove"
			:before-upload="beforeUpload"
			drag
		>
			<SvgIcon name="ele-UploadFilled" size="42px" />
			<div class="el-upload__text">点击或将文件拖拽到这里上传</div>
			<template #tip>
				<div class="el-upload__tip">大小限制：20M</div>
			</template>
		</el-upload>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="closeDialog" class="default-button">取 消</el-button>
				<el-button type="primary" @click="onSave" :loading="loading">保 存</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script setup lang="ts" name="parameterAdd">
import { computed, reactive, ref } from 'vue';
import { useAppConfig } from '@/stores/appConfig';
import { storeToRefs } from 'pinia';
import { ElMessage, UploadFile, UploadFiles, UploadUserFile } from 'element-plus';
import Other from '@/utils/other';
import { uploadRecordSave } from '@/api/tels/uploadRecord';
// 定义子组件向父组件传值/事件
const emit = defineEmits(['updateList']);

// 定义变量内容
const state = reactive<any>({
	dialogVisible: false,
	ruleForm: {
		settingName: '', // 参数名称
		code: '', // 参数
		settingValue: '', // 参数值
		sort: 1, // 排序
		remark: '', // 参数说明
	},
});

const appConfigStore = useAppConfig();
const { AppConfigInfo } = storeToRefs(appConfigStore); // 系统配置信息
const fileTypeAccept = AppConfigInfo.value?.fileExt;
const action = computed(() => {
	return import.meta.env.VITE_API_UPLOAD_URL + '/file/upload?source=hotline';
	// return 'http://171.94.154.2:50105/hlfs/file/upload?source=hotline';
});

const fileList = ref<EmptyArrayType>([]);
const uploadListRef = ref<RefType>(); // 上传组件ref

// 格式化数据
const formatData = (data: any) => {
	return data.map((v: any) => {
		return {
			name: v.name,
			fileName: v.name,
			additions: v?.response?.result.id,
			path: v?.response?.result?.path,
			publicity: v?.publicity ? 1 : 0,
			classify: '录音上传',
			url: import.meta.env.VITE_API_UPLOAD_URL + v?.response?.result?.path,
			allPath: import.meta.env.VITE_API_UPLOAD_URL + v?.response?.result?.path,
		};
	});
};
// 更新数据
const transformData = ref<EmptyArrayType>([]);
const updateData = () => {
	transformData.value = formatData(Other.deepClone(fileList.value));
};

//文件限制
const fileLimit = ref(10);
const handleExceed = (files: any, uploadFiles: UploadUserFile[]) => {
	ElMessage.warning(`当前限制最多上传 ${fileLimit.value} 个文件,已经上传了${uploadFiles.length}个文件，本次选择了 ${files.length} 个文件。`);
	setTimeout(() => {
		uploadLoading.value = false; // 模拟上传过程
		uploadingDisabled.value = false;
	}, 100);
};

//限制文件大小
const handleChangeFile = (file: any, fileList: any) => {
	//限制上传文件大小
	setTimeout(() => {
		updateData();
	}, 100);
	if (!file) return;
	const isLt2M = file.size / 1024 / 1024 < 20;
	if (!isLt2M) {
		const currIdx = fileList.indexOf(file);
		fileList.splice(currIdx, 1);
		ElMessage.warning(`文件超过了最大限度 20MB!`);
		setTimeout(() => {
			uploadLoading.value = false; // 模拟上传过程
			uploadingDisabled.value = false;
		}, 100);
		return false;
	}
};
// 删除文件
const handRemove = () => {
	setTimeout(() => {
		updateData();
	}, 100);
};
// 上传失败
const onUploadError = (error: Error, uploadFile: UploadFile) => {
	try {
		const errMessage = JSON.parse(error.message)?.message ?? `文件 ${uploadFile.name} 上传失败`;
		// 从文件列表中移除失败的文件
		fileList.value = fileList.value.filter((item) => item.response);
		console.error(`文件 ${uploadFile.name} 上传失败`);
		ElMessage.error(errMessage);
	} catch (e) {
		ElMessage.error(`文件 ${uploadFile.name} 上传失败`);
	}
	setTimeout(() => {
		updateData();
		uploadLoading.value = false; // 模拟上传过程
		uploadingDisabled.value = false;
	}, 100);
};

const uploadLoading = ref(false);
const uploadingDisabled = ref(false);
const beforeUpload = () => {
	uploadLoading.value = true; // 模拟上传过程
	uploadingDisabled.value = true;
};

// 上传成功
const updateSuccess = (response: any, uploadFile: UploadFile, uploadFiles: UploadFiles) => {
	if (response.result.path) {
		fileList.value = uploadFiles;
		setTimeout(() => {
			updateData();
			uploadLoading.value = false;
			uploadingDisabled.value = false;
		}, 100);
	} else {
		uploadListRef.value.handleRemove(uploadFile);
		ElMessage.error('上传失败');
	}
};

let loading = ref<boolean>(false); // 加载状态
// 打开弹窗
const ruleFormRef = ref<RefType>();
const openDialog = async () => {
	ruleFormRef.value?.resetFields();
	try {
		state.dialogVisible = true;
	} catch (error) {
		console.log(error);
	}
};
// 关闭弹窗
const closeDialog = () => {
	state.dialogVisible = false;
};
// 保存
const onSave = () => {
	uploadRecordSave(transformData.value)
		.then(() => {
			ElMessage.success('保存成功');
			closeDialog();
			emit('updateList');
		})
		.catch((err: any) => {
			console.log(err, 'err');
			closeDialog();
		});
};
// 暴露变量
defineExpose({
	openDialog,
	closeDialog,
});
</script>
