<template>
	<!-- 品牌索引弹窗 -->
	<view v-if="showBrandPopup" class="brand-popup-mask">
		<view class="brand-popup">
			<view class="brand-popup-header">
				<text class="brand-popup-close" @click="close">关闭</text>
				<text class="brand-popup-title">可回收的品牌</text>
			</view>
			<view class="brand-popup-search">
				<input class="brand-search-input" v-model="brandSearch" placeholder="请输入要查询的内容" @input="onBrandSearchInput" />
			</view>
			
			
			<scroll-view class="brand-popup-list" scroll-y :scroll-into-view="scrollToView">

				<!-- 热门品牌区域 -->
				<view v-if="hotBrandList.length > 0 && !brandSearch" class="hot-brands-section">
					<view class="hot-brands-title">热门品牌</view>
					<view class="hot-brands-grid">
						<view v-for="brand in hotBrandList" :key="brand.id" class="hot-brand-item" @click="openBrandConfirm(brand)">
							<image :src="brand.logo" class="hot-brand-logo" mode="aspectFit" />
							<text class="hot-brand-name">{{brand.name}}</text>
						</view>
					</view>
				</view>

				<view v-for="letter in brandIndexList" :key="letter" :id="'brand-letter-' + letter">
					<view class="brand-letter">{{letter}}</view>
					<view v-for="brand in filteredBrandList.filter(b => b.letter === letter)" :key="brand.name" class="brand-item" @click="openBrandConfirm(brand)">
						<image :src="brand.logo" class="brand-logo" mode="aspectFit" />
						<text class="brand-name">{{brand.name}}</text>
					</view>
				</view>
			</scroll-view>
			<view class="brand-index-bar">
				<text v-for="letter in brandIndexList" :key="letter" :class="{active: currentLetter === letter}" @click="scrollToLetter(letter)">{{letter}}</text>
			</view>
		</view>
	</view>

	<!-- 品牌确认弹窗 -->
	<view v-if="showBrandConfirm" class="brand-confirm-mask" @click.self="closeBrandConfirm">
		<view class="brand-confirm-popup">
			<view class="brand-confirm-title">品牌确认提示</view>
			<view class="brand-confirm-logo-wrap">
				<image :src="brandConfirmInfo.logo" class="brand-confirm-logo" mode="aspectFit" />
			</view>
			<view class="brand-confirm-name">{{ brandConfirmInfo.name }}</view>
			<view class="brand-confirm-desc">请确认所选品牌是否与实物品牌信息一致，否则将无法进行回收。</view>
			<view class="brand-confirm-btn-row">
				<button class="brand-confirm-btn retry" @click="closeBrandConfirm">重新选择</button>
				<button class="brand-confirm-btn confirm" @click="confirmBrand">确认一致</button>
			</view>
		</view>
	</view>

	<!-- 减少数量时的品牌选择弹窗 -->
	<view v-if="showBrandReducePopup" class="brand-reduce-popup-mask" @click.self="closeBrandReducePopup">
		<view class="brand-reduce-popup">
			<view class="brand-reduce-popup-header">
				<text class="brand-reduce-popup-close" @click="closeBrandReducePopup">关闭</text>
				<text class="brand-reduce-popup-title">选择要减少的品牌</text>
			</view>
			<scroll-view class="brand-reduce-popup-list" scroll-y>
				<view v-for="brand in reduceBrandList" :key="brand.brandId" class="brand-item" @click="selectReduceBrand(brand)">
					<image :src="brand.logo" class="brand-logo" mode="aspectFit" />
					<text class="brand-name">{{brand.name}}</text>
				</view>
			</scroll-view>
		</view>
	</view>
	
	<!-- 商品款式选择组件 -->
	<product-style-selector ref="styleSelector" @style-confirm="onStyleConfirm" @close="onStyleSelectorClose"></product-style-selector>
</template>

<script>
import { pinyin } from '../../utils/pinyin.js'
import ProductStyleSelector from './product-style-selector.vue'

