<!-- 历史订单列表-->
<template>
	<view class="content">
		<view style="background: #317dfa">
			<VNavigationBar title="扣车管理"></VNavigationBar>
			<view class="search-box">
				<view class="s-input">
					<uni-icons type="search" color=" #999999" size="16"></uni-icons>
					<input type="text" v-model="licenseNum" placeholder="车牌号搜索">
					<uni-icons @click="licenseNum = ''" type="clear" color="#8E8E93"></uni-icons>
				</view>
				<view class="search-button" @click="getlist()">搜索</view>
			</view>
			<view class="top-tap">
				<view class="tap-box" :class="{'cc' : gindex == 9 }" @click="getindex(9)"
					v-if="checkPermi(['rescue_home_page'])">
					<view style="margin-bottom: 4px;">扣车中 ({{one}}) </view>
					<view class="gang" v-if="9 == gindex"></view>
				</view>
				<view class="tap-box" :class="{'cc' : gindex == 3 }" @click="getindex(3)">
					<view style="margin-bottom: 4px;">已解扣 ({{two}}) </view>
					<view class="gang" v-if="3 == gindex"></view>
				</view>
				<view class="tap-box" :class="{'cc' : gindex == 8 }" @click="getindex(8)">
					<view style="margin-bottom: 4px;">已还车 ({{three}}) </view>
					<view class="gang" v-if="8 == gindex"></view>
				</view>
			</view>
		</view>
		<view class="dil">
			<view class="ques" v-if="orderList.length== 0 ">
				<image src="../../static/quesheng.png" mode=""></image>
			</view>
			<view class="boxa-box" v-for="(item,index) in orderList" :key="index">
				<view class="boxa" :style="{borderRadius: gindex === 3 ? '10px 10px 0 0' : '10px'}"
					@click="onShowDetail(item.id)">
					<view class="car-card-line">
						<view class="car-card-line">
							<view class="car-card">车牌号</view>
							<view class="hei-title">{{item.licenseNum || ''}}</view>
						</view>
						<view class="car-card-state"
							:class="8 == gindex ? 'state-blue' : 3 == gindex ? 'state-green' : 'state-red'">
							{{ 8 == gindex ? '已还车' : 3 == gindex ? '已解扣' : '扣车中' }}
						</view>
					</view>
					<view class="box-bs">
						<view class="zc">车主：{{item.connectionName || ''}}</view>
						<view class="zc">联系电话：{{item.connectionPhone || ''}}</view>
					</view>
					<view class="yihang">扣车时间：{{ formatTimestamp(item.createTime) || ''}}</view>
					<view class="yihang">扣车地点：{{item.rescuePosition || ''}}</view>
					<view class="yihang">取车地点：{{item.kcPosition || ''}}</view>
				</view>
				<view class="janniu" v-if="gindex == 3" @click="openReturnCarDialog(item.id, item.licenseNum)">
					<text>立即还车</text>
				</view>
				<view class="janniu" v-if="item.rescueStatus < 6" @click="openUnclampDialog(item.id, item.licenseNum)">
					<text>解扣</text>
				</view>
			</view>
			<view style="width: 100%; height: 60px;"></view>
		</view>

		<!-- 解扣确认弹窗 -->
		<uni-popup ref="unclampDialog" type="dialog">
			<view class="custom-dialog">
				<view class="dialog-title">
					<text class="license-num">{{currentLicenseNum}} - 解扣确认</text>
				</view>
				<view class="dialog-content">
					<text class="dialog-tip">请输入解扣备注信息</text>
					<textarea class="remark-input" v-model="unclampRemark" placeholder="请输入备注信息"
						maxlength="200"></textarea>
				</view>
				<view class="dialog-buttons">
					<view class="dialog-button cancel" @click="cancelUnclamp">取消</view>
					<view class="dialog-button confirm" @click="confirmUnclamp">确认</view>
				</view>
			</view>
		</uni-popup>

		<!-- 立即还车弹框 -->
		<uni-popup ref="returnCarDialog" type="dialog">
			<view class="custom-dialog return-car-dialog">
				<view class="dialog-title">
					<text class="license-num">{{currentLicenseNum}} - 还车确认</text>
				</view>
				<view class="dialog-content">
					<text class="dialog-tip">请输入还车备注信息</text>
					<textarea class="remark-input" v-model="returnRemark" placeholder="请输入备注信息"
						maxlength="200"></textarea>

					<!-- 图片上传区域 -->
					<view class="upload-section">
						<view class="section-title">现场照片（必传）</view>
						<view class="upload-tips" v-if="uploading">
							<u-loading-icon size="20" color="#0D2E8D"></u-loading-icon>
							<text>图片上传中，请稍候...</text>
						</view>
						<u-upload :fileList="returnFileList" @afterRead="returnAfterRead" @delete="deleteReturnPic"
							name="return" multiple :maxCount="5" :disabled="uploading"></u-upload>
					</view>
				</view>
				<view class="dialog-buttons">
					<view class="dialog-button cancel" @click="cancelReturn">取消</view>
					<view class="dialog-button confirm" @click="confirmReturn"
						:disabled="uploading || returnFileList.length === 0">
						{{uploading ? '提交中...' : '确认'}}
					</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import tabBar from '../../components/tabBar/tabBar.vue'
	import request from '../../utils/request';
	import VNavigationBar from 'components/VNavigationBar.vue'
	import upload from '@/utils/upload.js'
	import {
		checkPermi,
		checkRole
	} from "@/utils/permission"; // 权限判断函数

	export default {
		data() {
			return {
				one: 0,
				two: 0,
				three: 0,
				gindex: 9,
				orderList: [],
				licenseNum: '',
				rescueStatus: '',
				total: 0,
				pageNum: 1,
				pageSize: 10,
				totalPages: 0,
				userinfo: {},

				// 解扣相关
				unclampRemark: '',
				currentCarId: '',
				currentLicenseNum: '',

				// 还车相关
				returnRemark: '',
				returnFileList: [],
				returnImages: [],
				uploading: false,
			}
		},
		components: {
			tabBar,
			VNavigationBar
		},
		onLoad(option) {
			if (option.id) {
				this.gindex = option.id
			}
			this.userinfo = uni.getStorageSync('userInfo')
			this.getthree()
			this.getlist()
		},
		onReachBottom() {
			if (this.orderList.length >= this.totalPages) {
				uni.showToast({
					title: '没有下一页数据',
					icon: 'none'
				})
			} else {
				this.pageNum++
				this.getlist()
			}
		},
		methods: {
			checkPermi,
			checkRole,
			onShowDetail(id) {
				uni.navigateTo({
					url: '/pages/details/details?id=' + id
				})
			},
			getthree() {
				// 获取各状态数量
				const statuses = [9, 3, 8];
				const promises = statuses.map(status => {
					return request({
						url: '/app/rescueInfo/getRescueList',
						method: 'get',
						params: {
							licenseNum: '',
							rescueStatus: status,
							pageSize: 10,
							pageNum: 1,
						}
					})
				});

				Promise.all(promises).then(results => {
					this.one = results[0].code === 200 ? results[0].total : 0;
					this.two = results[1].code === 200 ? results[1].total : 0;
					this.three = results[2].code === 200 ? results[2].total : 0;
				});
			},

			getlist() {
				let data = {
					licenseNum: this.licenseNum,
					rescueStatus: this.gindex,
					pageSize: this.pageSize,
					pageNum: this.pageNum,
				}
				request({
					url: '/app/rescueInfo/getRescueList',
					method: 'get',
					params: data
				}).then((res) => {
					if (res.code == 200) {
						if (this.pageNum != 1) {
							this.orderList = this.orderList.concat(res.rows)
						} else {
							this.orderList = res.rows
						}
						this.totalPages = res.total
					}
				})
			},

			getindex(index) {
				this.orderList = []
				this.gindex = index
				this.pageNum = 1
				this.getlist()
			},

			// 解扣相关方法
			openUnclampDialog(id, licenseNum) {
				this.currentCarId = id;
				this.currentLicenseNum = licenseNum;
				this.unclampRemark = '';
				this.$refs.unclampDialog.open();
			},

			cancelUnclamp() {
				this.unclampRemark = '';
				this.currentLicenseNum = '';
				this.$refs.unclampDialog.close();
			},

			async confirmUnclamp() {
				if (!this.unclampRemark) {
					uni.showToast({
						title: '请输入解扣备注',
						icon: 'none'
					})
					return
				}

				try {
					// 执行解扣操作
					const jkResult = await this.jiekou(this.currentCarId);

					// 上传解扣详情
					const detailData = {
						rescueInfoId: this.currentCarId,
						title: '车辆解扣',
						autoRemark: '解扣人: ' + this.userinfo.nickname,
						remark: this.unclampRemark,
					};

					await this.uploadDetailByDriver(detailData);

					// 关闭弹窗
					this.$refs.unclampDialog.close();
					this.currentLicenseNum = '';

					// 刷新数据
					this.getlist();
					this.getthree();

					uni.showToast({
						title: jkResult.msg || '解扣成功',
						icon: 'success'
					});
				} catch (error) {
					console.error('解扣操作失败:', error);
					uni.showToast({
						title: jkResult.msg || '解扣失败，请重试',
						icon: 'none',
						duration: 3000
					});
				}
			},

			jiekou(id) {
				return new Promise((resolve, reject) => {
					request({
						url: '/app/rescueInfo/openKc',
						method: 'post',
						params: {
							rescueId: id
						}
					}).then((res) => {
						if (res.code == 200) {
							resolve(res);
						} else {
							reject(new Error(res.msg || '解扣失败'));
						}
					}).catch(error => {
						reject(error);
					});
				});
			},

			// 还车相关方法
			openReturnCarDialog(id, licenseNum) {
				this.currentCarId = id;
				this.currentLicenseNum = licenseNum;
				this.returnRemark = '';
				this.returnFileList = [];
				this.returnImages = [];
				this.$refs.returnCarDialog.open();
			},

			cancelReturn() {
				this.returnRemark = '';
				this.returnFileList = [];
				this.returnImages = [];
				this.$refs.returnCarDialog.close();
			},

			async confirmReturn() {
				if (this.returnImages.length === 0) {
					uni.showToast({
						title: '请上传现场照片',
						icon: 'none'
					});
					return;
				}

				if (!this.returnRemark) {
					uni.showToast({
						title: '请输入还车备注',
						icon: 'none'
					});
					return;
				}

				try {
					this.uploading = true;

					// 执行还车操作
					const hcResult = await this.getjiji(this.currentCarId);

					// 上传还车详情
					const detailData = {
						rescueInfoId: this.currentCarId,
						title: '车辆还车',
						autoRemark: '还车人: ' + this.userinfo.nickname,
						remark: this.returnRemark,
						images: this.returnImages.join(",")
					};

					await this.uploadDetailByDriver(detailData);

					// 关闭弹框
					this.$refs.returnCarDialog.close();

					// 刷新数据
					this.getlist();
					this.getthree();

					uni.showToast({
						title: hcResult.msg || '还车成功',
						icon: 'success'
					});
				} catch (error) {
					console.error('还车失败:', error);
					uni.showToast({
						title: hcResult.msg || '还车失败，请重试',
						icon: 'none',
						duration: 3000
					});
				} finally {
					this.uploading = false;
				}
			},

			getjiji(id) {
				return new Promise((resolve, reject) => {
					request({
						url: '/app/rescueInfo/hcOpen',
						method: 'post',
						params: {
							rescueId: id
						}
					}).then((res) => {
						if (res.code == 200) {
							resolve(res);
						} else {
							reject(new Error(res.msg || '还车失败'));
						}
					}).catch(error => {
						reject(error);
					});
				});
			},

			// 通用方法
			uploadDetailByDriver(data) {
				return new Promise((resolve, reject) => {
					request({
						url: '/app/driver/uploadDetailByDriver',
						method: 'post',
						data: data
					}).then((res) => {
						if (res.code == 200) {
							resolve(res);
						} else {
							reject(new Error(res.msg || '提交失败'));
						}
					}).catch(error => {
						reject(error);
					});
				});
			},

			// 图片上传相关
			async returnAfterRead(event) {
				if (this.uploading) return;

				let lists = [].concat(event.file);
				let fileListLen = this.returnFileList.length;

				lists.map((item) => {
					this.returnFileList.push({
						...item,
						status: 'uploading'
					});
				});

				this.uploading = true;

				for (let i = 0; i < lists.length; i++) {
					try {
						const result = await this.uploadFilePromise(lists[i].url);

						let item = this.returnFileList[fileListLen];
						this.returnFileList.splice(fileListLen, 1, Object.assign(item, {
							status: 'success',
							message: '',
							url: result
						}));

						this.returnImages.push(result);
						fileListLen++;
					} catch (error) {
						console.error('上传失败:', error);
						let item = this.returnFileList[fileListLen];
						this.returnFileList.splice(fileListLen, 1, Object.assign(item, {
							status: 'failed',
							message: '上传失败'
						}));
						fileListLen++;
					}
				}

				this.uploading = false;
			},

			deleteReturnPic(event) {
				if (this.uploading) return;
				this.returnFileList.splice(event.index, 1);
				this.returnImages.splice(event.index, 1);
			},

			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					upload({
						url: '/infra/file/upload',
						filePath: url,
					}).then((res) => {
						resolve(res.data);
					}).catch(reject);
				});
			},

			// 格式化时间戳
			formatTimestamp(timestamp) {
				if (!timestamp) return null;
				const date = new Date(timestamp);
				const year = date.getFullYear();
				const month = (date.getMonth() + 1).toString().padStart(2, '0');
				const day = date.getDate().toString().padStart(2, '0');
				const hours = date.getHours().toString().padStart(2, '0');
				const minutes = date.getMinutes().toString().padStart(2, '0');
				return `${year}-${month}-${day} ${hours}:${minutes}`;
			},
		}
	}
