<template>
	<view class="xingma-lab-container">
		<!-- 第一层：顶部导航 -->
		<view class="top-navigation">
			<view class="nav-left">
				<image class="back-btn" :src="$baseUrl + `xingmaLab/1001/backBtn.png`" mode="aspectFit"
					@click="handleBack" />
			</view>
			<view class="nav-center">
				<text class="nav-title">星妈Lab</text>
			</view>
			<view class="nav-right"></view>
		</view>

		<!-- 第二层：内容区域 -->
		<view class="content-area">
			<!-- 藏馆内容 - 单列瀑布流 -->
			<scroll-view v-if="activeTab === 'cangguan'" scroll-y="true" class="cangguan-content"
				@scrolltolower="handleScroll_cangguan">
				<view class="banner_content">
					<image class="banner_img" :src="$baseUrl + `xingmaLab/1001/bannerImg0.png`" mode="aspectFill" />
				</view>
				
				<view v-for="(item, index) in cangguanList" :key="index" class="item_cangguan"
					@click="handleItemClick_cangguan(item, index)">
					<!-- <image class="item_cangguan_img" :src="`${item.imgUrl}`" mode="widthFix">
						<image class="item_cangguan_img_up" :src="`${item.imgUrl}`" mode="widthFix"></image>
					</image> -->
					<view class="item_cangguan_img1" 
					:style="`background-image: url(${item.imgUrl}); background-size: 707rpx auto; background-repeat: no-repeat;`"
					 mode="widthFix">
						<image class="item_cangguan_img" :src="`${item.imgUrl}`" mode="widthFix" @load="(e) => handleImageLoad(e, item, index)"></image>
						<image class="item_cangguan_img_up" :src="`${item.imgUrl}`" mode="aspectFill" :style="`width: ${item.targetWidth - 30}rpx; height: ${item.targetHeight - 126}rpx;`"></image>
					</view>
					
					<view class="item_cangguan_bottom">
						<view class="item_cangguan_bottom_bg">
						</view>
						<image class="item_logo" :src="$baseUrl + `xingmaLab/1001/item_logo_cangguan.png`"
							mode="aspectFill" />
						<view class="title_line"></view>
						<view class="nick_name_content">
							<text class="nick_name">No.{{ item.bizNo }}</text>
							<text class="user_num">By.{{ item.nickname }}</text>
						</view>
					</view>
					<view class="item_cangguan_text">
						<text class="item_desc">{{ item.content }}</text>
						<view class="nicheng_shoucang_zhaungtai">
							<view class="nicheng_shoucang_item">
								<image class="avatar_img" :src="`${item.avatar}`" mode="aspectFit" />
								<text class="nick_name_text">{{ item.nickname }}</text>
								<text class="shoucang_text">{{ item.collection ? '已收藏' : '未收藏' }}</text>
								<image class="shoucang_icon"
									:src="item.collection ? $baseUrl + `xingmaLab/1001/shoucang_on.png` : $baseUrl + `xingmaLab/1001/shoucang_off.png`"
									mode="aspectFit" />
							</view>
						</view>
					</view>
				</view>
			</scroll-view>

			<!-- 我的藏馆内容 - 双切页两列瀑布流 -->
			<view v-if="activeTab === 'wodecangguan'" class="wodecangguan-content">
				<!-- 切页tab -->
				<view class="sub-tab-container">
					<view class="sub-tab-item" :class="{ active: activeSubTab === 'collections' }"
						@click="switchSubTab('collections')">
						<text class="sub-tab-text">我的藏品</text>
						<view class="sub-tab-line"></view>
					</view>
					<view class="sub-tab-item" :class="{ active: activeSubTab === 'favorites' }"
						@click="switchSubTab('favorites')">
						<text class="sub-tab-text">我的收藏</text>
						<view class="sub-tab-line"></view>
					</view>
				</view>

				<!-- 我的藏品列表 - 使用与藏馆相同的数据 -->
				<view v-if="activeSubTab === 'collections'" class="wodecangpin-content">
					<view class="waterfall-list-noval" v-if="!(cangpinList && cangpinList.length > 0)">
						<view class="noval-content">
							<!-- 卡片插图 -->
							<view class="noval-illustration">
								<image class="noval-img" :src="$baseUrl + `xingmaLab/1001/cangpin_noval_img0.png`"
									mode="aspectFit" />
							</view>

							<!-- 提示文字 -->
							<text class="noval-tip">快去发布属于你的藏品吧!</text>

							<!-- 发布按钮 -->
							<view class="publish-btn" @click="handlePublish">
								<text class="publish-text">去发布</text>
							</view>
						</view>
					</view>
					<scroll-view class="waterfall-list1" scroll-y="true" @scrolltolower="handleScrollToLower_cangpin"
						v-if="cangpinList && cangpinList.length > 0">
						<grid-view column="2" main-axis-gap="{{10}}" cross-axis-gap="{{10}}"
							padding="{{ [0, 12, 0, 12] }}" type="masonry">
							<view v-for="(item, index) in cangpinList" :key="index" class="waterfall-item"
								@click="handleItemClick_cangpin(item, index)">
							<view class="item-up-content">
								
								<image class="item-image" :src="item.imgUrl" mode="widthFix" />
								<view class="item-num">
									<text class="badge-num">N0.{{ item.bizNo }}</text>
								</view>
									<view v-if="item.state == 1" class="item-badge">
									<text class="badge-text">精选推荐</text>
								</view>
							</view>
							<view class="item-info">
									<view class="item-title">{{ item.content }}</view>
								<view class="item-meta">
									<view class="creator-info">
											<image class="creator-avatar" :src="item.avatar" mode="aspectFit" />
										<text class="creator-name">{{ item.nickname }}</text>
										</view>
									</view>
								</view>
							</view>
						</grid-view>
					</scroll-view>
					
				</view>

				<!-- 我的收藏列表 -->
				<view v-if="activeSubTab === 'favorites'" class="sub-tab-content">
					<view class="waterfall-list-noval2" v-if="!(shoucangList && shoucangList.length > 0)">
						<view class="noval-content">
							<!-- 卡片插图 -->
							<view class="noval-illustration">
								<image class="noval-img" :src="$baseUrl + `xingmaLab/1001/cangpin_noval_img0.png`"
									mode="aspectFit" />
							</view>

							<!-- 提示文字 -->
							<text class="noval-tip">暂无收藏的藏品哦</text>
						</view>
					</view>
					<scroll-view class="waterfall-list1" scroll-y="true" @scrolltolower="handleScrollToLower_shoucang"
						v-if="shoucangList && shoucangList.length > 0">
						<grid-view column="2" main-axis-gap="{{10}}" cross-axis-gap="{{10}}"
							padding="{{ [0, 12, 0, 12] }}" type="masonry">
							<view v-for="(item, index) in shoucangList" :key="index" class="waterfall-item"
								@click="handleItemClick_shoucang(item, index)">
								<view class="item-up-content">

									<image class="item-image" :src="item.imgUrl" mode="widthFix" />
									<view class="item-num">
										<text class="badge-num">N0.{{ item.bizNo }}</text>
									</view>
									<view v-if="item.state == 1" class="item-badge">
										<text class="badge-text">精选推荐</text>
									</view>
								</view>
							<view class="item-info">
									<view class="item-title">{{ item.content }}</view>
								<view class="item-meta">
									<view class="creator-info">
											<image class="creator-avatar" :src="item.avatar" mode="aspectFit" />
											<text class="creator-name">{{ item.nickname }}</text>
										</view>
									</view>
								</view>
							</view>
						</grid-view>
					</scroll-view>
					</view>
			</view>
		</view>

		<!-- 底部导航 -->
		<view class="bottom-navigation">
			<view class="bottom-nav-item1" :class="{ active: activeTab === 'cangguan' }"
				@click="handleBottomNavClick('cangguan')">
				<image class="bottom-nav-icon1"
					:src="activeTab === 'cangguan' ? $baseUrl + `xingmaLab/1001/tab_cangguang_selected.png` : $baseUrl + `xingmaLab/1001/tab_cangguang_normal.png`"
					mode="aspectFit" />
			</view>
			<view class="bottom-nav-item2">
				<image class="publish-icon" :src="$baseUrl + `xingmaLab/1001/tab_fabu.png`" @click="handleBottomNavFabu"
					mode="aspectFit" />
			</view>
			<view class="bottom-nav-item3" :class="{ active: activeTab === 'wodecangguan' }"
				@click="handleBottomNavClick('wodecangguan')">
				<image class="bottom-nav-icon3"
					:src="activeTab === 'wodecangguan' ? $baseUrl + `xingmaLab/1001/tab_wodecangguan_selected.png` : $baseUrl + `xingmaLab/1001/tab_wodecangguan_normal.png`"
					mode="aspectFit" />
			</view>
		</view>

		<!-- 无次数弹窗 - 使用 Xingmalabnotimepop 组件 -->
		<Xingmalabnotimepop :visible="showNoTimePopup" title="发布次数已用完" @button-click="handleNoTimeButtonClick"
			@close="showNoTimePopup = false" />
    </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { fetchRecordList, fetchRecordMyrecords, fetchFavoriteList } from '../../api/xingmaLab'
