<template>
	<view class="page">
		<!-- 用于计算主题色的隐藏Canvas -->
		<view style="position: absolute; top: -9999px; left: -9999px;">
			<canvas canvas-id="themeCanvas" id="themeCanvas" style="width: 100px; height: 100px;"></canvas>
		</view>
		<view class="topBody">
			<!-- <view class="header" :class="{ 'header-isvip': !isRecharge }"> -->
			<view class="header"
				:style="{ backgroundImage: `url(${bgImage || '../../static/me/theme3.jpg'})`, marginBottom: labelBoxHeight < 45 ? '-80rpx' : '-40rpx' }">
				<view class="header-box" :style="headerBoxStyle">
					<view class="reserveASeat"></view>
					<view class="benner-box">
						<view class="setUp-box">
							<view class="my-box">我的</view>
							<view class="settingBtn-box">
								<image @click="clickShare()" src="@/static/me/fenxiang.png" mode=""></image>
								<image src="@/static/me/shezhi.png" mode="" @click="navigateToSettings">
								</image>
							</view>
						</view>
						<view class="profilePicture-box">
							<CircleAvatar class="avator" @click="goPage('/pages/my/editInfo')" :src="myinfo.avator">
							</CircleAvatar>
							<view class="profilePicture-box-right" @click="goPage('/pages/my/creativeExpert')">
								<view class="one-omit">{{ myinfo.nickname }}</view>
								<image v-if="myinfo.my_level || myinfo.my_level == 0"
									:src="`../../static/icon/level_${myinfo.my_level}.png`" mode="widthFix"
									class="level-icon" />
							</view>
						</view>

						<view class="intro_row" @click="goPage('/pages/my/editInfo')">
							<block v-if="myinfo.content == ''">
								<text class="intro_text two-omit">添加简介</text>
								<image src="@/static/me/xiugai.png" mode="widthFix" class="add_icon">
								</image>
							</block>
							<uv-text color="#fff" v-else :text="formatText(myinfo.content)" class="intro_text two-omit">
							</uv-text>
						</view>


						<view class="label-box" id="labelBox" @click="goPage('/pages/my/editInfo')">
							<view class="label-item sex-item">

								<image src="../../static/icon/wd_icon_nv.png" mode="widthFix" v-if="myinfo.sex_id == 2">
								</image>
								<image src="../../static/icon/wd_icon_nan.png" mode="widthFix" v-else></image>
							</view>
							<view class="label-item" v-for="(item, index) in aihao_tags" :key="index + item">
								{{ item }}
							</view>
						</view>

						<view class="follow_info" @click="navigateToFollow">
							<view class="follow-box">
								<view class="num">{{ scientificCounting(myinfo.num_attention) }}</view>
								<view class="label">关注</view>
							</view>
							<!-- <view class="separator"></view> -->
							<view class="follow-box">
								<view class="num">{{ scientificCounting(myinfo.num_fans) }}</view>
								<view class="label">粉丝</view>
							</view>
							<!-- <view class="separator"></view> -->
							<view class="follow-box">
								<view class="num">{{ scientificCounting(myinfo.num_like) }}</view>
								<view class="label">获赞</view>
							</view>
						</view>
						<view class="bom-box">
							<view class="bom-item bom-item1 scale-tap" @click="goPage('/pages/my/wallet')">
								<view class="bom-item-title">钱包</view>
								<view class="bom-item-subtitle">查看我的钱包</view>
							</view>
							<view class="bom-item bom-item2 scale-tap">
								<view class="bom-item-title" @click="initiateFundraising()">发起募集</view>
								<view class="bom-item-subtitle">查看我的众筹</view>
							</view>
							<view class="bom-item bom-item3 scale-tap" @click="goPage('/pages/crowdFunding/orderList')">
								<view class="bom-item-title">订单</view>
								<view class="bom-item-subtitle">查看我的订单</view>
							</view>

						</view>
					</view>

					<view class="card-box" v-if="false">
						<view class="card-top">
							<view class="top-box">
								1
							</view>
							<view class="userinfo-box" @click="goPage('/pages/my/editInfo')">
								<view class="userinfo-left">
									<CircleAvatar class="avator" :src="myinfo.avator"></CircleAvatar>
								</view>
								<view class="userinfo-right">
									<view class="nickname">
										<text class="one-omit">{{ myinfo.nickname }}</text>

										<view class="level">Lv{{ myinfo.my_level }}</view>
									</view>
									<view class="label">

									</view>
								</view>
							</view>

							<view class="line"></view>
							<view class="bom">

								<view class="points-box">
									<view class="points" @click="isRecharge ? goPage('/pages/vip/M_purchase') : ''">
										<image src="@/static/icon/wd_icon_coin.png" mode=""></image>
										<text>{{ myinfo.num_gmm | formatNumberToK }}</text>
										<image class="money-add" v-if="isRecharge" src="/static/icon/coin_add.png"
											mode="aspectFit"></image>
									</view>
									<view class="points"
										@click="isRecharge ? goPage('/pages/my/job?type=recharge') : ''">
										<image src="@/static/icon/coin_cd.png" mode=""></image>
										<text>{{ myinfo.num_gmd | formatNumberToK }}</text>
										<image class="money-add" v-if="isRecharge" src="/static/icon/coin_add.png"
											mode="aspectFit"></image>
									</view>
								</view>
							</view>
						</view>
						<!-- <view class="card-bom" v-if="isRecharge" @click="goPage('/pages/vip/index')"> -->

					</view>
				</view>
			</view>

			<view class="myinfo">
				<view class="vip-box" @click="isRecharge ? goPage('/pages/vip/index') : ''">
					<view class="content-box">
						<image v-if="false" src="@/static/me/icon-vip2.png" mode=""></image>
						<image v-else-if="0" src="@/static/me/icon-vip1.png" mode=""></image>
						<image v-else src="@/static/me/icon-vip0.png" mode=""></image>
						<text v-if="myinfo.is_vip == 0">开启专属会员权益</text>
						<text v-else style="font-size: 28rpx;">会员权益生效中 <text
								style="font-size: 24rpx; color: rgba(172 ,249 ,52, .5);"> ({{ myinfo.vip_date }})
							</text>
						</text>
					</view>
					<!-- <view class=""> -->

					<!-- <image v-if="isRecharge" src="@/static/me/wd_icon_jiantou.png" mode="aspectFit"></image> -->
					<view class="vip-btn">
						会员中心
					</view>
					<!-- </view> -->
				</view>
				<!-- <view class="line"></view> -->
				<view class="tablist">
					<view class="item" :class="{ active: firstLevelNavActive === 0 }"
						@click="firstLevelNavActiveSwitch(0)">我的作品
						<view class="indicator-triangle"> </view>
					</view>
					<view class="item" :class="{ active: firstLevelNavActive === 1 }"
						@click="firstLevelNavActiveSwitch(1)">我的帖子
						<view class="indicator-triangle"> </view>
					</view>
				</view>
				<!-- 作品列表 -->
				<template v-if="firstLevelNavActive == 0">
					<view class="line"></view>
					<view class="subtitle">
						<view class="item" :class="{ active: activeTab === 0 }" @click="switchTab(0)">
							作品
						</view>
						<view class="item" :class="{ active: activeTab === 1 }" @click="switchTab(1)">
							生成中
						</view>
					</view>
					<view class="numlist1" v-if="activeTab === 0" style="margin-top: 15rpx">
						<WorkItem v-for="(item, index) in worksList" :secrecy="true" :subtitle="true" :key="index"
							:item="item" @click="goWork(item)" />
						<!-- 修改空状态显示条件 -->
						<view v-if="isDataLoaded && worksList.length === 0" class="empty-state">
							<image src="@/static/icon/xx_img_zanwuxiaoxi.png" mode="aspectFit" class="empty-image">
							</image>
							<text class="empty-text">暂无作品</text>
							<text class="empty-subtext">快来创作你的第一个作品吧~</text>
						</view>
					</view>
					<view class="numlist2" v-if="activeTab === 1" style="margin-top: 15rpx">
						<view class="item" v-for="(item, index) in worksList" :key="index"
							style="margin-bottom: 28rpx;">
							<view class="num" @click="goWork(item)"
								:class="{ 'clickable': item.status !== 3 && item.status !== 4 }">
								<WorkItem :item="item" style="margin-bottom: 12rpx" />

								<image class="incomplete-bg" v-if="item.status != 9"
									src="@/static/me/wd_bg_zhizuozhong.png"></image>
								<view class="maskLayer"></view>
								<!-- 当activeTab为1时显示队列状态 -->
								<view class="queue-status">
									<!-- 排队中 -->
									<view v-if="item.status === 1" class="status-text">
										<image class="state-img" src="@/static/me/wd_icon_paiduizhong.png"></image>
									</view>
									<!-- 生成失败 -->
									<view v-if="item.status === 3 || item.status === 4" class="status-text">
										<image class="state-img" src="@/static/me/wd_icon_zhizuoshibai.png"></image>
									</view>
									<!-- 制作中 -->
									<view v-else-if="item.status < 9" class="status-text">
										<image class="state-img" src="@/static/me/wd_icon_zhizuozhong.png"></image>
									</view>
									<!-- 创作完成 -->
									<view v-else-if="item.status === 9" class="status-text">
										<image class="state-img" src="@/static/me/wd_icon_chuangzuowancheng.png">
										</image>
									</view>
								</view>
								<view class="name one-omit" style="
                    font-family: 'PingFang SC-Medium';
                    font-weight: 500;
                    font-size: 28rpx;
                    color: #1a4d2e;
					max-width: 40vw;
                  ">
									{{ item.title || item.description || "作品" + index }}
								</view>

								<!-- 显示任务类型标签 -->
								<view class="task-type-tag" style="position: absolute; left: 14rpx;top: 14rpx;">
									<image style="width: 120rpx; height: 36rpx" v-if="item.task_type === 1"
										src="@/static/me/wd_icon_lingganchuangzuo.png"></image>
									<image style="width: 82rpx; height: 36rpx" v-else-if="item.task_type === 2"
										src="@/static/me/wd_icon_yinyue.png"></image>
									<!-- <text v-if="item.task_type === 1">灵感创作</text>
                  <text v-else-if="item.task_type === 2">音乐</text> -->
								</view>
							</view>
						</view>
						<!-- 修改空状态显示条件 -->
						<view v-if="isDataLoaded && worksList.length === 0" class="empty-state">
							<image src="@/static/icon/xx_img_zanwuxiaoxi.png" mode="aspectFit" class="empty-image">
							</image>
							<text class="empty-text">暂无生成中的作品</text>
							<text class="empty-subtext">快去创作新作品吧~</text>
						</view>
					</view>
				</template>
				<template v-else>
					<view class="numlist2" style="margin-top: 30rpx">
						<view class="item" v-for="(item, index) in worksList" :key="index" style="margin-bottom: 15rpx">
							<view class="num" @click="goWork2(item)"
								:class="{ 'clickable': item.status !== 3 && item.status !== 4 }">
								<WorkItem :item="item" style="margin-bottom: 20rpx" />

								<view class="incomplete-bg" style="background: #f8f9fa"></view>
								<image class="incomplete-bg" v-if="item.status != 1"
									src="@/static/me/wd_bg_zhizuozhong.png"></image>
								<image class="incomplete-bg2" v-else-if="item.status == 1" :src="item.image"
									mode="aspectFill" style="max-height: 520rpx;"></image>

								<view class="maskLayer" v-if="item.status != 1"></view>
								<!-- 当activeTab为1时显示队列状态 -->
								<view class="queue-status">
									<!-- 已发布 -->
									<view v-if="item.status == 1" class="status-text">
									</view>
									<!-- 待审核 -->
									<view v-if="item.status == 2 || item.status === 4" class="status-text">
										<image class="state-img" src="@/static/me/wd_icon_shenhezhong.png"></image>
									</view>
									<!-- 审核失败 -->
									<view v-else-if="item.status == 3" class="status-text">
										<image class="state-img" src="@/static/me/wd_icon_fabushibai.png"></image>
									</view>
								</view>
								<view class="name one-omit" style="
                    font-family: 'PingFang SC-Medium';
                    font-weight: 500;
                    font-size: 28rpx;
                    color: #1a4d2e;
					max-width: 40vw;
                  ">
									{{ item.title || item.description || "作品" + index }}
								</view>
							</view>
						</view>
						<!-- 修改空状态显示条件 -->
						<view v-if="isDataLoaded && worksList.length === 0" class="empty-state">
							<image src="@/static/icon/xx_img_zanwuxiaoxi.png" mode="aspectFit" class="empty-image">
							</image>
							<text class="empty-text">暂无帖子</text>
							<text class="empty-subtext">快来发布你的第一个帖子吧~</text>
						</view>
					</view>
				</template>
				<!-- 加载更多提示 -->
				<!-- <view class="loading-more" v-if="isLoading">加载中...</view>
				<view class="no-more" v-if="!hasMore && worksList.length > 0">没有更多作品了</view>
				<view class="no-more" v-if="!hasMore && worksList.length === 0">暂无作品</view> -->
			</view>

			<view class="blankHeight"></view>
		</view>
		<view class="reserveASeatBom"></view>
		<!-- 确认框 -->
		<CustomConfirm ref="customConfirm"></CustomConfirm>
		<!-- 提示框 -->
		<DialogBox ref="DialogBox"></DialogBox>
		<tabbar-view :tabbars="tabbars" :currentIndex="4" ref="tabbar"></tabbar-view>
		<!-- SharePopup组件 -->
		<SharePopup :visible="showShare" :userId="userId" :share-title="shareTitle" :share-desc="shareDesc"
			:share-img="shareImg" view="makeDetail" @close="showShare = false" />
		<DialogBox ref="DialogBox"></DialogBox>
	</view>
