<template>
	<view class="rental-detail-page">
		<!-- 自定义导航栏 -->
		<view class="custom-nav safe-area-top">
			<view class="nav-content">
				<view class="nav-btn" @click="goBack">
					<uni-icons type="left" size="22" color="#1E293B"></uni-icons>
				</view>
				<text class="nav-title">租赁详情</text>
				<view class="nav-btn" @click="editRental">
					<uni-icons type="compose" size="22" color="#2563EB"></uni-icons>
				</view>
			</view>
		</view>

		<!-- 内容区域 -->
		<scroll-view scroll-y class="detail-content" v-if="rental.id">
			<!-- 状态卡片 -->
			<view class="status-card">
				<view class="status-header">
					<view class="status-tag" :class="rental.status">
						{{rental.statusText}}
					</view>
					<text class="create-time">创建于 {{rental.createTime}}</text>
				</view>
				<view class="progress-section" v-if="rental.status === 'active'">
					<view class="progress-bar">
						<view class="progress-fill" :style="{ width: progressPercent + '%' }"></view>
					</view>
					<view class="progress-info">
						<text>已租 {{rentedDays}} 天</text>
						<text>剩余 {{remainingDays}} 天</text>
					</view>
				</view>
			</view>

			<!-- 房源信息 -->
			<view class="section-title">房源信息</view>
			<view class="info-card">
				<view class="info-row">
					<text class="row-label">公寓</text>
					<text class="row-value">{{rental.apartmentName}}</text>
				</view>
				<view class="info-divider"></view>
				<view class="info-row">
					<text class="row-label">房间号</text>
					<text class="row-value">{{rental.roomNumber}}</text>
				</view>
				<view class="info-divider"></view>
				<view class="info-row" @click="viewRoomDetail">
					<text class="row-label">查看房间</text>
					<uni-icons type="arrowright" size="16" color="#94A3B8"></uni-icons>
				</view>
			</view>

			<!-- 租客信息 -->
			<view class="section-title">租客信息</view>
			<view class="renter-card">
				<view class="renter-header">
					<view class="renter-avatar">
						<text>{{rental.renterName.charAt(0)}}</text>
					</view>
					<view class="renter-info">
						<text class="renter-name">{{rental.renterName}}</text>
						<text class="renter-phone">{{rental.renterPhone}}</text>
					</view>
					<view class="contact-btn" @click="callRenter">
						<uni-icons type="phone-filled" size="20" color="#FFFFFF"></uni-icons>
					</view>
				</view>
				<view class="info-divider" v-if="rental.renterIdCard"></view>
				<view class="info-row" v-if="rental.renterIdCard">
					<text class="row-label">身份证号</text>
					<text class="row-value">{{maskIdCard(rental.renterIdCard)}}</text>
				</view>
			</view>

			<!-- 租赁信息 -->
			<view class="section-title">租赁信息</view>
			<view class="info-card">
				<view class="info-row">
					<text class="row-label">付租方式</text>
					<view class="payment-tag" :class="rental.paymentType">{{rental.paymentTypeText}}</view>
				</view>
				<view class="info-divider"></view>
				<view class="info-row">
					<text class="row-label">开始日期</text>
					<text class="row-value">{{rental.startDate}}</text>
				</view>
				<view class="info-divider"></view>
				<view class="info-row">
					<text class="row-label">结束日期</text>
					<text class="row-value" :class="{ 'text-danger': rental.isExpiringSoon }">{{rental.endDate}}</text>
				</view>
				<view class="info-divider"></view>
				<view class="info-row">
					<text class="row-label">月租金</text>
					<text class="row-value price">¥{{rental.rent}}</text>
				</view>
				<view class="info-divider"></view>
				<view class="info-row">
					<text class="row-label">押金</text>
					<text class="row-value">¥{{rental.deposit || 0}}</text>
				</view>
				<view class="info-divider" v-if="rental.waterMeterStart !== null"></view>
				<view class="info-row" v-if="rental.waterMeterStart !== null">
					<text class="row-label">水表起始</text>
					<text class="row-value">{{rental.waterMeterStart}} 吨</text>
				</view>
				<view class="info-divider" v-if="rental.electricityMeterStart !== null"></view>
				<view class="info-row" v-if="rental.electricityMeterStart !== null">
					<text class="row-label">电表起始</text>
					<text class="row-value">{{rental.electricityMeterStart}} 度</text>
				</view>
				<view class="info-divider" v-if="rental.remark"></view>
				<view class="info-row" v-if="rental.remark">
					<text class="row-label">备注</text>
					<text class="row-value">{{rental.remark}}</text>
				</view>
			</view>

			<!-- 即将到期提示 -->
			<view v-if="rental.isExpiringSoon && rental.status === 'active'" class="warning-card">
				<uni-icons type="info-filled" size="20" color="#EF4444"></uni-icons>
				<view class="warning-content">
					<text class="warning-title">租约即将到期</text>
					<text class="warning-desc">该租约还有 {{remainingDays}} 天到期，请及时处理续租或退租</text>
				</view>
			</view>

			<!-- 操作按钮 -->
			<view class="action-section" v-if="rental.status === 'active'">
				<view class="action-btn primary" @click="handleRenew">
					<uni-icons type="refresh-filled" size="20" color="#FFFFFF"></uni-icons>
					<text>办理续租</text>
				</view>
				<view class="action-btn warning" @click="handleChangeRoom">
					<uni-icons type="home-filled" size="20" color="#FFFFFF"></uni-icons>
					<text>办理换房</text>
				</view>
				<view class="action-btn danger" @click="handleTerminate">
					<uni-icons type="closeempty" size="20" color="#FFFFFF"></uni-icons>
					<text>办理退租</text>
				</view>
			</view>

			<!-- 退租信息 -->
			<view v-if="rental.status === 'terminated' && rental.terminateInfo" class="section-title">退租信息</view>
			<view v-if="rental.status === 'terminated' && rental.terminateInfo" class="info-card">
				<view class="info-row">
					<text class="row-label">退租日期</text>
					<text class="row-value">{{rental.terminateInfo.terminateDate}}</text>
				</view>
				<view class="info-divider"></view>
				<view class="info-row">
					<text class="row-label">水表最终读数</text>
					<text class="row-value">{{rental.terminateInfo.waterMeterEnd}} 吨</text>
				</view>
				<view class="info-divider"></view>
				<view class="info-row">
					<text class="row-label">电表最终读数</text>
					<text class="row-value">{{rental.terminateInfo.electricityMeterEnd}} 度</text>
				</view>
				<view class="info-divider"></view>
				<view class="info-row">
					<text class="row-label">退还押金</text>
					<text class="row-value">¥{{rental.terminateInfo.refundDeposit}}</text>
				</view>
				<view class="info-divider" v-if="rental.terminateInfo.remark"></view>
				<view class="info-row" v-if="rental.terminateInfo.remark">
					<text class="row-label">退租备注</text>
					<text class="row-value">{{rental.terminateInfo.remark}}</text>
				</view>
			</view>

			<view class="safe-area-bottom" style="height: 40rpx;"></view>
		</scroll-view>

		<!-- 加载状态 -->
		<view class="loading-state" v-else-if="isLoading">
			<uni-load-more status="loading"></uni-load-more>
		</view>

		<!-- 空状态 -->
		<view class="empty-state" v-else>
			<uni-icons type="folder-add-filled" size="80" color="#CBD5E1"></uni-icons>
			<text class="empty-text">租赁记录不存在</text>
			<button class="back-btn" @click="goBack">返回</button>
		</view>

		<!-- 退租弹窗 -->
		<uni-popup ref="terminatePopup" type="center">
			<view class="popup-content">
				<view class="popup-header">
					<text class="popup-title">办理退租</text>
					<uni-icons type="close" size="20" color="#94A3B8" @click="closeTerminatePopup"></uni-icons>
				</view>
				<view class="popup-body">
					<view class="form-item">
						<text class="form-label">租客</text>
						<text class="form-static">{{rental.renterName}}</text>
					</view>
					<view class="form-item">
						<text class="form-label">押金金额</text>
						<text class="form-static price">¥{{rental.deposit || 0}}</text>
					</view>
					<view class="form-item">
						<text class="form-label">水表最终读数</text>
						<input 
							type="digit" 
							v-model="terminateForm.waterMeterEnd" 
							placeholder="请输入水表读数"
							class="form-input"
						/>
					</view>
					<view class="form-item">
						<text class="form-label">电表最终读数</text>
						<input 
							type="digit" 
							v-model="terminateForm.electricityMeterEnd" 
							placeholder="请输入电表读数"
							class="form-input"
						/>
					</view>
					<view class="form-item">
						<text class="form-label">退还押金</text>
						<input 
							type="digit" 
							v-model="terminateForm.refundDeposit" 
							placeholder="请输入退还金额"
							class="form-input"
						/>
					</view>
					<view class="form-item">
						<text class="form-label">退租备注</text>
						<textarea 
							v-model="terminateForm.remark" 
							placeholder="请输入退租备注（选填）"
							class="form-textarea"
						/>
					</view>
				</view>
				<view class="popup-footer">
					<button class="btn-cancel" @click="closeTerminatePopup">取消</button>
					<button class="btn-confirm" :loading="submitLoading" @click="confirmTerminate">确认退租</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import rentalApi from '@/api/rental.js'
	
	export default {
		data() {
			return {
				rentalId: null,
				isLoading: false,
				submitLoading: false,
				rental: {},
				terminateForm: {
					waterMeterEnd: '',
					electricityMeterEnd: '',
					refundDeposit: '',
					remark: ''
				}
			}
		},
		computed: {
			progressPercent() {
				if (!this.rental.startDate || !this.rental.endDate) return 0
				const start = new Date(this.rental.startDate).getTime()
				const end = new Date(this.rental.endDate).getTime()
				const now = Date.now()
				const total = end - start
				const current = now - start
				const percent = (current / total) * 100
				return Math.min(Math.max(percent, 0), 100)
			},
			rentedDays() {
				if (!this.rental.startDate) return 0
				const start = new Date(this.rental.startDate)
				const now = new Date()
				return Math.floor((now - start) / (1000 * 60 * 60 * 24))
			},
			remainingDays() {
				if (!this.rental.endDate) return 0
				const end = new Date(this.rental.endDate)
				const now = new Date()
				return Math.ceil((end - now) / (1000 * 60 * 60 * 24))
			}
		},
		onLoad(options) {
			if (options.id) {
				this.rentalId = options.id
				this.loadRentalDetail(options.id)
			}
		},
		methods: {
			async loadRentalDetail(id) {
				this.isLoading = true
				try {
					const res = await rentalApi.getDetail(id)
					if (res.data) {
						const data = res.data
						this.rental = {
							id: data.id,
							apartmentName: data.Room?.Apartment?.name || '--',
							roomId: data.roomId,
							roomNumber: data.Room?.roomNumber || '--',
							renterId: data.renterId,
							renterName: data.Renter?.name || '--',
							renterPhone: data.Renter?.phone || '--',
							renterIdCard: data.Renter?.idCard || '',
							startDate: data.startDate,
							endDate: data.endDate,
							paymentType: data.paymentType,
							paymentTypeText: this.getPaymentTypeText(data.paymentType),
							rent: data.rent,
							deposit: data.deposit || 0,
							waterMeterStart: data.waterMeterStart,
							electricityMeterStart: data.electricityMeterStart,
							status: data.status,
							statusText: this.getStatusText(data.status),
							remark: data.remark,
							createTime: data.createTime,
							isExpiringSoon: this.isExpiringSoon(data.endDate) && data.status === 'active',
							terminateInfo: data.terminateInfo
						}
					}
				} catch (error) {
					console.error('加载租赁详情失败:', error)
					uni.showToast({
						title: '加载失败',
						icon: 'none'
					})
				} finally {
					this.isLoading = false
				}
			},
			
			editRental() {
				uni.navigateTo({
					url: `/pages/rental-add/rental-add?id=${this.rentalId}&mode=edit`
				})
			},
			
			viewRoomDetail() {
				uni.navigateTo({
					url: `/pages/room-detail/room-detail?id=${this.rental.roomId}`
				})
			},
			
			callRenter() {
				if (this.rental.renterPhone) {
					uni.makePhoneCall({
						phoneNumber: this.rental.renterPhone
					})
				}
			},
			
			maskIdCard(idCard) {
				if (!idCard || idCard.length < 8) return idCard
				return idCard.substring(0, 4) + '********' + idCard.substring(idCard.length - 4)
			},
			
			handleRenew() {
				uni.navigateTo({
					url: `/pages/rental-renew/rental-renew?id=${this.rentalId}`
				})
			},

			handleChangeRoom() {
				uni.navigateTo({
					url: `/pages/rental-change-room/rental-change-room?id=${this.rentalId}`
				})
			},
			
			handleTerminate() {
				this.terminateForm = {
					waterMeterEnd: '',
					electricityMeterEnd: '',
					refundDeposit: this.rental.deposit || '',
					remark: ''
				}
				this.$refs.terminatePopup.open()
			},
			
			closeTerminatePopup() {
				this.$refs.terminatePopup.close()
			},
			
			async confirmTerminate() {
				// 表单验证
				if (!this.terminateForm.waterMeterEnd) {
					uni.showToast({ title: '请输入水表读数', icon: 'none' })
					return
				}
				if (!this.terminateForm.electricityMeterEnd) {
					uni.showToast({ title: '请输入电表读数', icon: 'none' })
					return
				}
				
				this.submitLoading = true
				try {
					await rentalApi.terminate(this.rentalId, {
						waterMeterEnd: parseFloat(this.terminateForm.waterMeterEnd),
						electricityMeterEnd: parseFloat(this.terminateForm.electricityMeterEnd),
						refundDeposit: parseFloat(this.terminateForm.refundDeposit) || 0,
						remark: this.terminateForm.remark
					})
					
					uni.showToast({
						title: '退租办理成功',
						icon: 'success'
					})
					
					this.closeTerminatePopup()
					this.loadRentalDetail(this.rentalId)
				} catch (error) {
					console.error('退租失败:', error)
					uni.showToast({
						title: '退租办理失败',
						icon: 'none'
					})
				} finally {
					this.submitLoading = false
				}
			},
			
			goBack() {
				uni.navigateBack()
			},
			
			getPaymentTypeText(type) {
				const map = {
					monthly: '月租',
					quarterly: '季租',
					half_year: '半年租',
					yearly: '年租'
				}
				return map[type] || type
			},
			
			getStatusText(status) {
				const map = {
					active: '在租',
					expired: '已到期',
					terminated: '已终止'
				}
				return map[status] || status
			},
			
			isExpiringSoon(endDate) {
				if (!endDate) return false
				const end = new Date(endDate)
				const now = new Date()
				const diffDays = Math.ceil((end - now) / (1000 * 60 * 60 * 24))
				return diffDays <= 7 && diffDays >= 0
			}
		}
	}
