<template>
	<view class="rank-page" :style="{'--statusbar': statusBarHeight + 'px'}">
		<view class="nav" :style="{paddingTop: statusBarHeight + 'px'}">
			<view class="nav-back" @tap="goBack"><text>‹</text></view>
			<view class="nav-title">星球排行榜</view>
		</view>

		<scroll-view scroll-y enhanced :show-scrollbar="false" class="page" :style="{paddingTop: (statusBarHeight + 58) + 'px'}" @scrolltolower="loadMore">
			<view v-if="loading" class="loading-card">正在扫描财富坐标...</view>
			<block v-else>
				<view class="radar-card">
					<view class="radar-visual">
						<view class="radar-sweep"></view>
						<view class="radar-ring ring-a"></view>
						<view class="radar-ring ring-b"></view>
						<view class="radar-dot"></view>
					</view>
					<view class="radar-copy">
						<view class="radar-kicker">SCHOOL RICH LIST</view>
						<view class="radar-title">全校首富雷达</view>
						<view class="radar-sub">从榜单里选定目标，发起星际追查，抢回今日补给权。</view>
					</view>
					<view class="radar-count">
						<text>{{home.remainHunt || 0}}</text>
						<text>次追查</text>
					</view>
				</view>

				<view class="rank-head">
					<view>
						<view class="rank-kicker">WEALTH COORDINATES</view>
						<view class="rank-title">财富坐标榜</view>
					</view>
					<view class="rank-page-no">已加载 {{pageNum}} / {{totalPages}} 页</view>
				</view>

				<view v-if="pagedList.length" class="rank-list">
					<view
						class="rank-row"
						v-for="(item, index) in pagedList"
						:key="item._rankKey">
						<view class="rank-no">#{{item._displayRankNo}}</view>
						<image class="avatar" :class="{stealth: item.stealth}" :src="item.stealth ? defaultAvatar : (item.avatar || defaultAvatar)" mode="aspectFill"></image>
						<view class="user-main">
							<view class="user-name">
								<text>{{item.stealth ? '隐身侠' : (item.nickname || '神秘同学')}}</text>
								<text v-if="item.stealth" class="stealth-tag">隐身</text>
								<text v-if="item.self" class="me-tag">ME</text>
							</view>
							<view class="user-meta">
								<text>{{item.ticketCount || 0}} 张星球券</text>
								<text v-if="!item.stealth && item.rankKeepDays > 0">霸榜 {{item.rankKeepDays}} 天</text>
							</view>
						</view>
						<view
							class="hunt-btn"
							:class="{disabled: item.self || item.stealth || item.shielded || (home.remainHunt || 0) <= 0}"
							@tap="onHunt(item)">
							{{huntText(item)}}
						</view>
					</view>
				</view>
				<view v-else class="empty-card">暂无上榜居民，攒券登顶成为今日主角</view>

				<view v-if="rankList.length" class="load-more">{{loadMoreText}}</view>

				<view class="bottom-space"></view>
			</block>
		</scroll-view>

		<hunt-modal
			:show="huntModal.show"
			:phase="huntModal.phase"
			:result="huntModal.result"
			:target="huntModal.target"
			@close="closeHunt">
		</hunt-modal>
	</view>
</template>

