<template>
	<view class="brand-detail-container">
		<!-- 自定义沉浸式头部导航 -->
		<view class="custom-header" :class="{ 'header-scrolled': scrollY > 50 }">
			<view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>
			<view class="nav-bar">
				<view class="nav-left back-area" @click="goBack">
					<text class="back-icon">〈</text>
				</view>
				<view class="nav-title" v-if="scrollY > 50">{{ brandInfo.fq_brand_name || '品牌详情' }}</view>
				<view class="nav-title" v-else></view>
				<view class="nav-right"></view>
			</view>
		</view>

		<!-- 页面滚动主视图区 -->
		<scroll-view scroll-y class="main-scroll-view" :show-scrollbar="false" @scroll="onScroll" @scrolltolower="loadMoreItems">
			<!-- 顶部品牌英雄传记大幕区 -->
			<view class="hero-biography-section">
				<!-- 底层唯美梦幻光影背景 -->
				<image class="biography-bg" :src="heroBgImage" mode="aspectFill"></image>
				<view class="biography-overlay"></view>

				<!-- 品牌身份核心图腾层 -->
				<view class="biography-core" :style="{ paddingTop: navBarHeight + 'px' }">
					<view class="logo-wrapper">
						<image class="brand-logo-img" :src="brandInfo.brand_logo || brandInfo.inside_logo" mode="aspectFit"></image>
					</view>
					<view class="brand-title-box">
						<text class="b-name">{{ brandInfo.fq_brand_name || brandInfo.tb_brand_name }}</text>
						<!-- 并列双认证背书矩阵 -->
						<view class="capsules-row">
							<view class="b-fans-capsule" v-if="brandInfo.fans">
								<text class="heart-icon">❤</text>
								<text>{{ formattedFans }} 粉丝关注</text>
							</view>
							<!-- 月销量动态胶囊，0值全隐 -->
							<view class="b-sale-capsule" v-if="brandInfo.todaysale && Number(brandInfo.todaysale) > 0">
								<text class="fire-icon">🔥</text>
								<text>月销 {{ formatSale(brandInfo.todaysale) }} 件</text>
							</view>
						</view>
					</view>
					<!-- 顶层海报极度纯净减负，旧版简介彻底下沉至卡片内展示 -->
				</view>
			</view>

			<!-- 浮动式品牌卖点、话题与下沉简介展示墙 (高级拟态玻璃卡片) -->
			<view class="compile-card-wrapper" v-if="compileLines.length > 0 || recommendTags.length > 0 || brandInfo.introduce">
				<view class="glass-compile-card">
					<!-- <view class="card-tag-title" v-if="compileLines.length > 0">✨ 品牌深度精编卖点</view>
					<view class="compile-line-item" v-for="(line, lIdx) in compileLines" :key="lIdx">
						<text class="line-dot">▪</text>
						<text class="line-text">{{ line }}</text>
					</view> -->

					<!-- 推荐话题列表 (横向丝滑拖动轴) -->
					<scroll-view scroll-x class="recommend-tags-scroll" :show-scrollbar="false" v-if="recommendTags.length > 0">
						<view class="tags-scroll-inner">
							<text class="r-tag" v-for="(tag, tIdx) in recommendTags" :key="tIdx">{{ tag }}</text>
						</view>
					</scroll-view>

					<!-- 下沉式高定深色简介与行末跟随红字按钮 -->
					<view class="card-intro-section" v-if="brandInfo.introduce">
						<text class="c-intro-txt">{{ isExpanded ? brandInfo.introduce : (brandInfo.introduce.length > 95 ? brandInfo.introduce.slice(0, 95) + '...' : brandInfo.introduce) }}</text>
						<text class="inline-toggle-btn" v-if="brandInfo.introduce.length > 95" @click="isExpanded = !isExpanded">{{ isExpanded ? ' 收起' : ' 展开'}}</text>
					</view>
				</view>
			</view>

			<!-- 纯白容器大盘装配货盘引擎 -->
			<view class="items-container-box">
				<!-- 排序选项卡栏 (极细线分割) -->
				<view class="filter-bar">
					<view class="filter-item" :class="{ 'active': sortType === 1 }" @click="changeSort(1)">综合</view>
					<view class="filter-divider"></view>
					<view class="filter-item" :class="{ 'active': sortType === 2 }" @click="changeSort(2)">销量</view>
					<view class="filter-divider"></view>
					<view class="filter-item" :class="{ 'active': sortType === 3 }" @click="changeSort(3)">
						券后价
						<view class="price-arrows">
							<text class="up" :class="{ 'hl': sortType === 3 && priceOrder === 'asc' }">▲</text>
							<text class="down" :class="{ 'hl': sortType === 3 && priceOrder === 'desc' }">▼</text>
						</view>
					</view>
				</view>

				<!-- 横向单列左图右文精装流 -->
				<view class="goods-list-single">
					<view class="single-goods-item" v-for="(goods, gIdx) in itemList" :key="gIdx" @click="goToDetail(goods.id)">
						<!-- 左侧圆角方图预览 -->
						<view class="g-img-left">
							<image class="goods-pic" :src="goods.itempic" mode="aspectFill"></image>
						</view>

						<!-- 右侧高阶信息核心带 -->
						<view class="g-info-right">
							<!-- 平台红标与加粗题词 -->
							<view class="g-title-row">
								<image src="https://img-haodanku-com.cdn.fudaiapp.com/FlyOSTvjC3LjrkUoJ0NPxx1qnGz4" class="platform-icon"></image>
								<text class="title-text">{{ goods.itemshorttitle || goods.itemtitle }}</text>
							</view>

							<!-- 精装浅粉底色圆角标签阵列 -->
							<view class="g-labels-row" v-if="goods.label && goods.label.length > 0">
								<text class="g-label-tag" v-for="(tag, tIdx) in goods.label.slice(0, 2)" :key="tIdx">{{ tag }}</text>
							</view>
							<view class="g-labels-row" v-else-if="goods.discount">
								<text class="g-label-tag">省{{ goods.discount }}元</text>
							</view>
							<view class="g-labels-row" v-else>
								<text class="g-label-tag">精选特卖</text>
							</view>

							<!-- 超大字粉红券后价与实心红底连体券标 -->
							<view class="g-price-row">
								<view class="price-left">
									<text class="p-tip">券后</text>
									<text class="p-symbol">￥</text>
									<text class="p-integer">{{ goods.itemendprice }}</text>
								</view>

								<!-- 连体实心红胶囊 -->
								<view class="coupon-solid-box" v-if="goods.couponmoney > 0">
									<text class="c-left">券</text>
									<text class="c-right">{{ goods.couponmoney }}元</text>
								</view>
							</view>

							<!-- 底部已售与店铺背书墙 -->
							<view class="g-bottom-row">
								<text class="sales">已售{{ formatSale(goods.itemsale) }}件</text>
								<text class="divider">|</text>
								<text class="shop">店铺：{{ goods.shopname || brandInfo.tb_brand_name || brandInfo.fq_brand_name || '官方旗舰店' }}</text>
							</view>
						</view>
					</view>
				</view>

				<!-- 底部极致干脆的高端提示语留白区 -->
				<view class="pure-loading-footer">
					<text v-if="loading">加载中...</text>
					<text v-else-if="finished">已为您加载完毕</text>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	import http from '@/request/request.js';

	export default {
		data() {
			return {
				statusBarHeight: 44,
				scrollY: 0,
				brandId: 0,
				brandInfo: {},
				itemList: [],
				page: 1,
				sortType: 1, // 1:综合, 2:销量, 3:券后价
				priceOrder: 'desc',
				isExpanded: false,
				loading: false,
				finished: false,
				// 预设高定静态莫兰迪光影壁纸库，用于海报衬底自愈
				defaultBanners: [
					'https://images.unsplash.com/photo-1556228720-195a672e8a03?w=800&q=80',
					'https://images.unsplash.com/photo-1590080875515-8a3a8dc5735e?w=800&q=80',
					'https://images.unsplash.com/photo-1585771724684-38269d6639fd?w=800&q=80',
					'https://images.unsplash.com/photo-1607082348824-0a96f2a4b9da?w=800&q=80'
				]
			}
		},
		computed: {
			navBarHeight() {
				return this.statusBarHeight + 44;
			},
			heroBgImage() {
				// 优先采用配置中的合成图或随机自愈壁纸
				if (this.brandInfo.composeimage) {
					return this.brandInfo.composeimage.replace('http://', 'https://');
				}
				const idx = Number(this.brandId) || 1;
				return this.defaultBanners[idx % this.defaultBanners.length];
			},
			formattedFans() {
				const f = this.brandInfo.fans;
				if (!f) return '10万+';
				if (f >= 10000) {
					return (f / 10000).toFixed(1) + '万';
				}
				return f;
			},
			compileLines() {
				const comp = this.brandInfo.brand_compile || '';
				if (!comp) return [];
				// 根据 \n 拆分，过滤掉空行，并去掉首位可能带有的星号及箭头
				return comp.split('\n')
					.map(s => s.trim())
					.filter(s => s.length > 0)
					.map(s => s.replace(/^[★☆▪•]/, '').trim());
			},
			recommendTags() {
				const rec = this.brandInfo.brand_recommend;
				if (Array.isArray(rec)) return rec;
				if (typeof rec === 'string' && rec.length > 0) {
					try {
						return JSON.parse(rec);
					} catch (e) {
						return rec.split(' ').filter(s => s.length > 0);
					}
				}
				return [];
			}
		},
		onLoad(options) {
			const sysInfo = uni.getSystemInfoSync();
			this.statusBarHeight = sysInfo.statusBarHeight || 44;
			
			this.brandId = options.id || options.brand_id || 1292;
			console.log('品牌详情专页加载，传入目标ID:', this.brandId);

			this.fetchBrandDetailData();
		},
		methods: {
			goBack() {
				const pages = getCurrentPages();
				if (pages && pages.length > 1) {
					uni.navigateBack({ delta: 1 });
				} else {
					uni.reLaunch({ url: '/pages/special-sale/choicen' });
				}
			},
			goToDetail(id) {
				uni.navigateTo({
					url: `/pages/detail/detail?id=${id}`
				});
			},
			onScroll(e) {
				this.scrollY = e.detail.scrollTop;
			},
			formatSale(val) {
				if (!val) return '1.0万';
				if (val >= 10000) {
					return (val / 10000).toFixed(1) + '万';
				}
				return val;
			},
			changeSort(type) {
				if (type === 3 && this.sortType === 3) {
					this.priceOrder = this.priceOrder === 'asc' ? 'desc' : 'asc';
				} else {
					this.sortType = type;
					if (type === 3) this.priceOrder = 'desc';
				}
				this.page = 1;
				this.finished = false;
				this.itemList = [];
				this.fetchBrandDetailData();
			},
			loadMoreItems() {
				if (this.loading || this.finished) return;
				this.page += 1;
				console.log('品牌单品列表触发触底翻页，发起页码:', this.page);
				this.fetchBrandDetailData(true);
			},
			fetchBrandDetailData(isLoadMore = false) {
				if (this.loading) return;
				this.loading = true;
				
				if (!isLoadMore) {
					uni.showLoading({ title: '加载中...', mask: true });
				}

				// 推导后端要求排序规则：综合为0，销量为3，券后价升序为8，降序为9
				let sortParam = 0;
				if (this.sortType === 2) {
					sortParam = 3;
				} else if (this.sortType === 3) {
					sortParam = this.priceOrder === 'asc' ? 8 : 9;
				}

				http.get(`https://api.cmspro.haodanku.com/brandItem/detail?page=${this.page}&page_size=20&sort=${sortParam}&brand_id=${this.brandId}&cid=YsWZ21tx`)
					.then((res) => {
						if (res.data) {
							// 挂载核心品牌自画像
							if (res.data.brand_info) {
								const info = res.data.brand_info;
								if (info.brand_logo) info.brand_logo = info.brand_logo.replace('http://', 'https://');
								if (info.inside_logo) info.inside_logo = info.inside_logo.replace('http://', 'https://');
								this.brandInfo = info;
							}

							// 挂载分页商品方阵
							if (res.data.items && Array.isArray(res.data.items.list)) {
								const list = res.data.items.list.map(goods => {
									let pic = goods.itempic ? goods.itempic.replace('http://', 'https://') : '';
									return {
										id: goods.id,
										itemtitle: goods.itemtitle,
										itemshorttitle: goods.itemshorttitle,
										itempic: pic,
										itemprice: goods.itemprice,
										itemendprice: goods.itemendprice,
										itemsale: goods.itemsale,
										discount: goods.discount,
										couponmoney: parseFloat(goods.couponmoney || 0),
										shopname: goods.shopname || (goods.shoptype === 'B' ? '天猫超市' : ''),
										label: Array.isArray(goods.label) ? goods.label : []
									};
								});

								if (isLoadMore) {
									this.itemList = [...this.itemList, ...list];
								} else {
									this.itemList = list;
								}

								const pagination = res.data.items.pagination;
								if (pagination && this.page >= pagination.page_count) {
									this.finished = true;
								} else if (list.length < 20) {
									this.finished = true;
								}
							} else {
								if (isLoadMore) this.finished = true;
							}
						} else {
							uni.showToast({ title: '加载专区数据失败', icon: 'none' });
						}
					})
					.catch((err) => {
						console.log('拉取品牌专页接口错误', err);
						if (isLoadMore && this.page > 1) this.page -= 1;
					})
					.finally(() => {
						this.loading = false;
						if (!isLoadMore) uni.hideLoading();
					});
			}
		}
	}