import { onPageScroll, onShow } from "@dcloudio/uni-app";
import { showLoading, hideLoading, jump, JumpType } from '../../utils/index.js'
import { useXingmaLabStore } from '../../stores/xingmaLab'
import Xingmalabnotimepop from '../../components/xingmaLab/Xingmalabnotimepop.vue'
import md from '../../md';

// 定义组件名称
defineOptions({
	name: 'XingmaLab'
})

// 响应式数据
const activeTab = ref('cangguan')
const activeSubTab = ref('collections')
const cangguanList = ref([]);
const cangpinList = ref([]);
const shoucangList = ref([]);
const xingmaLabStore = useXingmaLabStore();

// 弹窗显示状态
const showNoTimePopup = ref(false) // 无次数弹窗

// 收藏列表分页管理
const shoucangListIdx = ref(1);
const shoucangTotalPage = ref(0);

// onPageScroll((e) => {
// 		console.log('e.scrollTop=',e);
// 		const newVal = e.scrollTop;
		
		
			

// });
const isGeting = ref(false);
const handleScroll_cangguan = async (e) => {

	console.log('cangguan_已到底部');
	if (cangguanListIdx.value > cangguanTotalPage.value - 1) return;

	if (isGeting.value) return;

	showLoading()
	isGeting.value = true;
	cangguanListIdx.value++;
	const data1 = await fetchRecordList(cangguanListIdx.value, 4);
	cangguanList.value = cangguanList.value.concat(data1.data.list);
	cangguanTotalPage.value = data1?.data?.totalPage;
	setTimeout(() => {
		isGeting.value = false;
	}, 500);
	hideLoading();
}

