<template>
	<view class="container">	
		<!-- 表单区域 -->
		<scroll-view class="content" scroll-y>
			<view class="form-section">
				<view class="form-item">
					<view class="form-label">开户行</view>
					<!-- <input 
						class="form-input" 
						v-model="formData.bankName" 
						placeholder="请输入开户行"
						placeholder-class="text-placeholder"
					/> -->
					<view style="flex:1" @click="openBankPicker">
						<view class="form-input picker-input" :class="{ placeholder: !formData.bankName }">
							{{ getBankLabel() || '请选择开户行' }}
							<image class="w32 h32" src="/static/image/icon_my_more.png" mode=""></image>
						</view>
					</view>
				</view>
				<view class="divider"></view>
				
				<view class="form-item">
					<view class="form-label">支行</view>
					<input 
						class="form-input" 
						v-model="formData.bankBranch" 
						placeholder="请输入支行"
						placeholder-class="text-placeholder"
					/>
				</view>
				<view class="divider"></view>
				
				<view class="form-item">
					<view class="form-label">银行卡号</view>
					<input 
						class="form-input" 
						 :value="isEditing ? formData.bankCardNo : formatBankCard(formData.bankCardNo)"
						      @input="handleCardInput"
						      @focus="isEditing = true"
						      @blur="handleCardBlur"
						placeholder="请输入银行卡号"
						type="number"
						maxlength="19"
						placeholder-class="text-placeholder"
					/>
				</view>
			</view>
			
			<!-- 注意事项 -->
			<view class="notes-section">
				<view class="notes-title">注意:</view>
				<view class="notes-item">1、只能绑定认证用户本人的银行卡;</view>
				<view class="notes-item">2、每次更换次数不得超过三次。</view>
			</view>
		</scroll-view>
		<!-- 银行搜索弹窗 -->
		<view class="search-picker-popup" v-if="showBankPicker" @click="closeBankPicker">
			<view class="popup-content" @click.stop>
				<view class="popup-header">
					<text class="popup-title">选择开户行</text>
					<view class="popup-close" @click="closeBankPicker">×</view>
				</view>
				<view class="search-box">
					<input 
						class="search-input" 
						v-model="bankSearchKeyword" 
						placeholder="请输入银行名称搜索"
						@blur="onBankSearch"
					/>
				</view>
				<scroll-view class="search-list" scroll-y>
					<view 
						class="search-item" 
						v-for="(item, index) in filteredBankList" 
						:key="index"
						:class="{ active: formData.bankName === item.label }"
						@click="selectBank(item)"
					>
						<text>{{ item.label }}</text>
						<text v-if="formData.bankName === item.label" class="check-icon">✓</text>
					</view>
					<view class="search-empty" v-if="filteredBankList.length === 0">
						<text>暂无匹配结果</text>
					</view>
				</scroll-view>
			</view>
		</view>
		<!-- 底部按钮 -->
		<view class="bottom-bar">
			<view class="save-btn" @click="handleSave">保存</view>
			<!-- <view class="unbind-btn" @click="handleUnbind">解除绑定</view> -->
		</view>
	</view>
</template>