</template>

<script>
	import tabbarView from "@/components/tabbar/tabbar.vue";
	import tabbar from "@/mixins/tabbar";
	import CustomConfirm from "@/components/custome-confirm/customeConfirm.vue";
	import CircleAvatar from "@/components/CircleAvatar/CircleAvatar.vue";
	import meCard from "@/components/meCard/meCard.vue";
	import WorkItem from "@/components/WorkItem/WorkItem.vue";
	import {
		mapState
	} from 'vuex'
	import {
		scientificCounting
	} from "@/common/util.js";
	import {
		RgbQuant
	} from '@/common/RgbQuant.js';
	export default {
		components: {
			tabbarView,
			CustomConfirm,
			CircleAvatar,
			meCard,
			WorkItem,
		},
		mixins: [tabbar],
		data() {
			return {
				bgImage: '',
				title: "",
				sel: 1,
				firstLevelNavActive: 0,
				labelBoxHeight: 0,
				myinfo: {
					avator: "../../static/logo.png",
					nickname: "",
					join_name: "",
					num_1: 0,
					num_2: 0,
					num_3: 0,
					num_4: 0,
					is_login: "no",
					num_history: 0,
					num_collection: 0,
				},
				aihao_tags: [],
				menu_list: [],
				data_list: [],
				activeTab: 0,
				offset: 0,
				hasMore: true,
				isLoading: false,
				isDataLoaded: false,
				worksList: [],
				showShare: false,
				shareTitle: "",
				shareDesc: "",
				shareImg: "",
				userId: 0,
				headerBoxStyle: {
					background: 'linear-gradient(360deg, #16210E 0%, rgba(55,73,36,0) 100%)'
				},
			};
		},
		onLoad(e) {
			// setTimeout(function() {
			// 	uni.setNavigationBarColor({
			// 		frontColor: '#ffffff',
			// 		backgroundColor: '#00000000',
			// 		animation: {
			// 			duration: 400,
			// 			timingFunc: 'easeIn'
			// 		}
			// 	})
			// }, 200); 
			uni.$on('switchToMyPage', (data) => {
				if (data.type === 'article') {
					this.firstLevelNavActiveSwitch(1);
				} else if (data.type === 'generatingInProgress') {
					this.firstLevelNavActiveSwitch(0)
					this.switchTab(1);
				} else {
					this.firstLevelNavActiveSwitch(0)
					this.switchTab(0);
				}
			});
		},
		onUnload() {
			// 移除事件监听
			uni.$off('switchToMyPage');
		},
		computed: {
			...mapState('switchingModule', ['isRecharge'])
		},
		onShow() {
			uni.$emit("check_login", () => {});
			this.offset = 0;
			this.hasMore = true;
			this.worksList = [];
			this.loadInfo();

			// 使用nextTick确保DOM已更新
			this.$nextTick(() => {
				this.getLabelBoxHeight();
			});

			// 检查全局变量，如果需要切换到生成中标签
			if (getApp().globalData.needSwitchToGenerating) {
				setTimeout(() => {
					this.switchTab(1);
					// 重置全局变量
					getApp().globalData.needSwitchToGenerating = false;
				}, 300);
			} else {
				this.loadWorksList();
			}
		},
		onReachBottom() {
			if (this.hasMore && !this.isLoading) {
				this.loadMoreWorks();
			}
		},
		methods: {
			clickShare(item) {
				this.showShare = true;
			},
			async showConfirm() {
				let that = this;
				this.$refs["customConfirm"]
					.confirm({
						title: "确认解绑",
						content: "解绑微信账号后将无法继续使用它登录该App账号？",
						DialogType: "inquiry",
						btn1: "再考虑一下",
						btn2: "确认解绑",
						animation: 0,
					})
					.then((res) => {});
			},
			onBack() {},
			chkSel() {
				if (this.sel == 1) {
					this.sel = 0;
				} else {
					this.sel = 1;
				}
			},
			goPage(page) {
				console.log(999);

				uni.navigateTo({
					url: page,
				});

			},
			initiateFundraising() {
				if (this.myinfo.my_level < 3) {
					this.$refs["DialogBox"]
						.confirm({
							title: "提示",
							content: "您当前的等级为" + this.myinfo.my_level + "级，需要达到3级才能发起募集",
							DialogType: "inquiry",
							btn1: "取消",
							btn2: "去查看等级",
							animation: 0,
						})
						.then((res) => {
							this.goPage('/pages/my/creativeExpert')

						}, (res) => {});
					return;
				}
				this.goPage('/pages/my/initiateCrowdfunding')
			},
			async calculateThemeColor(imageUrl) {
				if (!imageUrl) {
					// 如果没有图片，则使用默认样式
					this.headerBoxStyle = {
						background: 'linear-gradient(to bottom, rgba(0, 0, 0, 0.5), transparent)'
					};
					return;
				}
				console.log('开始计算主题色, imageUrl:', imageUrl);
				const canvasId = 'themeCanvas';
				const ctx = uni.createCanvasContext(canvasId, this);

				uni.getImageInfo({
					src: imageUrl,
					success: (imageInfo) => {
						console.log('图片信息获取成功:', imageInfo);
						const canvasWidth = 100; // 缩小图片以加快处理速度
						const canvasHeight = Math.floor(canvasWidth * (imageInfo.height / imageInfo
							.width));

						// 绘制图片到canvas
						ctx.drawImage(imageInfo.path, 0, 0, canvasWidth, canvasHeight);
						ctx.draw(false, () => {
							console.log('Canvas 绘制完成');
							// 获取像素数据
							uni.canvasGetImageData({
								canvasId: canvasId,
								x: 0,
								y: 0,
								width: canvasWidth,
								height: canvasHeight,
								success: (res) => {
									console.log('像素数据获取成功');
									const pixels = res.data;

									// 使用 RgbQuant 提取主要颜色
									const quant = new RgbQuant({
										colors: 16, // 提取16种主要颜色
										method: 2, // 使用 WuQuant 算法
									});
									quant.sample(pixels);
									const palette = quant.quantize();

									if (quant.vboxes && quant.vboxes.length > 0) {
										let dominantColor = null;
										let maxPopulation = 0;

										// 找到像素数最多的颜色区域
										quant.vboxes.forEach(vbox => {
											const population = vbox.size(quant
												.histogram);
											if (population > maxPopulation) {
												maxPopulation = population;
												dominantColor = vbox.color(
													quant.histogram);
											}
										});

										if (dominantColor) {
											const [r, g, b] = dominantColor.map(
												value => Math.min(255, Math.max(0,
													value)));
											const themeColor =
												`rgba(${r}, ${g}, ${b}, 0.5)`;
											console.log('计算出的主题色 (Dominant):',
												themeColor);

											// 更新 header-box 的背景样式
											this.headerBoxStyle = {
												background: `linear-gradient(to bottom, ${themeColor}, transparent)`
											};
										}
									}
								},
								fail: (err) => {
									console.error('获取像素数据失败:', err);
								}
							});
						});
					},
					fail: (err) => {
						console.error('获取图片信息失败:', err);
					}
				});
			},
			async loadInfo() {
				console.log({
					uuid: getApp().globalData.uuid,
					skey: getApp().globalData.skey,
				});
				uni.request({
					url: this.$apiHost + "/User/getinfo",
					data: {
						uuid: getApp().globalData.uuid,
						skey: getApp().globalData.skey,
					},
					header: {
						"content-type": "application/json",
						sign: getApp().globalData.headerSign,
					},
					success: (res) => {
						console.log("----:", JSON.parse(JSON.stringify(res.data)));
						if (res.data) {

							this.shareTitle = res.data.nickname
							this.shareDesc = res.data.content
							this.shareImg = res.data.avator
							this.userId = res.data.user_id
						}
						if (res.data.need_login == "yes") {
							// getApp().globalData.skey = "";
							// getApp().globalData.uuid = "";

							uni.removeStorageSync("wapptoken");
							uni.redirectTo({
								url: "/pages/login/login",
							});
							return;
						}
						if (res.data.aihao) {
							this.aihao_tags = res.data.aihao.split(",");
						}
						this.myinfo = res.data;
						getApp().globalData.user_id = res.data.user_id;
						// this.bgImage = res.data.bgimg;
						// 在获取到背景图片后，计算主题色
						// this.calculateThemeColor(this.bgImage);
					},
					complete: (com) => {
						// uni.hideLoading();
					},
					fail: (e) => {
						console.log("----e:", e);
					},
				});

				uni.request({
					url: this.$apiHost + "/Member/getinfoData",
					data: {
						uuid: getApp().globalData.uuid,
						skey: getApp().globalData.skey,
					},
					header: {
						"content-type": "application/json",
						sign: getApp().globalData.headerSign,
					},
					success: async (res) => {
						console.log("----:", JSON.parse(JSON.stringify(res.data)));
						if (res.data) {
							this.bgImage = res.data.bgimg;
							if (this.bgImage) {
								// 计算主题色并更新蒙版背景
								// const gradient = await this.calculateThemeColor(this.bgImage);
								const gradient =
									`linear-gradient(to bottom,transparent, rgba(0, 0, 0, .8))`;
								this.headerBoxStyle = {
									background: gradient
								};
							}
						}
					},
					complete: (com) => {
						// uni.hideLoading();
					},
					fail: (e) => {
						console.log("----e:", e);
					},
				});
			},
			onLogout() {
				let that = this;
				this.$refs["DialogBox"]
					.confirm({
						title: "提示",
						content: "确定退出吗？",
						DialogType: "inquiry",
						btn1: "取消",
						btn2: "退出",
						animation: 0,
					})
					.then((res) => {
						uni.request({
							url: that.$apiHost + "/My/logout",
							data: {
								uuid: getApp().globalData.uuid,
								skey: getApp().globalData.skey,
							},
							header: {
								"content-type": "application/json",
								sign: getApp().globalData.headerSign,
							},
							success: (res) => {
								console.log("----:", res.data);
								// getApp().globalData.skey = "";
								// getApp().globalData.uuid = "";
								uni.removeStorageSync("wapptoken");
								uni.redirectTo({
									url: "/pages/login/login",
								});
							},
							complete: (com) => {
								// uni.hideLoading();
							},
							fail: (e) => {
								console.log("----e:", e);
							},
						});
					});
			},
			switchTab(index) {
				this.activeTab = index;
				this.offset = 0;
				this.hasMore = true;
				this.worksList = [];
				this.loadWorksList();
			},
			loadWorksList() {
				if (this.isLoading) return;
				this.isLoading = true;
				this.isDataLoaded = false;

				// 根据activeTab选择不同的API
				let apiUrl = "";
				if (this.firstLevelNavActive == 0) {
					if (this.activeTab === 0) {
						apiUrl = "/Work/getlist";
					} else {
						apiUrl = "/WorkAI/getMyQueueList";
					}
				} else if (this.firstLevelNavActive == 1) {
					apiUrl = "/Article/getlist";
				}
				uni.request({
					url: this.$apiHost + apiUrl,
					data: {
						uuid: getApp().globalData.uuid,
						skey: getApp().globalData.skey,
						type: "my",
						offset: this.offset,
						status: this.activeTab === 0 ? 1 : undefined,
					},
					header: {
						"content-type": "application/json",
						sign: getApp().globalData.headerSign,
					},
					success: (res) => {
						console.log("列表数据:", JSON.parse(JSON.stringify(res.data)));
						if (res.data.success == "yes" && res.data.list) {
							if (res.data.list.length > 0) {
								this.worksList = [...this.worksList, ...res.data.list];
								this.offset += res.data.list.length;
							}

							if (res.data.list.length < 20) {
								this.hasMore = false;
							}
						} else {
							this.hasMore = false;
							this.worksList = [];
						}

						if (this.activeTab === 0) {
							this.updateDataList();
						}
						console.log("作品列表数据:", this.worksList);
					},
					complete: () => {
						this.isLoading = false;
						this.isDataLoaded = true;
					},
					fail: (e) => {
						console.log("请求列表失败:", e);
						this.isLoading = false;
						this.isDataLoaded = true;
						this.worksList = [];
					},
				});
			},
			firstLevelNavActiveSwitch(n) {
				this.firstLevelNavActive = n;
				this.offset = 0;
				this.hasMore = true;
				this.worksList = [];
				if (this.firstLevelNavActive == 0) {
					this.activeTab = 0;
				}
				this.loadWorksList();
			},

			loadMoreWorks() {
				if (this.hasMore && !this.isLoading) {
					this.loadWorksList();
				}
			},
			updateDataList() {
				this.data_list = this.worksList.map((item) => {
					return {
						url: item.images || item.img_url || item.url || "../../static/logo.png",
						title: item.title || item.description || "作品",
						id: item.id,
					};
				});
			},
			goWork(item) {
				uni.$emit("check_login", () => {});
				// , //任务状态(1:排队中,3:生成失败,4:生成失败,9:创作完成)
				if (this.activeTab == 0) {
					uni.navigateTo({
						// url: "/pages/index/workDetail?id=" + item.id,
						url: "/pages/makedetail/makeDetail?id=" +
							item.queue_id +
							"&queueId=" +
							item.id,
					});
				} else {
					if (item.status >= 9) {
						uni.navigateTo({
							url: "/pages/makedetail/makeDetail?id=" + item.id,
						});
					}
					if (item.status < 9 && item.status != 3 && item.status != 4) {
						// <!-- <text v-if="item.task_type === 1">灵感创作</text>
						// <text v-else-if="item.task_type === 2">音乐</text> -->
						var url = "";
						if (item.task_type === 1) {
							url = "/makedetail/makeImgDetail";
						}
						if (item.task_type === 2) {
							url = "/makedetail/makeMusicDetail";
						}
						if (url) {
							uni.navigateTo({
								url: "/pages" + url + "?id=" + item.id,
							});
						}
					}
				}
			},
			goWork2(item) {
				uni.navigateTo({
					// url: "/pages/index/workDetail?id=" + item.id,
					url: "/pages/index/articleDetail?id=" + item.id,
				});
			},
			navigateToSettings() {
				uni.$emit("check_login", () => {
					uni.navigateTo({
						url: "/pages/my/setting",
					});
				});
			},
			navigateToFollow() {
				uni.navigateTo({
					url: "/pages/my/follow",
				});
			},
			formatText(text) {
				if (!text) return '';
				return text.length > 20 ? text.substring(0, 20) + '...' : text;
			},
			scientificCounting(num) {
				if (!num) {
					return 0;
				}
				if (num < 1000) {
					return num;
				} else if (num < 1000000) {
					return (num / 1000).toFixed(1) + 'k';
				} else if (num < 1000000000) {
					return (num / 1000000).toFixed(1) + 'M';
				} else {
					return (num / 1000000000).toFixed(1) + 'B';
				}
			},
			// 获取label-box高度的方法
			getLabelBoxHeight() {
				setTimeout(() => {
					const query = uni.createSelectorQuery();
					query.select('#labelBox').boundingClientRect(data => {
						if (data) {
							this.labelBoxHeight = data.height;
							console.log('label-box高度:', this.labelBoxHeight);
						}
					}).exec();
				}, 100);
			},
		},
	};
</script>

<style scoped lang="scss">
	@import "my.scss";

	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 60rpx 0;
		margin-top: 40rpx;
		background: #FFFFFF;
		border-radius: 20rpx;
		width: 710rpx;

		.empty-image {
			width: 240rpx;
			height: 240rpx;
			margin-bottom: 30rpx;
		}

		.empty-text {
			font-size: 32rpx;
			color: #333333;
			margin-bottom: 16rpx;
			font-weight: 500;
		}

		.empty-subtext {
			font-size: 28rpx;
			color: #999999;
		}
	}
</style>