const handleScroll1 = (e) => {
	console.log('e.scrollTop=', e);
}

const handleScrollToLower_cangpin = async () => {
	console.log('已到底部');

	if (cangpinListIdx.value > cangpinTotalPage.value - 1) return;

	if (isGeting.value) return;

	showLoading();
	isGeting.value = true;
	cangpinListIdx.value++;

	const data2 = await fetchRecordMyrecords(cangpinListIdx.value, 1);
	cangpinList.value = cangpinList.value.concat(data2.data.list);
	cangpinTotalPage.value = data2?.data?.totalPage;
	setTimeout(() => {
		isGeting.value = false;
	}, 500);
	hideLoading();
}

const handleScrollToLower_shoucang = async () => {
	console.log('收藏列表已到底部');

	if (shoucangListIdx.value > shoucangTotalPage.value - 1) return;

	if (isGeting.value) return;

	showLoading();
	isGeting.value = true;
	shoucangListIdx.value++;

	const data3 = await fetchFavoriteList(shoucangListIdx.value, 1);
	shoucangList.value = shoucangList.value.concat(data3.data.list);
	shoucangTotalPage.value = data3?.data?.totalPage;
	setTimeout(() => {
		isGeting.value = false;
	}, 500);
	hideLoading();
}

const handleImageLoad = (e, item, index) => {
	// 获取图片的实际尺寸
	const { width, height } = e.detail;
	// 计算图片在360rpx宽度下的实际高度
	// 360rpx 转换为 px (假设 1rpx = 0.5px，根据实际设备调整)
	const targetWidth = 707;
	const rpxToPx = targetWidth / width;
	const targetHeight = height * rpxToPx;

	item.targetWidth = targetWidth;
	item.targetHeight = targetHeight;

	console.log(`图片 ${index} 加载完成，设置宽度为: ${item.targetWidth}px, 设置高度为:${item.targetHeight}px`);
}


