<template>
	<view class="maintenance-container">
		<uni-nav-bar fixed="true" statusBar="true" left-icon="back" title="报工信息" @clickLeft="back"></uni-nav-bar>
		<view class="maintenance-wrapper">
			<view class="maintenance-content">
				<scroll-view :scroll-y='true' class="kd-baseInfo">
					<view class="kd-cell">
						<text class="kd-label">开始里程</text>
						<uni-easyinput v-model="formData.startMileage" type="number" :clearable="false" :inputBorder="false" @blur="validateStartMileage">
							<template #right>
								<view>KM</view>
							</template>
						</uni-easyinput>
					</view>
					<view class="kd-cell">
						<text class="kd-label">结束里程</text>
						<uni-easyinput v-model="formData.endMileage" type="number" :clearable="false" :inputBorder="false" @blur="validateEndMileage">
							<template #right>
								<view>KM</view>
							</template>
						</uni-easyinput>
					</view>
					<view class="kd-cell">
						<text class="kd-label">总里程</text>
						<uni-easyinput v-model="formData.mileage" type="number" :clearable="false" :inputBorder="false" :disabled="true">
							<template #right>
								<view>KM</view>
							</template>
						</uni-easyinput>
					</view>
					<view class="kd-cell" style="display: block;">
						<text class="kd-label">开始里程图片</text>
						<view class="image-list">
							<view class="image-item" v-for="(img, index) in (formData.startMileageImages || [])" :key="index">
								<image :src="getImageUrl(img)" mode="aspectFill" @click="previewImage(formData.startMileageImages, index)"></image>
								<view class="delete-btn" v-if="formData.status == 1" @click="deleteImage('start', index)">×</view>
							</view>
							<view class="image-add" v-if="formData.status == 1 && (!formData.startMileageImages || formData.startMileageImages.length < 9)" @click="chooseImage('start')">
								<text>+</text>
							</view>
						</view>
					</view>
					<view class="kd-cell" style="display: block;">
						<text class="kd-label">结束里程图片</text>
						<view class="image-list">
							<view class="image-item" v-for="(img, index) in (formData.endMileageImages || [])" :key="index">
								<image :src="getImageUrl(img)" mode="aspectFill" @click="previewImage(formData.endMileageImages, index)"></image>
								<view class="delete-btn" v-if="formData.status == 1" @click="deleteImage('end', index)">×</view>
							</view>
							<view class="image-add" v-if="formData.status == 1 && (!formData.endMileageImages || formData.endMileageImages.length < 9)" @click="chooseImage('end')">
								<text>+</text>
							</view>
						</view>
					</view>

					<template v-if="formData.costList && formData.costList.length > 0">
						<view class="kd-cell-divider"></view>
						<view class="kd-cell">
							<text class="kd-label">费用信息</text>
							<text class="kd-content"></text>
						</view>
						<view v-for="(item, index) in formData.costList" :key="index">
							<view class="kd-cell">
								<text class="kd-label">费用类型</text>
								<text class="kd-content">{{ getDict('logistic_list_cost_type', item.costType) }}</text>
							</view>
							<view class="kd-cell">
								<text class="kd-label">金额</text>
								<text class="kd-content">{{ item.cost }}</text>
							</view>
							<view class="kd-cell">
								<text class="kd-label">备注</text>
								<text class="kd-content">{{ item.remark }}</text>
							</view>
							<view v-if="formData.status == 1" style="float: right;">
								<button class="btn-reassignment del" type="primary" @click="handleDelFee(index)">删除</button>
							</view>
						</view>
					</template>
					<template v-else>
						<view class="kd-cell">
							<text class="kd-label">费用信息</text>
							<text class="kd-content" style="color: #999;">暂无费用信息</text>
						</view>
					</template>
				</scroll-view>

				<template v-if="formData.status == 1">
					<button class="btn-execute" type="primary" @click="handleExecute(2)">保存</button>
					<button class="btn-reassignment" type="primary" @click="handleAddFee">新增费用</button>
				</template>
				<template v-else>
					<button class="btn-execute" type="primary" @click="back(1)">返回</button>
				</template>
			</view>
		</view>

		<u-popup :show="popShow" @close="close">
			<view class="select-container">
				<view class="title">
					<text class="btn cancel" @tap="close">取消</text>
					新增费用
					<text class="btn confirm" @tap="submit">确定</text>
				</view>
				<view class="select-wrapper">
					<view class="col deptInp">
						<text class="label">费用类型：</text>
						<zxz-uni-data-select :localdata="costTypeList" v-model="form.costType" filterable></zxz-uni-data-select>
					</view>

					<view class="col userInp">
						<text class="label">金额：</text>
						<uni-easyinput v-model="form.cost" type='number'></uni-easyinput>
					</view>
					<view class="col userInp">
						<text class="label">备注：</text>
						<uni-easyinput v-model="form.remark" type='textarea'></uni-easyinput>
					</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import {
		logistictraklistnoteUpdateAPI
	} from '@/api/pda/dispatchManage/index.js'
	export default {
		components: {},
		data() {
			return {
				costTypeList: [],
				form: {},
				popShow: false,
				value: '',
				info: {},
				formData: {
					costList: []
				},
				isSubmitting: false // 防重复提交标志
			}
		},
		onLoad(options) {
			console.log('options~~~', options)
			let initData = JSON.parse(options.item)
			
			// 处理开始里程图片（使用路径生成URL，同步ID）
			initData.startMileageImages = initData.startMileageImagesPaths
				? initData.startMileageImagesPaths.split(',').map((path, index) => ({
					id: initData.startMileageImagesFileIds.split(',')[index] || '', // 对应ID
					url: `${window.location.origin}/api/main/file/getFile?objectName=${path}`, // 使用路径作为参数
					status: 'done'
				}))
				: [];

			// 处理结束里程图片（同上）
			initData.endMileageImages = initData.endMileageImagesPaths
				? initData.endMileageImagesPaths.split(',').map((path, index) => ({
					id: initData.endMileageImagesFileIds.split(',')[index] || '',
					url: `${window.location.origin}/api/main/file/getFile?objectName=${path}`,
					status: 'done'
				}))
				: [];
			this.formData = initData
			console.log('initData~~~', initData)
			this.costTypeList = this.formData.dictList['logistic_list_cost_type'].map(item => {
				let values = Object.keys(item)
				return {
					text: item[values[0]],
					value: values[0],
				}
			})
		},
		computed: {
			getDict() {
				return (dictName, val) => {
					let find = this.formData.dictList[dictName].find(item => item[val]) || {}
					return find[val] ? find[val] : ''
				}
			},
			// 获取图片URL
			getImageUrl() {
				return (img) => {
					if (typeof img === 'string') {
						return img
					}
					return img.url
				}
			}
		},
		methods: {
			back(num = 1) {
				uni.navigateBack({
					delta: num
				})
			},
			// 验证开始里程
			validateStartMileage() {
				const start = parseFloat(this.formData.startMileage)
				const end = parseFloat(this.formData.endMileage)
				if (start !== 0 && !start) {
					uni.showToast({
						icon: 'none',
						title: '请输入开始里程'
					})
					return
				}
				if (start && end && start >= end) {
					uni.showToast({
						icon: 'none',
						title: '开始里程必须小于结束里程'
					})
					this.formData.startMileage = ''
					this.formData.mileage = ''
				} else if (start !== '' && end !== '') {
					this.calcTotalMileage()
				}
			},
			// 验证结束里程
			validateEndMileage() {
				const start = parseFloat(this.formData.startMileage)
				const end = parseFloat(this.formData.endMileage)
				if (!end) {
					uni.showToast({
						icon: 'none',
						title: '请输入结束里程'
					})
					return
				}
				if (start && end && end <= start) {
					uni.showToast({
						icon: 'none',
						title: '结束里程必须大于开始里程'
					})
					this.formData.endMileage = ''
					this.formData.mileage = ''
				} else if (start !== '' && end !== '') {
					this.calcTotalMileage()
				}
			},
			// 计算总里程
			calcTotalMileage() {
				const start = parseFloat(this.formData.startMileage) || 0
				const end = parseFloat(this.formData.endMileage) || 0
				this.formData.mileage = (end - start).toFixed(2)
			},
			// 选择图片
			chooseImage(type) {
				const maxCount = 9
				const currentImages = type === 'start' ? (this.formData.startMileageImages || []) : (this.formData.endMileageImages || [])
				const remainingCount = maxCount - currentImages.length

				if (remainingCount <= 0) {
					uni.showToast({
						icon: 'none',
						title: '最多上传9张图片'
					})
					return
				}

				uni.chooseImage({
					count: remainingCount,
					sizeType: ['compressed'],
					sourceType: ['camera', 'album'],
					success: (res) => {
						const tempFilePaths = res.tempFilePaths
						this.uploadImages(tempFilePaths, type)
					}
				})
			},
			// 上传多张图片
			async uploadImages(filePaths, type) {
				uni.showLoading({
					title: '上传中...'
				})

				const uploadPromises = filePaths.map(filePath => {
					return new Promise((resolve, reject) => {
						uni.uploadFile({
							url: this.apiUrl + '/main/file/upload',
							filePath: filePath,
							name: 'multiPartFile',
							header: {
								authorization: uni.getStorageSync("token")
							},
							success: (res) => {
								const data = JSON.parse(res.data)
								console.log('data~~~', data)
								if (data.code == 0) {
									// 构建完整的图片URL
									// const fileNames = data.data.storePath.split('/')
									// const url = this.apiUrl +
									// 	'/main/file/getFile?objectName=' + data.data.storePath +
									// 	'&fullfilename=' + fileNames[fileNames.length - 1]
									resolve(data.data)
								} else {
									reject(data.message || '上传失败')
								}
							},
							fail: () => {
								reject('上传失败')
							}
						})
					})
				})

				try {
					const results = await Promise.all(uploadPromises)
					console.log('results~~~', results)
					if (type === 'start') {
						if (!this.formData.startMileageImages) {
							this.formData.startMileageImages = []
						}
						this.formData.startMileageImages.push(...results)
					} else {
						if (!this.formData.endMileageImages) {
							this.formData.endMileageImages = []
						}
						this.formData.endMileageImages.push(...results)
					}
					console.log('startMileageImages~~~', this.formData.startMileageImages)
					// 强制更新视图
					this.$forceUpdate()
					uni.hideLoading()
					uni.showToast({
						title: '上传成功',
						icon: 'success'
					})
				} catch (error) {
					uni.hideLoading()
					uni.showToast({
						title: error || '上传失败',
						icon: 'none'
					})
				}
			},
			// 删除图片
			deleteImage(type, index) {
				uni.showModal({
					title: '确认删除',
					content: '确定要删除这张图片吗？',
					confirmColor: '#157A2C',
					success: res => {
						if (res.confirm) {
							console.log('index~~~', index)
							if (type === 'start') {
								this.formData.startMileageImages.splice(index, 1)
							} else {
								this.formData.endMileageImages.splice(index, 1)
							}
							this.$forceUpdate();
							console.log('startMileageImages~~~', this.formData.startMileageImages)
							console.log('endMileageImages~~~', this.formData.endMileageImages)
						}
					}
				})
			},
			// 预览图片
			previewImage(images, index) {
				// 处理图片数据,确保是字符串数组
				const urls = images.map(img => {
					if (typeof img === 'string') {
						return img
					} else if (img && img.url) {
						return img.url
					}
					return ''
				}).filter(url => url) // 过滤掉空字符串
				uni.previewImage({
					urls: urls,
					current: index
				})
			},
			async handleExecute(status) {
				// 防重复提交检查
				if (this.isSubmitting) {
					return
				}
				this.isSubmitting = true

				try {
					// 验证开始里程(允许0,但不允许负数、空值或NaN)
					if (this.formData.startMileage === '' || this.formData.startMileage === null || this.formData.startMileage === undefined || isNaN(this.formData.startMileage) || parseFloat(this.formData.startMileage) < 0) {
						uni.showToast({
							icon: 'none',
							title: '请输入有效的开始里程'
						})
						return
					}

					// 验证结束里程(不允许为0、负数、空值或NaN)
					if (!this.formData.endMileage || isNaN(this.formData.endMileage) || parseFloat(this.formData.endMileage) <= 0) {
						uni.showToast({
							icon: 'none',
							title: '请输入有效的结束里程'
						})
						return
					}

					// 验证里程关系:结束里程必须大于开始里程
					if (parseFloat(this.formData.endMileage) <= parseFloat(this.formData.startMileage)) {
						uni.showToast({
							icon: 'none',
							title: '结束里程必须大于开始里程'
						})
						return
					}

					// 验证开始里程图片
					if (!this.formData.startMileageImages || this.formData.startMileageImages.length === 0) {
						uni.showToast({
							icon: 'none',
							title: '请上传开始里程图片'
						})
						return
					}

					// 验证结束里程图片
					if (!this.formData.endMileageImages || this.formData.endMileageImages.length === 0) {
						uni.showToast({
							icon: 'none',
							title: '请上传结束里程图片'
						})
						return
					}

					// 验证费用信息
					if (!this.formData.costList || this.formData.costList.length === 0) {
						uni.showToast({
							icon: 'none',
							title: '请添加费用信息'
						})
						return
					}

					// 显示加载状态
					uni.showLoading({
						title: '提交中...',
						mask: true
					})

					const data = JSON.parse(JSON.stringify(this.formData))
					data.endMileageImagesFileIds = data.endMileageImages.map(img => img.id).join(',')
					data.startMileageImagesFileIds = data.startMileageImages.map(img => img.id).join(',')
					console.log('data~~~', data)
				
					// 调用API
					await logistictraklistnoteUpdateAPI({...data, status})

					uni.hideLoading()
					uni.showModal({
						title: '此工单报工成功',
						content: '',
						confirmText: '确认',
						showCancel: false,
						success: res => {
							if (res.confirm) {
								this.back(2)
							}
						}
					})
				} catch (error) {
					uni.hideLoading()
					uni.showToast({
						icon: 'none',
						title: error.message || '提交失败,请重试',
						duration: 3000
					})
					console.error('提交失败:', error)
				} finally {
					this.isSubmitting = false
				}
			},
			handleAddFee() {
				this.form = {}
				this.popShow = true
			},
			handleDelFee(index) {
				uni.showModal({
					title: '确认删除',
					content: '确定要删除这条费用信息吗？',
					confirmColor: '#157A2C',
					success: res => {
						if (res.confirm) {
							this.formData.costList.splice(index, 1)
						}
					}
				})
			},
			submit() {
				if (!this.form.costType) {
					uni.showToast({
						icon: 'error',
						title: '请选择费用类型'
					})
					return
				}
				if (!this.form.cost) {
					uni.showToast({
						icon: 'error',
						title: '请输入金额'
					})
					return
				}
				this.form.listId = this.formData.id
				this.formData.costList.push({
					...this.form
				})
				this.form = {}
				this.close()
			},
			close() {
				this.popShow = false
			},
		}
	}
