<template>
	<view class="page">
		<view class="page-content">
			<!-- 上传logo部分 -->
			<view class="section">
				<view class="section-title">酒款图片</view>
				<view class="upload-content">
					<view class="img-box" @click="handleUpload('barLogo')">
						<image v-if="form.barLogo" :src="form.barLogo" mode="aspectFill" class="preview-image"></image>
						<view v-else class="upload-placeholder">
							<text class="cuIcon-camerafill"></text>
							<text class="upload-text">添加图片</text>
						</view>
					</view>
					<text class="upload-tip">请上传酒款图片（必填）</text>
				</view>
			</view>

			<!-- 基本信息部分 -->
			<view class="section">
				<view class="section-title">基本信息</view>
				<view class="info-list">
					<!-- 酒厂名称 -->
					<view class="info-item">
						<text>酒厂名称</text>
						<view class="right-content">
							<input 
								v-model="form.nickName" 
								@input="handleBrewerySearch" 
								placeholder="请输入酒厂名称" 
								class="input-field"
							/>
							<!-- 搜索建议列表 -->
							<view v-if="brewerySuggestions.length > 0" class="suggestion-list">
								<view 
									v-for="(item, index) in brewerySuggestions" 
									:key="index"
									class="suggestion-item"
									@click="selectBrewery(item)"
								>
									<view class="suggestion-content">
										<image v-if="item.logo" :src="item.logo" class="suggestion-logo"></image>
										<view class="suggestion-info">
											<text class="suggestion-name">{{item.name}}</text>
											<text class="suggestion-desc">{{item.description || '已有品牌'}}</text>
										</view>
									</view>
								</view>
							</view>
						</view>
					</view>

					<!-- 酒款名称 -->
					<view class="info-item">
						<text>酒款名称</text>
						<view class="right-content">
							<input 
								v-model="form.phone" 
								@input="handleBeerSearch" 
								placeholder="请输入酒款名称" 
								class="input-field"
							/>
							<!-- 搜索建议列表 -->
							<view v-if="beerSuggestions.length > 0" class="suggestion-list">
								<view 
									v-for="(item, index) in beerSuggestions" 
									:key="index"
									class="suggestion-item"
									@click="selectBeer(item)"
								>
									<view class="suggestion-content">
										<image v-if="item.cover" :src="item.cover" class="suggestion-logo"></image>
										<view class="suggestion-info">
											<text class="suggestion-name">{{item.name}}</text>
											<text class="suggestion-desc">{{item.brewery || '已有酒款'}}</text>
										</view>
									</view>
								</view>
							</view>
						</view>
					</view>

					<!-- 酒精含量 -->
					<view class="info-item">
						<text>酒精含量</text>
						<view class="right-content">
							<input 
								v-model="form.barName" 
								placeholder="请输入酒精含量" 
								class="input-field"
							/>
						</view>
					</view>

					<!-- 简介 -->
					<view class="info-item description-item">
						<text>简介</text>
						<view class="right-content">
							<textarea 
								v-model="form.description"
								placeholder="请输入酒款简介" 
								class="textarea-field"
								maxlength="72"
							/>
							<text class="word-count">{{form.description ? form.description.length : 0}}/72</text>
						</view>
					</view>
				</view>
			</view>

			<!-- 提交按钮 -->
			<view class="save-btn" @click="submitForm">
				确认提交
			</view>
		</view>
	</view>
</template>