</script>

<style scoped>
	.rental-detail-page {
		min-height: 100vh;
		background: #F8FAFC;
		display: flex;
		flex-direction: column;
	}

	/* 自定义导航栏 */
	.custom-nav {
		background: #FFFFFF;
		border-bottom: 2rpx solid #F1F5F9;
	}

	.nav-content {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 20rpx 32rpx;
	}

	.nav-btn {
		width: 72rpx;
		height: 72rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 50%;
	}

	.nav-btn:active {
		background: #F1F5F9;
	}

	.nav-title {
		font-size: 34rpx;
		font-weight: 600;
		color: #1E293B;
	}

	/* 内容区域 */
	.detail-content {
		flex: 1;
		padding: 24rpx 32rpx;
	}

	/* 状态卡片 */
	.status-card {
		background: #FFFFFF;
		border-radius: 20rpx;
		padding: 24rpx;
		margin-bottom: 24rpx;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
	}

	.status-header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-bottom: 20rpx;
	}

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

	.status-tag.active {
		background: #D1FAE5;
		color: #059669;
	}

	.status-tag.expired {
		background: #F3F4F6;
		color: #6B7280;
	}

	.status-tag.terminated {
		background: #FEE2E2;
		color: #DC2626;
	}

	.create-time {
		font-size: 24rpx;
		color: #94A3B8;
	}

	/* 进度条 */
	.progress-section {
		margin-top: 16rpx;
	}

	.progress-bar {
		height: 8rpx;
		background: #F1F5F9;
		border-radius: 4rpx;
		overflow: hidden;
	}

	.progress-fill {
		height: 100%;
		background: linear-gradient(90deg, #2563EB 0%, #3B82F6 100%);
		border-radius: 4rpx;
		transition: width 0.3s ease;
	}

	.progress-info {
		display: flex;
		justify-content: space-between;
		margin-top: 12rpx;
		font-size: 24rpx;
		color: #64748B;
	}

	/* 标题 */
	.section-title {
		font-size: 28rpx;
		font-weight: 600;
		color: #1E293B;
		margin-bottom: 16rpx;
		margin-top: 8rpx;
	}

	/* 信息卡片 */
	.info-card {
		background: #FFFFFF;
		border-radius: 20rpx;
		padding: 0 24rpx;
		margin-bottom: 24rpx;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
	}

	.info-row {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 24rpx 0;
	}

	.row-label {
		font-size: 28rpx;
		color: #64748B;
	}

	.row-value {
		font-size: 28rpx;
		color: #1E293B;
		font-weight: 500;
	}

	.row-value.price {
		color: #EF4444;
		font-size: 32rpx;
		font-weight: 700;
	}

	.row-value.text-danger {
		color: #EF4444;
	}

	.info-divider {
		height: 2rpx;
		background: #F1F5F9;
	}

	/* 租客卡片 */
	.renter-card {
		background: #FFFFFF;
		border-radius: 20rpx;
		padding: 24rpx;
		margin-bottom: 24rpx;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
	}

	.renter-header {
		display: flex;
		align-items: center;
		gap: 20rpx;
	}

	.renter-avatar {
		width: 88rpx;
		height: 88rpx;
		border-radius: 50%;
		background: linear-gradient(135deg, #2563EB 0%, #1D4ED8 100%);
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.renter-avatar text {
		font-size: 36rpx;
		font-weight: 600;
		color: #FFFFFF;
	}

	.renter-info {
		flex: 1;
		display: flex;
		flex-direction: column;
	}

	.renter-name {
		font-size: 32rpx;
		font-weight: 600;
		color: #1E293B;
	}

	.renter-phone {
		font-size: 26rpx;
		color: #64748B;
		margin-top: 4rpx;
	}

	.contact-btn {
		width: 72rpx;
		height: 72rpx;
		border-radius: 50%;
		background: linear-gradient(135deg, #10B981 0%, #059669 100%);
		display: flex;
		align-items: center;
		justify-content: center;
	}

	/* 付租方式标签 */
	.payment-tag {
		padding: 4rpx 16rpx;
		border-radius: 6rpx;
		font-size: 24rpx;
	}

	.payment-tag.monthly {
		background: #DBEAFE;
		color: #2563EB;
	}

	.payment-tag.quarterly {
		background: #FEF3C7;
		color: #D97706;
	}

	.payment-tag.half_year {
		background: #F3F4F6;
		color: #4B5563;
	}

	.payment-tag.yearly {
		background: #D1FAE5;
		color: #059669;
	}

	/* 警告卡片 */
	.warning-card {
		display: flex;
		align-items: flex-start;
		gap: 16rpx;
		background: #FEF2F2;
		border-radius: 16rpx;
		padding: 24rpx;
		margin-bottom: 24rpx;
	}

	.warning-content {
		flex: 1;
		display: flex;
		flex-direction: column;
	}

	.warning-title {
		font-size: 28rpx;
		font-weight: 600;
		color: #DC2626;
	}

	.warning-desc {
		font-size: 24rpx;
		color: #EF4444;
		margin-top: 8rpx;
	}

	/* 操作区域 */
	.action-section {
		display: flex;
		gap: 24rpx;
		margin-top: 32rpx;
	}

	.action-btn {
		flex: 1;
		height: 88rpx;
		border-radius: 16rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 12rpx;
	}

	.action-btn.primary {
		background: linear-gradient(135deg, #2563EB 0%, #1D4ED8 100%);
		box-shadow: 0 8rpx 24rpx rgba(37, 99, 235, 0.3);
	}

	.action-btn.warning {
		background: linear-gradient(135deg, #F59E0B 0%, #D97706 100%);
		box-shadow: 0 8rpx 24rpx rgba(245, 158, 11, 0.28);
	}

	.action-btn.danger {
		background: linear-gradient(135deg, #EF4444 0%, #DC2626 100%);
		box-shadow: 0 8rpx 24rpx rgba(239, 68, 68, 0.3);
	}

	.action-btn text {
		font-size: 30rpx;
		font-weight: 600;
		color: #FFFFFF;
	}

	/* 加载状态 */
	.loading-state {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	/* 空状态 */
	.empty-state {
		flex: 1;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 120rpx 60rpx;
	}

	.empty-text {
		font-size: 30rpx;
		color: #64748B;
		margin-top: 24rpx;
		margin-bottom: 40rpx;
	}

	.back-btn {
		background: linear-gradient(135deg, #2563EB 0%, #1D4ED8 100%);
		color: #FFFFFF;
		font-size: 30rpx;
		font-weight: 600;
		padding: 24rpx 80rpx;
		border-radius: 16rpx;
		border: none;
		box-shadow: 0 8rpx 24rpx rgba(37, 99, 235, 0.3);
	}

	/* 弹窗样式 */
	.popup-content {
		background: #FFFFFF;
		border-radius: 24rpx;
		width: 600rpx;
		max-height: 800rpx;
	}

	.popup-header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 32rpx;
		border-bottom: 2rpx solid #F1F5F9;
	}

	.popup-title {
		font-size: 32rpx;
		font-weight: 700;
		color: #1E293B;
	}

	.popup-body {
		padding: 32rpx;
		max-height: 560rpx;
		overflow-y: auto;
	}

	.form-item {
		margin-bottom: 24rpx;
	}

	.form-label {
		display: block;
		font-size: 26rpx;
		color: #64748B;
		margin-bottom: 12rpx;
	}

	.form-static {
		font-size: 30rpx;
		color: #1E293B;
		font-weight: 500;
	}

	.form-static.price {
		color: #EF4444;
		font-weight: 700;
	}

	.form-input {
		width: 100%;
		height: 80rpx;
		background: #F8FAFC;
		border-radius: 12rpx;
		padding: 0 24rpx;
		font-size: 28rpx;
		color: #1E293B;
	}

	.form-textarea {
		width: 100%;
		height: 160rpx;
		background: #F8FAFC;
		border-radius: 12rpx;
		padding: 20rpx 24rpx;
		font-size: 28rpx;
		color: #1E293B;
	}

	.popup-footer {
		display: flex;
		gap: 20rpx;
		padding: 24rpx 32rpx;
		border-top: 2rpx solid #F1F5F9;
	}

	.btn-cancel {
		flex: 1;
		height: 80rpx;
		background: #F3F4F6;
		border-radius: 12rpx;
		font-size: 28rpx;
		color: #64748B;
		border: none;
	}

	.btn-confirm {
		flex: 1;
		height: 80rpx;
		background: linear-gradient(135deg, #EF4444 0%, #DC2626 100%);
		border-radius: 12rpx;
		font-size: 28rpx;
		color: #FFFFFF;
		font-weight: 600;
		border: none;
	}
</style>