<script>
import {getBankTypeList} from '@/api/certification'
import { addBankCard, deleteBankCard, getBankCardInfo } from '@/api/bankCard'
export default {
	data() {
		return {
			cardId: '',
			isEditing: false,
			formData: {
				"bankBranch": "",
				  "bankCardNo": "",
				  "bankName": ""
			},
			showBankPicker: false,
			bankSearchKeyword: '',
			filteredBankList: []
		}
	},
	onLoad(options) {
		// if (options.id) {
		// 	this.cardId = options.id
			
		// }
		this.loadBankCardDetail()
		this.loadBankList()
	},
	methods: {
		getBankLabel() {
			return this.formData.bankName || ''
		},
		openBankPicker() {
			this.showBankPicker = true
			this.bankSearchKeyword = ''
		},
		openBankPicker() {
			this.showBankPicker = true
			this.bankSearchKeyword = ''
		},
		closeBankPicker() {
			this.showBankPicker = false
		},
		async onBankSearch() {
			const keyword = this.bankSearchKeyword.trim()
			this.loadBankList(keyword)
		},
		selectBank(item) {
			this.formData.bankName = item.label
			this.closeBankPicker()
		},
		// 加载银行列表
		async loadBankList(keyword) {
			const params = {}
			   // 如果传入了关键词，就用传入的
			   if (keyword) {
			     params.bankName = keyword.trim()
			   }
		  try {
		    const res = await getBankTypeList(params)
		    if (res.code === 200) {
		      const arr = res.data
		      this.filteredBankList = arr.map(item => ({
		        label: item.bankName,
		        value: item.id
		      })).filter(opt => opt.label)
		    }
		  } catch (err) {
		    console.log('银行类型加载失败', err)
		  }
		},
		formatBankCard(cardNo) {
		     if (!cardNo || cardNo.length < 8) return cardNo;
		     const prefix = cardNo.substring(0, 4);
		     const suffix = cardNo.substring(cardNo.length - 4);
		     return `${prefix}****${suffix}`;
		   },
		   handleCardInput(e) {
		         // 实时更新原始卡号数据
		         this.formData.bankCardNo = e.detail.value;
		       },
			   handleCardBlur() {
			         // 延迟切换状态，避免输入完成瞬间的视觉闪烁
			         setTimeout(() => {
			           this.isEditing = false;
			         }, 100);
			         
			         // 可选：失去焦点后自动格式化卡号（每4位加空格，如需保留数字格式可注释）
			         // this.formData.bankCardNo = this.formData.bankCardNo.replace(/\D/g, '');
			       },
		async loadBankCardDetail() {
			try {
				uni.showLoading({ title: '加载中...' })
				const res = await getBankCardInfo({ id: this.cardId })
				uni.hideLoading()
				if (res.code === 200 && res.data) {
					// 根据接口返回的数据结构映射字段
					const data = res.data
					this.formData = {
						...this.formData,
						bankBranch: data.bankBranch,
						bankCardNo: data.bankCardNo || '',
						bankName: data.bankName
					}
				}
			} catch (e) {
				uni.hideLoading()
				console.error('加载银行卡详情失败', e)
			}
		},
		goBack() {
			uni.navigateBack()
		},
		async handleSave() {
			// 表单验证
			if (!this.formData.bankName || !this.formData.bankName.trim()) {
				uni.showToast({
					icon: 'none',
					title: '请选择开户行'
				})
				return
			}
			if (!this.formData.bankBranch || !this.formData.bankBranch.trim()) {
				uni.showToast({
					icon: 'none',
					title: '请输入支行'
				})
				return
			}
			if (!this.formData.bankCardNo) {
				uni.showToast({
					icon: 'none',
					title: '请输入银行卡号'
				})
				return
			}
			// 银行卡号验证（简单验证）
			if (this.formData.bankCardNo.length < 16) {
				uni.showToast({
					icon: 'none',
					title: '请输入正确的银行卡号'
				})
				return
			}
			try {
				uni.showLoading({ title: '保存中...' })
				
				// 构建提交数据，按照接口字段要求
				const submitData = {
					bankName: this.formData.bankName,
					bankBranch: this.formData.bankBranch,
					bankCardNo: this.formData.bankCardNo
				}
				
				// 如果有ID（编辑时），添加id字段
				if (this.cardId || this.formData.id) {
					submitData.id = this.cardId || this.formData.id
				}
				
				const res = await addBankCard(submitData)
				uni.hideLoading()
				
				if (res.code === 200) {
					uni.showToast({
						icon: 'success',
						title: '保存成功'
					})
					setTimeout(() => {
						uni.navigateBack()
					}, 1500)
				} else {
					uni.showToast({
						icon: 'none',
						title: res.msg || '保存失败'
					})
				}
			} catch (e) {
				uni.hideLoading()
				console.error('保存银行卡失败', e)
				uni.showToast({
					icon: 'none',
					title: e.message || '保存失败'
				})
			}
		},
		handleUnbind() {
			uni.showModal({
				title: '提示',
				content: '确定要解除绑定该银行卡吗？',
				success: async (res) => {
					if (res.confirm) {
						try {
							uni.showLoading({ title: '解除绑定中...' })
							const result = await deleteBankCard({ id: this.cardId })
							uni.hideLoading()
							if (result.code === 200) {
								uni.showToast({
									icon: 'success',
									title: '解除绑定成功'
								})
								setTimeout(() => {
									uni.navigateBack()
								}, 1500)
							} else {
								uni.showToast({
									icon: 'none',
									title: result.msg || '解除绑定失败'
								})
							}
						} catch (e) {
							uni.hideLoading()
							uni.showToast({
								icon: 'none',
								title: '解除绑定失败'
							})
						}
					}
				}
			})
		}
	}
}
</script>
<style lang="stylus">
	.text-placeholder{
	  color: #C8C9CC !important;
	}
</style>
<style lang="scss" scoped>
	
