<template>
	<view>
		<view class="orderCard" @click="onShowDetail">
			<!-- 司机信息部分 - 适用于司机端和历史订单 -->
			<view class="orderInfoContainer" v-if="activeTab === 0 || isHistoryPage || isExpanded">
				<view class="infoRow" style="margin-top: 20rpx;">
					<text class="infoLabel" style="color: black; font-weight: bold; font-size: 32rpx;">司机信息</text>
				</view>
				<view class="infoRow">
					<text class="infoLabel">司机姓名:</text>
					<text class="infoValue">{{ orderData.driverName || '暂无数据' }}</text>
				</view>
				<view class="infoRow">
					<text class="infoLabel">司机手机号:</text>
					<text class="infoValue">{{ orderData.driverPhoneNum || '暂无数据' }}</text>
				</view>
				<view class="infoRow">
					<text class="infoLabel">救援车辆：</text>
					<text class="infoValue">{{ orderData.driverCarNum || '暂无数据' }}</text>
				</view>
				<view class="infoRow">
					<text class="infoLabel">救援类型：</text>
					<text class="infoValue">{{ orderData.rescueTypeStr || '暂无数据' }}</text>
				</view>

				<view class="infoRow">
					<text class="infoLabel">开始时间：</text>
					<text class="infoValue">{{ formatTimestamp(orderData.rescueStartTime) || '暂无数据' }}</text>
				</view>
				<view class="infoRow">
					<text class="infoLabel">完成时间：</text>
					<text class="infoValue">{{ formatTimestamp(orderData.rescueEndTime) || '暂无数据' }}</text>
				</view>
				<view class="infoRow">
					<text class="infoLabel">耗时：</text>
					<text
						class="infoValue">{{ calculateDuration(orderData.rescueStartTime, orderData.rescueEndTime) }}</text>
				</view>
			</view>

			<!-- 业务信息部分 - 适用于业务端和历史订单 -->
			<view class="orderInfoContainer" v-if="activeTab === 1 || isExpanded || isHistoryPage">
				<view class="infoRow" style="margin-top: 20rpx;">
					<text class="infoLabel" style="color: black; font-weight: bold; font-size: 32rpx;">业务信息</text>
				</view>
				<view class="infoRow">
					<text class="infoLabel">渠道：</text>
					<text class="infoValue">{{ orderData.channel || '暂无数据' }}</text>
				</view>
				<view class="infoRow">
					<text class="infoLabel">来源：</text>
					<text class="infoValue">{{ orderData.source || '暂无数据' }}</text>
				</view>
				<view class="infoRow">
					<text class="infoLabel">故障车经办人：</text>
					<text class="infoValue">{{ orderData.connectionName || '暂无数据' }}</text>
				</view>
				<view class="infoRow">
					<text class="infoLabel">经办人电话：</text>
					<text class="infoValue">{{ orderData.connectionPhone || '暂无数据' }}</text>
				</view>
				<view class="infoRow">
					<text class="infoLabel">调度：</text>
					<text class="infoValue">{{ orderData.secondDispatchName || '暂无数据' }}</text>
				</view>
				<view class="infoRow">
					<text class="infoLabel">当前状态</text>
					<text class="infoValue">{{ orderData.rescueStatusStr || '暂无数据' }}</text>
				</view>
				<view class="infoRow">
					<text class="infoLabel">收款状态：</text>
					<text class="infoValue">{{ orderData.orderStatusStr || '暂无数据' }}</text>
				</view>
				<view class="infoRow">
					<text class="infoLabel">收款人：</text>
					<text class="infoValue">{{ orderData.orderSigningRealName || '暂无数据' }}</text>
				</view>
			</view>

			<!-- 客户信息部分 - 适用于客户端和历史订单 -->
			<view class="orderInfoContainer" v-if="activeTab === 2 || isExpanded || isHistoryPage">
				<view class="infoRow" style="margin-top: 20rpx;">
					<text class="infoLabel" style="color: black; font-weight: bold; font-size: 32rpx;">客户信息</text>
				</view>
				<view class="infoRow">
					<text class="infoLabel">车牌号：</text>
					<text class="infoValue">{{ orderData.licenseNum || '暂无数据' }}</text>
				</view>
				<view class="infoRow">
					<text class="infoLabel">故障车经办人：</text>
					<text class="infoValue">{{ orderData.connectionName || '暂无数据' }}</text>
				</view>
				<view class="infoRow">
					<text class="infoLabel">联系电话：</text>
					<text class="infoValue">{{ orderData.connectionPhone || '暂无数据' }}</text>
				</view>
				<view class="infoRow">
					<text class="infoLabel">品牌：</text>
					<text class="infoValue">{{ orderData.carBrand || '暂无数据' }}</text>
				</view>
				<view class="infoRow">
					<text class="infoLabel">规格：</text>
					<text class="infoValue">{{ orderData.carTypeStr || '暂无数据' }}</text>
				</view>
				<view class="infoRow">
					<text class="infoLabel">故障现象：</text>
					<text class="infoValue">{{ orderData.faultPhenomenon || '暂无数据' }}</text>
				</view>
				<view class="infoRow">
					<text class="infoLabel">故障地点：</text>
					<text class="infoValue">{{ orderData.rescuePosition || '暂无数据' }}</text>
				</view>
				<view class="infoRow">
					<text class="infoLabel">救援需求：</text>
					<text class="infoValue">{{ orderData.rescueNeeds || '暂无数据' }}</text>
				</view>
				<view class="infoRow">
					<text class="infoLabel">预估下车地点：</text>
					<text class="infoValue">{{ orderData.estimateDownCar || '暂无数据' }}</text>
				</view>
				<view class="infoRow">
					<text class="infoLabel">预估费用：</text>
					<text class="infoValue">{{ orderData.estimateMoney || '暂无数据' }}</text>
				</view>
				<view class="infoRow">
					<text class="infoLabel">实际下车地点：</text>
					<text class="infoValue">{{ orderData.actualDownCar || orderData.estimateDownCar || '暂无数据' }}</text>
				</view>
				<view class="infoRow">
					<text class="infoLabel">公里数：</text>
					<text
						class="infoValue">{{ orderData.startScale && orderData.endScale ? (orderData.endScale - orderData.startScale) : '暂无数据' }}</text>
				</view>
				<view class="infoRow">
					<text class="infoLabel">实际费用：</text>
					<text
						class="infoValue">{{ orderData.setMoney != null ? (orderData.setMoney / 100) : '暂无数据'  }}</text>
				</view>
			</view>

			<view class="orderCardFooter">
				<text class="orderCardDateTime">{{ orderData.rescueTime || orderData.createTime || "" }}</text>
				<view class="orderCardBtnGroup">
					<template v-if="showDispatchButton || checkPermi(['rescue_dispatch_info_btn'])">
						<view @click.stop="revokeId" class="orderCardRevokeItem">撤销工单</view>
					</template>
					<template v-if="showDispatchButton  || checkPermi(['rescue_dispatch_process_btn'])">
						<view @click.stop="viewDispatchDetails" class="orderCardDispatchItem">调度流程</view>
					</template>
					<template v-if="showDispatchButton">
						<view @click.stop="contactCustomer" class="orderCardBtnGroupItem"
							v-if="orderData.connectionPhone">联系客户</view>
					</template>
					<template v-if="!isHistoryPage && orderData.rescueStatus > 2">
						<view @click.stop="gettel" class="orderCardBtnGroupItem">联系司机</view>
					</template>

					<!-- <template v-if="!isHistoryPage && orderData.orderStatus == 3 && orderData.isWeiXiu!=='1'">
						<view @click.stop="showRepair" class="orderCardBtnGroupItem">转维修</view>
					</template> -->

				</view>
			</view>

			<!-- <view class="orderCardRevoke">
				<view class="orderCardBtnGroup">
					<template v-if="showDispatchButton">
						<view @click.stop="revokeId" class="orderCardRevokeItem">撤销工单</view>
					</template>
				</view>
			</view> -->

			<view class="expand-control" @click.stop="toggleExpand" v-if="!isHistoryPage">
				<text class="expand-text">{{ isExpanded ? '收起' : '展开' }}全部信息</text>
				<u-icon :name="isExpanded ? 'arrow-up' : 'arrow-down'" color="#317DFA" size="16"></u-icon>
			</view>

			<!-- 历史订单的简单状态显示 -->
			<view class="history-status" v-if="isHistoryPage">
				<text :class="['status-tag', getStatusClass()]">{{ getStatusText() }}</text>
			</view>
		</view>

		<!-- 各种弹窗和选择器 -->
		<u-action-sheet :show="showDispatcherOptionsSheet" :actions="dispatcherActions" title="请选择指派类型"
			@select="onDispatcherOptionSelect" @close="showDispatcherOptionsSheet = false"></u-action-sheet>
		<u-picker :show="show" :columns="columns" @confirm="confirms" @cancel="cancels" keyName="realName"></u-picker>
		<u-picker :show="secondShow" :columns="secondColumns" @confirm="secondConfirms" @cancel="secondCancels"
			keyName="nickname"></u-picker>
		<u-modal :show="showDelete" title="是否确认删除" :showCancelButton="true" @confirm="deleteOk"
			@cancel="deleteCancel"></u-modal>
		<u-modal :show="toRepairShow" title="转维修" :showCancelButton="true" @confirm="toRepair"
			@cancel="()=>{toRepairShow=false}">
			<u-form labelPosition="left" :model="formData" ref="uForm">
				<u-form-item label="姓名" borderBottom>
					<u--input placeholder="请输入车主姓名" v-model="formData.name" border="none"></u--input>
				</u-form-item>
				<u-form-item label="联系电话" borderBottom>
					<u--input placeholder="请输入车主联系电话" v-model="formData.phone" border="none"></u--input>
				</u-form-item>

				<u-form-item label="品牌" borderBottom @click="pinpaiShow = true;" ref="item1">
					<u-input v-model="formData.brandName" disabled disabledColor="#ffffff" placeholder="请选择车辆品牌"
						border="none"></u-input>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>

				<u-form-item label="型号" borderBottom>
					<u--input placeholder="请输入车辆型号" v-model="formData.brandAndModel[1]" border="none"></u--input>
				</u-form-item>

				<u-form-item label="服务顾问" borderBottom @click="fuwuShow = true;" ref="item1">
					<u-input v-model="formData.adviserName" disabled disabledColor="#ffffff" placeholder="请选择服务顾问"
						border="none"></u-input>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>

			</u-form>
		</u-modal>

		<!-- 确认订单完成弹窗 -->
		<u-modal :show="showConfirmComplete" title="确认订单完成" :showCancelButton="true" @confirm="confirmComplete"
			@cancel="cancelComplete">
			<view class="confirm-modal-content">
				<text class="modal-label">备注信息（可选）:</text>
				<u--textarea v-model="completeRemark" placeholder="请输入备注信息" border="bottom" autoHeight
					class="remark-input"></u--textarea>
			</view>
		</u-modal>

		<!-- 同意挂账弹窗 -->
		<u-modal :show="showAgreeHangAccount" title="同意挂账" :showCancelButton="true" @confirm="agreeHangAccount"
			@cancel="cancelAgreeHangAccount">
			<view class="modal-content">
				<text>是否同意该订单挂账？</text>
			</view>
		</u-modal>

		<!-- 确认挂账信息弹窗 -->
		<u-modal :show="showConfirmHangAccount" :showConfirmButton="false" :showCancelButton="false">
			<view class="modal-content">
				<text class="modal-title">确认挂账信息</text>
				<view class="amount-display">
					<text class="amount-label">挂账金额：</text>
					<view class="amount-value">{{ orderData.setMoney != null ? (orderData.setMoney / 100) : '0' }}
						元</view>
				</view>
				<view class="amount-display">
					<text class="amount-label">救援司机：</text>
					<view class="amount-value-two">{{ orderData.driverName  }}</view>
				</view>
				<view class="amount-display">
					<text class="amount-label">挂账负责人：</text>
					<view class="amount-value-two">{{ orderData.orderSigningPersonName  }}</view>
				</view>
				<view class="amount-display">
					<text class="amount-label">故障车牌号：</text>
					<view class="amount-value-two">{{ orderData.licenseNum  }}</view>
				</view>
				<view class="confirm-modal-content">
					<text class="modal-label">备注信息（可选）:</text>
					<u--textarea v-model="completeRemark" placeholder="请输入备注信息" border="bottom" autoHeight
						class="remark-input"></u--textarea>
				</view>
				<view class="hang-account-buttons">
					<view class="hang-account-btn cancel" @click="cancelConfirmHangAccount">取消</view>
					<view class="hang-account-btn received" @click="confirmHangAccountReceived">确认</view>
				</view>
			</view>
		</u-modal>

		<!-- 查看挂账信息弹窗 -->
		<u-modal :show="showLookConfirmHangAccount" :showConfirmButton="false" :showCancelButton="false">
			<view class="modal-content">
				<text class="modal-title">已确认挂账信息</text>
				<view class="amount-display">
					<text class="amount-label">挂账金额：</text>
					<view class="amount-value">{{ orderData.setMoney != null ? (orderData.setMoney / 100) : '0' }}
						元</view>
				</view>
				<view class="amount-display">
					<text class="amount-label">救援司机：</text>
					<view class="amount-value-two">{{ orderData.driverName  }}</view>
				</view>
				<view class="amount-display">
					<text class="amount-label">故障车牌号：</text>
					<view class="amount-value-two">{{ orderData.licenseNum  }}</view>
				</view>
				<view class="amount-display">
					<text class="amount-label">挂账负责人：</text>
					<view class="amount-value-two">{{ orderData.orderSigningPersonName  }}</view>
				</view>
				<view class="amount-display">
					<text class="amount-label">挂账信息确认人：</text>
					<view class="amount-value-two">{{ orderData.orderSigningChargeName  }}</view>
				</view>
				<view class="confirm-modal-content">
					<text class="modal-label">备注信息:</text>
					<view class="amount-value-two">{{ orderData.orderSigningRemark  }}</view>
				</view>
				<view class="hang-account-buttons" style="margin-top: 20px;">
					<view class="hang-account-btn received" @click="cancelLookConfirmHangAccount">关闭</view>
				</view>
			</view>
		</u-modal>

		<u-picker :show="pinpaiShow" :columns="[brandList]" :keyName="'brandName'" @confirm="onPinpaiConfirm"
			@cancel="()=>{pinpaiShow=false}"></u-picker>
		<u-picker :show="fuwuShow" :columns="[staffList]" :keyName="'name'" @confirm="onFuwuConfirm"
			@cancel="()=>{fuwuShow=false}"></u-picker>
		<u-modal :show="showRevoke" title="是否确认撤销" :showCancelButton="true" @confirm="revokeOk"
			@cancel="revokeCancel"></u-modal>
	</view>