</script>

<style lang="scss" scoped>
	@import '@/components/submitted.scss';

	.list-cell {
		display: flex;
		align-items: center;
		justify-content: space-between;
		color: $uni-text-color-grey;
		padding: 5rpx 20rpx;
	}

	.font-sm {
		font-size: $uni-font-size-sm;
	}

	.font-text {
		color: $uni-text-color;
	}

	.btn-execute {
		background-color: $j-primary-border-green;
		width: 450rpx;
		margin-top: 10vh;
	}

	.btn-sparepart {
		width: 450rpx;
		margin-top: 20rpx;
	}

	.btn-reassignment {
		color: $uni-color-primary;
		background-color: transparent;
		border: none;
		box-shadow: none;

		&::after {
			display: none;
		}
	}

	.del {
		color: red;
		font-size: 1.5rex;
	}

	.maintenance-container {
		position: fixed;
		top: 0;
		bottom: 0;
		width: 100vw;
		display: flex;
		flex-direction: column;

		/deep/.u-popup {
			flex: none !important;
		}
	}

	.maintenance-wrapper {
		position: relative;
		flex: 1;
	}

	.maintenance-content {
		padding-top: 40rpx;
		box-sizing: border-box;
		position: absolute;
		top: 0;
		bottom: 0;
		left: 0;
		right: 0;
		display: flex;
		flex-direction: column;
	}

	.kd-cell {
			line-height: 90rpx;
			border-bottom: 1px dashed #dadada;
			display: flex;
			justify-content: space-between;

			.kd-label {
				display: inline-block;
				width: 7em;
				font-weight: bold;
			}

			.kd-content {
				flex: 1;
				text-align: left;
				word-break: break-all;
			}

			&.block {
				display: block;
			}
		}

	.kd-cell-divider {
		border-bottom: 2px solid #dadada;
		margin: 10px 0;
	}

	.upload-btn {
		flex: 1;
		text-align: center;
		color: $theme-color;
	}

	.image-list {
		display: flex;
		flex-wrap: wrap;
		padding: 10rpx 0;
		margin-left: 7em;

		.image-item {
			position: relative;
			width: 150rpx;
			height: 150rpx;
			margin: 0 10rpx 10rpx 0;
			box-sizing: border-box;

			image {
				width: 100%;
				height: 100%;
				border-radius: 8rpx;
			}

			.delete-btn {
				position: absolute;
				top: -10rpx;
				right: -10rpx;
				width: 40rpx;
				height: 40rpx;
				line-height: 40rpx;
				text-align: center;
				background-color: #ff4d4f;
				color: #fff;
				border-radius: 50%;
				font-size: 32rpx;
				cursor: pointer;
				z-index: 10;
			}
		}

		.image-add {
			width: 150rpx;
			height: 150rpx;
			border: 2rpx dashed #d9d9d9;
			border-radius: 8rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 60rpx;
			color: #999;
			margin: 0 10rpx 10rpx 0;
			cursor: pointer;
			box-sizing: border-box;

			&:active {
				background-color: #f5f5f5;
			}
		}
	}

	.kd-baseInfo {
		padding: 0 32rpx;
		font-size: 28rpx;
		height: 75%;
	}

	.kd-equipment {
		flex: 1;
		display: flex;
		flex-direction: column;
		overflow: hidden;

		.kd-type-box {
			text-align: center;
			padding: 26rpx 0;

			view {
				position: relative;
				display: inline-block;
				width: 120rpx;
				padding: 4rpx 0;
				color: #747474;
				margin: 0 20rpx;
				background-color: rgba(215, 215, 215, 0.5);

				&.type—active {
					background-color: #1e7f35;
					color: #fff;
				}

				.count {
					position: absolute;
					top: -9px;
					right: -9px;
					width: 18px;
					height: 18px;
					border-radius: 50%;
					font-size: 12px;
					background-color: red;
					color: #fff;
				}
			}
		}

		.kd-list-container {
			flex: 1;
			display: flex;
			flex-direction: column;
			overflow: hidden;
			padding: 12rpx 18rpx;
			background-color: $page-bg;

			.u-list {
				flex: 1;
				height: 100% !important;
			}
		}
	}

	.spare-parts {
		flex: 1;
		overflow: hidden;
	}

	.kd-card {
		background-color: #fff;
		margin-bottom: 20rpx;
		padding: 8rpx 0;
		font-size: 28rpx;
		word-break: break-all;

		.kd-card-wrapper {
			padding: 0 30rpx;
			border-bottom: 1px solid #dadada;
		}

		.kd-cell {
			line-height: 60rpx;
		}

		.kd-cell:last-of-type {
			border-bottom: none;
		}

		.status-box {
			margin-right: 16rpx;
		}

		.card-footer {
			display: flex;
			justify-content: flex-end;
			align-items: center;
			padding: 8rpx 0 20rpx;

			button {
				width: 180rpx;
				height: 56rpx;
				line-height: 56rpx;
				font-size: 28rpx;
				margin: 0 8rpx;
			}

			.primary-btn {
				background-color: $j-primary-border-green;
			}
		}
	}

	.apply-box {
		width: 70%;
		margin: 0 auto;
		display: flex;
		align-items: center;
		justify-content: space-around;
	}

	.select-container {
		min-height: 60vh;

		.title {
			display: flex;
			justify-content: space-between;
			align-items: center;
			height: 100rpx;
			line-height: 100rpx;
			text-align: center;
			background-color: $j-primary-border-green;
			font-weight: bold;
			position: relative;
			font-size: 32rpx;
			color: #fff;
			padding: 0 30rpx;
			box-sizing: border-box;

			.btn {
				display: flex;
				align-items: center;
				justify-content: center;
				width: 120rpx;
				height: 56rpx;
				font-size: 28rpx;
				border: 1px solid #fff;
				text-align: center;
				line-height: 56rpx;
				border-radius: 8rpx;
				transition: opacity 0.3s;
				cursor: pointer;

				&:active {
					opacity: 0.7;
				}

				&.cancel {
					background-color: transparent;
					color: #fff;
				}

				&.confirm {
					background-color: rgba(255, 255, 255, 0.2);
					color: #fff;
				}
			}
		}

		.select-wrapper {
			.col {
				display: flex;
				// min-height: 0rpx;
				margin-top: 22rpx;
				align-items: center;
				padding-right: 14rpx;

				.label {
					display: inline-block;
					width: 200rpx;
					text-align: right;
				}

				.input_text {
					flex: 1;
					height: 66rpx;
					line-height: 66rpx;
					padding: 0rpx 16rpx;
					box-sizing: border-box;
					font-size: 28rpx;
					border: 1px solid #eceeec;
					border-radius: 8rpx;
				}

				input {
					flex: 1;
					border: 1rpx solid #e5e5e5;
					height: 66rpx;
					border-radius: 8rpx;
					font-size: 28rpx;
					padding: 0rpx 16rpx;
					color: #6a6a6a;
				}

				textarea {
					border: 1rpx solid #e5e5e5;
					flex: 1;
					height: 100rpx;
				}

				.tab_box {
					display: flex;
					flex-direction: row;
					flex-wrap: wrap;
					width: 520rpx;

					.tab {
						display: flex;
						flex-direction: row;

						border: 2rpx solid #d9ecff;
						background-color: #f4f4f5;
						border-color: #e9e9eb;
						color: #909399;
						margin-left: 8rpx;
						margin-bottom: 8rpx;
						padding: 2rpx 8rpx;
						font-size: 28rpx;
					}

					.icon {
						margin-left: 6rpx;
					}
				}
			}
		}
	}
</style>
