<template>
	<view class="content">
		<image class="bg" src="@/static/images/bg.png" mode="aspectFill"></image>

		<view class="header-wrap">
			<SearchBar
				:margin-top="'24rpx'"
				:bg-color="bgColor"
				:status-bar-height="statusBarHeight"
				:cart-count="cartCount"
				:search-width="'100%'"
				placeholder="搜索商品"
				@searchClick="toSearch"
				@cartClick="goAuthUrl()"
			/>
		</view>

		<!-- 作为组件嵌入 indexOld 时，外层使用 overflow:hidden；这里改成 scroll-view 保障可滚动与触底加载 -->
		<scroll-view scroll-y class="scroll-content" @scroll="onScroll" @scrolltolower="loadMoreGoods">
			<!-- 顶部占位：避免固定搜索栏遮挡 -->
			<view style="padding-bottom:110rpx">
				<view class="status_bar" :style="{height: statusBarHeight}"></view>
			</view>

			<!-- 推荐频道 -->
			<ChannelEntry :list="channelList" :per-row="4" :rows="2" @click="onChannelClick" />

			<!-- 金刚区：分类图标 2 行 4 列，仅展示 -->
			<CategoryTags :tags="categoryTagsData" @selectClick="onCategoryTagsSelect" />

			<!-- 推荐区块：左侧直播卡（直播中/回放）+ 右上绿色有机 + 右下上新推荐 -->
			<RecommendSection
				:live="recommendData.live"
				:green="recommendData.green"
				:hot="recommendData.hot"
				@liveClick="onLiveClick"
				@more="onRecommendMore"
				@itemClick="onRecommendItemClick"
			/>

			<!-- 瀑布流：全部 + 分类标签横向滚动 -->
			<GoodsNav :nav-list="goodsNavList" :active-id="activeGoodsNavId" @select="onGoodsNavSelect" />

			<GoodsList
				:list="goodsList"
				:loading="goodsLoading"
				:has-more="goodsHasMore"
				@itemClick="showProduct"
				@loadMore="loadMoreGoods"
			/>

			<!--#ifdef MP-WEIXIN-->
			<view class="official-account">
				<official-account @load="bindload" @error="binderror"></official-account>
			</view>
			<!--#endif-->

			<view class="popup-box" v-if="activityShow">
				<view class="info-mask" @tap="closeActivity()"></view>
				<view class="info-form">
					<image :src="activity.logoUrl" @tap="showActivity()" />
				</view>
			</view>

			<!-- <Server /> -->
		</scroll-view>
	</view>
</template>

<script>
// import zModal from '@/components/z-modal/z-modal.vue'
import { getMenu, getIndexData, getCartCount } from '@/api/index'
import { getStoreConfig } from '@/api/common'
import { getHomeInit, getHomeRecommend, getHomeGoods } from '@/api/home.js'
import HotProduct from './components/HotProduct.vue'
//import TuiProduct from '@/components/tuiProduct.vue'
import SearchBar from './components/SearchBar.vue'
import CategoryTags from './components/CategoryTags.vue'
import ChannelEntry from './components/ChannelEntry.vue'
import RecommendSection from './components/RecommendSection.vue'
import GoodsNav from './components/GoodsNav.vue'
import GoodsList from './components/GoodsList.vue'
import { getUserInfo, bindPromoter } from '@/api/user'

