<template>
	<view class="lease-cancel-page">
		<!-- 顶部自定义导航栏 -->
		<customNavbar title="退租申请" />

		<!-- 表单内容 -->
		<view class="form-section">
			<!-- 关联合同 -->
			<view class="form-item">
				<text class="label">关联合同</text>
				<picker :range="contracts" range-key="contractName" @change="onContractChange">
					<view class="picker-value">
						{{ selectedContract ? selectedContract.contractName : '请选择合同' }}
					</view>
				</picker>
			</view>

			<!-- 关联资产 -->
			<view class="form-item">
				<text class="label">关联资产</text>
				<view class="picker-value" @click="openAssetsPopup">
					{{ selectedAssetsList.length
            ? selectedAssetsList.map(a => a.assetsName).join('，')
            : '请选择资产' }}
					<text v-if="selectedAssetsList.length">（{{ selectedAssetsList.length }}）</text>
				</view>
			</view>

			<!-- 退租日期 -->
			<view class="form-item">
				<text class="label">退租日期</text>
				<picker mode="date" @change="onDateChange">
					<view class="picker-value">
						{{ cancelDate || '请选择退租日期' }}
					</view>
				</picker>
			</view>

			<!-- 退租原因 -->
			<view class="form-item">
				<text class="label">退租原因</text>
				<textarea v-model="reason" placeholder="请输入退租原因" class="textarea" />
			</view>
		</view>

		<!-- 提交按钮 -->
		<view class="bottom-bar">
			<button class="submit-btn" @click="submitForm">提交申请</button>
		</view>

		<!-- 弹窗多选资产 -->
		<u-popup v-model="showAssetsPopup" mode="bottom">
			<view class="popup-header">
				<input v-model="assetSearch" placeholder="搜索资产" class="search-input" />
			</view>
			<scroll-view scroll-y style="height:500rpx;">
				<checkbox-group @change="onAssetsChange">
					<label v-for="asset in filteredAssets" :key="asset.assetsNo"
						style="display:block;padding:12rpx 20rpx;border-bottom:1rpx solid #f0f0f0;">
						<checkbox :value="asset.assetsNo" :checked="selectedAssetsKeys.includes(asset.assetsNo)" /> {{ asset.assetsName }}
					</label>
				</checkbox-group>
			</scroll-view>
			<button class="popup-btn" @click="confirmAssets">确定</button>
		</u-popup>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				contracts: [],
				selectedContract: null,
				assetsList: [],
				assetSearch: '',
				showAssetsPopup: false,
				selectedAssetsKeys: [], // 存储选中的资产编号
				selectedAssetsList: [], // 存储选中的资产对象
				cancelDate: '',
				reason: '',
			};
		},
		onLoad() {
			// fetchContractList 移到 onShow 中，等 token 校验通过后再加载
		},
		async onShow() {
			try {
				await this.$checkToken(this.$getToken())
				this.fetchContractList()
			} catch (e) {
				return
			}
		},
		computed: {
			filteredAssets() {
				if (!this.assetSearch) return this.assetsList;
				return this.assetsList.filter(a =>
					a.name.toLowerCase().includes(this.assetSearch.toLowerCase())
				);
			},
		},
		methods: {
			onContractChange(e) {
				const index = e.detail.value;
				this.selectedContract = this.contracts[index];
				this.assetsList = this.contracts[index].assetsInfos || [];
				// 清空之前选择
				this.selectedAssetsKeys = [];
				this.selectedAssetsList = [];
			},
			onAssetsChange(e) {
						this.selectedAssetsKeys = e.detail.value
					},
			openAssetsPopup() {
				if (!this.selectedContract) {
					uni.showToast({
						title: '请先选择合同',
						icon: 'none'
					});
					return;
				}
				this.showAssetsPopup = true;
			},
			confirmAssets() {
				console.log(this.selectedAssetsKeys)
				this.selectedAssetsList = this.assetsList.filter(a =>
					this.selectedAssetsKeys.includes(a.assetsNo)
				);
				this.showAssetsPopup = false;
			},
			onDateChange(e) {
				this.cancelDate = e.detail.value;
			},
			fetchContractList() {
				const url = '/contract/queryAll';
				this.$u.get(
						url, {
						}, {
							WT: this.$getToken()
						}
					)
					.then(res => {
						this.contracts = res.data;
					})
					.catch(err => {
						console.error('获取合同信息失败：', err);
					});
			},
			submitForm() {
				const token = this.$getToken()
				if (!token) {
					uni.showToast({
						title: '请先登录',
						icon: 'none'
					});
					return
				}
				let userInfo = uni.getStorageSync('userInfo');
				if(!userInfo || !userInfo.cusNo) {
					uni.showToast({
						title: '您还未实名',
						icon: 'none'
					});
					return;
				}
				if (
					!this.selectedContract ||
					!this.cancelDate ||
					!this.reason ||
					!this.selectedAssetsList.length
				) {
					uni.showToast({
						title: '请填写完整信息',
						icon: 'none'
					});
					return;
				}
                
				const data = {
					contractNo: this.selectedContract.contractNo,
					cancelDate: this.cancelDate,
					reason: this.reason,
					assetsNoList: this.selectedAssetsList.map(a => a.assetsNo),
				};

				this.$u.post('/discharge/apply', data, {
						WT: this.$getToken()
					})
					.then((res) => {
						if (res.flag) {
							this.$mytip.toast('提交退租申请成功')
							const pages = getCurrentPages();
							if (pages.length > 1) {
							  uni.navigateBack();
							} else {
							  uni.switchTab({
							  		url:'/pages/index/index'
							  	})
							}
						} else {
							this.$mytip.toast('提交退租申请失败:' + res.message )
						}
					})
					.catch(err => {
						this.$mytip.toast('提交退租申请失败')
						console.error('提交退租申请失败：', err);
					});
			},
		},
	};
</script>

<style lang="scss" scoped>
	.lease-cancel-page {
		background-color: #f6f8fa;
		height: 100vh;
		display: flex;
		padding-top: 160rpx;
		padding-bottom: 120rpx;
		flex-direction: column;
	}

	.form-section {
		padding: 20rpx;
	}

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

	.label {
		font-size: 28rpx;
		margin-bottom: 10rpx;
		display: block;
	}

	.picker-value {
		padding: 14rpx 20rpx;
		background: #fff;
		border-radius: 8rpx;
		color: #333;
	}

	.textarea {
		width: 100%;
		min-height: 120rpx;
		padding: 14rpx 20rpx;
		border-radius: 8rpx;
		background: #fff;
		color: #333;
	}

	.bottom-bar {
		padding: 20rpx;
		background: #fff;
	}

	.submit-btn {
		width: 100%;
		height: 80rpx;
		background: linear-gradient(90deg, #FF6F63 0%, #FB392A 100%);
		border-radius: 10rpx;
		color: #ffffff;
		font-size: 32rpx;
		border: none;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	/* 弹窗样式 */
	.popup-header {
		padding: 20rpx;
		border-bottom: 1rpx solid #eee;
	}

	.search-input {
		width: 100%;
		padding: 10rpx;
		border: 1rpx solid #ccc;
		border-radius: 8rpx;
	}

	.popup-btn {
		margin: 20rpx;
		height: 80rpx;
		background: #FB392A;
		color: #fff;
		border-radius: 8rpx;
		font-size: 28rpx;
	}
</style>