<!-- 订单详情 -->
<template>
	<view class="order-detail">
		<view class="user-info order-card">
			<view class="font-title">基本信息</view>
			<view class="user-box">
				<view class="info-list">
					<view>被服务人员：{{ detaile.clientName }}</view>
					<view style="display: flex;">服务类别：{{ detaile.businessTireName }}</view>
					<view @click="onPhone">电话号码：<label class="phone">{{ detaile.clientPhoneNumber.replace(/(\d{3})\d{4}(\d{4})/,  '$1****$2')  }}</label></view>
					<view>地址：{{ detaile.address }}</view>
				</view>
			</view>
		</view>
		<view class="service-info order-card">
			<view class="font-title ">备注信息</view>
			<view class="info-list">
				{{ detaile.remark || '暂无备注信息'}}
			</view>
		</view>
		<view class="service-info order-card" v-if="isStatus">
			<view class="font-title ">反馈信息</view>
			<view class="info-list">
				<up-textarea v-model="detaile.volunteerReview" placeholder="请输入内容"></up-textarea>
			</view>
		</view>

		<view v-if="detaile.orderStatus !== '3'">
			<view class="user-info order-card">
				<view class="font-title">志愿者反馈信息</view>
				<view class="user-box">
					<view class="info-list">
						<view class="info-item">{{ detaile.volunteerReview || '暂无志愿者反馈信息'}}</view>
					</view>
				</view>
				<view class="upload-box-see">
					<view class="upload-img-item" v-for="(item) in volunteerPicture" :key="item.url">
						<up-image class="upload-img-see" :show-loading="true" :src="item.url"
							:alt="item.fileName" mode="widthFix"></up-image>
					</view>
				</view>
			</view>

			<view class="user-info order-card">
				<view class="font-title">用户评价信息</view>
				<view class="user-box">
					<view class="info-list">
						<view class="info-item">{{ detaile.userReview || '用户未完成评价' }}</view>
					</view>
				</view>
				<view class="upload-box-see">
					<view class="upload-img-item" v-for="(item) in userPicture" :key="item.url">
						<up-image class="upload-img-see" :show-loading="true" :src="item.url"
							:alt="item.fileName"></up-image>
					</view>
				</view>
			</view>
		</view>



		<view class="service-info order-card" v-if="isStatus">
			<view class="font-title">图片上传</view>
			<view class="upload-box">
				<view class="upload-img-item" v-for="(item, index) in fileList" :key="item.url">
					<view class="delete-icon" @click="deletePic(index)"><up-icon name="close-circle-fill"
							color="#f64a1f" size="18" v-if="isStatus"></up-icon></view>
					<img class="upload-img" :src="item.url" :alt="item.fileName" srcset="">
				</view>
				<img src="/static/img/upload.png" alt="" class="upload-img" @click="uploadClick('img')"
					v-if="fileList.length < 10 && isStatus">
			</view>
		</view>



		<view class=" footer-g" v-if="isStatus">
			<view class="status-btn" @click="submit">结束服务</view>
		</view>
	</view>
</template>

<script setup>
import { ref, toRaw, computed } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { getVolunteerOrderInfo, getVolunteerFinishSecondOrder } from '@/api/volunteer.js'
import { getAddress } from '@/api/address.js'
import { wxUploadFile, wxMakePhoneCall } from '@/utils/wxRequest.js'
import { useDict } from '@/utils/dict.js';
import DictTag from '@/components/DictTag/index.vue'
import { getLatLong } from '@/utils/adress'
const fileList = ref([]);
const secondOrderId = ref('');
const detaile = ref({
	volunteerReview: ''
});

const {
	lrr_service_category
} = useDict('lrr_service_category');

const isEnd = ref(false);//详情、结束服务

const isStatus = computed(() => {
	console.log('isEnd.value',isEnd.value,detaile.value.orderStatus);
	
	return isEnd.value ? !isEnd.value : (detaile.value.orderStatus === '3')
})

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


const uploadClick = async (type) => {
	const res = await wxUploadFile(type);
	fileList.value = [...fileList.value, ...res];
	console.log('xxxxres', res, fileList.value);
}
const onPhone = (phone) => {
	wxMakePhoneCall(phone)
}

//志愿者图片反馈
const volunteerPicture = computed(() => {
	if (detaile.value.volunteerPicture) {
		return detaile.value.volunteerPicture.split(',').map(item => {
			return { url: item }
		});
	}
	return [];
})

//用户图片评价
const userPicture = computed(() => {
	if (detaile.value.userPicture) {
		return detaile.value.userPicture.split(',').map(item => {
			return { url: item }
		});
	}
	return [];
})

const getOrderDetail = async () => {
	try {
		// uni.showLoading({
		// 	title: '数据加载中...'
		// });
		const res = await getVolunteerOrderInfo({ secondOrderId: secondOrderId.value });
		console.log('API response:', res);

		// Check if the response was successful
		if (res.code === 200) {
			// Directly assign the data from response
			detaile.value = res.data;

			// Check if volunteer pictures exist and process them
			if (res.data.volunteerPicture) {
				fileList.value = res.data.volunteerPicture.split(',').map(item => {
					return { url: item }
				});
			}
		} else {
			uni.showToast({
				title: res.msg || '获取数据失败',
				icon: 'error',
			});
		}

		console.log('detaile.value after assignment:', detaile.value);

	} catch (error) {
		console.log('error', error);
		uni.showToast({
			title: error.msg || '获取数据失败',
			icon: 'error',
		})
	} finally {
		// uni.hideLoading();
	}
}

