<template>
	<view class="wanlgroups-user-container">
		<image class="pagebg" :src="pagebgImage" mode="widthFix">
		</image>
		<view class="wanlgroups-user-container__head" :style="{ height: headHeight + 'px' }">
			<view class="background" v-if="headerOpacity > 0" :style="{
					height: headHeight + 'px',
					opacity: headerOpacity,
					backgroundColor: '#9efeff'
				}">
				<view class="bgcolor"></view>
			</view>
			<view class="navigater text-black" :style="{
					height: headHeight + 'px',
					paddingTop: headTop + 'px'
				}">
				<view class="text-xl">
					<view v-if="fromUserPage" class="margin-right">
						<text class="wlIcon-fanhui1 text-bold" @tap="handleBack"></text>
					</view>
					<view class="text-cut" style="width: 100rpx;">
						<text class="text-lg" v-if="headerOpacity > 0" :style="{ opacity: headerOpacity }">
							{{ userData.user.nickname }}
						</text>
					</view>
				</view>
				<view class="text-xl">
					<text v-if="headerOpacity > 0 && $store.state.user.isLogin && !isMyfind && userData.isFollow === 0"
						:style="{ opacity: headerOpacity }" class="margin-right text-sm"
						@tap="handleFollow(userData.shop)">
						+ {{$t('user.follow')}}
					</text>
					<!-- 隐藏分享 -->
					<!-- <text class="wlIcon-fenxiangcopy margin-right-xl text-bold" @tap="showModal('share')" /> -->
					<!-- <text class="wlIcon-gengduo text-bold" @tap="showModal('menu')" /> -->
					<text class="wlIcon-gengduo text-bold" @tap="$appKit.auth('/pages/user/setting/setting')" />
				</view>
			</view>
		</view>
		<!-- 主体 -->
		<view class="wanlgroups-user-container__main">
			<view class="head  text-black" :style="{ paddingTop: headHeight + 'px' }" @click="handleTheme">
				<!-- 未登录状态 -->
				<block v-if="!$store.state.user.isLogin">
					<view class="userinfo" @click.stop="$appKit.to('/pages/user/auth/newpreLogin')">
						<view class="cu-avatar margin-right-bj round" :style="{
								backgroundImage: `url(${$appKit.oss('', 88, 88)})`
							}" />
						<view class="flex-sub">
							<view class="mz">{{ $t('user.loginRegister') }}</view>
							<!-- <view class="txt mt-1">
								{{ $t('user.welcomeLogin') }}
							</view> -->
						</view>
					</view>
					<view class="qianming px-3">
						<!-- <text>{{ $t('user.welcomeLogin') }}</text> -->
					</view>
					<view class="findinfo margin-top">
					<view class="flex align-center">
						<view class="quantity flex flex-1 justify-around">
							<view class="project">
								<text class="num">0</text>
								<text class="mz ml-0_5">{{$t('user.follow')}}</text>
							</view>
							<view class="project">
								<text class="num">0</text>
								<text class="mz ml-0_5">{{$t('user.followers')}}</text>
							</view>
							<view class="project">
								<text class="num">0</text>
								<text class="mz ml-0_5">{{$t('user.liked')}}</text>
							</view>
						</view>
						<view>
							<button class="cu-btn anniu-btn mr-2"
								@click.stop="$appKit.to('/pages/user/auth/newpreLogin')">
								{{ $t('user.loginRegister') }}
							</button>
						</view>
					</view>
						<view class="jieshao">
								{{ $t('user.welcomeLogin') }}
							<!-- 元嘉草草，封狼居胥，赢得仓皇北顾。四十三年，望中犹记，烽火扬州路。可堪回首，佛狸祠下，一片神鸦社鼓。凭谁问：廉颇老矣，尚能饭否？... -->
						</view>
					</view>
				</block>
				<!-- 已登录状态 -->
				<block v-else>
					<view class="userinfo">
						<view class="userinfo-main">
							<view class="cu-avatar margin-right-bj round" :style="{
									backgroundImage: `url(${$appKit.oss(userData.user.avatar, 88, 88)})`
								}" />
							<view class="flex-sub">
								<view class="mz">{{ userData.user.nickname }}</view>
								<view class="txt">
									<view class="flex-direction" v-if="userData.user_no">
										<text>{{$t('user.account-number')}}</text>
										<text>{{ userData.user_no }}</text>
										<text class="wlIcon-fuzhi margin-left-sm"
											@click.stop="$appKit.copy(userData.user_no)"></text>
									</view>
								</view>
							</view>
							<!-- 开启直播按钮 - 移动到个人信息区域右侧 -->
							<button v-if="isMyfind" class="cu-btn anniu-btn " @click.stop="handleStartLive">
								<text>{{$t('start-live')}}</text>
							</button>
						</view>
						<!-- 个性签名放在头像下面，与头像左边齐平 -->
						<view class="qianming">
							<text>{{ userData.user.bio || $t('user.no-signature') }}</text>
							<text v-if="isMyfind" class="wlIcon-jifen margin-left-xs" @click.stop="handleUserEdit"></text>
						</view>
					</view>
				</block>
				<view v-if="$store.state.user.isLogin" class="findinfo bg-white " @tap.stop="">
					<!-- 粉丝信息 -->
					<view class="flex align-center">
						<view class="quantity flex flex-1 justify-around">
							<view class="project" @click.stop="
								$appKit.auth(`/pages/apps/find/user/follow?id=${userData.user_no}`)
							">
								<text class="num">
									{{ $appKit.toFormat( userData.follow < 0 ? 0 : userData.follow, 'thousand' ) }}
								</text>
								<text class="mz ml-0_5">{{$t('user.follow')}}</text>
							</view>
							<view class="project" @click.stop="
								$appKit.auth(`/pages/apps/find/user/fans?id=${userData.user_no}`)
							">
								<text class="num">
									{{ $appKit.toFormat( userData.fans < 0 ? 0 : userData.fans, 'thousand' ) }}
								</text>
								<text class="mz ml-0_5">{{$t('user.followers')}}</text>
							</view>
							<view class="project" @click.stop="showModal('praised')">
								<text class="num">
									{{ $appKit.toFormat( userData.praised < 0 ? 0 : userData.praised, 'thousand' ) }}
								</text>
								<text class="mz ml-0_5">{{$t('user.liked')}}</text>
							</view>
						</view>

						<view>
							<button v-if="isMyfind" class="cu-btn anniu-btn mr-2" @click.stop="handleUserEdit">
								{{$t('edit_profile')}}
							</button>
							<block v-else>
								<block v-if="loadingFollow">
									<button v-if="userData.isFollow === 0" class="cu-btn round line-white">
										<text class="wlIcon-jiazai1 wlIconfont-spin margin-right-xs"></text>
										{{$t('user.following-ellipsis')}}
									</button>
									<button v-else class="cu-btn round line-white">
										<text class="wlIcon-jiazai1 wlIconfont-spin margin-right-xs"></text>
										{{$t('user.unfollowing-ellipsis')}}
									</button>
								</block>
								<block v-else>
									<button v-if="userData.isFollow === 0" class="cu-btn round line-white"
										@click.stop="handleFollow(userData.shop)">
										<text class="wlIcon-tianjia margin-right-xs"></text>
										{{$t('user.follow')}}
									</button>
									<button v-else class="cu-btn round line-white"
										@click.stop="handleFollow(userData.shop)">
										{{$t('user.followed')}}
									</button>
								</block>
							</block>
						</view>
					</view>
					
					<!-- 用户资产信息（仅本人显示） -->
					<view v-if="isMyfind" class="user-assets solid-top margin-top padding-top" @tap.stop="">
						<view class="project text-sm wanl-gray-dark">
							<!-- <view style="line-height: 1.8;" @tap.stop="$appKit.auth('/pages/user/coupon/mycard')">
								<view class="wanl-pip text-lg text-bold6">{{ $store.state.statistics.dynamic.coupon || 0 }}</view>
								{{ $t('user.myCards') }}
							</view> -->
							<view style="line-height: 1.8;" @tap.stop="$appKit.auth('/pages/user/money/money')">
								<view class="wanl-pip text-lg text-bold6">{{ user.money ? user.money : '0.00' }}</view>
								{{ $t('user.balance') }}
							</view>
							<view style="line-height: 1.8;" @tap.stop="$appKit.auth('/pages/user/money/diamond-top-up')">
								<view class="wanl-pip text-lg text-bold6">{{ diamondBalance !== null ? diamondBalance.toFixed(2) : '0.00' }}</view>
								{{ $t('money.diamond') }}
							</view>
							<view class="solid-left bill-details-center" style="line-height: 1.8;" @tap.stop="$appKit.auth('/pages/user/money/tipwallet')">
								<view class="wanl-pip text-lg text-bold6">{{ tipWallet !== null ? tipWallet : '0.00' }}</view>
								{{ $t('user.tipWallet') }}
							</view>
						</view>
					</view>
				</view>
				<view v-if="$store.state.user.isLogin && userData.shop"
					class="shopinfo margin-top-bj solid-top padding-top-bj" @click.stop="onShop(userData.shop.id)">
					<view class="cu-avatar margin-right-bj round"
						:style="{ backgroundImage: `url(${$appKit.oss(userData.shop.avatar, 88, 88)})` }" />
					<view class="subject">
						<view class="info">
							<view v-if="userData.shop.isself == 1">
								<view class="cu-tag sm line-white radius margin-right-xs">
									{{$t('user.self-store')}}
								</view>
								<text class="text-cut" style="width: 50%;">
									{{ userData.shop.shopname }}
								</text>
							</view>
							<view v-else>
								<view class="cu-tag sm line-white radius margin-right-xs"
									v-if="userData.shop.state == 0">
									{{$t('user.personal-store')}}
								</view>
								<view class="cu-tag sm line-white radius margin-right-xs"
									v-if="userData.shop.state == 1">
									{{$t('user.enterprise-store')}}
								</view>
								<view class="cu-tag sm line-white radius margin-right-xs"
									v-if="userData.shop.state == 2">
									{{$t('user.flagship-store')}}
								</view>
								<text class="text-cut" style="width: 50%;">
									{{ userData.shop.shopname }}
								</text>
							</view>
						</view>
						<view class="menu">
							<button class="cu-btn wlIcon margin-right-sm line-white round">
								<text class="wlIcon-31dianpu"></text>
							</button>
						</view>
					</view>
				</view>
			</view>
		</view>
		
		<view class="wanlgroups-user-container__list bg-white">
			<view class="questionbag">
				<scroll-view scroll-x class="nav">
					<view class=" flex align-center justify-around">
						<view class="item " :class="getNavItemIndex(item) === currentId ? 'active' : ''"
							v-for="(item, index) in filteredNavList" :key="index" @tap="handleSelectByType(item.type)">
							{{ item.type_text }}
						</view>
					</view>
				</scroll-view>
			</view>
			<view class="main">
				<!-- 未登录提示 -->
				<view v-if="!$store.state.user.isLogin" class="empty empty--guest">
					<view class="text-center wanl-gray">
						<image :src="$appKit.appstc('/default/collect_default3x.png')"></image>
						<view class="text-30 margin-bottom-bj">
							{{ $t('user.welcomeLogin') }}
						</view>
						<button class="cu-btn line-black" @tap="$appKit.to('/pages/user/auth/newpreLogin')">
							{{ $t('user.loginRegister') }}
						</button>
					</view>
				</view>
				<!-- 已登录内容 -->
				<view v-else v-show="keys === currentId" v-for="(data, keys) in navList" :key="keys">
					<block v-if="isMyfind">
						<view v-if="data.dataList.length === 0 && data.loaded" class="empty">
							<view class="text-center wanl-gray">
								<image :src="$appKit.appstc('/default/collect_default3x.png')"></image>
								<view class="text-30 margin-bottom-bj">
									{{ data.type === 'Comp' ? $t('find.no-compilation') : (keys === 0 ? $t('user.no-works') : $t('user.no-likes')) }}
								</view>
								<button v-if="data.type === 'Comp'" class="cu-btn line-black" @tap="$appKit.to('/pages/apps/find/user/add_compilation')">
									{{$t('find.go-create-compilation')}}
								</button>
								<button v-else-if="keys === 0" class="cu-btn line-black" @tap="handlePublish()">
									{{$t('send_work')}}
								</button>
								<button v-else class="cu-btn line-black" @click="$appKit.to('/pages/apps/find/list')">
									{{$t('user.go-see')}}
								</button>
							</view>
						</view>
					</block>
					<block v-else>
						<empty v-if="data.dataList.length === 0 && data.loaded"
							:text="keys === 0 ? $t('user.other-no-works') : $t('user.other-no-likes')"
							src="collect_default3x" />
					</block>
					<!-- Comp 合辑列表 -->
					<view class="list" v-if="data.type === 'Comp' && data.dataList.length > 0">
						<view class="item" v-for="(item, index) in data.dataList" :key="index">
							<view class="examine radius-bock" :style="{
								backgroundImage: 'url(' + $appKit.oss(item.image || item.cover || '', 200, 0) + ')'
							}" @tap="handleOpenCompilation(item)">
								<view class="cover radius-bock" :style="{
									backgroundImage: 'url(' + $appKit.oss(item.image || item.cover || '', 200, 0) + ')'
								}" />
							</view>
							<view class="padding-xs text-bold5">
								<view class="text-cut-2">
									<view class="cu-tag sm radius margin-right-xs wanl-bg-pink">Comp</view>
									{{ item.title || '' }}
								</view>
							</view>
							<!-- Comp 操作：编辑 / 删除（仅本人） -->
							<view v-if="isMyfind" class="flex wanl-gray text-min padding-lr-xs justify-between">
								<view>
									<text class="text-red margin-left-xs" @tap="handleCompEdit(item)">{{$t('find.edit-compilation')}}</text>
									<text class="text-red margin-left-xs" @tap="handleCompDel(index)">{{$t('find.delete-compilation')}}</text>
								</view>
							</view>
						</view>
					</view>
					<!-- 默认作品/喜欢列表 -->
					<view class="list" v-else-if="$store.state.user.isLogin && data.dataList.length > 0">
						<view class="item" v-for="(item, index) in data.dataList" :key="index">
							<view v-if="item.state === 'normal'" class="examine radius-bock" :style="{
									backgroundImage:
										'url(' + $appKit.oss(item.images[0], 200, 0) + ')'
								}" @tap="onFind(item)">
								<view class="cover radius-bock" :style="{
										backgroundImage:
											'url(' + $appKit.oss(item.images[0], 200, 0) + ')'
									}" />
								<view v-if="item.type === 'video'" class="state padding-sm text-white text-xxxl">
									<text class="wlIcon-video" />
								</view>
							</view>
							<view v-else class="examine radius-bock"
								@tap="$appKit.msg(`${stateText[item.state].text}`)">
								<view class="cover" :style="{
										backgroundImage:
											'url(' + $appKit.oss(item.images[0], 200, 0) + ')'
									}" />
								<view class="state flex justify-center align-center">
									<view v-if="item.state" class="text-xxl text-center"
										:style="{ color: stateText[item.state].color }">
										<text :class="stateText[item.state].icon" />
										<view class="text-df">
											{{ stateText[item.state].text }}
										</view>
									</view>
								</view>
							</view>
							<view class="padding-xs  text-bold5">
								<view class="text-cut-2">
									<view class="cu-tag sm radius margin-right-xs" :class="[typeList[item.type]]">
										{{ item.type_text }}
									</view>
									{{ formatHtml(item.content) }}
								</view>
							</view>
							<view class="flex wanl-gray text-min padding-lr-xs justify-between">
								<view>
									<text>
										{{ $appKit.timeFormat(item.createtime, 'mm-dd') }} {{$t('user.published')}}
									</text>
									<text v-if="isMyfind && keys === 0" class="text-red margin-left-xs"
										@tap="handleDel(index)">
										{{$t('user.delete')}}
									</text>
								</view>
								<view :class="{ 'text-red': item.isLike === 1 }" @tap="handleLike(index)">
									<text :class="[
											item.isLike === 1 ? 'wlIcon-yiguanzhu1' : 'wlIcon-likes'
										]"></text>
									<text class="margin-left-xs">{{ item.likes }}</text>
								</view>
							</view>
						</view>
					</view>
					<uni-load-more v-if="$store.state.user.isLogin" :status="data.loadingType"
						:content-text="contentText" />
				</view>
			</view>
		</view>
		
		<!-- Comp 悬浮创建按钮（右下角） -->
		<view
			v-if="navList[currentId] && navList[currentId].type === 'Comp' && isMyfind"
			class="comp-fab"
			@tap="$appKit.to('/pages/apps/find/user/add_compilation')"
		>
			<text class="comp-fab-text">＋</text>
		</view>
		
		<!-- 模态框 -->
		<view class="WANL-MODAL wanlgroups-user-container__modal">
			<view class="cu-modal top-modal" :class="modalName == 'menu' ? 'show' : ''" @tap="hideModal()">
				<view class="wanl-modal-menu cu-dialog" @tap.stop="">
					<direct @change="hideModal" />
				</view>
			</view>
			<!-- 分享 -->
			<!-- <view class="cu-modal wanl-share bottom-modal" :class="modalName == 'share' ? 'show' : ''"
				@tap="hideModal()">
				<view class="cu-dialog" @tap.stop="">
					<share
						ref="wanlShare"
						page="pages/apps/find/user"
						:scene="{id:find_user, qr:'fu'}"
						:scrollAnimation="scrollAnimation" 
						@change="hideModal()"
					/>
				</view>
			</view> -->
			<view class="cu-modal praised" :class="modalName == 'praised' ? 'show' : ''" @tap="hideModal()">
				<view class="cu-dialog" @tap.stop="">
					<image :src="$appKit.appstc('/common/find_fans3x.png')" mode="widthFix"></image>
					<view class="margin-tb-lg">
						<text class="wanl-gray-dark">
							{{
								`“${userData.user.nickname}”共收獲得 ${$appKit.toFormat(
									userData.praised < 0 ? 0 : userData.praised,
									'thousand'
								)} 個讚`
							}}
						</text>
					</view>
					<view class="padding-tb-bj solid-top" @tap="hideModal()">
						<text class="text-bold">{{$t('user.confirm')}}</text>
					</view>
				</view>
			</view>
		</view>

		<view class="myuser-tabbar-pad" />
		<app-tabbar active="mine" />
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex';
	import AppTabbar from '@/components/app-tabbar/app-tabbar.vue'
	export default {
		components: { AppTabbar },
		data() {
			return {
				pagebgImage: '/static/imgs/topbg1.png',
				find_user: null,
				fromUserPage: false, // 是否从 user.vue 跳转过来（用于显示返回按钮）
				headHeight: 0,
				headerOpacity: 0,
				windowHeight: 0,
				headTop: 0,
				isMyfind: false,
				loadingFollow: false,
				modalName: null,
				scrollAnimation: 300,
				diamondBalance: null, // 钻石余额
				tipWallet: null, // 赏金余额
				userData: {
					user_no: '',
					user: {
						avatar: '',
						nickname: this.$t('user.loading')
					},
					follow: 0,
					fans: 0,
					likes: 0,
					praised: 0,
					color: '#F9EEC4',
					image: '',
					isFollow: 0
				},
				stateText: {
					publish: {
						icon: 'wlIcon-jiazai wlIconfont-spin',
						text: this.$t('send_work'),
						color: '#fff'
					},
					examine: {
						icon: 'wlIcon-shouhoufuwu-zidongpingjia',
						text: this.$t('user.under-review'),
						color: '#e6442b'
					},
					hazard: {
						icon: 'wlIcon-zhuyidapx',
						text: this.$t('user.content-violation'),
						color: '#e6442b'
					},
					transcoding: {
						icon: 'wlIcon-jiazai1 wlIconfont-spin',
						text: this.$t('user.transcoding'),
						color: '#fff'
					},
					screenshot: {
						icon: 'wlIcon-tupian wlIconfont-spin',
						text: this.$t('user.generating-cover'),
						color: '#fff'
					}
				},
				currentId: 0,
				typeList: {
					new: 'bg-gradual-yellow',
					live: 'wanl-bg-orange',
					want: 'bg-gradual-green',
					activity: 'bg-gradual-orange',
					show: 'wanl-bg-pink',
					video: 'wanl-bg-pink'
				},
				navList: [{
						type: 'works',
						type_text: this.$t('work'),
						dataList: [],
						loadingType: 'more',
						current_page: 1
					},
					{
						type: 'likes',
						type_text: this.$t('my_like'),
						dataList: [],
						loadingType: 'more',
						current_page: 1
					},
					{
						type: 'Comp',
						type_text: this.$t('find.compilation'),
						dataList: [],
						loadingType: 'more',
						current_page: 1
					}
				],
				contentText: {
					contentdown: ' ',
					contentrefresh: this.$t('user.loading'),
					contentnomore: this.$t('user.no-more-data')
				},
				isRefreshing: false
			};
		},
		computed: {
			...mapState(['common', 'user']),
			// 过滤后的导航列表（非作者不显示 Comp tab）
			filteredNavList() {
				if (this.isMyfind) {
					return this.navList;
				}
				return this.navList.filter(item => item.type !== 'Comp');
			}
		},
		watch: {
			// 监听用户登录状态变化，退出登录时清除用户信息
			'$store.state.user': {
				handler(newUser) {
					// 当用户退出登录时，重置用户数据
					if (!newUser.isLogin) {
						this.userData = {
							user_no: '',
							user: {
								avatar: '',
								nickname: this.$t('user.loginRegister')
							},
							follow: 0,
							fans: 0,
							likes: 0,
							praised: 0,
							color: '#F9EEC4',
							image: '',
							isFollow: 0
						};
						this.isMyfind = false;
						// 清空列表数据
						this.navList.forEach(item => {
							item.dataList = [];
							item.current_page = 1;
							item.loadingType = 'more';
							item.loaded = false;
						});
					} else {
						// 用户登录后，如果有用户ID，重新加载数据
						if (this.find_user) {
							this.loadData();
						}
					}
				},
				deep: true
			}
		},
		onLoad(query) {
			// 计算页面尺寸
			let sys = this.$appKit.wanlsys();
			this.headTop = sys.top;
			this.headHeight = sys.height;
			this.windowHeight = sys.windowHeight;

			// 是否从个人中心 user.vue 进入（显示返回按钮）
			this.fromUserPage = query.from === 'user';
			// 判断是否小程序来源 1.1.9升级
			if (query.hasOwnProperty('scene')) {
				let scene = decodeURIComponent(query.scene);
				scene = this.$appKit.getParam(scene);
				this.find_user = scene.id;
			} else {
				if (query.hasOwnProperty('id')) {
					this.find_user = query.id;
				}
			}
			// 加载 Api（如果已登录或传入了用户ID）
			if (this.$store.state.user.isLogin || this.find_user) {
				this.refreshPageData({
					silent: true,
					source: 'silentRefresh'
				});
			}
		},
		onShow() {
			setTimeout(() => {
				try { uni.hideTabBar({ animation: false }) } catch (_) {}
			}, 0)
			// 检查是否需要刷新 Comp 列表（从 add_compilation.vue 返回）
			const shouldRefresh = uni.getStorageSync('user_compilation_should_refresh');
			if (shouldRefresh) {
				// 清除标志
				uni.removeStorageSync('user_compilation_should_refresh');
				// 如果当前在 Comp tab，刷新列表
				const navItem = this.navList[this.currentId];
				if (navItem && navItem.type === 'Comp') {
					// 重置列表数据
					navItem.dataList = [];
					navItem.current_page = 1;
					navItem.loadingType = 'more';
					navItem.loaded = false;
					navItem._lastLoadedPage = undefined;
					// 重新加载
					this.loadCompilationList('refresh');
				}
			}
			// 如果是本人，刷新钻石余额和赏金余额
			if (this.$store.state.user.isLogin && this.isMyfind) {
				this.loadDiamondBalance();
				this.loadTipWallet();
			}
			// 进入页面时静默刷新当前展示内容
			if (this.$store.state.user.isLogin || this.find_user) {
				this.refreshPageData({
					silent: true,
					source: 'silentRefresh'
				});
			}
		},
		// 下拉刷新
		onPullDownRefresh() {
			this.refreshPageData({
				silent: false,
				source: 'refresh'
			});
		},
		// 下拉刷新
		onReachBottom() {
			this.loadFindData();
		},
		onPageScroll(e) {
			let tmpY = 170;
			e.scrollTop = e.scrollTop > tmpY ? 170 : e.scrollTop;
			this.headerOpacity = e.scrollTop * (1 / tmpY);
		},
		methods: {
			async refreshPageData({
				silent = true,
				source = 'refresh'
			} = {}) {
				if (this.isRefreshing) {
					uni.stopPullDownRefresh();
					return;
				}
				this.isRefreshing = true;
				try {
					await this.loadData({
						silent,
						source
					});
				} finally {
					this.isRefreshing = false;
					uni.stopPullDownRefresh();
				}
			},
			async loadData({
				silent = false,
				source = 'append'
			} = {}) {
				// 首先检查用户是否已登录，未登录时不加载数据
				if (!this.$store.state.user.isLogin) {
					// 如果未登录且没有传入用户ID，显示默认信息
					if (!this.find_user) {
						this.userData = {
							user_no: '',
							user: {
								avatar: '',
								nickname: this.$t('user.loginRegister')
							},
							follow: 0,
							fans: 0,
							likes: 0,
							praised: 0,
							color: '#F9EEC4',
							image: '',
							isFollow: 0
						};
						this.refreshThemeBackground();
						this.isMyfind = false;
					}
					return;
				}

				await uni.request({
					url: '/wanlshop/find/user/userInfo',
					method: 'POST',
					data: {
						id: this.find_user
					},
					success: res => {
						if (res.data.user_id === this.$store.state.user.id) {
							this.isMyfind = true;
							// 如果是本人，加载钻石余额和赏金余额
							this.loadDiamondBalance();
							this.loadTipWallet();
						} else {
							// 如果不是作者，且当前选中的是 Comp tab（索引为 2），则切换到第一个 tab
							if (this.currentId === 2) {
								this.currentId = 0;
							}
						}
						// this.navList[0].type_text = `作品(${res.data.works})`;
						// this.navList[1].type_text = `喜欢(${res.data.likes})`;
						this.userData = res.data;
						this.refreshThemeBackground();
						this.loadFindData(source);
					}
				});
			},
			loadFindData(source) {
				//这里是将订单挂载到tab列表下
				let navItem = this.navList[this.currentId];
				// Comp 合辑：走独立接口
				if (navItem.type === 'Comp') {
					this.loadCompilationList(source);
					return;
				}
				const isRefreshRequest = source === 'refresh' || source === 'silentRefresh';
				if (isRefreshRequest) {
					// 刷新当前 tab：回到第一页；手动下拉时先清空，静默刷新保持旧列表避免闪烁。
					navItem.current_page = 1;
					navItem.loadingType = 'more';
					navItem.loaded = false;
					navItem._lastLoadedPage = undefined;
					if (source === 'refresh') {
						navItem.dataList = [];
					}
				}
				//判断是否最后一页
				if (navItem.loadingType == 'noMore') {
					console.log("请求作品列表：1")
					return;
				}
				//tab切换只有第一次需要加载数据
				if (source === 'tabChange' && navItem.loaded === true) {
					console.log("请求作品列表：2")
					return;
				}
				//防止重复加载
				if (navItem.loadingType === 'loading') {
					console.log("请求作品列表：3")
					return;
				}
				navItem.loadingType = 'loading';
				let type =
					navItem.type === 'works' ? (this.isMyfind ? 'myfind' : navItem.type) : navItem.type;
				// 获取列表
				uni.request({
					url: '/wanlshop/find/find/getList',
					data: {
						type: type,
						user_no: this.userData.user_no,
						page: navItem.current_page
					},
					success: res => {
						console.log("请求作品列表成功：" + res.data)
						navItem.current_page = res.data.current_page; //当前页码
						if (res.data.last_page === res.data.current_page) {
							navItem.loadingType = 'noMore';
						} else {
							navItem.loadingType = 'more';
							navItem.current_page++;
						}
						const incoming = Array.isArray(res.data.data) ? res.data.data : [];
						if (isRefreshRequest) {
							navItem.dataList = incoming;
						} else {
							incoming.forEach(item => {
								navItem.dataList.push(item);
							});
						}
						this.$set(navItem, 'loaded', true);

					},
					fail() {
						navItem.loadingType = 'more';
					}

				});
			},
			// 加载合辑列表
			loadCompilationList(source) {
				let navItem = this.navList[this.currentId];
				// 刷新模式：重置数据并重新加载第一页
				if (source === 'refresh') {
					navItem.dataList = [];
					navItem.current_page = 1;
					navItem.loadingType = 'more';
					navItem.loaded = false;
					navItem._lastLoadedPage = undefined;
				}
				// tab切换只有第一次需要加载数据
				if (source === 'tabChange' && navItem.loaded === true) {
					return;
				}
				// 防止重复加载
				if (navItem.loadingType === 'loading') {
					return;
				}
				navItem.loadingType = 'loading';
				uni.request({
					url: '/wanlshop/videoseries/list',
					method: 'GET',
					data: {
						user_no: this.userData.user_no,
						page: navItem.current_page
					},
					success: res => {
						// 兼容返回结构：code 包装 / 直接数组 / 分页结构
						const body = res.data;
						const payload = (body && body.code !== undefined) ? body.data : body;

						// 提取列表
						const list = Array.isArray(payload)
							? payload
							: (payload && payload.data ? payload.data : []);

						// 提取分页信息（优先 payload，其次 body 顶层兜底）
						const currentPage =
							(payload && payload.current_page) ? payload.current_page :
							(body && body.current_page) ? body.current_page :
							navItem.current_page;
						const lastPage =
							(payload && payload.last_page) ? payload.last_page :
							(body && body.last_page) ? body.last_page :
							currentPage;

						// 刷新模式：直接替换列表数据
						if (source === 'refresh') {
							navItem.dataList = list || [];
							navItem._lastLoadedPage = Number(currentPage);
						} else {
							// 防重复：如果后端不生效 page，可能一直返回同一页，避免重复 append
							if (navItem._lastLoadedPage !== undefined && Number(currentPage) <= Number(navItem._lastLoadedPage)) {
								navItem.loadingType = 'noMore';
								this.$set(navItem, 'loaded', true);
								return;
							}
							navItem._lastLoadedPage = Number(currentPage);

							// 去重：按 id 过滤，避免重复页导致数据越来越多
							const exists = new Set((navItem.dataList || []).map(x => x && x.id).filter(Boolean));
							list.forEach(item => {
								if (!item) return;
								if (item.id && exists.has(item.id)) return;
								if (item.id) exists.add(item.id);
								navItem.dataList.push(item);
							});
						}

						// 空列表直接 noMore
						if (!list || list.length === 0) {
							navItem.loadingType = 'noMore';
							this.$set(navItem, 'loaded', true);
							return;
						}

						// 更新下一页
						if (Number(currentPage) >= Number(lastPage)) {
							navItem.loadingType = 'noMore';
						} else {
							navItem.loadingType = 'more';
							navItem.current_page = Number(currentPage) + 1;
						}
						this.$set(navItem, 'loaded', true);
					},
					fail: () => {
						navItem.loadingType = 'more';
						this.$set(navItem, 'loaded', true);
					}
				});
			},
			// Comp：打开合辑视频列表
			handleOpenCompilation(item) {
				if (!item) return;
				const seriesId = item.id || item.series_id || item.seriesId;
				if (!seriesId) {
					this.$appKit.msg(this.$t('find.missing-compilation-id-cannot-open'));
					return;
				}
				// 进入合辑视频列表页
				this.$appKit.to(`/pages/apps/find/details/compilationlist?series_id=${encodeURIComponent(String(seriesId))}&id=${encodeURIComponent(String(seriesId))}`);
			},
			// Comp：编辑合辑
			handleCompEdit(item) {
				if (!item) return;
				const id = item.id || item.series_id || item.seriesId || '';
				const title = encodeURIComponent(item.title || '');
				const image = encodeURIComponent(item.image || item.cover || '');
				// 进入编辑模式：传入 id/title/image
				this.$appKit.to(`/pages/apps/find/user/add_compilation?id=${id}&title=${title}&image=${image}&edit=1`);
			},
			// Comp：删除合辑
			handleCompDel(index) {
				const navItem = this.navList[this.currentId];
				const item = navItem && navItem.dataList ? navItem.dataList[index] : null;
				if (!item) return;
				const id = item.id || item.series_id || item.seriesId;
				if (!id) {
					this.$appKit.msg(this.$t('find.missing-compilation-id-cannot-delete'));
					return;
				}
				uni.showModal({
					content: this.$t('find.confirm-delete-compilation'),
					success: (res) => {
						if (!res.confirm) return;
						uni.request({
							url: '/wanlshop/videoseries/del',
							method: 'POST',
							data: { id },
							success: (r) => {
								const body = (r && r.data !== undefined) ? r.data : r;
								if (r.res.code === 1) {
									navItem.dataList.splice(index, 1);
									this.$appKit.msg(body.msg || this.$t('find.delete-compilation-success'));
								} else {
									this.$appKit.msg((body && body.msg) ? body.msg : this.$t('find.delete-compilation-failed'));
								}
							},
							fail: () => {
								this.$appKit.msg(this.$t('find.delete-compilation-failed'));
							}
						});
					}
				});
			},
			async handleFollow(shop) {
				if (this.$store.state.user.isLogin) {
					this.loadingFollow = true;
					await uni.request({
						url: '/wanlshop/find/user/setFindUser',
						method: 'POST',
						data: {
							id: this.userData.user_no,
							type: 'follow'
						},
						success: res => {
							if (shop) {
								let concern = this.$store.state.statistics.dynamic.concern;
								if (res.data.data === 0) {
									concern -= 1;
								} else {
									concern += 1;
								}
								this.$store.commit('statistics/dynamic', {
									concern: concern
								});
							}
							if (res.data.data === 1) {
								this.userData.fans += 1;
							} else if (res.data.data === 0) {
								this.userData.fans -= 1;
							}
							this.userData.isFollow = res.data.data;
							this.loadingFollow = false;
						}
					});
				} else {
					this.$appKit.to('/pages/user/auth/newpreLogin');
				}
			},
			async handleLike(index) {
				if (this.$store.state.user.isLogin) {
					let data = this.navList[this.currentId].dataList[index];
					await uni.request({
						url: '/wanlshop/find/user/setFindUser',
						method: 'POST',
						data: {
							id: data.id,
							type: 'likes'
						},
						success: res => {
							if (res.data.data === 0) {
								data.likes -= 1;
							} else {
								data.likes += 1;
							}
							data.isLike = res.data.data;
						}
					});
				} else {
					this.$appKit.to('/pages/user/auth/newpreLogin');
				}
			},
			async handleDel(index) {
				if (this.$store.state.user.isLogin) {
					uni.showModal({
						content: this.$t('user.delete-confirm'),
						success: res => {
							if (res.confirm) {
								let data = this.navList[this.currentId].dataList;
								uni.request({
									url: '/wanlshop/find/find/delData',
									method: 'POST',
									data: {
										id: data[index].id
									},
									success: del => {
										data.splice(index, 1);
									}
								});
							}
						}
					});
				} else {
					this.$appKit.to('/pages/user/auth/newpreLogin');
				}
			},
			async handleTheme() {
				if (this.isMyfind) {
					uni.showActionSheet({
						itemList: [this.$t('user.select-theme'), this.$t('user.upload-image')],
						success: action => {
							if (action.tapIndex === 0) {
								this.$appKit.to('/pages/user/theme');
							} else if (action.tapIndex === 1) {
								uni.chooseImage({
									success: res => {
										uni.request({
											url: '/wanlshop/common/uploadData',
											success: updata => {
												uni.uploadFile({
													url: updata.data
														.uploadurl,
													filePath: res
														.tempFilePaths[0],
													name: 'file',
													formData: updata.data
														.storage ==
														'local' ? null :
														updata.data
														.multipart,
													success: data => {
														this.editTheme({
															url: JSON
																.parse(
																	data
																	.data
																)
																.data
																.url,
															type: 'upload'
														});
													},
													fail: error => {
														uni.showToast({
															title: JSON
																.parse(
																	error
																	.data
																)
																.msg,
															icon: 'error',
															position: true
														});
													}
												});
											}
										});
									}
								});
							}
						}
					});
				}
			},
			async editTheme(data) {
				await uni.request({
					url: '/wanlshop/find/user/editTheme',
					method: 'POST',
					data: data,
					success: res => {
						this.userData.image = res.data.image;
						this.userData.color = res.data.color;
						this.refreshThemeBackground();
					}
				});
			},
			refreshThemeBackground() {
				if (this.userData && this.userData.image) {
					// 与 user.vue 保持一致，主题图使用 oss 处理后的地址
					this.pagebgImage = this.$appKit.oss(this.userData.image, 0, 50, 1, 'transparent', 'png');
				} else {
					this.pagebgImage = '/static/imgs/topbg1.png';
				}
			},
			handlePublish() {
				let itemList = [],
					url = [];
				if (this.userData.shop) {
					if (this.userData.isVideo) {
						if (this.userData.isLive) {
							itemList = [this.$t('user.publish-grass'), this.$t('user.publish-video'), this.$t(
								'user.merchant-live')];
							url = ['/pages/apps/find/user/add?type=want', '/pages/apps/find/user/add?type=video',
								'/pages/shop/live/live'
							];
						} else {
							itemList = [this.$t('user.publish-grass'), this.$t('user.publish-video')];
							url = ['/pages/apps/find/user/add?type=want', '/pages/apps/find/user/add?type=video'];
						}
					} else {
						if (this.userData.isLive) {
							itemList = [this.$t('user.publish-grass'), this.$t('user.merchant-live')];
							url = ['/pages/apps/find/user/add?type=want', '/pages/apps/find/user/add?type=video'];
						} else {
							itemList = [this.$t('user.publish-grass')];
							url = ['/pages/apps/find/user/add?type=want'];
						}
					}
				} else {
					if (this.userData.isVideo) {
						itemList = [this.$t('user.publish-grass'), this.$t('user.publish-video')];
						url = ['/pages/apps/find/user/add?type=want', '/pages/apps/find/user/add?type=video'];
					} else {
						itemList = [this.$t('user.publish-grass')];
						url = ['/pages/apps/find/user/add?type=want'];
					}
				}
				uni.showActionSheet({
					itemList: itemList,
					success: res => {
						if (res.tapIndex === 2) {
							// #ifdef APP-PLUS || MP-WEIXIN
							this.$appKit.to(url[res.tapIndex]);
							// #endif
							// #ifndef APP-PLUS || MP-WEIXIN
							this.$appKit.msg(this.$t('user.app-wechat-only'));
							// #endif
						} else {
							this.$appKit.to(url[res.tapIndex]);
						}
					}
				});
			},
			// 选择Tag（通过索引）
			handleSelect(index) {
				this.currentId = index;
				this.loadFindData('tabChange');
			},
			// 选择Tag（通过类型，用于过滤后的列表）
			handleSelectByType(type) {
				const index = this.navList.findIndex(item => item.type === type);
				if (index !== -1) {
					this.currentId = index;
					this.loadFindData('tabChange');
				}
			},
			// 获取导航项在原始列表中的索引（用于高亮显示）
			getNavItemIndex(item) {
				return this.navList.findIndex(nav => nav.type === item.type);
			},
			handleBack() {
				this.$appKit.back(1);
			},
			handleUserEdit() {
				this.$appKit.auth('/pages/user/setting/user');
			},
			// 开启直播
			handleStartLive() {
				// 检查是否是当前用户的页面
				if (this.isMyfind) {
					// #ifdef APP-PLUS || MP-WEIXIN
					this.$appKit.to('/pages/shop/live/live');
					// #endif
					// #ifndef APP-PLUS || MP-WEIXIN
					this.$appKit.msg(this.$t('user.app-wechat-only'));
					// #endif
				} else {
					this.$appKit.msg(this.$t('user.only-self-live'));
				}
			},
			// 格式化html
			formatHtml(content) {
				return content.replace(/<\/?.+?>/g, '').replace(/ /g, '');
			},
			// 弹出层
			showModal(name) {
				// 滚动下分享
				if (name == 'share' && this.modalName != 'share') {
					setTimeout(() => {
						this.scrollAnimation = 300;
					}, 300);
				}
				this.modalName = name;
			},
			hideModal(name) {
				if (name) {
					this.showModal(name);
				} else {
					// 强制关闭海报
					if (this.modalName == 'share') {
						// this.$refs.wanlShare.closePoster();
					}
					this.modalName = null;
				}
			},
			// 加载钻石余额
			async loadDiamondBalance() {
				try {
					const [err, res] = await uni.request({
						url: '/user/getdiamondnum'
					});
					
					if (err) {
						console.error('Load diamond balance error:', err);
						this.diamondBalance = 0;
						return;
					}
					
					// 兼容不同的返回格式
					if (typeof res.data === 'string') {
						this.diamondBalance = Number(res.data) || 0;
					} else if (res.data != null && typeof res.data === 'object') {
						if (res.data.diamond != null) {
							this.diamondBalance = Number(res.data.diamond) || 0;
						} else if (res.data.data != null && typeof res.data.data === 'object' && res.data.data.diamond != null) {
							this.diamondBalance = Number(res.data.data.diamond) || 0;
						} else {
							const body = res && res.data ? res.data : res;
							if (body && typeof body === 'object') {
								if (body.code !== undefined && Number(body.code) === 1) {
									if (typeof body.data === 'string') {
										this.diamondBalance = Number(body.data) || 0;
									} else if (body.data && typeof body.data === 'object' && body.data.diamond != null) {
										this.diamondBalance = Number(body.data.diamond) || 0;
									}
								} else if (body.diamond != null) {
									this.diamondBalance = Number(body.diamond) || 0;
								}
							}
						}
					}
				} catch (error) {
					console.error('Load diamond balance error:', error);
					this.diamondBalance = 0;
				}
			},
			// 加载赏金余额
			async loadTipWallet() {
				try {
					const [err, res] = await uni.request({
						url: '/user/gettipwallet'
					});
					
					if (err) {
						console.error('Load tip wallet error:', err);
						this.tipWallet = '0.00';
						return;
					}
					
					// 处理返回格式: {"data": {"tip_wallet": "8440.00"}}
					if (res.data && typeof res.data === 'object') {
						if (res.data.data && res.data.data.tip_wallet != null) {
							this.tipWallet = res.data.data.tip_wallet;
						} else if (res.data.tip_wallet != null) {
							this.tipWallet = res.data.tip_wallet;
						} else {
							this.tipWallet = '0.00';
						}
					} else {
						this.tipWallet = '0.00';
					}
				} catch (error) {
					console.error('Load tip wallet error:', error);
					this.tipWallet = '0.00';
				}
			}
		}
	};
