<template>
	<view class="content">
		<image class="bg" src="@/static/images/bg.png" mode="aspectFill"></image>
		<view class="header-wrap">
			<SearchBar
			    :margin-top="menuButtonInfo.top"
				:bg-color="bgColor"
				:status-bar-height="statusBarHeight"
				:cart-count="cartCount"
				:search-width="'500rpx'"
				placeholder="搜索商品"
				@searchClick="toSearch"
				@cartClick="goAuthUrl('/pages/shopping/cart')"
			/>
		</view>
         <view style="padding-bottom:100rpx">
         	<view class="status_bar" :style="{height: statusBarHeight}"></view>
         </view>
		<!-- 主横幅：两图横向 -->
		<!-- <view class="banner-row-wrap" v-if="showBannerBlock">
			<view class="banner-row" :class="{ 'banner-skeleton': showBannerSkeleton }">
				<template v-if="showBannerContent">
					<view class="banner-item" v-for="(item, i) in bannerList" :key="item.slotKey" @tap="handleAdvClick(item.course)">
						<image class="banner-img" :src="item.image" mode="widthFix"></image>
					</view>
				</template>
				<template v-else-if="showBannerSkeleton">
					<view class="banner-sk-item" v-for="i in 2" :key="'banner-sk-' + i"></view>
				</template>
			</view>
		</view> -->

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

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


		<!-- 推荐区块：左侧直播卡（直播中/回放）+ 右上绿色有机 + 右下上新推荐 -->
		<RecommendSection
			:loading="recommendLoading"
			: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"
			:refreshing="goodsRefreshing"
			: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>

		<GuidePopup ref="guidePopup" />
		<z-modal :show="tuiModalControl" placeholderText="请输入邀请码" :btnGroup="btnGroup" :contentType="2"
			titleText="填写邀请码" @cancle="cancleTui" @sure="submitTui"></z-modal>
		<Server />
	</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, listPublicCourse, getHisStoreConfig } 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 GuidePopup from './components/GuidePopup.vue'
import { getUserInfo, bindPromoter } from '@/api/user'

const HOME_RECOMMEND_CACHE_KEY = 'home_recommend_cache'
const HOME_INIT_CACHE_KEY = 'home_init_cache'