</script>

<style scoped>
	.brand-detail-container {
		width: 100%;
		height: 100vh;
		background-color: #f5f6f8;
		display: flex;
		flex-direction: column;
	}

	/* 顶部回退沉浸式导航栏 */
	.custom-header {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		z-index: 999;
		transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
		background: transparent;
	}

	.status-bar {
		width: 100%;
	}

	.header-scrolled {
		background: rgba(255, 255, 255, 0.98);
		backdrop-filter: blur(20rpx);
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	.nav-bar {
		height: 44px;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 30rpx;
	}

	.nav-left {
		width: 80rpx;
		height: 100%;
		display: flex;
		align-items: center;
	}

	.back-icon {
		font-size: 38rpx;
		color: #ffffff;
		font-weight: bold;
		text-shadow: 0 2rpx 4rpx rgba(0,0,0,0.4);
	}

	.header-scrolled .back-icon {
		color: #333333;
		text-shadow: none;
	}

	.nav-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333333;
		opacity: 0;
		transition: opacity 0.2s;
	}

	.header-scrolled .nav-title {
		opacity: 1;
	}

	.nav-right {
		width: 80rpx;
	}

	/* 滚动主体区 */
	.main-scroll-view {
		flex: 1;
		width: 100%;
		overflow-y: auto;
	}

	/* 品牌英雄大幕传记层 */
	.hero-biography-section {
		position: relative;
		width: 100%;
		min-height: 480rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: flex-end;
		padding-bottom: 40rpx;
	}

	.biography-bg {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		width: 100%;
		height: 100%;
	}

	.biography-overlay {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: linear-gradient(to bottom, rgba(0,0,0,0.15) 0%, rgba(138,43,226,0.35) 50%, rgba(20,20,20,0.85) 100%);
	}

	.biography-core {
		position: relative;
		z-index: 2;
		display: flex;
		flex-direction: column;
		align-items: center;
		width: 100%;
		padding: 0 40rpx;
		box-sizing: border-box;
	}

	.logo-wrapper {
		width: 140rpx;
		height: 140rpx;
		background: #ffffff;
		border-radius: 50%;
		padding: 12rpx;
		box-shadow: 0 6rpx 20rpx rgba(0,0,0,0.25);
		border: 4rpx solid rgba(255,255,255,0.8);
		margin-bottom: 16rpx;
	}

	.brand-logo-img {
		width: 100%;
		height: 100%;
		border-radius: 50%;
	}

	.brand-title-box {
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.b-name {
		font-size: 40rpx;
		font-weight: 800;
		color: #ffffff;
		letter-spacing: 2rpx;
		text-shadow: 0 4rpx 8rpx rgba(0,0,0,0.4);
	}

	.capsules-row {
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 16rpx;
		margin-top: 10rpx;
	}

	.b-fans-capsule {
		background: linear-gradient(to right, rgba(255,65,108,0.85), rgba(255,75,43,0.85));
		padding: 4rpx 20rpx;
		border-radius: 20rpx;
		display: flex;
		align-items: center;
		backdrop-filter: blur(8rpx);
	}

	.b-sale-capsule {
		background: linear-gradient(to right, rgba(255,140,0,0.85), rgba(255,69,0,0.85));
		padding: 4rpx 20rpx;
		border-radius: 20rpx;
		display: flex;
		align-items: center;
		backdrop-filter: blur(8rpx);
	}

	.heart-icon, .fire-icon {
		color: #ffffff;
		font-size: 22rpx;
		margin-right: 8rpx;
	}

	.b-fans-capsule text, .b-sale-capsule text {
		color: #ffffff;
		font-size: 22rpx;
		font-weight: bold;
	}

	/* 拟态玻璃精编卖点与下沉简介卡片层 */
	.card-intro-section {
		margin-top: 16rpx;
		border-top: 1rpx dashed rgba(0,0,0,0.06);
		padding-top: 16rpx;
		width: 100%;
	}

	.c-intro-txt {
		font-size: 26rpx;
		color: #333333;
		line-height: 1.6;
		text-align: justify;
	}

	.inline-toggle-btn {
		color: #ff416c;
		font-size: 26rpx;
		font-weight: bold;
		padding-left: 6rpx;
		display: inline;
	}

	/* 拟态玻璃精编卖点卡片层 */
	.compile-card-wrapper {
		padding: 0 30rpx;
		margin-top: -24rpx;
		position: relative;
		z-index: 5;
	}

	.glass-compile-card {
		background: rgba(255, 255, 255, 0.95);
		border-radius: 24rpx;
		padding: 30rpx;
		box-shadow: 0 8rpx 24rpx rgba(0,0,0,0.06);
		border: 1rpx solid rgba(255,255,255,0.8);
		display: flex;
		flex-direction: column;
	}

	.card-tag-title {
		font-size: 26rpx;
		font-weight: bold;
		color: #8a2be2;
		margin-bottom: 16rpx;
	}

	.compile-line-item {
		display: flex;
		align-items: baseline;
		margin-bottom: 10rpx;
	}

	.line-dot {
		color: #ff416c;
		font-size: 24rpx;
		margin-right: 12rpx;
	}

	.line-text {
		font-size: 26rpx;
		color: #444444;
		line-height: 1.45;
		font-weight: 500;
	}

	.recommend-tags-scroll {
		width: 100%;
		white-space: nowrap;
		box-sizing: border-box;
	}

	.tags-scroll-inner {
		display: inline-flex;
		align-items: center;
		padding: 4rpx 0;
	}

	.r-tag {
		font-size: 24rpx;
		color: #555555;
		background-color: #f4f5f9;
		padding: 10rpx 24rpx;
		border-radius: 26rpx;
		margin-right: 16rpx;
		font-weight: 500;
		display: inline-block;
		white-space: nowrap;
		word-break: keep-all;
		flex-shrink: 0;
	}

	/* 纯白装配大底盘与过滤排序引擎 */
	.items-container-box {
		background: #ffffff;
		border-top-left-radius: 24rpx;
		border-top-right-radius: 24rpx;
		margin: 0 24rpx;
		padding-bottom: 40rpx;
		overflow: hidden;
		box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.02);
	}

	.filter-bar {
		display: flex;
		align-items: center;
		height: 88rpx;
		border-bottom: 1rpx solid #f6f6f6;
		background: #ffffff;
	}

	.filter-item {
		flex: 1;
		text-align: center;
		font-size: 28rpx;
		color: #666666;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.filter-item.active {
		color: #ff416c;
		font-weight: bold;
	}

	.filter-divider {
		width: 2rpx;
		height: 24rpx;
		background-color: #eeeeee;
	}

	.price-arrows {
		display: flex;
		flex-direction: column;
		margin-left: 8rpx;
		line-height: 1;
	}

	.price-arrows text {
		font-size: 16rpx;
		color: #cccccc;
	}

	.price-arrows text.hl {
		color: #ff416c;
	}

	/* 单列横排货盘流 */
	.goods-list-single {
		background: #ffffff;
	}

	.single-goods-item {
		display: flex;
		padding: 24rpx;
		border-bottom: 1rpx solid #f9f9f9;
	}

	.g-img-left {
		width: 220rpx;
		height: 220rpx;
		border-radius: 12rpx;
		overflow: hidden;
		flex-shrink: 0;
		background-color: #f5f5f5;
	}

	.goods-pic {
		width: 100%;
		height: 100%;
	}

	.g-info-right {
		flex: 1;
		margin-left: 24rpx;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		padding: 4rpx 0;
		overflow: hidden;
	}

	.g-title-row {
		display: flex;
		align-items: flex-start;
		line-height: 1.4;
	}

	.platform-icon {
		width: 26rpx;
		height: 26rpx;
		margin-right: 8rpx;
		margin-top: 4rpx;
		flex-shrink: 0;
	}

	.title-text {
		font-size: 26rpx;
		color: #333333;
		font-weight: bold;
		overflow: hidden;
		text-overflow: ellipsis;
		display: -webkit-box;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
	}

	.g-labels-row {
		display: flex;
		flex-wrap: wrap;
		margin-top: 10rpx;
	}

	.g-label-tag {
		font-size: 20rpx;
		color: #ff416c;
		background: #fff5f7;
		border: 1rpx solid #ffd6de;
		padding: 2rpx 12rpx;
		border-radius: 20rpx;
		margin-right: 12rpx;
		margin-bottom: 6rpx;
	}

	.g-price-row {
		display: flex;
		align-items: baseline;
		margin-top: auto;
		padding-top: 12rpx;
	}

	.price-left {
		display: flex;
		align-items: baseline;
	}

	.p-tip {
		font-size: 22rpx;
		color: #ff416c;
		margin-right: 4rpx;
	}

	.p-symbol {
		font-size: 24rpx;
		color: #ff416c;
		font-weight: bold;
	}

	.p-integer {
		font-size: 38rpx;
		color: #ff416c;
		font-weight: bold;
	}

	/* 连体实心红胶囊 */
	.coupon-solid-box {
		display: flex;
		align-items: center;
		background: #ff416c;
		border-radius: 6rpx;
		overflow: hidden;
		height: 32rpx;
		margin-left: 16rpx;
	}

	.c-left {
		font-size: 18rpx;
		color: #ffffff;
		background: rgba(255, 255, 255, 0.2);
		padding: 0 8rpx;
		height: 100%;
		display: flex;
		align-items: center;
		font-weight: bold;
	}

	.c-right {
		font-size: 18rpx;
		color: #ffffff;
		padding: 0 10rpx;
		font-weight: bold;
	}

	.g-bottom-row {
		display: flex;
		align-items: center;
		font-size: 22rpx;
		color: #999999;
		margin-top: 10rpx;
	}

	.divider {
		margin: 0 12rpx;
		color: #e0e0e0;
	}

	.shop {
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
		flex: 1;
	}

	.pure-loading-footer {
		text-align: center;
		font-size: 24rpx;
		color: #999999;
		padding: 40rpx 0 20rpx;
	}
</style>