export default {
	name: 'BrandSelector',
	components: {
		ProductStyleSelector
	},
	data() {
		return {
			showBrandPopup: false,
			showBrandConfirm: false,
			showBrandReducePopup: false,
			brandConfirmInfo: {
				logo: '',
				name: '',
				id: ''
			},
			brandList: [],
			hotBrandList: [], // 热门品牌列表
			currentLetter: 'A',
			scrollToView: '',
			brandSearch: '',
			reduceBrandList: [],
			currentProductId: null,
			searchTimer: null
		}
	},
	computed: {
		filteredBrandList() {
			return this.brandList
		},
		// 动态生成品牌字母索引，只显示有品牌的字母
		brandIndexList() {
			const letters = new Set()
			let hasSharp = false
			this.brandList.forEach(b => {
				if (b.letter && /^[A-Z]$/.test(b.letter)) {
					letters.add(b.letter)
				} else {
					letters.add('#')
					hasSharp = true
				}
			})
			const arr = Array.from(letters).filter(l => l !== '#').sort()
			if (hasSharp) arr.push('#')
			return arr
		}
	},
	methods: {
		// 打开品牌选择弹窗
		open(productId) {
			if (!productId) {
				console.error('productId is required')
				return
			}
			this.currentProductId = productId
			this.getGoodsBrandList(productId)
			this.showBrandPopup = true
		},
		
		// 关闭品牌选择弹窗
		close() {
			this.showBrandPopup = false
			this.showBrandConfirm = false
			this.showBrandReducePopup = false
			// 清理搜索状态
			this.brandSearch = ''
			this.currentProductId = null
			// 清空品牌列表
			this.brandList = []
			this.hotBrandList = []
			if (this.searchTimer) {
				clearTimeout(this.searchTimer)
				this.searchTimer = null
			}
			this.$emit('close')
		},
		
		// 打开减少品牌选择弹窗
		openReducePopup(brandList) {
			this.reduceBrandList = brandList || []
			this.showBrandReducePopup = true
		},
		
		// 关闭减少品牌选择弹窗
		closeBrandReducePopup() {
			this.showBrandReducePopup = false
			this.reduceBrandList = []
			this.$emit('reduce-close')
		},
		
		// 选择要减少的品牌
		selectReduceBrand(brandInfo) {
			this.closeBrandReducePopup()
			this.$emit('reduce-select', brandInfo)
		},
		
		// 滚动到指定字母
		scrollToLetter(letter) {
			this.currentLetter = letter
			this.scrollToView = 'brand-letter-' + letter
		},
		
		// 打开品牌确认弹窗
		openBrandConfirm(brand) {
			this.brandConfirmInfo = {
				id: brand.id,
				logo: brand.logo,
				name: brand.name
			}
			// this.showBrandConfirm = true
			this.confirmBrand()
		},
		
		// 关闭品牌确认弹窗
		closeBrandConfirm() {
			this.showBrandConfirm = false
		},
		
		// 确认品牌
		confirmBrand() {
			this.showBrandConfirm = false
			// 打开商品款式选择弹窗，传递已有数量
			this.$emit('get-existing-quantities', this.brandConfirmInfo.id, (existingQuantities) => {
				this.$refs.styleSelector.open(this.brandConfirmInfo, this.currentProductId, existingQuantities)
			})
		},
		
		// 处理款式确认事件
		onStyleConfirm(data) {
			this.showBrandPopup = false
			this.$emit('brand-confirm', {
				brandInfo: data.brandInfo,
				selectedStyles: data.selectedStyles
			})
		},
		
		// 处理款式选择器关闭事件
		onStyleSelectorClose() {
			// 款式选择器关闭时的处理逻辑
		},
		
		// 获取商品品牌列表
		getGoodsBrandList(productId, searchName = '') {
			this.currentProductId = productId
			const params = { productId }
			if (searchName.trim()) {
				params.name = searchName.trim()
			}
			this.$api('getGoodsBrandList', params, res => {
				if (res && res.success && res.result && res.result.records) {
					const allBrands = res.result.records.map(item => {
						// 获取品牌名称的拼音首字母
						const firstChar = this.getPinyinFirstLetter(item.name)
						return {
							id: item.id,
							logo: item.image || '/static/brand/alexander.png',
							name: item.name,
							letter: firstChar,
							isPin: item.isPin,
							hot: item.hot || 0,
							...item
						}
					})
					
					// 分离热门品牌和普通品牌
					this.hotBrandList = allBrands.filter(brand => brand.hot == 1)
					this.brandList = allBrands
				}
			})
		},
		
		// 获取中文拼音首字母
		getPinyinFirstLetter(str) {
			if (!str) return '#'
			const firstChar = str.charAt(0)
			// 遍历pinyin对象，查找包含该汉字的拼音
			for (let key in pinyin) {
				const chars = pinyin[key]
				if (chars && chars.indexOf(firstChar) !== -1) {
					return key.charAt(0).toUpperCase()
				}
			}
			// 英文首字母
			if (/^[A-Za-z]$/.test(firstChar)) {
				return firstChar.toUpperCase()
			}
			return '#'
		},
		
		// 品牌搜索输入事件处理
		onBrandSearchInput(e) {
			const searchValue = e.detail.value
			
			// 清除之前的定时器
			if (this.searchTimer) {
				clearTimeout(this.searchTimer)
			}
			
			// 设置防抖，500ms后执行搜索
			this.searchTimer = setTimeout(() => {
				if (this.currentProductId) {
					this.getGoodsBrandList(this.currentProductId, searchValue)
				}
			}, 500)
		}
	}
}
</script>