// 获取当前位置信息
const getCurrentLocation = () => {
	return new Promise((resolve, reject) => {
		// 先检查用户是否授权了位置权限
		uni.getSetting({
			success: (res) => {
				if (!res.authSetting['scope.userLocation']) {
					// 如果用户未授权，先请求授权
					uni.authorize({
						scope: 'scope.userLocation',
						success: () => {
							// 授权成功后获取位置
							getLocation(resolve, reject);
						},
						fail: (err) => {
							console.error('位置授权失败:', err);
							uni.showModal({
								title: '提示',
								content: '需要获取您的位置信息，请在设置中打开位置权限',
								confirmText: '去设置',
								success: (res) => {
									if (res.confirm) {
										uni.openSetting();
									}
								}
							});
							reject(err);
						}
					});
				} else {
					// 已授权，直接获取位置
					getLocation(resolve, reject);
				}
			},
			fail: (err) => {
				console.error('获取设置失败:', err);
				reject(err);
			}
		});
	});
}

// 获取位置的具体实现
const getLocation = (resolve, reject) => {
	// 删除开发环境模拟位置的代码，始终获取真实位置
	uni.getFuzzyLocation({
		type: 'gcj02',
		// isHighAccuracy: true, // 高精度
		// highAccuracyExpireTime: 3000, // 高精度过期时间
		success: (res) => {
			const { longitude, latitude } = res;
			console.log('当前位置 - 经度:', longitude);
			console.log('当前位置 - 纬度:', latitude);
			resolve({
				longitude,
				latitude
			});
		},
		fail: (err) => {
			console.error('获取位置失败:', err);
			// 获取位置失败时向用户提示
			uni.showToast({
				title: '获取位置失败，请确保已开启位置权限',
				icon: 'none',
				duration: 2000
			});
			reject(err);
		}
	});
}
const submit = () => {
	uni.$u.debounce(onSubmit, 300)
}
const onSubmit = async () => {
	try {
	// 调用结束服务接口，通过URL查询参数传递位置信息
	// uni.showLoading({
    //         title: '正在结束服务...',
    // })
	const img_urls = fileList.value.map(item => item.url).join(',');
	console.log('submit', fileList.value, img_urls);

	// 获取结束服务时的位置
	// const locationData = await getCurrentLocation().catch(err => {
	// 	// uni.hideLoading()
	// 	verify.value.initialization()
	// 	throw new Error('无法获取位置信息，请确保已开启位置权限')
	// })
	const locationData =await getLatLong()
	// 构建参数字符串
	const params = `volunteerPicture=${img_urls}&volunteerReview=${detaile.value.volunteerReview}&secondOrderId=${secondOrderId.value}&serviceFinishLongitude=${locationData.longitude.toString()}&serviceFinishLatitude=${locationData.latitude.toString()}`

	
	const res = await getVolunteerFinishSecondOrder(params);
	if (res.code === 200) {
			uni.showToast({
				title: '服务结束',
				icon: 'success',
				success: () => {
					setTimeout(() => {
						uni.switchTab({
							url: '/pages/classify'
						});
					}, 800)
				}
			})

		} else {
			uni.showToast({
				title: res.data,
				icon: 'error',
			})
		}
	} catch (error) {
		console.log("TCL: onSubmit -> error", error)
	} finally {
		// uni.hideLoading()
	}
}

onLoad((options) => {
	console.log('options received:', options);
	secondOrderId.value = options.secondOrderId;
	isEnd.value = options.type && options.type ==='details';
	console.log('secondOrderId set to:', secondOrderId.value);
	// orderId.value = '1911685346559660034';

	getOrderDetail();

})
</script>
<style lang="scss" scoped>
.order-detail {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	padding: 12px 12px 24px;
	background: rgba(245, 245, 245, 1);
	overflow-y: auto;

	.order-card {
		border-radius: 8px;
		background: rgba(255, 255, 255, 1);
		padding: 12px;
		margin-bottom: 12px;
	}

	.font-title {
		margin-bottom: 12px;
	}

	.user-box {
		display: flex;

		.user-img {
			width: 65.8px;
			height: 65.8px;
			margin-right: 12px;
		}

	}

	.register-box {
		display: flex;
		margin-bottom: 12px;

		.register-img {
			width: 90px;
			height: 90px;
			margin-right: 12px;
		}

	}

	.info-list {
		flex: 1;
		font-size: 14px;
		font-weight: 500;
		letter-spacing: 0px;
		line-height: 23.27px;
		color: rgba(51, 51, 51, 1);
	}

	.price {
		font-size: 18px;
		font-weight: 500;
		color: rgba(246, 74, 31, 1);

		.price-yuan {
			font-size: 13px;
			font-weight: 700;
			color: rgba(246, 74, 31, 1);
		}
	}

	.footer-g {
		padding: 12px;
		position: absolute;
		bottom: 18px;
		left: 0px;
		right: 0px;
	}

	.upload-img {
		height: 68px;
		width: 68px;
		margin-right: 12px;
		margin-bottom: 12px;
	}

	.upload-box {
		display: flex;
		flex-wrap: wrap;
		// display: flex;
		// flex-direction: column;
		// align-items: center;
		// justify-content: center;

		.upload-img-item {
			position: relative;

			.delete-icon {
				position: absolute;
				top: -7px;
				right: 7px;
				z-index: 1;
			}
		}
	}

	.upload-box-see {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;

		.upload-img-see {
			margin-bottom: 12px;
		}
	}

	.phone {
		color: #3c9cff;
	}

	.info-item {
		margin-bottom: 12px;
	}
}

.status-btn {
	// width: 716rpx;
	height: 96rpx;
	border-radius: 16rpx;
	background: rgba(221, 94, 69, 1);

	display: flex;
	align-items: center;
	justify-content: center;

	font-size: 32rpx;
	font-weight: 400;
	color: rgba(255, 255, 255, 1);
	margin-bottom: 88rpx;
}
</style>
