<template>
	<view class="upload-container">
		<view @click="chooseAndUploadFile" class="upload-button">+ 上传文件</view>
		<view v-for="(item, index) in internalFileList" :key="index" class="files-list">
			<view class="file-name">{{ item.file.name }}</view>
			<view class="delete-btn" @click="deleteFile(index)">删除</view>
		</view>
	</view>
</template>

<script>
//	import {
//		uploadImg
//	} from '@/api/company'
	// import config from '@/config'
import config from '@/utilsRc/config.js'
import { getToken } from "@/utilsRc/auth";
	//import {
	//	getToken
	//} from '@/utils/auth'
	export default {
		props: {
			maxSize: {
				type: Number,
				default: 5, // 最大文件大小（MB）
			},
			allowedFormats: {
				type: Array,
				default: () => ['.png', '.jpg', '.jpeg', '.doc', '.docx', '.pdf', '.xls', '.xlsx'], // 允许的文件格式
			},
			maxImageSize: {
				type: Object,
				default: () => ({
					width: 2048,
					height: 2048
				}), // 图片最大宽度和高度
			},
			width: {
				type: String,
				default: '100rpx', // 默认宽度
			},
			height: {
				type: String,
				default: '100rpx', // 默认高度
			},
			name: {
				type: String,
				default: 'file', // 默认name字段
			},
			multiple: {
				type: Boolean,
				default: false, // 是否允许多选，默认不允许
			},
			maxCount: {
				type: Number,
				default: 1, // 默认最大上传数量为1
			},
			fileList: {
				type: Array,
				default: () => [], // 默认的文件列表为空
			},
			disabled: {
				type: Boolean,
				default: false
			}

		},
		data() {
			return {
				internalFileList: [...this.fileList], // 内部的文件列表，确保与父组件的同步
			};
		},
		watch: {
			// 监听 fileList 的变化，确保内外部数据同步
			fileList(newVal) {
				this.internalFileList = [...newVal];
			},
		},
		methods: {
			deleteFile(index){
				this.internalFileList.splice(index, 1);
			},
			chooseAndUploadFile() {
				wx.chooseMessageFile({
					count: this.maxCount,
					extension: this.allowedFormats,
					// ['.png', '.jpg', '.jpeg', '.doc', '.docx', '.pdf', '.xls', '.xlsx' ],
					success: (res) => { 
						console.log('选择文件成功:', res);
						if(this.maxCount - this.internalFileList.length < res.tempFiles.length){
							uni.showToast({
								title: '最多只能上传' + this.maxCount + '个文件',
								icon: 'none'
							});
							return;
						}

						let path = "";
							const twoMBInBytes = 2 * 1024 * 1024; // 2MB转换为字节数
							res.tempFiles.forEach((file) => {

								if (file.size > twoMBInBytes) {
									uni.showToast({
										title: "图片大小不能超过2MB",
										icon: "none",
									});
									return;
								}
								if (res.tempFiles && res.tempFiles.length > 0) {
									path = file.path;
									if (this.allowedFormats.indexOf('.'+path.split(".")[1])!=-1) {
										uni.showLoading();
										const tempFilePath = file;
										uni.uploadFile({
											url: config.baseUrl+'/system/oss/upload', //图片上传地址
											filePath: tempFilePath.path,
											name: 'file',
											formData: {},
											header: {
												'Authorization': 'Bearer ' + getToken(),
											},
											success: (res) => {
												var data = JSON.parse(res.data);
												console.log(data, 'sdfjiosdjfoi')
												if(data.code==200) {
													this.internalFileList.push({
														url: data.data.url,
														file: file
													})
													this.$emit('update', this.internalFileList);
													// this.serviceForm.fileUrl = this.internalFileList.map(item => item.url).join(',')
													this.$forceUpdate()
													uni.hideLoading();
												} else {
													uni.hideLoading();
													uni.showToast({
														title: res.msg || '上传失败',
														icon: 'none',
														duration: 2000
													});
												}
											},
											fail: (error) => {
												uni.showToast({
													title: '上传失败',
													icon: 'none'
												});
												console.error(error);
											}
										})
									} else {
										uni.showToast({
											icon: "none",
											duration: 1500,
											title: `只能选择${this.allowedFormats.join('、')}格式文件`,
										});
									}
								}
							})



						// // 添加新选择的图片到列表
						// res.tempFiles.forEach((item, index) => {
						//   this.fileList.push({
						//     url: item.path,
						//     file: res.tempFiles[index]
						//   });
						// });
						// 更新 serviceForm.fileUrl
						// this.updateFileUrls();
					},
					fail: (err) => {
						console.error('选择图片失败:', err);
					}
				});
    
			},
			// 新增图片
			async handleAfterRead(event) {
				let lists = [].concat(event.file);
				let fileListLen = this.internalFileList.length;
				lists.map((item) => {
					this.internalFileList.push({
						...item,
						status: "uploading",
						message: "上传中",
					});
				});
				for (let i = 0; i < lists.length; i++) {
					if (this.allowedFormats.length > 0) {
						let fileType = lists[i].name.split('.').pop().toLowerCase();
						if (!this.allowedFormats.includes(fileType)) {
							// this.$emit('error', '不支持的文件格式');
							uni.showToast({
								title: '不支持的文件格式',
								icon: 'none',
							});
							this.internalFileList.splice(fileListLen, 1);
							this.$emit('update', this.internalFileList); // 通知父组件文件列表更新
							return;
						}
					}
					const result = await this.uploadFilePromise(lists[i].url);
					let item = this.internalFileList[fileListLen];
					this.internalFileList.splice(
						fileListLen,
						1,
						Object.assign(item, {
							status: "success",
							message: "",
							data: result,
						})
					);
					fileListLen++;
					this.$emit('update', this.internalFileList); // 通知父组件文件列表更新
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					uni.uploadFile({
						url: config.baseUrl + '/system/oss/upload',
						filePath: url,
						name: "file",
						header: {
							Authorization: "Bearer " + getToken(),
						},
						success: (uploadFileRes) => {
							let res = JSON.parse(uploadFileRes.data);
							resolve(res.data);
						},
						fail: (err) => {
							console.log(err);
						},
					});
				});
			},
			handleRemove({file, index}) {
				this.internalFileList.splice(index, 1); // 从文件列表中移除指定文件
				this.$emit('update', this.internalFileList); // 通知父组件文件列表更新
			},
		},
	};
</script>

<style scoped lang="scss">
	.upload-container {
	}
	.files-list {
		display: flex;
		justify-content: space-between;
		margin-top: 10rpx;
		line-height: 50rpx;
		.file-name{
			width: calc(100% - 80rpx);
			overflow: hidden;
			white-space: nowrap;
			text-overflow: ellipsis;
		}
		.delete-btn{
			width: 80rpx;
			text-align: right;
			color: red;
		}
	}

	.upload-slot {
		display: flex;
		align-items: center;
		justify-content: center;
		border: 1px dashed #ccc;
		border-radius: 4px;
		padding: 20px;
	}
	.upload-button {
		border: 1px dashed #ccc;
		border-radius: 4px;
		padding: 0 24rpx;
		width: 280rpx;
		text-align: center;
		background: #fff;
		line-height: 64rpx;
	}
</style>