<style lang="scss" scoped>
.brand-popup-mask {
	position: fixed;
	left: 0;
	right: 0;
	top: 0;
	bottom: 0;
	background: rgba(0,0,0,0.35);
	z-index: 3000;
	display: flex;
	align-items: flex-end;
	justify-content: center;
}
.brand-popup {
	position: relative;
	width: 100%;
	max-width: 750px;
	background: #fff;
	border-radius: 32rpx 32rpx 0 0;
	box-shadow: 0 -4rpx 24rpx rgba(0,0,0,0.08);
	padding-bottom: 40rpx;
	height: 94vh;
	display: flex;
	flex-direction: column;
	overflow: hidden;
}
.brand-popup-header {
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 32rpx 24rpx 0 24rpx;
	font-size: 32rpx;
	font-weight: bold;
	position: relative;
}
.brand-popup-close {
	position: absolute;
	left: 24rpx;
	font-size: 28rpx;
	color: #888;
}
.brand-popup-title {
	font-size: 32rpx;
	color: #222;
	font-weight: bold;
}
.brand-popup-search {
	padding: 20rpx 24rpx 0 24rpx;
}
.brand-search-input {
	height: 60rpx;
	border-radius: 30rpx;
	background: #f5f5f5;
	border: none;
	padding-left: 40rpx;
	font-size: 28rpx;
	color: #888;
}
.brand-popup-list {
	flex: 1;
	overflow-y: auto;
	max-height: calc(94vh - 160rpx);
	padding: 0 24rpx;
	scrollbar-width: none; /* Firefox */
	-ms-overflow-style: none; /* IE and Edge */
	&::-webkit-scrollbar {
		width: 0 !important;
		display: none; /* Chrome, Safari, Opera */
	}
}
.brand-letter {
	font-size: 28rpx;
	color: #888;
	background-color: #f8f8f8;
	margin: 24rpx 0 0 0;
	padding: 8rpx 8rpx;
	font-weight: bold;
}
.brand-item {
	display: flex;
	align-items: center;
	padding: 16rpx 0;
	border-bottom: 1px solid #f0f0f0;
}
.brand-logo {
	width: 60rpx;
	height: 60rpx;
	margin-right: 20rpx;
	border-radius: 8rpx;
	background: #f8f8f8;
}
.brand-name {
	font-size: 28rpx;
	color: #222;
}
.brand-index-bar {
	position: absolute;
	right: 12rpx;
	top: 120rpx;
	width: 32rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
	z-index: 10;
}
.brand-index-bar text {
	font-size: 22rpx;
	color: #bbb;
	margin: 4rpx 0;
	font-weight: bold;
	&.active {
		color: #ff9c00;
	}
}