const currentItem = ref(null);
onShow(async () => {

	md.sensorComponentLogTake({
        xcxComponentExposure: "true",
        pageName: "星妈lab首页",
        componentName: "底部切换组件",
        componentContent: "星妈会藏馆"
    });

	md.sensorComponentLogTake({
        xcxComponentExposure: "true",
        pageName: "星妈lab首页",
        componentName: "底部切换组件",
        componentContent: "发布"
    });

	md.sensorComponentLogTake({
        xcxComponentExposure: "true",
        pageName: "星妈lab首页",
        componentName: "底部切换组件",
        componentContent: "我的藏品"
    });

	md.sensorComponentLogTake({
        xcxComponentExposure: "true",
        pageName: "星妈lab首页",
        componentName: "星妈会藏馆",
        componentContent: "首页藏品"
    });
	
	const pages = getCurrentPages()
	let currentPage = pages[pages.length - 1]
	const isFavorite = currentPage?.properties?.isFavorite 

	console.log('isFavorite=', isFavorite);
	console.log('currentPage=', currentPage);
	// console.log('onshow')
	//1收藏，-1取消收藏，不存在刷新页面
	if(!isFavorite){
		await xingmaLabStore.loadXingmaInfo();

		await reloadCangguanList();
		await reloadCangpinList();
		await reloadShoucangList();
	}else{
		if(isFavorite == 1){
			currentItem.value.collection = true;
		}else{
			currentItem.value.collection = false;
		}
	}
	
})

const cangguanListIdx = ref(1);
const cangguanTotalPage = ref(0);
const cangpinListIdx = ref(1);
const cangpinTotalPage = ref(0);
onMounted(async () => {

	// await xingmaLabStore.loadXingmaInfo();
	// console.log('xingmaLabStore=', xingmaLabStore.xingmaInfo);
	
	// //获取藏馆列表
	// const data1 = await fetchRecordList(cangguanListIdx.value, 4);
	// cangguanList.value = cangguanList.value.concat(data1.data.list);
	// cangguanTotalPage.value = data1.data.totalPage;

	// //获取我的藏品列表
	// const data2 = await fetchRecordMyrecords(cangpinListIdx.value, 8);
	// cangpinList.value = cangpinList.value.concat(data2.data.list);
	// // debugger;
	// cangpinTotalPage.value = data2.data.totalPage;

	// // cangpinList.value = data.data.list;


	// //获取我的收藏列表
	// const data3 = await fetchFavoriteList(shoucangListIdx.value, 4);
	// shoucangList.value = shoucangList.value.concat(data3.data.list);
	// shoucangTotalPage.value = data3.data.totalPage;

	// shoucangList.value = data.data.list;


})

// 刷新数据：封装三个列表的刷新方法，供全局事件调用
const reloadCangguanList = async () => {
	showLoading()
	cangguanListIdx.value = 1;
	cangguanList.value = [];
	const data = await fetchRecordList(cangguanListIdx.value, 4);
	cangguanList.value = data.data.list;
	cangguanTotalPage.value = data.data.totalPage;
	hideLoading()
}

const reloadCangpinList = async () => {
	showLoading()
	cangpinListIdx.value = 1;
	cangpinList.value = [];
	const data = await fetchRecordMyrecords(cangpinListIdx.value, 8);
	cangpinList.value = data.data.list;
	cangpinTotalPage.value = data.data.totalPage;
	hideLoading()
}

const reloadShoucangList = async () => {
	showLoading()
	shoucangListIdx.value = 1;
	shoucangList.value = [];
	const data = await fetchFavoriteList(shoucangListIdx.value, 4);
	shoucangList.value = data.data.list;
	shoucangTotalPage.value = data.data.totalPage;
	hideLoading()
}

// 监听其他页面派发的全局事件
const handleGlobalRefresh = async (payload) => {
	console.log('收到全局刷新事件 xingmaLab:refresh，payload=', payload)
	// 可根据 payload.type 刷新指定列表，这里默认全部刷新
	await Promise.all([
		reloadCangguanList(),
		reloadCangpinList(),
		reloadShoucangList()
	])
}