export default {
	components: {
		// zModal,
		HotProduct,
		//TuiProduct,
		SearchBar,
		CategoryTags,
		ChannelEntry,
		RecommendSection,
		GoodsNav,
		GoodsList
	},
	data() {
		return {
			btnGroup: [
				{ text: '取消', color: '#FFFFFF', bgColor: '#999999', width: '150rpx', height: '80rpx', shape: 'fillet', eventName: 'cancle' },
				{ text: '确定', color: '#FFFFFF', bgColor: '#FF233C', width: '150rpx', height: '80rpx', shape: 'fillet', eventName: 'sure' }
			],
			menuButtonInfo: {
				top: '0px',
				height: '0px',
				centerY: '0px',
				right: '0px'
			}, // 胶囊按钮布局信息
			initDone: false,
			showInitRan: false,
			tuiModalControl: false,
			activity: null,
			activityShow: false,
			hotProductList: [],
			menus: [],
			channelList: [],
			categoryTagsData: [],
			goodsNav: [],
			recommendData: { live: [], green: [], hot: [] },
			activeGoodsNavId: 'all',
			goodsList: [],
			goodsLoading: false,
			goodsHasMore: true,
			goodsPageNum: 1,
			cartCount: 0,
			advList: [],
			top: 0,
			statusBarHeight: uni.getSystemInfoSync().statusBarHeight + 'px',
			userinfoa: [],
			isuser: false,
			currentTab: 0
		}
	},
	computed: {
		bgColor() {
			const t = this.top / 30
			if(t>0){
				return '/static/images/bg.png'
			}else{
				return ''
			}
		},
		// 瀑布流标签：后端 categoryTags（不包含“全部”）
		goodsNavList() {
			const tags = (this.goodsNav || []).map(t => ({
				id: t.id || t.cateId,
				name: t.categoryName || t.cateName || t.name,
				categoryName: t.categoryName || t.cateName || t.name
			}))
			return tags
		}
	},
	mounted() {
		// 作为组件嵌入 indexOld 时，onShow/onLoad 通常不会触发；这里兜底初始化数据
		setTimeout(() => {
			if (!this.showInitRan && !this.initDone) this.initIndexData(false)
		}, 30)
	},
	onLoad(option) {
		this.getMenuButtonInfo(); // 初始化获取胶囊信息
		if (option.userCode != null) {
			uni.setStorageSync('userCode', option.userCode)
			if (this.$isLogin()) this.getUserInfo()
		}
		if (option.hasOwnProperty('q') && option.q) {
			const url = decodeURIComponent(option.q)
			const obj = this.$urlToObj(url)
			uni.setStorageSync('userCode', obj.userCode)
			if (this.$isLogin()) this.getUserInfo()
		}
	},
	onUnload() {
		uni.showTabBar();
		uni.$emit('stop')
	},
	onHide() {
		uni.$emit('stop')
	},
	onBackPress() {
		uni.showTabBar();
		uni.switchTab({
			//url: '/pages_im/pages/conversation/conversationList/index'
			url: '../index/index'
		})
	},
	onPageScroll(e) {
		// 页面滚动时兼容 uni-app 事件结构
		this.top = e?.detail?.scrollTop ?? e?.scrollTop ?? 0
	},
	onShow() {
		this.showInitRan = true
		this.initIndexData(true)
		uni.hideTabBar();
	},
	onShareAppMessage() {
		return { title: '岚财优选-您的专属解决方案', path: '/pages/common/launch', imageUrl: '/static/logo.jpg' }
	},
	onShareTimeline() {
		return { title: '岚财优选-您的专属解决方案', query: '', imageUrl: '/static/logo.jpg' }
	},
	onReachBottom() {
		this.loadMoreGoods()
		//this.$refs.tuiProduct && this.$refs.tuiProduct.getTuiProducts()
	},
	methods: {
		onScroll(e) {
			// scroll-view 的滚动事件
			this.top = e?.detail?.scrollTop ?? e?.scrollTop ?? 0
		},
		switchTab(index) {
			this.currentTab = index;
		},
		initIndexData(force = false) {
			if (this.initDone && !force) return
			this.initDone = true

			//this.getMenuButtonInfo()
			this.getHomeInit()
			this.getHomeRecommend()
			this.getMenu()
			//this.getIndexData()

			if (uni.getStorageSync('AppToken')) {
				this.getUserInfo()
			} else {
				this.isuser = true
			}
			if (this.$isLogin()) this.getCartCount()
			this.getStoreConfig()
		},
		// 获取胶囊按钮布局参数
		getMenuButtonInfo() {
			// 微信小程序API（Uniapp可直接用uni.getMenuButtonBoundingClientRect）
			const menuBtn = uni.getMenuButtonBoundingClientRect();
			if (menuBtn) {
		
				this.menuButtonInfo = {
					top: menuBtn.top + 'px', // 胶囊顶部距离
					height: menuBtn.height + 'px', // 胶囊高度
					centerY: (menuBtn.top + menuBtn.height / 2) + 'px', // 胶囊垂直居中Y坐标
					right: menuBtn.right + 'px' // 胶囊右侧距离
				};
			}
		},
		getHomeInit() {
			getHomeInit().then(res => {
				if (res.code == 200 && res.data) {
					this.channelList = res.data.channelList || []
					this.categoryTagsData = res.data.categoryTags || []
					this.goodsNav = res.data.goodsNav || []
					if (this.activeGoodsNavId === null || this.activeGoodsNavId === undefined) {
						this.activeGoodsNavId = 'all'
					}
					this.fetchGoodsList(true)
				}
			}).catch(() => {})
		},
		getHomeRecommend() {
			getHomeRecommend().then(res => {
				if (res.code != 200) return
				this.recommendData = {
					live: res.live && Array.isArray(res.live) ? res.live.slice(0, 3) : [],
					green: res.green && Array.isArray(res.green) ? res.green : [],
					hot: res.hot && Array.isArray(res.hot) ? res.hot : []
				}
			}).catch(() => {})
		},
		fetchGoodsList(reset) {
			if (reset) {
				this.goodsPageNum = 1
				this.goodsList = []
				this.goodsHasMore = true
			}
			if (this.goodsLoading || !this.goodsHasMore) return
			this.goodsLoading = true
			const id = this.activeGoodsNavId === 'all' || this.activeGoodsNavId === '' ? 0 : this.activeGoodsNavId
			getHomeGoods({ id, position:2, pageNum: this.goodsPageNum, pageSize: 10 }).then(res => {
				this.goodsLoading = false
				if (res.code == 200 && res.data) {
					const list = Array.isArray(res.data.list) ? res.data.list : []
					const total = res.data.total != null ? Number(res.data.total) : 0
					if (reset) this.goodsList = list
					else this.goodsList = this.goodsList.concat(list)
					this.goodsHasMore = list.length >= 20 && (this.goodsList.length < total || total === 0)
					this.goodsPageNum++
				}
			}).catch(() => { this.goodsLoading = false })
		},
		loadMoreGoods() {
			this.fetchGoodsList(false)
		},
		onGoodsNavSelect(item) {
      //console.log("2222")
      //console.log(item.id)
			this.activeGoodsNavId = item.id
			this.fetchGoodsList(true)
		},
		onCategoryTagsSelect(item) {
			//console.log(this.categoryTagsData,'item')
			// 金刚区点击：带分类 id 跳转商品列表页筛选（防护 item 为空）
			if (!item || typeof item !== 'object') {
				uni.navigateTo({ url: '/pages_mall/productList' })
				return
			}
			const id = item.id ?? item.cateId ?? item.categoryId
			if (id != null && id !== '') {
				uni.navigateTo({ url: '/pages_mall/productList?id=' + id })
			} else {
				uni.navigateTo({ url: '/pages_mall/productList' })
			}
		},
		onChannelClick(item) {
			// 推荐频道点击，可跳转或筛选，按需扩展
		},
		onRecommendMore(section) {
			if (section && section.moreUrl) {
				uni.navigateTo({ url: '/pages_mall/recommendList' })
				return
			}
			if (section && (section.type === 'green' || section.type === 'hot')) {
				uni.navigateTo({ url: '/pages_mall/recommendList?type='+section.type})
			}
		},
		onLiveClick(item) {
			//console.log(item)
			if (item && item.liveId) uni.navigateTo({ url: '/pages_course/living?liveId=' + item.liveId })
		},
		onRecommendItemClick(item,type) {
			if (item.productId) this.showProduct(item,type)
		},
		getMenu() {
			// getMenu().then(res => {
			// 	if (res.code == 200) this.menus = res.data || []
			// })
		},
		getIndexData() {
			getIndexData({}).then(res => {
				if (res.code == 200) {
					this.advList = res.data.advList || []
					this.hotProductList = res.data.hotProductList || []
				} else {
					uni.showToast({ icon: 'none', title: '请求失败' })
				}
			})
		},
		getUserInfo() {
			getUserInfo().then(res => {
				if (res.code == 200 && res.user != null) this.userinfoa = res.user
				else uni.showToast({ icon: 'none', title: '请求失败' })
			})
		},
		getCartCount() {
			if (this.$isLogin()){
				getCartCount().then(cartRes => {
					if (cartRes.code == 200) this.cartCount = cartRes.data
					this.$emit('updateMallIndexCartCount', cartRes.data || 0)
				})
			}
		},
		getStoreConfig() {
			getStoreConfig().then(res => {
				if (res.code == 200) uni.setStorageSync('config', JSON.stringify(res.data))
			})
		},
		cancleTui() {
			this.tuiModalControl = false
		},
		submitTui(e) {
			if (!e.inputText) {
				uni.showToast({ icon: 'none', title: '请输入邀请码' })
				return
			}
			bindPromoter({ userCode: e.inputText }).then(res => {
				uni.showToast({ icon: 'none', title: res.msg })
				if (res.code == 200) this.tuiModalControl = false
			})
		},
		bindload() {},
		binderror() {},
		closeActivity() {
			this.activityShow = false
		},
		showActivity() {
			this.activityShow = false
			if (this.activity && this.activity.activityId) {
				uni.navigateTo({ url: '/pages_shopping/shopping/activityDetails?activityId=' + this.activity.activityId })
			}
		},
		menuClick(item) {
			const linkUrl = item.linkUrl || item.url
			const linkType = item.linkType != null ? item.linkType : (linkUrl ? 1 : 0)
			if (linkType == 1 && linkUrl) {
				if (linkUrl == '/pages/shopping/index' || linkUrl == '/pages/healthy/index') {
					uni.switchTab({ url: linkUrl })
				} else {
					uni.navigateTo({ url: linkUrl })
				}
			} else if (linkType == 0) {
				uni.showToast({ icon: 'none', title: '开发中...' })
			}
		},
		handleAdvClick(item) {
			if (item.showType == 1) {
				uni.setStorageSync('url', item.advUrl)
				uni.navigateTo({ url: 'h5' })
			} else if (item.showType == 2) {
				uni.navigateTo({ url: item.advUrl })
			} else if (item.showType == 3) {
				uni.setStorageSync('content', item.content)
				uni.navigateTo({ url: 'content' })
			}
		},
		goAuthUrl(url) {
			if (this.$isLogin()) {
				uni.switchTab({ url })
			}
		},
		navTo(url) {
			uni.navigateTo({ url })
		},
		toSearch() {
			
			//uni.navigateTo({ url: './productSearch' })
			uni.navigateTo({ url: '/pages_mall/productList' })
		},
		showProduct(item,type) {
			//console.log('item',type)
			//uni.navigateTo({ url: '../shopping/productDetails?productId=' + item.productId })
			uni.navigateTo({ url: '/pages_mall/recommendList?type='+type})
		}
	}
}
</script>