</script>

<style lang="scss">
	page {
		background-color: #F9F7FC;
	}

	.pagebg {
		width: 100%;
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
	}

	.wanlgroups-user-container {
		position: relative;

		&__head {
			position: fixed;
			top: 0;
			left: 0;
			right: 0;
			z-index: 9;

			.background {
				position: absolute;
				left: 0;
				right: 0;
				z-index: 1;

				.bgcolor {
					width: 100%;
					height: 100%;
					// background-color: rgba(0, 0, 0, 0.6);
				}
			}

			.navigater {
				display: flex;
				justify-content: space-between;
				align-items: center;
				position: absolute;
				left: 0;
				right: 0;
				z-index: 9;
				padding-left: 25rpx;
				padding-right: 25rpx;
				/* #ifdef MP */
				padding-right: 200rpx;

				/* #endif */
				&>view {
					display: flex;
					align-items: center;
				}
			}
		}

		&__main {
			padding:0 24rpx;
			position: relative;
			background-size: 100% auto;
			background-repeat: no-repeat;
			background-position-y: center;

			.text-white-agba {
				color: rgba(255, 255, 255, 0.9);
			}

			.head {

				.userinfo {
					padding-left: 24rpx;
					padding-right: 20rpx;

					.userinfo-main {
						display: flex;
						align-items: flex-start;
						justify-content: space-between;
					}

					.cu-avatar {
						width: 130rpx;
						height: 130rpx;
					}

					.mz {
						font-weight: 500;
						font-size: 43rpx;
						color: #121836;
						line-height: 62rpx;
					}

					.txt {
						font-weight: 500;
						font-size: 24rpx;
						color: #AAB0BA;
						line-height: 34rpx;
					}

					.qianming {
						font-weight: 400;
						font-size: 24rpx;
						color: #AAB0BA;
						line-height: 34rpx;
						margin-top: 16rpx;
						padding-left: 0;
					}
				}

				.anniu-btn {
					background: none;
					padding: 0 14rpx;
					height: 44rpx;
					font-weight: 500;
					font-size: 24rpx;
					color: #121836;
					line-height: 24rpx;
					border: 1px solid #121836;

				}

				.findinfo {
					padding: 20rpx 24rpx;
					background: #fff;
					border-radius: 20rpx 20rpx 0rpx 0rpx;

					.quantity {
						.project {
							margin-right: 10rpx;

							.num {
								font-weight: 700;
								font-size: 43rpx;
								color: #282C38;

								text {
									font-size: 20rpx;
								}
							}

							.mz {
								font-weight: 500;
								font-size: 24rpx;
								color: #AAB0BA;

							}
						}
					}

					.user-assets {
						margin-top: 20rpx;
						padding-top: 20rpx;

						.project {
							display: flex;
							justify-content: space-around;
							text-align: center;

							>view {
								position: relative;
								flex: 1;
							}

							.wanl-pip {
								font-weight: 600;
								font-size: 36rpx;
								color: #282C38;
								line-height: 50rpx;
							}

							.solid-left {
								border-left: 1rpx solid #F1F1F1;
								padding-left: 20rpx;
							}

							.bill-details-center {
								display: flex;
								flex-direction: column;
								justify-content: center;
								align-items: center;
								text-align: center;
							}
						}
					}
				}

				.shopinfo {
					display: flex;
					align-items: center;
					justify-content: space-between;

					&.solid-top {
						&::after {
							border-top: 1rpx solid rgba(255, 255, 255, 0.92);
						}
					}

					.cu-avatar {
						background-color: rgba(0, 0, 0, 0.1);
						width: 65rpx;
						height: 65rpx;
					}

					.subject {
						flex: 1;
						display: flex;
						align-items: center;
						justify-content: space-between;

						.info {
							&>view {
								display: flex;
								align-items: center;
							}
						}
					}
				}
			}
		}

		&__list {margin:0 24rpx;
			background: #fff;
			

			position: relative;

			.questionbag {
				position: -webkit-sticky;
				position: sticky;
				z-index: 99;
				padding: 24rpx;
				

				.nav {

					border-bottom: 1px solid #F1F1F1;

					.item {
						display: inline-block;
						font-weight: 500;
						font-size: 32rpx;
						color: #4D4E50;
						line-height: 60rpx;
						padding: 0 10rpx;
						position: relative;
						border-bottom: 2px solid #fff;

						&.active {
							font-size: 32rpx;
							color: #000000;
							border-bottom: 2px solid #FF000A;
						}
					}
				}
			}

			.main {
				.empty {
					padding-top: 100rpx;
					display: flex;
					justify-content: center;

					image {
						width: 320rpx;
						height: 320rpx;
					}

					/* 未登录：白底区域向下延伸，避免按钮贴底与背景断层 */
					&.empty--guest {
						flex-direction: column;
						align-items: center;
						padding-bottom: 160rpx;
						min-height: 520rpx;
						/* #ifndef APP-NVUE */
						padding-bottom: calc(160rpx + constant(safe-area-inset-bottom));
						padding-bottom: calc(160rpx + env(safe-area-inset-bottom));
						/* #endif */
					}
				}

				.list {
					display: flex;
					flex-direction: row;
					flex-wrap: wrap;
					padding: 0 24rpx;
					justify-content: space-between;

					.item {
						margin-bottom: 40rpx;
						flex: 0 0 calc((100% - 22rpx) / 2);
						overflow: hidden;

						.examine {
							height: 460rpx;
							position: relative;

							.cover {
								height: 460rpx;
								background-size: cover;
								background-position: center;
								background-repeat: no-repeat;
							}

							.state {
								position: absolute;
								top: 0;
								right: 0;
								left: 0;
								bottom: 0;
								background-color: rgba(0, 0, 0, 0.2);
							}
						}
					}
				}
			}
		}

		&__modal {
			.praised {
				.cu-dialog {
					width: 70%;
					overflow: hidden;

					image {
						height: 100%;
					}
				}
			}
		}
	}

	/* Comp 悬浮创建按钮 */
	.comp-fab {
		position: fixed;
		right: 24rpx;
		/* 预留底部安全区/避免遮挡 */
		bottom: 160rpx;
		z-index: 999;
		width: 96rpx;
		height: 96rpx;
		border-radius: 9999rpx;
		background-color: #e6162c;
		display: flex;
		align-items: center;
		justify-content: center;
		/* #ifndef APP-NVUE */
		box-shadow: 0 12rpx 24rpx rgba(230, 22, 44, 0.35);
		/* #endif */
	}
	.comp-fab-text {
		color: #fff;
		font-size: 48rpx;
		line-height: 48rpx;
		font-weight: bold;
	}

	.myuser-tabbar-pad {
		height: 160rpx;
		width: 100%;
	}

</style>