export default {
	components: {
		zModal,
		HotProduct,
		//TuiProduct,
		SearchBar,
		CategoryTags,
		ChannelEntry,
		RecommendSection,
		GoodsNav,
		GoodsList,
		GuidePopup
	},
	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: {}, // 胶囊按钮布局信息
			tuiModalControl: false,
			activity: null,
			activityShow: false,
			hotProductList: [],
			menus: [],
			channelList: [],
			categoryTagsData: [],
			categoryTagsLoading: true,
			goodsNav: [],
			recommendData: { live: [], green: [], hot: [] },
			recommendLoading: true,
			activeGoodsNavId: 'all',
			goodsList: [],
			goodsLoading: false,
			goodsRefreshing: false,
			goodsHasMore: true,
			goodsPageNum: 1,
			goodsRequestId: 0,
			cartCount: 0,
			bannerList: [],
			bannerLoading: false,
			top: 0,
			statusBarHeight: (uni.getStorageSync('menuInfo') && uni.getStorageSync('menuInfo').statusBarHeight) || 20,
			userinfoa: [],
			isuser: false,
			imageUrl:[
				'https://bjzmky-1323137866.cos.ap-chongqing.myqcloud.com/class/page01.png',
				'https://bjzmky-1323137866.cos.ap-chongqing.myqcloud.com/class/page02.png'
			],
		}
	},
	computed: {
		bgColor() {
			const t = this.top / 30
			if(t>0){
				return '/static/images/bg.png'
			}else{
				return ''
			}
		},
		showBannerSkeleton() {
			return this.bannerLoading && !(this.bannerList && this.bannerList.length)
		},
		showBannerContent() {
			return !!(this.bannerList && this.bannerList.length)
		},
		showBannerBlock() {
			return this.showBannerSkeleton || this.showBannerContent
		},
		// 瀑布流标签：后端 categoryTags（不包含“全部”）
		goodsNavList() {
			const tags = (this.goodsNav || []).map(t => ({
				id: t.id,
				name: t.categoryName,
				categoryName: t.categoryName
			}))
			return tags
		}
	},
	onLoad(option) {
		this.loadRecommendCache()
		this.loadHomeInitCache()
		this.getMenuButtonInfo(); // 初始化获取胶囊信息
		if (option.userCode != null) {
			uni.setStorageSync('userCode', option.userCode)
			if (this.utils.checkLoginState()) this.getUserInfo()
		}
		if (option.hasOwnProperty('q') && option.q) {
			const url = decodeURIComponent(option.q)
			const obj = this.utils.urlToObj(url)
			uni.setStorageSync('userCode', obj.userCode)
			if (this.utils.checkLoginState()) this.getUserInfo()
		}
		this.loadBannerConfig()
	},
	onUnload() {
		uni.$emit('stop')
	},
	onHide() {
		uni.$emit('stop')
	},
	onPageScroll(e) {
		this.top = e.scrollTop
	},
	onShow() {
		this.getHomeInit()
    this.getHomeRecommend()
		this.getMenu()
		if (uni.getStorageSync('AppToken')) {
			this.getUserInfo()
			this.runGuideCheck()
		} else {
			this.isuser = true
		}
		if (this.utils.checkLoginState()) this.getCartCount()
		this.getStoreConfig()
	},
	onShareAppMessage() {
		return { title: '岚财良品-您的专属解决方案', path: '/pages/common/launch', imageUrl: 'https://bjzmky-1323137866.cos.ap-chongqing.myqcloud.com/app/vip/share.png' }
	},
	onShareTimeline() {
		return { title: '岚财良品-您的专属解决方案', query: '', imageUrl: 'https://bjzmky-1323137866.cos.ap-chongqing.myqcloud.com/app/vip/share.png' }
	},
	onReachBottom() {
		this.loadMoreGoods()
		//this.$refs.tuiProduct && this.$refs.tuiProduct.getTuiProducts()
	},
	methods: {
		runGuideCheck() {
			const run = () => {
				if (!this.$refs.guidePopup) return
				this.$refs.guidePopup.syncViewedState()
				this.$refs.guidePopup.check()
			}
			if (this.$refs.guidePopup) run()
			else this.$nextTick(run)
		},
		// 获取胶囊按钮布局参数
		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' // 胶囊右侧距离
				};
			}
		},
		loadHomeInitCache() {
			try {
				const raw = uni.getStorageSync(HOME_INIT_CACHE_KEY)
				if (!raw) return
				const data = typeof raw === 'string' ? JSON.parse(raw) : raw
				if (data.channelList && data.channelList.length) {
					this.channelList = data.channelList
				}
				if (data.categoryTags && data.categoryTags.length) {
					this.categoryTagsData = data.categoryTags
					this.categoryTagsLoading = false
				}
				if (data.goodsNav && data.goodsNav.length) {
					this.goodsNav = data.goodsNav
				}
			} catch (e) {}
		},
		saveHomeInitCache(data) {
			try {
				uni.setStorageSync(HOME_INIT_CACHE_KEY, JSON.stringify(data))
			} catch (e) {}
		},
		getHomeInit() {
			if (!this.categoryTagsData.length) this.categoryTagsLoading = true
			getHomeInit().then(res => {
				if (res.code == 200 && res.data) {
					this.channelList = res.data.channelList || []
					this.categoryTagsData = res.data.categoryTags || []
					this.goodsNav = res.data.goodsNav || []
					this.saveHomeInitCache({
						channelList: this.channelList,
						categoryTags: this.categoryTagsData,
						goodsNav: this.goodsNav
					})
					if (this.activeGoodsNavId === null || this.activeGoodsNavId === undefined) {
						this.activeGoodsNavId = 'all'
					}
					this.fetchGoodsList(true)
				}
			}).catch(() => {}).finally(() => {
				this.categoryTagsLoading = false
			})
		},
		loadRecommendCache() {
			try {
				const raw = uni.getStorageSync(HOME_RECOMMEND_CACHE_KEY)
				if (!raw) return
				const data = typeof raw === 'string' ? JSON.parse(raw) : raw
				const hasCache = (data.live && data.live.length) || (data.green && data.green.length) || (data.hot && data.hot.length)
				if (!hasCache) return
				this.recommendData = {
					live: data.live || [],
					green: data.green || [],
					hot: data.hot || []
				}
				this.recommendLoading = false
			} catch (e) {}
		},
		saveRecommendCache(data) {
			try {
				uni.setStorageSync(HOME_RECOMMEND_CACHE_KEY, JSON.stringify(data))
			} catch (e) {}
		},
		getHomeRecommend() {
			const cached = this.recommendData
			const hasCache = (cached.live && cached.live.length) || (cached.green && cached.green.length) || (cached.hot && cached.hot.length)
			if (!hasCache) this.recommendLoading = true
			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 : []
				}
				this.saveRecommendCache(this.recommendData)
			}).catch(() => {}).finally(() => {
				this.recommendLoading = false
			})
		},
		fetchGoodsList(reset) {
			if (reset) {
				this.goodsPageNum = 1
				this.goodsHasMore = true
				this.goodsRefreshing = true
			} else if (this.goodsLoading || !this.goodsHasMore) {
				return
			}
			const requestId = ++this.goodsRequestId
			this.goodsLoading = true
			const id = this.activeGoodsNavId === 'all' || this.activeGoodsNavId === '' ? 0 : this.activeGoodsNavId
			getHomeGoods({ id, position: 2, pageNum: this.goodsPageNum, pageSize: 10 }).then(res => {
				if (requestId !== this.goodsRequestId) return
				this.goodsLoading = false
				this.goodsRefreshing = 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 >= 10 && (this.goodsList.length < total || total === 0)
					this.goodsPageNum++
				}
			}).catch(() => {
				if (requestId !== this.goodsRequestId) return
				this.goodsLoading = false
				this.goodsRefreshing = false
			})
		},
		loadMoreGoods() {
			this.fetchGoodsList(false)
		},
		onGoodsNavSelect(item) {
			if (!item || item.id === this.activeGoodsNavId) return
			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/home/productList' })
				return
			}
			const id = item.id ?? item.cateId ?? item.categoryId
			if (id != null && id !== '') {
				uni.navigateTo({ url: '/pages/home/productList?id=' + id })
			} else {
				uni.navigateTo({ url: '/pages/home/productList' })
			}
		},
		onChannelClick(item) {
			// 推荐频道点击，可跳转或筛选，按需扩展
		},
		onRecommendMore(section) {
			if (section && section.moreUrl) {
				uni.navigateTo({ url: '/pages/home/recommendList' })
				return
			}
			if (section && (section.type === 'green' || section.type === 'hot')) {
				uni.navigateTo({ url: '/pages/home/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 || []
			})
		},
		getBannerImage(item) {
			const images = this.imageUrl || []
			if (item && item.dictLabel === '原乡行') return images[1] || ''
			return images[0] || ''
		},
		loadBannerConfig() {
			if (this.bannerList.length) return
			getHisStoreConfig({ name: 'moduleShow' }).then(res => {
				if (res.code != 200) return
				const selectId = res.courseChannels || []
				if (!res.moduleOneShow && !res.moduleTwoShow) {
					this.bannerLoading = false
					return
				}
				const tasks = []
				if (res.moduleOneShow && selectId[0]) tasks.push({ channel: selectId[0], slotKey: '0' })
				if (res.moduleTwoShow && selectId[1]) tasks.push({ channel: selectId[1], slotKey: '1' })
				tasks.sort((a, b) => {
					const aBack = a.channel.dictLabel === '原乡行' ? 1 : 0
					const bBack = b.channel.dictLabel === '原乡行' ? 1 : 0
					return aBack - bBack
				})
				this.bannerLoading = true
				const newList = []
				const loadNext = (i) => {
					if (i >= tasks.length) {
						this.bannerList = newList
						this.bannerLoading = false
						return
					}
					const task = tasks[i]
					listPublicCourse({
						pageNum: 1,
						pageSize: 1,
						yxxTag: task.channel.dictValue,
						recommendSlot: 2
					}).then(r => {
						newList.push({
							slotKey: task.slotKey,
							image: this.getBannerImage(task.channel),
							course: r.code == 200 && r.data && r.data.list ? r.data.list[0] : null
						})
						loadNext(i + 1)
					}).catch(() => {
						newList.push({
							slotKey: task.slotKey,
							image: this.getBannerImage(task.channel),
							course: null
						})
						loadNext(i + 1)
					})
				}
				loadNext(0)
			})
		},
		getUserInfo() {
			getUserInfo().then(res => {
				if (res.code == 200 && res.user != null) this.userinfoa = res.user
				else uni.showToast({ icon: 'none', title: '请求失败' })
			})
		},
		getCartCount() {
			this.utils.isLogin().then(res => {
				if (res) getCartCount().then(cartRes => {
					if (cartRes.code == 200) this.cartCount = cartRes.data
				})
			})
		},
		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) {
			// console.log('item',item)
			if (item && item.courseId) {
				uni.navigateTo({ url: '/pages_index/courseDetail?courseId=' + item.courseId})
				return;
			}
		},
		goAuthUrl(url) {
			this.utils.isLogin().then(res => {
				if (res) uni.switchTab({ url })
			})
		},
		navTo(url) {
			uni.navigateTo({ url })
		},
		toSearch() {
			//uni.navigateTo({ url: './productSearch' })
			uni.navigateTo({ url: '../home/productList' })
		},
		showProduct(item,type) {
			//console.log('item',type)
			//uni.navigateTo({ url: '../shopping/productDetails?productId=' + item.productId })
			uni.navigateTo({ url: '/pages/home/recommendList?type='+type})
		}
	}
}
</script>