</template>

<script>
	import request from '../../utils/request';
	import {
		getTenantId,
		hasRole,
		hasRoleNew
	} from "@/utils/auth";
	import {
		getDictDataById
	} from "@/utils/utils.js";
	import {
		checkPermi,
		checkRole
	} from "@/utils/permission";
	export default {
		props: {
			orderData: {
				type: Object,
				default: () => {
					return {}
				}
			},
			activeTab: {
				type: Number,
				default: 0
			},
			status: {
				type: [String, Number],
				default: ''
			},
			brandList: {
				type: Array,
				default: () => []
			},
			staffList: {
				type: Array,
				default: () => []
			},
			// 新增属性：标识是否为历史订单页面
			isHistoryPage: {
				type: Boolean,
				default: false
			}
		},
		computed: {
			showDispatchButton() {
				// 基础条件
				if (this.isHistoryPage) return false
				if (this.orderData.rescueStatus <= 2) return false

				// 满足以下任一条件即可显示
				return (
					this.userinfo.id == this.orderData.secondDispatchId ||
					this.hasRoleNew('jiuyuan') ||
					(this.hasRoleNew('ddzx') && this.orderData.dispatchLevel == 2)
				)
			}
		},
		data() {
			return {
				columns: [],
				firstColumns: [],
				secondColumns: [],
				id: '',
				show: false,
				firstShow: false,
				secondShow: false,
				showDelete: false,
				toRepairShow: false,
				pinpaiShow: false,
				fuwuShow: false,
				formData: {
					brandAndModel: []
				},
				sectionRoadName: '未知',
				isExpanded: false,
				showDispatcherOptionsSheet: false,
				isSecondDispatcherDirect: false,
				dispatcherActions: [{
						name: '二级调度',
						value: 'second'
					},
					{
						name: '司机',
						value: 'driver'
					}
				],
				userinfo: {},
				showConfirmComplete: false,
				completeRemark: '',
				showAgreeHangAccount: false,
				showConfirmHangAccount: false,
				showLookAgreeHangAccount: false,
				showLookConfirmHangAccount: false,

				showRevoke: false,
			}
		},

		created() {
			this.userinfo = uni.getStorageSync('userInfo')
			console.log('userinfo', this.userinfo)
		},
		watch: {
			activeTab(newVal) {
				console.log('选项卡切换了:', newVal);
			}
		},
		methods: {
			hasRole,
			hasRoleNew,
			checkPermi,
			checkRole,

			toggleExpand() {
				this.isExpanded = !this.isExpanded;
			},

			onPinpaiConfirm(e) {
				console.log(e)
				this.formData.brandName = e.value[0].brandName
				this.formData.brandAndModel[0] = e.value[0].id
				this.pinpaiShow = false
			},
			onFuwuConfirm(e) {
				this.formData.adviserName = e.value[0].name
				this.formData.adviserId = e.value[0].id
				this.formData.userId = e.value[0].userId
				this.fuwuShow = false
			},
			showRepair() {
				if (this.orderData.connectionName) {
					this.formData.name = this.orderData.connectionName
				}
				if (this.orderData.connectionPhone) {
					this.formData.phone = this.orderData.connectionPhone
				}
				this.toRepairShow = true
			},
			toRepair() {
				let data = JSON.parse(JSON.stringify(this.formData))
				data.id = this.orderData.id
				console.log(data, 'data');
				request({
					url: '/app/rescueInfo/toRepair',
					method: 'post',
					params: data
				}).then((res) => {
					if (res.code == 200) {
						uni.showToast({
							title: '操作成功'
						})
						this.toRepairShow = false
						this.$emit('refresh')
					}
				})
			},
			onShowDetail() {
				uni.navigateTo({
					url: '/pages/details/details?id=' + this.orderData.id
				})
			},
			getzhipai() {
				console.log('getzhipai: ', this.getzhipai);
				if (hasRole('second_dispatcher')) {
					this.getSecondDriverlist()
				} else {
					this.getsjlist()
				}
				this.show = true
			},
			getSecondList() {
				this.getSecondDispatcher()
				this.secondShow = true
			},
			dispatcherSelect() {
				this.firstShow = true
			},

			// 显示指派选项弹窗
			showDispatcherOptions() {
				if (hasRoleNew('second_dispatcher')) {
					this.isSecondDispatcherDirect = true;
					this.getzhipai();
				} else {
					this.isSecondDispatcherDirect = false;
					this.showDispatcherOptionsSheet = true;
					console.log('hasRole', hasRole('ddzx'))
				}
			},

			// 处理指派选项选择
			onDispatcherOptionSelect(e) {
				if (e.value === 'second') {
					this.getSecondList()
				} else if (e.value === 'driver') {
					this.getzhipai()
				}
				this.showDispatcherOptionsSheet = false;
			},
			getsjlist() {
				this.columns = []
				request({
					url: '/app/rescueInfo/driverInMap?searchValue=',
					method: 'get',
				}).then((res) => {
					this.columns.push(res.data)
				})
			},
			getSecondDriverlist() {
				this.columns = []
				request({
					url: '/app/rescueInfo/secondDriverInMap?searchValue=',
					method: 'get',
				}).then((res) => {
					this.columns.push(res.data)
				})
			},
			getFirstDispatcher() {
				this.firstColumns = []
				const tenantId = getTenantId()
				request({
					url: `/company/staff/staffListByRoleCode?tenantId=${tenantId}&code=ddzx`,
					method: 'get',
				}).then((res) => {
					this.firstColumns.push(res.data)
					console.log('firstRes', res)
				})
			},
			getSecondDispatcher() {
				this.secondColumns = []
				const tenantId = getTenantId()
				request({
					url: `/company/staff/staffListByRoleCode?tenantId=${tenantId}&code=second_dispatcher`,
					method: 'get',
				}).then((res) => {
					this.secondColumns.push(res.data)
					console.log('secondRes', res)
				})
			},
			confirms(e) {
				console.log(e);
				let data = {
					rescueId: this.orderData.id,
					driverId: e.value[0].id
				}
				request({
					url: '/system/rescueInfo/designateDriver',
					method: 'post',
					params: data
				}).then((res) => {
					console.log('确认司机', res);
					if (res.code == 200) {
						if (hasRole('ddzx')) {
							let editData = {
								...this.orderData,
								secondDispatchId: this.userinfo.id,
								secondDispatchName: this.userinfo.nickname
							}
							request({
								url: '/app/rescueInfo/edit',
								method: 'post',
								data: editData
							}).then((editRes) => {
								console.log('ddzx更新二级调度信息', editRes);
								if (editRes.code == 200) {
									uni.showToast({
										title: '指派成功'
									})
									this.$emit('refresh')
								}
								this.show = false;
							}).catch((editErr) => {
								console.error('更新二级调度信息失败', editErr);
								this.show = false;
							})
						} else {
							uni.showToast({
								title: '指派成功'
							})
							this.$emit('refresh')
							this.show = false;
						}
					}
				}).catch((err) => {
					console.error('指派司机失败', err);
					this.show = false;
				})
			},
			secondConfirms(e) {
				let data = {
					...this.orderData,
					secondDispatchId: e.value[0].id,
					secondDispatchName: e.value[0].nickname
				}
				request({
					url: '/app/rescueInfo/edit',
					method: 'post',
					data: data
				}).then((res) => {
					console.log('确认司机', res);
					if (res.code == 200) {
						uni.showToast({
							title: '指派成功'
						})
						this.$emit('refresh')
					}
				})
				this.secondShow = false
			},
			cancels() {
				this.show = false;
				if (!this.isSecondDispatcherDirect) {
					this.showDispatcherOptions();
				} else {
					this.isSecondDispatcherDirect = false;
				}
			},
			secondCancels() {
				this.secondShow = false
				this.showDispatcherOptions();
			},
			deleteId() {
				this.showDelete = true
				return
			},
			deleteOk() {
				request({
					url: "/app/rescueInfo/delRescueInfo?id=" + this.orderData.id,
					method: 'post',
				}).then(res => {
					if (res.code == 200) {
						uni.showToast({
							title: "删除成功"
						})
						this.$emit('deleteOk')
					}
				})
				this.showDelete = false
			},
			deleteCancel() {
				console.log("取消");
				this.showDelete = false
			},
			gettel() {
				if (this.orderData.driverPhoneNum) {
					uni.makePhoneCall({
						phoneNumber: this.orderData.driverPhoneNum
					});
				}
			},

			// 联系客户（历史订单专用）
			contactCustomer() {
				if (this.orderData.connectionPhone) {
					uni.makePhoneCall({
						phoneNumber: this.orderData.connectionPhone
					});
				}
			},

			// 显示确认订单完成弹窗
			showConfirmModal() {
				this.completeRemark = '';
				this.showConfirmComplete = true;
			},

			// 取消确认
			cancelComplete() {
				this.completeRemark = '';
				this.showConfirmComplete = false;
			},

			// 确认订单完成
			async confirmComplete() {
				console.log('this.orderData', this.orderData)
				if (this.orderData.feeType == 2 && !this.orderData.secondDispatchId && !this.orderData
					.secondDispatchName) {
					uni.showToast({
						title: '请先确认挂账信息',
						icon: 'none'
					});
					return;
				}
				let saveData = {
					rescueInfoId: this.orderData.id,
					title: '调度 · 确认订单已完成',
					remark: this.completeRemark,
					autoRemark: '确认人: ' + this.userinfo.nickname
				}

				let rescueData = {
					id: this.orderData.id,
					feeType: this.orderData.feeType,
					carType: this.orderData.carType,
					isWeiXiu: this.orderData.isWeiXiu,
					rescueType: this.orderData.rescueType,
					isAppointment: this.orderData.isAppointment,
					isKouChe: this.orderData.isKouChe,
					rescuePosition: this.orderData.rescuePosition,
					rescueStatus: '5',
				}

				try {
					const [saveResult, rescueResult] = await Promise.all([
						this.saveConfirmMsg(saveData),
						this.rescueInfoEdit(rescueData)
					]);

					if (saveResult && rescueResult) {
						uni.showToast({
							title: '订单完成确认成功',
							icon: 'success'
						});
						this.$emit('refresh');
					} else {
						uni.showToast({
							title: '操作失败，请重试',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('确认订单完成失败:', error);
					uni.showToast({
						title: '操作失败，请重试',
						icon: 'none'
					});
				} finally {
					this.completeRemark = '';
					this.showConfirmComplete = false;
				}
			},

			// 更新救援信息
			rescueInfoEdit(rescueData) {
				return new Promise((resolve, reject) => {
					request({
						url: '/app/rescueInfo/edit',
						method: 'post',
						data: rescueData
					}).then((res) => {
						console.log(res);
						if (res.code == 200) {
							resolve(true);
						} else {
							resolve(false);
						}
					}).catch((error) => {
						console.error('rescueInfoEdit error:', error);
						reject(error);
					});
				});
			},

			// 更新订单信息
			orderInfoEdit(orderData) {
				return new Promise((resolve, reject) => {
					request({
						url: '/rescue/orderInfo/edit',
						method: 'post',
						data: orderData
					}).then((res) => {
						console.log(res);
						if (res.code == 200) {
							resolve(true);
						} else {
							resolve(false);
						}
					}).catch((error) => {
						console.error('orderInfoEdit error:', error);
						reject(error);
					});
				});
			},

			// 存储节点信息
			saveConfirmMsg(saveData) {
				return new Promise((resolve, reject) => {
					request({
						url: '/app/driver/uploadDetailByDriver',
						method: 'post',
						data: saveData
					}).then((res) => {
						console.log(res);
						if (res.code == 200) {
							resolve(true);
						} else {
							resolve(false);
						}
					}).catch((error) => {
						console.error('saveConfirmMsg error:', error);
						reject(error);
					});
				});
			},

			// 显示同意挂账弹窗
			showAgreeModal() {
				this.showAgreeHangAccount = true;
			},

			// 同意挂账
			async agreeHangAccount() {
				console.log('同意挂账', this.orderData.id);
				let rescueData = {
					id: this.orderData.id,
					feeType: '2',
					carType: this.orderData.carType,
					isWeiXiu: this.orderData.isWeiXiu,
					rescueType: this.orderData.rescueType,
					isAppointment: this.orderData.isAppointment,
					isKouChe: this.orderData.isKouChe,
					rescuePosition: this.orderData.rescuePosition,
					rescueStatus: this.orderData.rescueStatus,
				}

				let orderData = {
					id: this.orderData.orderId,
					payType: 'qd'
				}

				try {
					const [rescueResult, orderResult] = await Promise.all([
						this.rescueInfoEdit(rescueData),
						this.orderInfoEdit(orderData)
					]);

					if (rescueResult && orderResult) {
						uni.showToast({
							title: '同意挂账成功',
							icon: 'success'
						});
						this.$emit('refresh');
					} else {
						uni.showToast({
							title: '操作失败，请重试',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('同意挂账失败:', error);
					uni.showToast({
						title: '操作失败，请重试',
						icon: 'none'
					});
				} finally {
					this.showAgreeHangAccount = false;
				}
			},

			// 取消同意挂账
			cancelAgreeHangAccount() {
				this.showAgreeHangAccount = false;
			},

			// 显示确认挂账信息弹窗
			showConfirmHangAccountModal() {
				this.completeRemark = '';
				this.showConfirmHangAccount = true;
			},

			// 取消确认挂账信息
			cancelConfirmHangAccount() {
				this.completeRemark = '';
				this.showConfirmHangAccount = false;
			},

			// 确认挂账信息
			async confirmHangAccountReceived() {
				console.log('确认挂账信息', this.orderData.id);
				let saveData = {
					rescueInfoId: this.orderData.id,
					title: '调度 · 确认挂账信息',
					remark: this.completeRemark,
					autoRemark: '确认人: ' + this.userinfo.nickname
				}

				let rescueData = {
					id: this.orderData.id,
					orderSigningChargeId: this.userinfo.id,
					orderSigningChargeName: this.userinfo.nickname,
					orderSigningRemark: this.completeRemark
				}

				try {
					const [saveResult, rescueResult] = await Promise.all([
						this.saveConfirmMsg(saveData),
						this.rescueInfoEdit(rescueData)
					]);

					if (saveResult && rescueResult) {
						uni.showToast({
							title: '挂账信息确认成功',
							icon: 'success'
						});
						this.$emit('refresh');
					} else {
						uni.showToast({
							title: '操作失败，请重试',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('确认挂账信息失败:', error);
					uni.showToast({
						title: '操作失败，请重试',
						icon: 'none'
					});
				} finally {
					this.completeRemark = '';
					this.showConfirmHangAccount = false;
				}
			},

			// 显示查看确认挂账信息弹窗
			showLookConfirmHangAccountModal() {
				this.showLookConfirmHangAccount = true;
			},

			// 关闭查看确认挂账信息弹窗
			cancelLookConfirmHangAccount() {
				this.showLookConfirmHangAccount = false;
			},

			// 格式化时间戳
			formatTimestamp(timestamp) {
				if (!timestamp) return '';
				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}`;
			},

			// 计算耗时
			calculateDuration(startTime, endTime) {
				if (!startTime || !endTime) return '暂无数据';

				const start = new Date(startTime);
				const end = new Date(endTime);
				const duration = end - start;

				const hours = Math.floor(duration / (1000 * 60 * 60));
				const minutes = Math.floor((duration % (1000 * 60 * 60)) / (1000 * 60));

				if (hours > 0) {
					return `${hours}小时${minutes}分钟`;
				} else {
					return `${minutes}分钟`;
				}
			},

			// 获取救援类型字符串
			getRescueTypeStr() {
				if (this.orderData.rescueType) {
					return getDictDataById(this.orderData.rescueType);
				}
				return '暂无数据';
			},

			// 获取状态字符串
			getStatusStr() {
				if (this.orderData.rescueStatus) {
					const statusMap = {
						0: '待指派',
						1: '待接单',
						2: '已接单',
						3: '救援中',
						4: '待确认',
						5: '已完成',
						6: '已取消'
					};
					return statusMap[this.orderData.rescueStatus] || '未知状态';
				}
				return '暂无数据';
			},

			// 获取状态文本（历史订单用）
			getStatusText() {
				const statusMap = {
					0: '待指派',
					1: '待接单',
					2: '已接单',
					3: '救援中',
					4: '待确认',
					5: '已完成',
					6: '已取消'
				};
				return statusMap[this.orderData.rescueStatus] || '未知状态';
			},

			// 获取状态类名（历史订单用）
			getStatusClass() {
				const statusClassMap = {
					0: 'status-pending',
					1: 'status-waiting',
					2: 'status-accepted',
					3: 'status-rescuing',
					4: 'status-confirming',
					5: 'status-completed',
					6: 'status-cancelled'
				};
				return statusClassMap[this.orderData.rescueStatus] || 'status-unknown';
			},

			viewDispatchDetails() {
				uni.navigateTo({
					url: '/pages/details/dispatchDetails?id=' + this.orderData.id
				});
			},

			revokeId() {
				this.showRevoke = true
				return
			},
			revokeOk() {
				request({
					url: "/app/rescueInfo/revokeRescueInfo?id=" + this.orderData.id,
					method: 'put'
				}).then(res => {
					if (res.code == 200) {
						uni.showToast({
							title: "撤销成功"
						})
						this.$emit('refresh')
					}
				})
				this.showRevoke = false
			},
			revokeCancel() {
				console.log("取消");
				this.showRevoke = false
			},
		}
	}
</script>

<style lang="scss" scoped>
	.orderCard {
		background-color: #fff;
		border-radius: 16rpx;
		padding: 32rpx;
		margin-bottom: 24rpx;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
		position: relative;
	}

	.orderInfoContainer {
		margin-bottom: 24rpx;
	}

	.infoRow {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 16rpx;
	}

	.infoLabel {
		font-size: 28rpx;
		color: #666;
		font-weight: 400;
	}

	.infoValue {
		font-size: 28rpx;
		color: #333;
		font-weight: 500;
		max-width: 60%;
		text-align: right;
	}

	.orderCardFooter {
		display: flex;
		flex-direction: column;
		/* justify-content: flex-start;
		align-items: center; */
		margin-top: 24rpx;
		padding-top: 24rpx;
		border-top: 1rpx solid #eee;
	}

	.orderCardRevoke {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-top: 24rpx;
		padding-top: 24rpx;
	}

	.orderCardDateTime {
		margin-bottom: 20rpx;
		font-size: 24rpx;
		color: #999;
	}

	.orderCardBtnGroup {
		display: flex;
		justify-content: flex-end;
		align-items: center;
		gap: 16rpx;
	}

	.orderCardBtnGroupItem {
		padding: 12rpx 24rpx;
		background-color: #317DFA;
		color: #fff;
		border-radius: 8rpx;
		font-size: 24rpx;
	}

	.orderCardDispatchItem {
		padding: 12rpx 24rpx;
		background-color: #67c23a;
		color: #fff;
		border-radius: 8rpx;
		font-size: 24rpx;
	}

	.orderCardRevokeItem {
		padding: 12rpx 24rpx;
		background-color: red;
		color: #fff;
		border-radius: 8rpx;
		font-size: 24rpx;
	}

	.expand-control {
		display: flex;
		align-items: center;
		justify-content: center;
		margin-top: 24rpx;
		padding: 16rpx;
		color: #317DFA;
		font-size: 26rpx;
	}

	.expand-text {
		margin-right: 8rpx;
	}

	/* 历史订单状态标签样式 */
	.history-status {
		position: absolute;
		top: 32rpx;
		right: 32rpx;
	}

	.status-tag {
		padding: 8rpx 16rpx;
		border-radius: 8rpx;
		font-size: 24rpx;
		font-weight: bold;
	}

	.status-pending {
		background-color: #FFE58F;
		color: #D48806;
	}

	.status-waiting {
		background-color: #91D5FF;
		color: #096DD9;
	}

	.status-accepted {
		background-color: #B7EB8F;
		color: #389E0D;
	}

	.status-rescuing {
		background-color: #FFBB96;
		color: #D4380D;
	}

	.status-confirming {
		background-color: #FFD666;
		color: #D46B08;
	}

	.status-completed {
		background-color: #87E8DE;
		color: #08979C;
	}

	.status-cancelled {
		background-color: #D9D9D9;
		color: #595959;
	}

	.status-unknown {
		background-color: #D9D9D9;
		color: #595959;
	}

	/* 挂账按钮组样式 */
	.hang-account-btn-group {
		display: flex;
		gap: 16rpx;
		margin-top: 24rpx;
	}

	.hang-account-btn {
		padding: 12rpx 24rpx;
		border-radius: 8rpx;
		font-size: 24rpx;
		font-weight: 500;
	}

	.hang-account-btn.agree {
		background-color: #52C41A;
		color: #fff;
	}

	.hang-account-btn.confirm {
		background-color: #1890FF;
		color: #fff;
	}

	.hang-account-btn.confirmed {
		background-color: #FAAD14;
		color: #fff;
	}

	/* 完成订单按钮样式 */
	.complete-order-btn {
		margin-top: 24rpx;
	}

	.complete-btn {
		padding: 12rpx 24rpx;
		background-color: #52C41A;
		color: #fff;
		border-radius: 8rpx;
		font-size: 24rpx;
		font-weight: 500;
		text-align: center;
	}

	/* 弹窗内容样式 */
	.modal-content {
		padding: 32rpx;
	}

	.modal-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		text-align: center;
		margin-bottom: 32rpx;
	}

	.amount-display {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 24rpx;
	}

	.amount-label {
		font-size: 28rpx;
		color: #666;
	}

	.amount-value {
		font-size: 32rpx;
		color: #FF4D4F;
		font-weight: bold;
	}

	.amount-value-two {
		font-size: 28rpx;
		color: #333;
		font-weight: 500;
	}

	.hang-account-buttons {
		display: flex;
		justify-content: space-around;
		margin-top: 48rpx;
	}

	.hang-account-btn.cancel {
		background-color: #D9D9D9;
		color: #595959;
		padding: 20rpx 40rpx;
		border-radius: 8rpx;
	}

	.hang-account-btn.received {
		background-color: #1890FF;
		color: #fff;
		padding: 20rpx 40rpx;
		border-radius: 8rpx;
	}

	.confirm-modal-content {
		padding: 24rpx 0;
	}

	.modal-label {
		font-size: 28rpx;
		color: #666;
		margin-bottom: 16rpx;
		display: block;
	}

	.remark-input {
		background-color: #F5F5F5;
		border-radius: 8rpx;
		padding: 16rpx;
		min-height: 120rpx;
	}
</style>