index.vue 8.44 KB
<template>
	<view class="upload-image-box">
		<!-- <view class="upload-image-box-choose">
			<text class="upload-image-box-choose-txt">请选着上传图片类型:</text>
			<view class="upload-image-box-choose-type">
				<u-radio-group v-model="putType" @change="groupChange" placement="row">
					<u-radio activeColor="#19be6b" :customStyle="{ marginBottom: '8px' }" size="28" labelSize="28"
						v-for="(item, index) in chooseList" :key="index" :label="item.name" :name="item.name"
						@change="radioChange">
					</u-radio>
				</u-radio-group>
			</view>
		</view> -->
		<view class="upload-image-box-bottom">
			<text class="upload-image-box-bottom-txt">{{ putType }}(最多上传10张)</text>
			<view class="upload-image-box-button-container">
				<u-upload :fileList="fileList" @afterRead="afterRead" @delete="deletePic" name="3" multiple
					:maxCount="10" :previewFullImage="true" width="200" height="150"></u-upload>
			</view>
		</view>
		<view class="upload-image-box-submit-box">
			<view class="upload-image-box-submit-box-button" @click="handleSubmit(orderId, putType,driver,carPlate)">
				<view class="upload-image-box-submit-box-button-container">
					<up-button color="#19be6b" type="primary" shape="square" text="确定"></up-button>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		uploadFilePromise
	} from '@/apis/common.js';
  import {
    uploadImageUrlByType,
    queryLatitudeLongitude
  } from '@/apis/order.js';
	import {
		onLoad
	} from '@dcloudio/uni-app';
	import {
		reactive,
		ref,
		onMounted
	} from 'vue';
	import {
		useMainStore
	} from '@/stores/index.js';
	const store = useMainStore();
	const putType = ref("装车图片")
	const orderId = ref();
	const carPlate = ref();
	const driver = ref();
	const fileList = ref([])
	const chooseList = reactive([{
		name: "装车图片"
	}, {
		name: "卸车图片"
	}])
	const location = ref({});

	const isUpload = ref(false);


	// 删除图片
	const deletePic = (event) => {
		fileList.value.splice(event.index, 1);
	};

	const takeLocalCallBack = (lngLat) => {
		const ll = lngLat.split(",");
		console.log(ll);
		location.value = {
			longitude: ll[0],
			latitude: ll[1]
		};
	}

	// 生命周期处理
	onMounted(() => {
		// 挂载全局回调
		window.takeLocationCallBack = takeLocalCallBack
	})

  const takeLocation = () => {
    // 添加定位超时处理
    const timer = setTimeout(() => {
      if (!location.value.latitude) {
        uni.$u.toast("定位获取超时,请检查权限");
      }
    }, 5000);

    // 获取车辆位置信息
    queryLatitudeLongitude(carPlate.value).then(res => {
      if (res.data.success) {
        const data = res.data.data;
        location.value = {
          longitude: data.longitude,
          latitude: data.latitude
        };
        uni.$u.toast("车辆位置获取成功");
      } else {
        uni.$u.toast("车辆位置获取失败");
      }
    }).catch(err => {
      uni.$u.toast("车辆位置获取异常"+err);
      console.error("获取车辆位置失败:", err);
    }).finally(() => {
      clearTimeout(timer);
    });
  }
	// 新增图片
	const afterRead = async (event) => {
	// 当设置 mutiple 为 true 时, file 为数组格式,否则为对象格式
	let lists = [].concat(event.file);
	let fileListLen = fileList.value.length;
	lists.map((item) => {
		fileList.value.push({
		...item,
		status: 'uploading',
		message: '上传中',
		});
	});

	for (let i = 0; i < lists.length; i++) {
		// 图片压缩逻辑
		const compressImage = async (file) => {
		return new Promise((resolve) => {
			// 创建图片对象
			const img = new Image();
			img.onload = () => {
			// 创建canvas
			const canvas = document.createElement('canvas');
			const ctx = canvas.getContext('2d');

			// 设置压缩后的宽度和高度
			const maxWidth = 800;
			const maxHeight = 600;
			let width = img.width;
			let height = img.height;

			// 计算压缩后的尺寸
			if (width > maxWidth) {
				height = Math.round((height * maxWidth) / width);
				width = maxWidth;
			}
			if (height > maxHeight) {
				width = Math.round((width * maxHeight) / height);
				height = maxHeight;
			}

			// 设置canvas尺寸
			canvas.width = width;
			canvas.height = height;

			// 绘制图片
			ctx.drawImage(img, 0, 0, width, height);

			// 转换为blob
			canvas.toBlob(
				(blob) => {
				// 转换为file
				const compressedFile = new File([blob], file.name, {
					type: 'image/jpeg',
				});
				resolve(compressedFile);
				},
				'image/jpeg',
				0.6 // 压缩质量 0-1
			);
			};
			img.src = file.url;
		});
		};

		// 压缩图片
		const compressedFile = await compressImage(lists[i]);

		// 上传压缩后的文件
		let requestPath = import.meta.env.VITE_BASE_URL + import.meta.env
		.VITE_BASE_FILE_UPLOAD_PREFIX;
		uploadFilePromise(requestPath, compressedFile).then(result => {
		let item = fileList.value[fileListLen];
		fileList.value.splice(fileListLen, 1, {
			...item,
			status: 'success',
			message: '',
			url: result.data.fileName,
		});
		fileListLen++;
		});
	}
	};
	// 提交图片
	const handleSubmit = async (id, type, driver, carPlate) => {
			

			if (!validateImage()) {
				uni.$u.toast("请等待图片上传~")
				return
			}

			const userPhone = store.userPhone;
			let params = {
				garOrderId: id,
				driver: driver,
				carPlate: carPlate,
				userPhone: userPhone,
				type: type == "装车图片" ? 1 : 2,
				imageUrls: fileList.value.map(item => item.url),
				// 添加定位信息
				latitude: location.value.latitude,
				longitude: location.value.longitude
			}

			if (params.imageUrls && params.imageUrls.length == 0) {
				uni.$u.toast("请上传现场图片");
				return;
			}
			
			
			uploadImageUrlByType(params).then(res => {
				if (res.data.success) {
					uni.$u.toast("图片上传完毕!");
					setTimeout(() => {
						uni.$u.route({
							type: 'navigateBack',
							url: `pages/order-info/order-other/detail/index`,
						})
					}, 300)
				}
			})
	}
	// 提交图片
	// const handleSubmit = async (id, type,driver,carPlate) => {
	//   if (!validateImage()) {
	//     uni.$u.toast("请等待图片上传~")
	//     return
	//   }
	//   const userPhone = store.userPhone;
	//   let params = {
	//     garOrderId: id,
	// 	driver:driver,
	// 	carPlate:carPlate,
	// 	userPhone:userPhone,
	//     type: type == "装车图片" ? 1 : 2,
	//     imageUrls: fileList.value.map(item => item.url)
	//   }
	//   if(params.imageUrls && params.imageUrls.length == 0){
	//     uni.$u.toast("请上传现场图片");
	//     return;
	//   }

	//   uploadImageUrlByType(params).then(res => {
	//     if (res.data.success) {
	//       uni.$u.toast("图片上传完毕!");
	//       setTimeout(() => {
	//         uni.$u.route({
	//           type: 'navigateBack',
	//           url: `pages/order-info/order-other/detail/index`,
	//         })
	//       }, 300)
	//     }
	//   })
	// }

	const validateImage = () => {
		for (let index = 0; index < fileList.value.length; index++) {
			const str = fileList.value[index].url;
			if (!str.includes("/profile/upload")) {
				return false;
			}
		}
		return true;
	}

	onLoad((options) => {
		orderId.value = options.orderId;
		carPlate.value = options.carPlate;
		driver.value = options.driver;
		console.log(options.putType);
		putType.value = options.putType === "putOnImages" ? "装车图片" : "卸车图片";
		// 获取定位信息
		takeLocation();
	})
</script>

<style lang="scss" scoped>
	.upload-image-box {
		height: 100%;
		width: 100%;
		background-color: #ffffff;
		padding: 20rpx;
		box-sizing: border-box;
		line-height: 80rpx;

		.upload-image-box-choose {
			display: flex;

			.upload-image-box-choose-txt {
				white-space: nowrap;
			}

			.upload-image-box-choose-type {
				display: flex;
				justify-content: center;
				align-items: center;
			}
		}

		.upload-image-box-bottom {
			.upload-image-box-bottom-txt {
				color: $u-info;
			}

			.upload-image-box-button-container {
				min-height: 350rpx;
				min-width: 100%;
				padding: 20rpx;
				// background-color: $u-info-light;
				border: 2rpx solid $u-border-color;
				box-sizing: border-box;
				border-radius: 10rpx;
			}
		}

		.upload-image-box-submit-box {
			box-sizing: border-box;
			margin-top: 80rpx;
			width: 100%;

			.upload-image-box-submit-box-button {
				box-sizing: border-box;
				display: flex;
				justify-content: flex-end;
				align-items: center;

				.upload-image-box-submit-box-button-container {
					white-space: nowrap;
					box-sizing: border-box;
					width: 200rpx;
				}
			}
		}
	}
</style>