<style lang="scss" scoped>
	.tab-bar {
		height: 100rpx;
		background-color: #fff;
		display: flex;
		align-items: center;
		justify-content: space-around;
		border-top: 1rpx solid #eee;
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		z-index: 9999;
	
		.tab-item {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
	
			text {
				font-size: 24rpx;
				margin-top: 6rpx;
				color: #999999;
			}
	
			&.active text {
				color: #FF233C;
			}
	
			.icon-wrap {
				position: relative;
	
				.badge {
					position: absolute;
					top: -10rpx;
					right: -10rpx;
					background: #fa436a;
					color: #fff;
					font-size: 18rpx;
					width: 30rpx;
					height: 30rpx;
					border-radius: 50%;
					display: flex;
					align-items: center;
					justify-content: center;
				}
			}
		}
	}
.content {
	width: 100%;
	position: relative;
	min-height: 0;
	padding-top: 1rpx;
	display: flex;
	flex-direction: column;
	height: 100%;
}
.scroll-content {
	flex: 1;
	height: 0;
}
.header-wrap {
	position: relative;
	z-index: 10;
}
.banner-row {
	position: relative;
	display: flex;
	gap: 20rpx;
	padding: 20rpx 24rpx;
	// background: #fff;
}
.banner-item {
	flex: 1;
	height: 220rpx;
	border-radius: 16rpx;
	overflow: hidden;
	background: #f5f5f5;
}
.banner-img {
	width: 100%;
	height: 100%;
}
.bg {
	width: 100%;
	height: 380rpx;
	position: absolute;
	top: 0;
	left: 0;
	z-index: 0;
}
.status_bar {
	width: 100%;
}
.banner-box {
	padding: 0 20upx;
}
.banner-box .inner {
	width: 100%;
	height: 236upx;
	border-radius: 10upx;
	overflow: hidden;
}
.banner-box .swiper,
.banner-box .swiper-item,
.banner-box .swiper-item image {
	width: 100%;
	height: 100%;
}
.menu-content {
	background-color: #fff;
	overflow: hidden;
	padding: 20upx 20upx 0;
}
.menu-box {
	display: flex;
	align-items: center;
	background-color: #fff;
}
.online-inquiry {
	box-sizing: border-box;
	width: 100%;
	height: 300upx;
	padding: 20upx;
	background: linear-gradient(180deg, rgba(255, 255, 255, 0.38) 62%, rgba(255, 255, 255, 0) 100%);
}
.online-inquiry .item {
	width: 100%;
	height: 100%;
	position: relative;
}
.online-inquiry .bg-img {
	width: 100%;
	height: 100%;
	position: absolute;
	top: 0;
	left: 0;
	border-radius: 15rpx;
}
.index-cont {
	box-sizing: border-box;
	padding: 0 20upx 120rpx;
}
.official-account {
	width: 100%;
}
.popup-box {
	position: fixed;
	top: 0;
	right: 0;
	left: 0;
	bottom: 0;
	z-index: 999;
	display: flex;
	justify-content: center;
	align-items: center;
}
.popup-box .info-mask {
	position: fixed;
	top: 0;
	right: 0;
	bottom: 0;
	left: 0;
	background-color: rgba(0, 0, 0, 0.5);
	z-index: 999;
}
.popup-box .info-form {
	z-index: 1000;
	width: 450rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
}
.popup-box .info-form image {
	width: 100%;
}
</style>