.container {
	// min-height: 100vh;
	background: #f5f5f5;
	display: flex;
	flex-direction: column;
}

.navbar {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 20rpx 24rpx;
	background: #fff;
	border-bottom: 1rpx solid #f0f0f0;
	
	.nav-left {
		width: 60rpx;
		
		.back-icon {
			font-size: 36rpx;
			color: #333;
			font-weight: bold;
		}
	}
	
	.nav-title {
		flex: 1;
		text-align: center;
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
	}
	
	.nav-right {
		display: flex;
		align-items: center;
		gap: 24rpx;
		width: 60rpx;
		justify-content: flex-end;
		
		.more-icon {
			font-size: 32rpx;
			color: #333;
		}
		
		.eye-icon {
			font-size: 32rpx;
			color: #333;
		}
	}
}

.content {
	// flex: 1;
	// padding-bottom: 140rpx;
}

.form-section {
	background: #fff;
	// margin: 24rpx;
	// border-radius: 16rpx;
	overflow: hidden;
	
	.form-item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 28rpx 32rpx;
		// min-height: 100rpx
		.form-label {
			font-family: PingFang SC, PingFang SC;
			font-weight: 400;
			font-size: 28rpx;
			color: #666666;
			width: 150rpx;
		}
	.form-input {
		flex: 1;
		font-size: 28rpx;
		color: #333;
		text-align: right;
		margin-left: 24rpx;
		
		&.picker-input {
			display: flex;
			align-items: center;
			justify-content: flex-end;
			
			.arrow-right {
				font-size: 32rpx;
				color: #999;
				margin-left: 8rpx;
			}
		}
	}
}

// placeholder 样式（需要独立定义，不能嵌套）
.placeholder {
	//color: #C8C9CC !important;
	}
	
	.divider {
		height: 1rpx;
		background: #EBEDF0;
		margin-left: 24rpx;
	}
}

.notes-section {
	// background: #fff;
	// border-radius: 16rpx;
	padding: 22rpx 32rpx;
	// margin: 0 24rpx 24rpx;
	
	.notes-title {
		font-family: PingFang SC, PingFang SC;
		font-weight: 400;
		font-size: 28rpx;
		color: #999999;
		line-height: 40rpx;
	}
	
	.notes-item {
		font-family: PingFang SC, PingFang SC;
		font-weight: 400;
		font-size: 28rpx;
		color: #999999;
		line-height: 40rpx;
	}
}

.bottom-bar {
    display: flex;
	align-items: center;
	flex-direction: column;
	padding: 32rpx;
	
	.save-btn {
		width: 100%;
		height: 88rpx;
		background: #388BFF;
		border-radius: 44rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 32rpx;
		color: #fff;
	}
	.unbind-btn{
		margin-top: 20rpx;
		width: 100%;
		height: 88rpx;
		color: #388BFF;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 32rpx;
	}
}
.search-picker-popup {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(0, 0, 0, 0.5);
	z-index: 1000;
	display: flex;
	align-items: flex-end;
	
	.popup-content {
		width: 100%;
	    height: 80vh;
		background: #fff;
		border-radius: 24rpx 24rpx 0 0;
		display: flex;
		flex-direction: column;
	}
	
	.popup-header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 32rpx;
		border-bottom: 1rpx solid #f0f0f0;
		
		.popup-title {
			font-size: 32rpx;
			font-weight: bold;
			color: #333;
		}
		
		.popup-close {
			font-size: 48rpx;
			color: #999;
			line-height: 1;
		}
	}
	
	.search-box {
		padding: 24rpx 32rpx;
		
		.search-input {
			//width: 100%;
			height: 72rpx;
			background: #f5f5f5;
			border-radius: 36rpx;
			padding: 0 32rpx;
			font-size: 28rpx;
		}
	}
	
	.search-list {
		flex: 1;
		height: 60%;
		padding: 0 32rpx 40rpx;
		box-sizing: border-box;
		.search-item {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 28rpx 0;
			border-bottom: 1rpx solid #f5f5f5;
			
			&:last-child {
				border-bottom: none;
			}
			
			&.active {
				color: #388BFF;
				
				text {
					color: #388BFF;
				}
			}
			
			.check-icon {
				color: #388BFF;
				font-size: 32rpx;
				font-weight: bold;
			}
			
			text {
				font-size: 28rpx;
				color: #333;
			}
		}
		
		.search-empty {
			display: flex;
			align-items: center;
			justify-content: center;
			padding: 60rpx 0;
			
			text {
				font-size: 28rpx;
				color: #999;
			}
		}
	}
}
</style>