<script>
	import huntModal from '@/package1/components/planet/hunt-modal.vue'

	export default {
		components: {
			huntModal
		},
		data() {
			return {
				statusBarHeight: 20,
				loading: true,
				userId: '',
				regionId: '',
				nickname: '',
				avatar: '',
				college: '',
				pageNum: 1,
				pageSize: 10,
				rankRows: [],
				listLoading: false,
				noMore: false,
				defaultAvatar: 'https://jewel-shop.oss-cn-beijing.aliyuncs.com/41cfb56caff4419b94b69d0f2303b602.png',
				home: {
					remainHunt: 0,
					rankList: []
				},
				huntModal: {
					show: false,
					phase: 'searching',
					result: null,
					target: {}
				},
				huntTimers: []
			}
		},
		computed: {
			rankList() {
				return (this.rankRows || []).map((item, index) => {
					return Object.assign({}, item, {
						_rankKey: String(item.userId || item.rankNo || index),
						_displayRankNo: item.rankNo || (index + 1)
					})
				})
			},
			totalPages() {
				return Math.max(1, Number(this.home.rankTotalPages || 1))
			},
			pagedList() {
				return this.rankList
			},
			loadMoreText() {
				if (this.listLoading) return '正在加载更多坐标...'
				if (this.noMore) return '没有更多财富坐标了'
				return '上滑加载更多坐标'
			}
		},
		onLoad() {
			const sys = uni.getSystemInfoSync()
			this.statusBarHeight = sys.statusBarHeight || 20
			this.userId = uni.getStorageSync('id') || ''
			this.nickname = uni.getStorageSync('nickName') || uni.getStorageSync('nickname') || ''
			this.avatar = uni.getStorageSync('avatarUrl') || uni.getStorageSync('avatar') || ''
			try {
				const area = uni.getStorageSync('area')
				if (area) this.regionId = JSON.parse(area).id || ''
			} catch (e) {}
			this.loadHome(true)
		},
		onUnload() {
			this.clearHuntTimers()
		},
		methods: {
			loadHome(reset) {
				if (this.listLoading) return
				if (!this.userId) {
					this.tui.toast('请先登录')
					return
				}
				if (!this.regionId) {
					this.loading = false
					this.tui.toast('未获取到校区信息')
					return
				}
				if (reset) {
					this.pageNum = 1
					this.noMore = false
					this.rankRows = []
				}
				if (reset) this.loading = true
				this.listLoading = true
				this.tui.request('/app/planet/home', 'POST', {
					userId: this.userId,
					regionId: this.regionId,
					nickname: this.nickname,
					avatar: this.avatar,
					college: this.college,
					pageNumber: this.pageNum,
					pageSize: this.pageSize
				}, false, false, true).then((res) => {
					this.loading = false
					this.listLoading = false
					if (res.code == 200 && res.result) {
						this.home = res.result
						this.pageNum = Number(res.result.rankPageNumber || this.pageNum)
						if (this.pageNum > this.totalPages) this.pageNum = this.totalPages
						const records = res.result.rankList || []
						this.rankRows = reset ? records : this.rankRows.concat(records)
						this.noMore = this.pageNum >= this.totalPages || records.length < this.pageSize
					} else if (res.message) {
						this.tui.toast(res.message)
					}
				}).catch(() => {
					this.loading = false
					this.listLoading = false
				})
			},
			loadMore() {
				if (this.listLoading || this.noMore) return
				if (this.pageNum >= this.totalPages) {
					this.noMore = true
					return
				}
				this.pageNum += 1
				this.loadHome(false)
			},
			huntText(item) {
				if (item.self) return '榜上有我'
				if (item.stealth) return '已隐身'
				if (item.shielded) return '防护中'
				if ((this.home.remainHunt || 0) <= 0) return '次数用完'
				return '发起追查'
			},
			onHunt(item) {
				if (item.self) {
					this.tui.toast('不能追捕自己')
					return
				}
				if (item.stealth) {
					this.tui.toast('目标正在隐身，暂时无法追查')
					return
				}
				if (item.shielded) {
					this.tui.toast('目标已开启防护罩')
					return
				}
				if ((this.home.remainHunt || 0) <= 0) {
					this.tui.toast('今日追捕次数已用完')
					return
				}
				this.clearHuntTimers()
				this.huntModal.show = true
				this.huntModal.phase = 'searching'
				this.huntModal.result = null
				this.huntModal.target = item
				this.huntTimers.push(setTimeout(() => { this.huntModal.phase = 'locking' }, 900))
				this.huntTimers.push(setTimeout(() => { this.huntModal.phase = 'chasing' }, 1800))
				this.tui.request('/app/planet/hunt', 'POST', {
					userId: this.userId,
					regionId: this.regionId,
					toUserId: item.userId
				}, false, false, true).then((res) => {
					this.huntTimers.push(setTimeout(() => {
						if (res.code == 200 && res.result) {
							this.huntModal.result = res.result
							this.huntModal.phase = 'result'
							this.loadHome(true)
						} else {
							this.huntModal.show = false
							this.tui.toast(res.message)
						}
					}, 2600))
				}).catch(() => {
					this.huntModal.show = false
				})
			},
			clearHuntTimers() {
				this.huntTimers.forEach((timer) => clearTimeout(timer))
				this.huntTimers = []
			},
			closeHunt() {
				this.huntModal.show = false
				this.huntModal.result = null
			},
			goBack() {
				uni.navigateBack({
					delta: 1,
					fail() {
						uni.navigateTo({ url: '/package1/planet/index' })
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.rank-page { min-height: 100vh; background: linear-gradient(155deg, #F3FFF4 0%, #EAF8FF 46%, #FFF7DD 100%); color: #12342F; }
	.nav { position: fixed; top: 0; left: 0; right: 0; height: 44px; z-index: 20; display: flex; align-items: center; justify-content: center; box-sizing: content-box; background: linear-gradient(180deg, rgba(243,255,244,0.98), rgba(243,255,244,0)); }
	.nav-back { position: absolute; left: 20rpx; bottom: 0; height: 44px; width: 60rpx; display: flex; align-items: center; justify-content: center; }
	.nav-back text { color: #12342F; font-size: 48rpx; font-weight: 300; }
	.nav-title { color: #12342F; font-size: 34rpx; font-weight: 900; align-self: flex-end; padding-bottom: 6rpx; }
	.page { height: 100vh; box-sizing: border-box; padding-left: 22rpx; padding-right: 22rpx; }
	.loading-card, .empty-card { margin-top: 24rpx; height: 220rpx; border-radius: 38rpx; background: rgba(255,255,255,0.76); display: flex; align-items: center; justify-content: center; color: #6B817D; font-size: 26rpx; }
	.radar-card { position: relative; margin-top: 24rpx; min-height: 210rpx; padding: 30rpx 24rpx; border-radius: 46rpx; background: radial-gradient(circle at 18% 50%, rgba(255,122,89,0.16), transparent 34%), linear-gradient(135deg, rgba(255,255,255,0.9), rgba(255,246,219,0.7)); border: 2rpx solid rgba(255,255,255,0.94); box-shadow: 0 24rpx 58rpx rgba(255,122,89,0.12); display: flex; align-items: center; overflow: hidden; }
	.radar-visual { position: relative; width: 138rpx; height: 138rpx; border-radius: 50%; border: 2rpx solid rgba(255,122,89,0.22); background: radial-gradient(circle, rgba(255,122,89,0.13), rgba(255,255,255,0.48)); flex-shrink: 0; overflow: hidden; }
	.radar-ring { position: absolute; border-radius: 50%; border: 1rpx solid rgba(255,122,89,0.22); }
	.ring-a { left: 24rpx; top: 24rpx; width: 88rpx; height: 88rpx; }
	.ring-b { left: 48rpx; top: 48rpx; width: 40rpx; height: 40rpx; }
	.radar-sweep { position: absolute; left: 50%; top: 50%; width: 64rpx; height: 5rpx; border-radius: 999rpx; transform-origin: left center; background: linear-gradient(90deg, rgba(255,122,89,0.76), rgba(255,122,89,0)); animation: sweep 1.8s linear infinite; }
	.radar-dot { position: absolute; right: 30rpx; top: 38rpx; width: 16rpx; height: 16rpx; border-radius: 50%; background: #FF7A59; box-shadow: 0 0 18rpx rgba(255,122,89,0.55); }
	@keyframes sweep { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
	.radar-copy { flex: 1; min-width: 0; margin-left: 22rpx; }
	.radar-kicker, .rank-kicker { color: #FF7A59; font-size: 18rpx; font-weight: 900; letter-spacing: 3rpx; }
	.radar-title { margin-top: 6rpx; color: #12342F; font-size: 38rpx; font-weight: 900; }
	.radar-sub { margin-top: 8rpx; color: #7E9691; font-size: 23rpx; line-height: 1.42; font-weight: 600; }
	.radar-count { width: 112rpx; height: 112rpx; border-radius: 34rpx; background: linear-gradient(135deg, #FF7A59, #FFB84D); color: #FFFFFF; display: flex; flex-direction: column; align-items: center; justify-content: center; box-shadow: 0 12rpx 26rpx rgba(255,122,89,0.18); transform: rotate(4deg); flex-shrink: 0; }
	.radar-count text:first-child { font-size: 40rpx; font-weight: 900; line-height: 42rpx; }
	.radar-count text:last-child { font-size: 19rpx; font-weight: 800; margin-top: 4rpx; }
	.rank-head { margin-top: 30rpx; display: flex; align-items: flex-end; justify-content: space-between; }
	.rank-title { margin-top: 6rpx; color: #12342F; font-size: 40rpx; font-weight: 900; }
	.rank-page-no { color: #6B817D; font-size: 23rpx; font-weight: 800; }
	.rank-list { margin-top: 18rpx; }
	.rank-row { margin-top: 16rpx; padding: 22rpx; border-radius: 34rpx; background: rgba(255,255,255,0.82); border: 2rpx solid rgba(255,255,255,0.94); box-shadow: 0 16rpx 36rpx rgba(53,214,166,0.1); display: flex; align-items: center; }
	.rank-no { min-width: 70rpx; color: #22B889; font-size: 28rpx; font-weight: 900; }
	.avatar { width: 86rpx; height: 86rpx; border-radius: 28rpx; border: 4rpx solid rgba(255,255,255,0.94); box-shadow: 0 12rpx 24rpx rgba(18,52,47,0.12); flex-shrink: 0; }
	.avatar.stealth { opacity: .58; filter: grayscale(100%); }
	.user-main { flex: 1; min-width: 0; margin-left: 18rpx; }
	.user-name { display: flex; align-items: center; color: #12342F; font-size: 28rpx; font-weight: 900; }
	.user-name text:first-child { max-width: 220rpx; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
	.me-tag { margin-left: 10rpx; padding: 4rpx 10rpx; border-radius: 999rpx; background: linear-gradient(135deg, #35D6A6, #4FB7FF); color: #FFFFFF; font-size: 18rpx; }
	.stealth-tag { margin-left: 10rpx; padding: 4rpx 10rpx; border-radius: 999rpx; background: #EEF2FF; color: #7C3AED; font-size: 18rpx; }
	.user-meta { margin-top: 8rpx; display: flex; flex-wrap: wrap; gap: 10rpx; color: #6B817D; font-size: 22rpx; font-weight: 700; }
	.hunt-btn { width: 132rpx; height: 62rpx; line-height: 62rpx; border-radius: 999rpx; text-align: center; background: linear-gradient(135deg, #FF7A59, #FFB84D); color: #FFFFFF; font-size: 22rpx; font-weight: 900; box-shadow: 0 14rpx 28rpx rgba(255,122,89,0.2); flex-shrink: 0; }
	.hunt-btn.disabled { background: rgba(18,52,47,0.08); color: #9AA9A5; box-shadow: none; }
	.load-more { margin-top: 28rpx; height: 66rpx; line-height: 66rpx; text-align: center; border-radius: 999rpx; background: rgba(255,255,255,0.72); color: #22B889; font-size: 24rpx; font-weight: 900; box-shadow: 0 12rpx 26rpx rgba(53,214,166,0.1); }
	.bottom-space { height: 70rpx; }
</style>
