<template>
	<div class="">
		<div>
			<a-upload-dragger
				v-model:fileList="fileList"
				name="file"
				:maxCount="1"
				:customRequest="uploadFile"
				@drop="handleDrop"
				:disabled="disabled || (progressType && fileData.progress != 100)"
				accept=".jpeg,.jpg,.png,.tiff,.psd,.ai,.mp4,.avi,.mov,.wmv,.pdf,.ppt,.obj.fbx"
			>
				<p class="ant-upload-drag-icon">
					<inbox-outlined></inbox-outlined>
				</p>
				<p class="ant-upload-text" style="font-size: 14px">点击或拖拽上传{{ name }}（{{ name }}上传限制500M）</p>
				<template #itemRender="{ file, actions }">
					<div class="flex-box">
						<a-tooltip placement="topLeft" :title="file.name">
							<span class="flex-name" :style="file.status === 'error' ? 'color: red' : ''" @click="downLoadUrl">{{ file.name }}</span>
						</a-tooltip>
						<DeleteOutlined @click="removeUrl" />
					</div>
				</template>
			</a-upload-dragger>
		</div>
		<div>
			<a-progress style="width: 313px" v-if="progressType" :percent="fileData.progress" />
		</div>
	</div>
</template>

<script setup lang="ts">
import { InboxOutlined, DeleteOutlined } from '@ant-design/icons-vue';
import { onMounted, reactive, ref, watch } from 'vue';
import OSS from 'ali-oss';
import { nanoid } from 'nanoid';
import { getSsoUrl } from '@/api/system';
import { message } from 'ant-design-vue';
const emits = defineEmits(['uploadFileDown', 'removeUrl', 'changeType']);
const ossData = reactive({
	accessKeyId: '',
	accessKeySecret: '',
	securityToken: '',
});
let ossClient;
const progressType = ref(false);
let fileData = reactive({
	progress: 0,
	fileNam: '',
	fileSize: 0,
	materialUrl: '',
});
const props = defineProps({
	//oss文件夹名称
	packageName: {
		type: String,
		default: '',
	},
	//拖拽上传名
	name: {
		type: String,
		default: '',
	},
	//是否禁用
	disabled: {
		type: Boolean,
		default: false,
	},
	fileData: {
		type: String,
		default: '',
	},
	fileType: {
		type: String,
		default: '',
	},
	fileUrl: {
		type: String,
		default: '',
	},
});
const fileList = ref([]);
let ossFileName = ref('');
// watch(() => props.fileType, (newValue, oldValue) => {
//   if (oldValue) {
//     removeUrl()
//   }
// })
watch(
	() => props.fileData,
	(newValue) => {
		if (newValue && !progressType.value) {
			fileList.value[0] = {
				name: newValue,
			};
		}
	}
);
//限制上传格式
const beforeUpload = async (file_) => {
	// if (!props.fileType) {
	//   message.error(`请选择${props.name}类型`)
	//   fileList.value = [];
	//   return false
	// }
	const accept = '.jpeg,.jpg,.png,.tiff,.psd,.ai,.mp4,.avi,.mov,.wmv,.pdf,.ppt,.obj.fbx';
	const accept1 = '.jpeg,.jpg,.png,.tiff,.psd,.ai,';
	const accept2 = '.mp4,.avi,.mov,.wmv,';
	const file = file_;
	const fileType = file?.name.split('.');
	const fileDate = fileType.slice(-1);
	// if (props.fileType == '1') {
	const docsArr = accept?.split(',');
	if (!docsArr?.includes(`.${fileDate[0]}`)) {
		message.error(`仅支持文件格式：${accept}格式附件!`);
		fileList.value = [];
		return false;
	}
	// } else if (props.fileType == '2') {
	//   const docsArr = accept2?.split(",");
	//   if (!docsArr?.includes(`.${fileDate[0]}`)) {
	//     message.error(`视频仅支持文件格式：${accept2}格式附件!`);
	//     fileList.value = [];
	//     return false;
	//   }
	// }
	const isLt2M = file.size / 1024 / 1024 < 500;
	if (!isLt2M) {
		message.error(`${props.name}大小不能超过500MB!`);
		fileList.value = [];
		return false;
	}
	return true;
};
//覆盖默认上传
const uploadFile = async (option) => {
	let type = await beforeUpload(option.file);
	if (!type) {
		return;
	}
	let res = await upload(option.file);
	if (res.res.status == 200) {
		message.success('上传成功！');
		fileData.fileSize = option.file.size;
		fileData.fileNam = option.file.name;
		fileData.materialUrl = res.res.requestUrls[0].split('?')[0];
		emits('uploadFileDown', {
			fileSize: fileData.fileSize,
			fileName: fileData.fileNam,
			filrUrl: ossFileName.value,
		});
	} else {
		message.success('上传失败！');
	}
};
const ossSystem = [
	{
		endPoint: 'oss-cn-shanghai.aliyuncs.com',
		region: 'oss-cn-shanghai',
		bucket: 'siyu-dq',
		secure: false,
	},
	{
		endPoint: 'oss-cn-hangzhou.aliyuncs.com',
		region: 'oss-cn-hangzhou',
		bucket: 'wlgg',
		secure: true,
	},
];
const ossIndex = 0;
//获取oss临时上传
async function getOSSUrl() {
	progressType.value = false;
	await getSsoUrl({}).then((res: any) => {
		if (res.code == 200) {
			ossData.accessKeyId = res.data.accessKeyId;
			ossData.accessKeySecret = res.data.accessKeySecret;
			ossData.securityToken = res.data.securityToken;
			ossClient = new OSS({
				endPoint: ossSystem[ossIndex].endPoint,
				region: ossSystem[ossIndex].region, // 为存储空间对应的地域域名，根据你的实际情况填写，如https://oss-cn-hangzhou.aliyuncs.com
				accessKeyId: ossData.accessKeyId, //  你的阿里云accessKeyId
				accessKeySecret: ossData.accessKeySecret, //  临时token  accessKeySecret: credentials.accessKeySecret,  //  你的阿里云accessKeySecret
				stsToken: ossData.securityToken,
				bucket: ossSystem[ossIndex].bucket, //  oss存储桶的名称
				// secure: ossSystem[ossIndex].secure, //http是false，https是true
				secure: true,
			});
		}
	});
}
//oss切片上传
async function upload(file) {
	await getOSSUrl();
	const uuid = nanoid();
	const index = file.name.lastIndexOf('.');
	const suffix = file.name.substring(index + 1);
	ossFileName.value = props.packageName + '/' + uuid + '.' + suffix;
	fileData.progress = 0;
	return ossClient.multipartUpload(ossFileName.value, file, {
		progress: function (p) {
			if (p == 0) {
				progressType.value = true;
				emits('changeType', true);
			}
			if (p !== 1) {
				fileData.progress = Math.ceil(p * 100);
			} else {
				fileData.progress = 100;
				emits('changeType', false);
			}
		},
		partSize: 20 * 1024 * 1024,
	});
}
async function downLoadUrl() {
	if (progressType.value && fileData.progress != 100) {
		return;
	}
	await getOSSUrl();
	let url = ossClient.signatureUrl(props.fileUrl, {
		response: {
			'content-disposition': 'attachment; filename="' + props.fileData + '"',
		},
		expires: 3600,
	});
	window.open(url);
}
//拖拽
function handleDrop(e) {
	console.log(e);
}
//删除
function removeUrl() {
	if (!props.disabled) {
		progressType.value = false;
		fileData.progress = 0;
		fileList.value = [];
		emits('removeUrl');
	}
}
</script>

<style lang="scss" scoped>
.flex-name {
	width: 250px;
	white-space: nowrap;
	/* 确保文本在一行内显示 */
	overflow: hidden;
	/* 隐藏溢出的内容 */
	text-overflow: ellipsis;
	/* 使用省略号表示文字被截断 */
	cursor: pointer;
}

.flex-box {
	padding-top: 4px;
	display: flex;
	justify-content: space-between;
}
</style>