</script>

<style scoped lang="scss">
	.car-card-line {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.car-card {
		font-size: 15px;
		font-weight: bold;
		width: 70px;
		height: 28px;
		line-height: 28px;
		border-radius: 10px 0 10px 0;
		background: #edf3fe;
		color: #4487fa;
		text-align: center;
	}

	.car-card-state {
		font-size: 15px;
		width: 70px;
		height: 28px;
		line-height: 28px;
		text-align: center;
	}

	.state-blue {
		background: #edf3fe;
		color: #4487fa;
	}

	.state-red {
		background: #fbeced;
		color: #d63338;
	}

	.state-green {
		background: #edf7ec;
		color: #48be3a;
	}

	.content {
		width: 100%;
		height: calc(100vh);
		background-color: #f6f7fc;
		box-sizing: border-box;
	}

	.top-icon {
		box-sizing: border-box;
		width: 100%;
		padding: 5px 14px;
		background: #317dfa;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.dil {
		background-color: #f6f7fc;
		box-sizing: border-box;
		padding: 15px 12px;
		height: calc(100% - 155px);
		overflow-y: auto;
	}

	.h-text {
		font-size: 14px;
		font-weight: 400;
		color: #ffffff;
	}

	.search-box {
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.search-button {
		width: 15%;
		height: 30px;
		font-size: 14px;
		margin: 10px;
		line-height: 30px;
		text-align: center;
		color: #ffffff;
		background: rgba(255, 255, 255, 0.3);
		border-radius: 15px;
	}

	.s-input {
		margin-left: 10px;
		width: 78%;
		height: 56rpx;
		background: #fff;
		border-radius: 50px;
		box-sizing: border-box;
		display: flex;
		align-items: center;
		padding: 0px 10px;

		input {
			margin-left: 5px;
			flex: 1;
			width: 0;
			font-size: 14px;
			color: #999999;
		}
	}

	.top-tap {
		width: 100%;
		display: flex;
		align-items: center;
		box-sizing: border-box;
		padding-top: 5px;
	}

	.tap-box {
		width: 33%;
		font-size: 15px;
		font-weight: 400;
		color: #ffffff;
		text-align: center;
	}

	.gang {
		width: 80%;
		height: 3px;
		margin: 1px auto;
		border-radius: 12px;
		background: white;
	}

	.d-box {
		width: 100%;
		background: white;
		border-radius: 10px;
		margin-bottom: 15px;
		box-sizing: border-box;
		padding: 8px;
		position: relative;
		overflow: hidden;
		padding-top: 30px;
	}

	.d-y-top {
		position: absolute;
		top: 0px;
		left: 0px;
		width: 40px;
		height: 20px;
		border-radius: 0px 0px 6px 0px;
		background-color: #339DFF;
		color: white;
		font-size: 12px;
		text-align: center;
	}

	.t-right {
		width: 100%;
		display: flex;
		justify-content: flex-end;

		.bq {
			width: 55px;
			height: 20px;
			background: #FFD7D7;
			border-radius: 4px;
			font-size: 12px;
			font-weight: 400;
			color: #FF4C4C;
			display: flex;
			justify-content: center;
			align-items: center;
		}

		.bq2 {
			width: 55px;
			height: 20px;
			background: #CDE2FF;
			border-radius: 4px;
			font-size: 12px;
			font-weight: 400;
			color: #3289FF;
			display: flex;
			justify-content: center;
			align-items: center;
		}
	}

	.d-left {
		margin-left: 10px;
		display: flex;
		font-size: 16px;
		font-weight: bold;
		color: #666666;
		margin-bottom: 10px;
	}

	.t-left {
		margin-left: 10px;
		display: flex;
		font-size: 12px;
		font-weight: 400;
		color: #666666;
		margin-bottom: 5px;
	}

	.x-left {
		margin-left: 10px;
		display: flex;
		justify-content: space-between;
		font-size: 12px;
		font-weight: 400;
		color: #666666;
	}

	.cc {
		font-weight: bold;
	}

	.hong {
		font-size: 16px;
		font-weight: 400;
		color: #F85021;
	}

	.ques {
		margin: 0px auto;
		margin-top: 40px;
		width: 80%;

		image {
			width: 100%;
		}
	}

	.boxt {
		width: 100%;
		background-color: white;
		border-radius: 6px;
		margin-top: 14px;
		overflow: hidden;
		display: flex;
		align-items: center;
		box-sizing: border-box;
		padding-bottom: 15px;
	}

	.boxt-left {
		width: 80%;
		height: 100%;
	}

	.left-lan {
		width: 50px;
		height: 25px;
		display: flex;
		justify-content: center;
		align-items: center;
		background-color: #207EFE;
		font-size: 14px;
		color: white;
		border-radius: 0px 0px 6px 0px;
	}

	.text1 {
		margin-left: 24px;
		margin-top: 5px;
		color: #333333;
		font-size: 16px;
		font-weight: bold;
		color: #333333;
	}

	.lanzi {
		font-weight: bold;
		color: #4C98FF;
	}

	.text2 {
		margin-left: 24px;
		margin-top: 5px;
		color: #333333;
		font-size: 16px;
		font-weight: 400;
		color: #333333;
	}

	.boxt-right {
		width: 20%;
		height: 100%;
		position: relative;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.zhtai {
		position: absolute;
		top: 10px;
		right: 10px;
		width: 60px;
		height: 25px;
		box-sizing: border-box;
		background: #FFD7D7;
		border-radius: 4px;
		display: flex;
		justify-content: center;
		align-items: center;
		color: #FF4C4C;
		font-size: 14px;
	}

	.dianhua {
		position: absolute;
		bottom: -110px;
		right: 10px;
		display: flex;
		font-size: 14px;
		font-weight: 400;
		color: #3289FF;
	}

	.ticon {
		width: 12px;
		height: 13px;
		margin-right: 5px;

		image {
			width: 100%;
			height: 100%;
		}
	}

	.aniiu {
		width: 55px;
		height: 55px;
		border-radius: 50%;
		background: #3289FF;
		color: white;
		display: flex;
		align-items: center;
		font-size: 18px;
		font-weight: bold;
		justify-content: center;
	}

	.boxa-box {
		box-sizing: border-box;
		width: 95%;
		margin: 8px auto;
	}

	.boxa {
		background: #FFFFFF;
		padding: 15px;
		box-shadow: 0px 0px 8px -5px #888888;
	}

	.box-bs {
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin: 10px auto;
	}

	.zc {
		font-size: 16px;
		font-weight: 400;
		color: #363636
	}

	.hei-title {
		margin-left: 10px;
		font-size: 18px;
		font-weight: 600;
		color: #363636;
	}

	.yihang {
		font-size: 16px;
		font-weight: 400;
		color: #363636;
		margin-top: 10px;
	}

	.right-box {
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: flex-end;
		margin-top: 10px;
	}

	.janniu {
		width: 100%;
		height: 45px;
		background: #317cfa;
		border-radius: 0 0 10px 10px;
		display: flex;
		align-items: center;
		justify-content: center;
		color: white;
		font-size: 16px;
	}

	.ques {
		width: 90%;
		margin: 100px auto;
	}

	.custom-dialog {
		width: 320px;
		background-color: #fff;
		border-radius: 12px;
		padding: 20px;
		box-sizing: border-box;
	}

	.dialog-title {
		font-size: 18px;
		font-weight: bold;
		text-align: center;
		margin-bottom: 15px;
		color: #333;
	}

	.dialog-content {
		margin-bottom: 20px;
	}

	.dialog-tip {
		font-size: 14px;
		color: #666;
		margin-bottom: 10px;
		display: block;
	}

	.remark-input {
		width: 100%;
		height: 100px;
		border: 1px solid #ddd;
		border-radius: 6px;
		padding: 10px;
		box-sizing: border-box;
		font-size: 14px;
	}

	.dialog-buttons {
		display: flex;
		justify-content: space-between;
	}

	.dialog-button {
		width: 45%;
		height: 40px;
		line-height: 40px;
		text-align: center;
		border-radius: 6px;
		font-size: 16px;
	}

	.dialog-button.cancel {
		background-color: #f1f1f1;
		color: #666;
	}

	.dialog-button.confirm {
		background-color: #317dfa;
		color: #fff;
	}

	.license-num {
		font-size: 20px;
		margin-bottom: 5px;
		font-weight: 700;
	}

	.return-car-dialog {
		width: 340px;
		padding: 20px;
	}

	.upload-section {
		margin-top: 20px;
	}

	.section-title {
		font-size: 16px;
		font-weight: bold;
		margin-bottom: 10px;
		color: #333;
	}

	.dialog-button:disabled {
		opacity: 0.6;
		pointer-events: none;
	}
</style>