/* 热门品牌样式 */
.hot-brands-section {
	padding: 20rpx 0;
	border-bottom: 1px solid #f0f0f0;
}
.hot-brands-title {
	font-size: 28rpx;
	color: #222;
	font-weight: bold;
	margin-bottom: 20rpx;
}
.hot-brands-grid {
	display: flex;
	flex-wrap: wrap;
	gap: 10rpx;
}
.hot-brand-item {
	width: calc((100% - 120rpx) / 3);
	display: flex;
	// flex-direction: column;
	align-items: center;
	padding: 2rpx 4rpx;
	border-radius: 40rpx;
	background: #f3f3f3;
	border: 1px solid #eee;
	&:active {
		background: #eee;
	}
}
.hot-brand-logo {
	width: 48rpx;
	height: 48rpx;
	border-radius: 8rpx;
	margin-bottom: 8rpx;
	background: #fff;
	flex-shrink: 0;
}
.hot-brand-name {
	font-size: 22rpx;
	color: #333;
	text-align: center;
	line-height: 1.2;
	max-width: 100%;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.brand-confirm-mask {
	position: fixed;
	left: 0;
	right: 0;
	top: 0;
	bottom: 0;
	background: rgba(0,0,0,0.25);
	z-index: 5001;
	display: flex;
	align-items: center;
	justify-content: center;
}
.brand-confirm-popup {
	width: 70vw;
	max-width: 270px;
	background: #fff;
	border-radius: 32rpx;
	box-shadow: 0 8rpx 32rpx rgba(0,0,0,0.12);
	display: flex;
	flex-direction: column;
	align-items: center;
	padding: 48rpx 20rpx 36rpx 20rpx;
	position: relative;
}
.brand-confirm-title {
	font-size: 36rpx;
	color: #222;
	font-weight: bold;
	text-align: center;
	margin-bottom: 24rpx;
}
.brand-confirm-logo-wrap {
	width: 120rpx;
	height: 120rpx;
	background: #f8f8f8;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	margin-bottom: 18rpx;
}
.brand-confirm-logo {
	width: 80rpx;
	height: 80rpx;
	border-radius: 50%;
}
.brand-confirm-name {
	font-size: 28rpx;
	color: #222;
	font-weight: bold;
	text-align: center;
	margin-bottom: 16rpx;
}
.brand-confirm-desc {
	font-size: 24rpx;
	color: #999;
	text-align: center;
	margin-bottom: 32rpx;
	line-height: 1.6;
}
.brand-confirm-btn-row {
	width: 100%;
	display: flex;
	justify-content: space-between;
	gap: 24rpx;
}
.brand-confirm-btn {
	flex: 1;
	height: 72rpx;
	border-radius: 36rpx;
	font-size: 28rpx;
	font-weight: bold;
	display: flex;
	align-items: center;
	justify-content: center;
	border: none;
	margin: 0 0;
}
.brand-confirm-btn.retry {
	background: #fff;
	color: #ff9c00;
	border: 2rpx solid #ff9c00;
}
.brand-confirm-btn.confirm {
	background: linear-gradient(to right, #ffd01e, #ff8917);
	color: #fff;
	border: none;
}

/* 减少数量时的品牌选择弹窗 */
.brand-reduce-popup-mask {
	position: fixed;
	left: 0;
	right: 0;
	top: 0;
	bottom: 0;
	background: rgba(0,0,0,0.35);
	z-index: 5001;
	display: flex;
	align-items: center;
	justify-content: center;
}
.brand-reduce-popup {
	width: 70vw;
	max-width: 270px;
	background: #fff;
	border-radius: 32rpx;
	box-shadow: 0 8rpx 32rpx rgba(0,0,0,0.12);
	display: flex;
	flex-direction: column;
	align-items: center;
	padding: 48rpx 20rpx 36rpx 20rpx;
	position: relative;
}
.brand-reduce-popup-header {
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 32rpx 24rpx 0 24rpx;
	font-size: 32rpx;
	font-weight: bold;
	position: relative;
}
.brand-reduce-popup-close {
	position: absolute;
	left: 24rpx;
	font-size: 28rpx;
	color: #888;
}
.brand-reduce-popup-title {
	font-size: 32rpx;
	color: #222;
	font-weight: bold;
}
.brand-reduce-popup-list {
	flex: 1;
	overflow-y: auto;
	max-height: 60vh;
	padding: 0 24rpx;
	scrollbar-width: none; /* Firefox */
	-ms-overflow-style: none; /* IE and Edge */
	&::-webkit-scrollbar {
		width: 0 !important;
		display: none; /* Chrome, Safari, Opera */
	}
}
</style>