<script>
	// import QQMapSdk from '@/common/qqmap-wx-jssdk.min.js'
	import {
		barRegister
	} from '@/api/login.js'
	import {
		base_url
	} from '@/api/config.js'
	export default {
		data() {
			return {
				form: {
					barLogo: '',
					nickName: '',
					phone: '',
					barName: '',
					address: '',
					businessLicense: '', // 营业执照
					storefrontPhoto: '', // 门头照
					position: '', // 职务
					openId: '',
					description: '', // 简介
				},
				userInfo: {},
				QQMap: null,
				// 酒厂搜索建议
				brewerySuggestions: [],
				// 酒款搜索建议
				beerSuggestions: [],
				// 搜索防抖定时器
				searchTimer: null,
			};
		},
		onLoad({
			openId
		}) {
			this.form.openId = openId
			// this.QQMap = new QQMapSdk({
			//                     key: "YQCBZ-SQZ6A-P6EKD-CAUGZ-L7IWO-JMFMJ"//密钥
			//                 });
		},
		computed: {
		    containerHeight() {
		      const baseHeight = 160; // 基础高度，根据实际情况调整
		      return this.filteredList.length > 0 ? baseHeight + this.filteredList.length * 50 : baseHeight;
		    }
		  },
		methods: {
			// 酒厂名称搜索
			handleBrewerySearch() {
				// 清除之前的定时器
				if (this.searchTimer) {
					clearTimeout(this.searchTimer);
				}
				
				// 设置新的定时器，实现防抖
				this.searchTimer = setTimeout(() => {
					const keyword = this.form.nickName.trim();
					if (keyword === '') {
						this.brewerySuggestions = [];
						return;
					}
					
					// 调用搜索接口
					this.searchBreweries(keyword);
				}, 300);
			},
			
			// 酒款名称搜索
			handleBeerSearch() {
				// 清除之前的定时器
				if (this.searchTimer) {
					clearTimeout(this.searchTimer);
				}
				
				// 设置新的定时器，实现防抖
				this.searchTimer = setTimeout(() => {
					const keyword = this.form.phone.trim();
					if (keyword === '') {
						this.beerSuggestions = [];
						return;
					}
					
					// 调用搜索接口
					this.searchBeers(keyword);
				}, 300);
			},
			
			// 搜索酒厂（预留接口）
			searchBreweries(keyword) {
				// 这里预留接口，后期对接数据库
				// 示例代码，实际应该调用API
				/*
				uni.request({
					url: base_url + '/api/breweries/search',
					method: 'GET',
					data: {
						keyword: keyword
					},
					success: (res) => {
						if (res.data.code === 200) {
							this.brewerySuggestions = res.data.data;
						}
					}
				});
				*/
				
				// 临时模拟数据
				this.brewerySuggestions = [
					{ id: 1, name: '青岛啤酒', logo: '/static/bg/pc-1.png', description: '中国知名啤酒品牌' },
					{ id: 2, name: '百威啤酒', logo: '/static/bg/pc-1.png', description: '国际知名啤酒品牌' },
					{ id: 3, name: '哈尔滨啤酒', logo: '/static/bg/pc-1.png', description: '中国知名啤酒品牌' }
				].filter(item => item.name.includes(keyword));
			},
			
			// 搜索酒款（预留接口）
			searchBeers(keyword) {
				// 这里预留接口，后期对接数据库
				// 示例代码，实际应该调用API
				/*
				uni.request({
					url: base_url + '/api/beers/search',
					method: 'GET',
					data: {
						keyword: keyword
					},
					success: (res) => {
						if (res.data.code === 200) {
							this.beerSuggestions = res.data.data;
						}
					}
				});
				*/
				
				// 临时模拟数据
				this.beerSuggestions = [
					{ id: 1, name: '青岛纯生', cover: '/static/bg/pc-1.png', brewery: '青岛啤酒' },
					{ id: 2, name: '百威经典', cover: '/static/bg/pc-1.png', brewery: '百威啤酒' },
					{ id: 3, name: '哈尔滨冰纯', cover: '/static/bg/pc-1.png', brewery: '哈尔滨啤酒' }
				].filter(item => item.name.includes(keyword));
			},
			
			// 选择酒厂
			selectBrewery(item) {
				this.form.nickName = item.name;
				this.brewerySuggestions = [];
				
				// 可以在这里添加其他逻辑，如自动填充酒厂相关信息
			},
			
			// 选择酒款
			selectBeer(item) {
				this.form.phone = item.name;
				this.beerSuggestions = [];
				
				// 可以在这里添加其他逻辑，如自动填充酒款相关信息
			},
			
			// 提交
			submitForm() {
				if (!this.form.barLogo) {
					uni.showToast({
						title: '请上传酒款图片',
						icon: 'none',
						mask: true
					})
					return
				}
				if (!this.form.nickName) {
					uni.showToast({
						title: '请输入酒厂名称',
						icon: 'none',
						mask: true
					})
					return
				}
				if (!this.form.phone) {
					uni.showToast({
						title: '请输入酒款名称',
						icon: 'none',
						mask: true
					})
					return
				}
				if (!this.form.barName) {
					uni.showToast({
						title: '请输入酒精含量',
						icon: 'none',
						mask: true
					})
					return
				}
				if (!this.form.description) {
					uni.showToast({
						title: '请输入酒款简介',
						icon: 'none',
						mask: true
					})
					return
				}
				
				// 检查是否选择了已有品牌或酒款
				const isExistingBrewery = this.brewerySuggestions.some(item => item.name === this.form.nickName);
				const isExistingBeer = this.beerSuggestions.some(item => item.name === this.form.phone);
				
				if (isExistingBrewery) {
					uni.showModal({
						title: '提示',
						content: '该酒厂已存在，是否继续提交？',
						success: (res) => {
							if (res.confirm) {
								this.submitData();
							}
						}
					});
					return;
				}
				
				if (isExistingBeer) {
					uni.showModal({
						title: '提示',
						content: '该酒款已存在，是否继续提交？',
						success: (res) => {
							if (res.confirm) {
								this.submitData();
							}
						}
					});
					return;
				}
				
				// 直接提交
				this.submitData();
			},
			
			// 提交数据
			submitData() {
				uni.showLoading({
					title: '提交中',
					mask: true
				});
				
				// 这里预留接口，后期对接数据库
				// 示例代码，实际应该调用API
				/*
				uni.request({
					url: base_url + '/api/beers/add',
					method: 'POST',
					data: this.form,
					success: (res) => {
						if (res.data.code === 200) {
							uni.showToast({
								title: '提交成功',
								icon: 'success'
							});
							setTimeout(() => {
								uni.navigateBack();
							}, 1500);
						} else {
							uni.showToast({
								title: res.data.msg || '提交失败',
								icon: 'none'
							});
						}
					},
					fail: () => {
						uni.showToast({
							title: '提交失败',
							icon: 'none'
						});
					},
					complete: () => {
						uni.hideLoading();
					}
				});
				*/
				
				// 临时模拟提交成功
				setTimeout(() => {
					uni.hideLoading();
					uni.showToast({
						title: '提交成功',
						icon: 'success'
					});
					setTimeout(() => {
						uni.navigateBack();
					}, 1500);
				}, 1000);
			},
			// 上传事件
			handleUpload(key) {
				uni.chooseImage({
					count: 1,
					success: (res) => {
						uni.uploadFile({
							url: base_url + '/bar/common/upload', //仅为示例，非真实的接口地址
							filePath: res.tempFilePaths[0],
							name: 'file',
							formData: {
								type: 'image'
							},
							success: (uploadFileRes) => {
								this.form[key] = JSON.parse(uploadFileRes.data).url
							}
						});
					}
				})
			},
			// 获取位置
			getMyLocation() {
				uni.getSetting({
					success: (res) => {
						console.log(res)
						if (!res.authSetting['scope.userLocation']) {
							uni.authorize({
								scope: 'scope.userLocation',
								success: (res) => {
									this.handleGetLocation()
								},
								fail: (err) => {
									uni.showModal({
										title: '提示',
										content: '请先授权获取您的位置信息',
										success: (res) => {
											if (res.confirm) {
												uni.openSetting({
													success: (res) => {
														if (res.authSetting['scope.userLocation']) {
															this.handleGetLocation()
														}
													}
												})
											} else if (res.cancel) {
												console.log('用户点击取消')
											}
										}
									})
								}
							})
						}else {
							this.handleGetLocation()
						}
					},
				})

			},
			handleGetLocation() {
				uni.getLocation({
					type: "gcj02",
					success: (res) => {
						console.log(res)
						uni.chooseLocation({
							complete: (res) => {
								console.log(res)
								if (res.errMsg == 'chooseLocation:ok') {
									this.form.address = res.address
									this.form.latitude = res.latitude
									this.form.longitude = res.longitude
								}
							}
						})
					},
					fail: (err) => {
						console.log(err)
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
.page {
	min-height: 100vh;
	background: #F7F7F7;

	.page-content {
		padding: 24rpx 32rpx;
	}

	.section {
		background: #FFFFFF;
		border-radius: 16rpx;
		margin-bottom: 24rpx;
		padding: 24rpx;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);

		.section-title {
			font-size: 32rpx;
			font-weight: 600;
			color: #333;
			margin-bottom: 24rpx;
			position: relative;
			padding-left: 24rpx;

			&::before {
				content: '';
				position: absolute;
				left: 0;
				top: 50%;
				transform: translateY(-50%);
				width: 6rpx;
				height: 24rpx;
				background: #19367A;
				border-radius: 3rpx;
			}
		}
	}

	.upload-content {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 20rpx 0;

		.img-box {
			width: 200rpx;
			height: 200rpx;
			border-radius: 16rpx;
			overflow: hidden;
			background: #F7F8FA;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			margin-bottom: 16rpx;
			position: relative;
			box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);

			.preview-image {
				width: 100%;
				height: 100%;
				object-fit: cover;
			}

			.upload-placeholder {
				display: flex;
				flex-direction: column;
				align-items: center;
				color: #999;

				.cuIcon-camerafill {
					font-size: 48rpx;
					margin-bottom: 8rpx;
				}

				.upload-text {
					font-size: 24rpx;
				}
			}
		}

		.upload-tip {
			font-size: 24rpx;
			color: #999;
		}
	}

	.info-list {
		.info-item {
			display: flex;
			align-items: flex-start;
			padding: 24rpx 0;
			border-bottom: 1rpx solid #F5F5F5;

			&:last-child {
				border-bottom: none;
			}

			text {
				width: 160rpx;
				font-size: 28rpx;
				color: #333;
				padding-top: 8rpx;
			}

			.right-content {
				flex: 1;
				position: relative;

				.input-field {
					width: 100%;
					height: 72rpx;
					background: #F7F8FA;
					border-radius: 12rpx;
					padding: 0 24rpx;
					font-size: 28rpx;
					color: #333;
				}

				.textarea-field {
					width: 100%;
					height: 200rpx;
					background: #F7F8FA;
					border-radius: 12rpx;
					padding: 24rpx;
					font-size: 28rpx;
					color: #333;
				}

				.word-count {
					position: absolute;
					right: 24rpx;
					bottom: 24rpx;
					font-size: 24rpx;
					color: #999;
				}
			}

			&.description-item {
				align-items: flex-start;
			}
		}
	}

	.suggestion-list {
		position: absolute;
		top: 100%;
		left: 0;
		right: 0;
		background: #FFFFFF;
		border-radius: 12rpx;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
		z-index: 100;
		max-height: 400rpx;
		overflow-y: auto;

		.suggestion-item {
			padding: 20rpx 24rpx;
			font-size: 28rpx;
			color: #333;
			border-bottom: 1rpx solid #F5F5F5;

			&:last-child {
				border-bottom: none;
			}

			&:active {
				background: #F7F8FA;
			}
			
			.suggestion-content {
				display: flex;
				align-items: center;
				
				.suggestion-logo {
					width: 60rpx;
					height: 60rpx;
					border-radius: 8rpx;
					margin-right: 16rpx;
					object-fit: cover;
				}
				
				.suggestion-info {
					flex: 1;
					display: flex;
					flex-direction: column;
					
					.suggestion-name {
						font-size: 28rpx;
						color: #333;
						font-weight: 500;
						margin-bottom: 4rpx;
					}
					
					.suggestion-desc {
						font-size: 24rpx;
						color: #999;
					}
				}
			}
		}
	}

	.save-btn {
		width: 100%;
		height: 88rpx;
		background: #19367A;
		border-radius: 44rpx;
		color: #FFFFFF;
		font-size: 32rpx;
		font-weight: 500;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-top: 48rpx;
		box-shadow: 0 4rpx 12rpx rgba(25, 54, 122, 0.2);
		transition: all 0.3s ease;

		&:active {
			transform: scale(0.98);
			opacity: 0.9;
		}
	}
}
</style>