// uni.$emit('xingmaLab:refresh', { type: 'all' }) // or type: 'cangpin' | 'shoucang' | 'cangguan'
onMounted(() => {
	uni.$on('xingmaLab:refresh', handleGlobalRefresh)
})

onUnmounted(() => {
	uni.$off('xingmaLab:refresh', handleGlobalRefresh)
})

const convertDobuleList = (list) => {
	let newList = [];
	newList.push([]);
	newList.push([]);
	for (let i = 0; i < list.length; i++) {
		if (i % 2 == 0) {
			newList[0].push(list[i]);
		} else {
			newList[1].push(list[i]);
		}
	}
	return newList;
}

// 方法
const handleBack = () => {
	uni.navigateBack({
		delta: 1
	})
}

const switchTab = (tab) => {
	activeTab.value = tab
	if (tab === 'wodecangguan') {
		activeSubTab.value = 'collections'
	}
}

const switchSubTab = async (subTab) => {
	if(subTab == 'collections'){
		if(currentFrontNavType != 'collections'){
			currentFrontNavType = 'collections'

			md.sensorComponentLogTake({
				xcxComponentClick: "true",
				pageName: "星妈lab首页",
				componentName: "我的藏品",
				componentContent: "我的藏品-我的藏品"
			});
			await reloadCangpinList();
		}

	}else if(subTab == 'favorites'){
		if(currentFrontNavType != 'favorites'){
			md.sensorComponentLogTake({
				xcxComponentClick: "true",
				pageName: "星妈lab首页",
				componentName: "我的藏品",
				componentContent: "我的藏品-我的收藏"
			});
			currentFrontNavType = 'favorites'
			await reloadShoucangList();
		}
	}
	activeSubTab.value = subTab
	// if(currentFrontNavType == 'collections'){
	// 	await reloadCangguanList();
	// }else{
	// 	await reloadShoucangList();
	// }
}

const handleBottomNavFabu = () => {

	md.sensorComponentLogTake({
		xcxComponentClick: "true",
		pageName: "星妈lab首页",
		componentName: "底部切换组件",
		componentContent: "发布"
	});

	console.log('showNoTimePopup 变量状态:', showNoTimePopup)
	console.log('xingmaLabStore.xingmaInfo:', xingmaLabStore.xingmaInfo)

	if (xingmaLabStore.xingmaInfo && xingmaLabStore.xingmaInfo.isReachedLimit) {
		console.log('已达到发布上线')
		// 显示无次数弹窗
		showNoTimePopup.value = true
		console.log('弹窗状态已设置为:', showNoTimePopup.value)

	} else {
		console.log('跳转发布页面')
		uni.navigateTo({
			url: '/pages/XingmaLabPublishPage/XingmaLabPublishPage'
		})
	}
}