<style lang="scss" scoped>
.content {
	width: 100%;
	position: relative;
	min-height: 100vh;
	padding-top: 1rpx;
}
.header-wrap {
	position: relative;
	z-index: 10;
}
.banner-row-wrap {
	position: relative;
}
.banner-row {
	position: relative;
	display: flex;
	align-items: flex-start;
	gap: 20rpx;
	padding: 0 20rpx 24rpx;
}
.banner-skeleton .banner-sk-item::after {
	content: '';
	display: block;
	width: 100%;
	padding-bottom: 63.8%;
}
.banner-sk-item {
	flex: 1;
	min-width: 0;
	border-radius: 16rpx;
	overflow: hidden;
	background: linear-gradient(90deg, #eee 25%, #f5f5f5 50%, #eee 75%);
	background-size: 200% 100%;
	animation: banner-shimmer 1.2s ease-in-out infinite;
}
@keyframes banner-shimmer {
	0% { background-position: 100% 0; }
	100% { background-position: -100% 0; }
}
.banner-item {
	flex: 1;
	min-width: 0;
	border-radius: 16rpx;
	overflow: hidden;
}
.banner-img {
	width: 100%;
	display: block;
}
.bg {
	width: 100%;
	height: 380rpx;
	position: absolute;
	top: 0;
	left: 0;
	z-index: -1;
}
.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>