let currentButtomNavType = 'cangguan';
let currentFrontNavType = '';
// 底部导航点击处理
const handleBottomNavClick = async (navType) => {



	if (navType == 'cangguan') {
		md.sensorComponentLogTake({
			xcxComponentClick: "true",
			pageName: "星妈lab首页",
			componentName: "底部切换组件",
			componentContent: "星妈会藏馆"
		});

		// 点击"星妈会藏馆"时，切换到藏馆tab，展示单列列表
		activeTab.value = 'cangguan'
		if(currentButtomNavType != 'cangguan'){
			md.sensorComponentLogTake({
				xcxComponentExposure: "true",
				pageName: "星妈lab首页",
				componentName: "星妈会藏馆",
				componentContent: "首页藏品"
			});
			currentButtomNavType = 'cangguan'
			await reloadCangguanList();
		}


	} else if (navType == 'wodecangguan') {
		md.sensorComponentLogTake({
			xcxComponentClick: "true",
			pageName: "星妈lab首页",
			componentName: "底部切换组件",
			componentContent: "我的藏品"
		});

		// 点击"我的藏品"时，切换到我的藏馆tab，默认展示我的藏品
		activeTab.value = 'wodecangguan'

		if(currentButtomNavType != 'wodecangguan'){
			currentButtomNavType = 'wodecangguan';
			if(currentFrontNavType == ''){

				if(!(cangpinList && cangpinList.length > 0)){
					md.sensorComponentLogTake({
						xcxComponentExposure: "true",
						pageName: "星妈lab-我的藏品页",
						componentName: "我的藏品",
						componentContent: "我的藏品-去发布"
					});
				}else{
					md.sensorComponentLogTake({
						xcxComponentExposure: "true",
						pageName: "星妈lab-我的藏品页",
						componentName: "我的藏品",
						componentContent: "我的藏品-我的藏品"
					});
				}

				activeSubTab.value = 'collections'
				currentFrontNavType = 'collections'
				await reloadCangpinList();
			}else{
				currentFrontNavType = activeSubTab.value;
				if(activeSubTab.value == 'collections'){
					if(!(cangpinList && cangpinList.length > 0)){

						md.sensorComponentLogTake({
							xcxComponentExposure: "true",
							pageName: "星妈lab-我的藏品页",
							componentName: "我的藏品",
							componentContent: "我的藏品-去发布"
						});
					}else{
						md.sensorComponentLogTake({
							xcxComponentExposure: "true",
							pageName: "星妈lab-我的藏品页",
							componentName: "我的藏品",
							componentContent: "我的藏品-我的藏品"
						});
					}
					await reloadCangpinList();
				}else{
					md.sensorComponentLogTake({
						xcxComponentExposure: "true",
						pageName: "星妈lab-我的藏品页",
						componentName: "我的藏品",
						componentContent: "我的藏品-我的收藏"
					});
					await reloadShoucangList();
				}
			}

		}
	}
}

const handleItemClick_cangguan = (item, index) => {
	console.log('点击了项目藏馆:', item)
	currentItem.value = item;
	md.sensorComponentLogTake({
        xcxComponentClick: "true",
        pageName: "星妈lab首页",
        componentName: "星妈会藏馆",
        componentContent: `首页藏品-藏品标题${item.content}`
    });

	// 这里可以添加跳转逻辑
	uni.navigateTo({
		url: '/pages/XingmaLabDetailPage/XingmaLabDetailPage?id=' + item.id + '&index=' + index
	})
}

const handleItemClick_cangpin = (item, index) => {
	console.log('点击了项目藏品:', item)
	// currentItem.value = item;
	// 这里可以添加跳转逻辑
	uni.navigateTo({
		url: '/pages/XingmaLabDetailPage/XingmaLabDetailPage?id=' + item.id + '&index=' + index
	})
}


const handleItemClick_shoucang = (item, index) => {
	console.log('点击了项目收藏:', item)
	// 这里可以添加跳转逻辑
	// currentItem.value = item;
	uni.navigateTo({
		url: '/pages/XingmaLabDetailPage/XingmaLabDetailPage?id=' + item.id + '&index=' + index
	})
}

const handlePublish = () => {
	console.log('点击了发布按钮')
	md.sensorComponentLogTake({
		xcxComponentClick: "true",
		pageName: "星妈lab-我的藏品页",
		componentName: "我的藏品",
		componentContent: "我的藏品-去发布"
	});
	// 这里可以添加发布逻辑或跳转
	if (xingmaLabStore.xingmaInfo && xingmaLabStore.xingmaInfo.isReachedLimit) {
		console.log('已达到发布上线')
		// 显示无次数弹窗
		showNoTimePopup.value = true
		console.log('弹窗状态已设置为:', showNoTimePopup.value)

	} else {
		console.log('跳转发布页面')
		uni.navigateTo({
			url: '/pages/XingmaLabPublishPage/XingmaLabPublishPage'
		})
	}

}

// 无次数弹窗按钮点击处理
const handleNoTimeButtonClick = () => {
	showNoTimePopup.value = false

	// // 显示更详细的发布次数信息
	// const { currentMonthPublishCount, maxPublishCount, remainingPublishCount } = xingmaLabStore.xingmaInfo
	// uni.showToast({
	// 	title: `本月已发布${currentMonthPublishCount}次，剩余${remainingPublishCount}次`,
	// 	icon: 'none',
	// 	duration: 3000
	// })
}
</script>

<style lang="less" scoped>
@import './xingmaLab.less';
</style>