Files
hfb_jysh/frontend/src/features/mobile/MobileHomePage.tsx
T

829 lines
25 KiB
TypeScript

import { useMemo, useState, type ReactNode } from 'react'
import { useQuery } from '@tanstack/react-query'
import {
Button,
Empty,
ErrorBlock,
Popup,
PullToRefresh,
SearchBar,
Skeleton,
Swiper,
Tag,
} from 'antd-mobile'
import {
AddCircleOutline,
BillOutline,
CheckShieldOutline,
DownOutline,
FlagOutline,
GiftOutline,
PhoneFill,
RightOutline,
SearchOutline,
ShopbagOutline,
SmileOutline,
} from 'antd-mobile-icons'
import { Link, useNavigate } from 'react-router-dom'
import { BrandLogo } from '@/components/BrandLogo'
import {
fallbackBanners,
useHomeConfig,
type HomeBannerItem,
type HomeEntryConfig,
} from '@/features/home/api'
import { useInfiniteListings } from '@/features/listings/api'
import {
banRecordText,
faceOwnerText,
gameNameChangeText,
listingRatioText,
listingRentalDays,
listingResources,
onlineTimeText,
resourceBadgeText,
} from '@/features/listings/labels'
import {
awmRanges,
coinRanges,
dailyLossRanges,
depositRanges,
emptyListingFilters,
fireLevelRanges,
priceRanges,
ratioRanges,
secretKdRanges,
totalRanges,
type ListingFilterState,
} from '@/features/listings/ListingFilterPanel'
import { fetchListingPublishOptions } from '@/features/seller/options'
import { formatCoinM } from '@/shared/utils/format'
import type { Listing } from '@/shared/api/types'
const sortOptions = [
{ value: '', label: '综合推荐' },
{ value: 'published', label: '最新发布' },
{ value: 'ratioDesc', label: '比例最高' },
{ value: 'ratioAsc', label: '比例最低' },
{ value: 'priceAsc', label: '价格最低' },
{ value: 'priceDesc', label: '价格最高' },
{ value: 'coinDesc', label: '哈夫币最多' },
{ value: 'coinAsc', label: '哈夫币最少' },
{ value: 'awmDesc', label: 'AWM最多' },
{ value: 'awmAsc', label: 'AWM最少' },
]
const zoneTabs = [
{ key: 'all', label: '全部' },
{ key: 'premium', label: '极品' },
{ key: 'sale', label: '特惠' },
{ key: 'gift', label: '赠送' },
{ key: 'night', label: '夜间' },
{ key: 'password', label: '账密' },
{ key: 'highCoin', label: '高币' },
]
const insuranceOptions = ['2*1', '2*2', '2*3', '3*3']
const levelOptions = ['4级', '5级', '6级', '7级']
const loginOptions = ['扫码', '账号密码']
type MultiFilterKey =
'insurance' | 'stamina' | 'load' | 'loginMethod' | 'ranks' | 'regions' | 'skinNames'
type RangeFilterKey =
| 'coinKey'
| 'priceKey'
| 'ratioKey'
| 'awmKey'
| 'depositKey'
| 'totalKey'
| 'fireLevelKey'
| 'dailyLossKey'
| 'secretKdKey'
function money(cents: number) {
return `¥${(cents / 100).toFixed(2)}`
}
function assetText(item: Listing, key: string) {
const value = item.asset_summary?.[key]
if (value == null || value === '' || typeof value === 'object') return ''
return String(value)
}
function MobileChipGroup({
label,
options,
selected,
onToggle,
}: {
label: string
options: string[]
selected: string[]
onToggle: (option: string) => void
}) {
if (options.length === 0) return null
return (
<div className="mobile-filter-group">
<span className="mobile-filter-group__label">{label}</span>
<div className="mobile-filter-chips">
{options.map(option => (
<button
key={option}
type="button"
className={`mobile-filter-chip${selected.includes(option) ? ' is-active' : ''}`}
onClick={() => onToggle(option)}
>
{option}
</button>
))}
</div>
</div>
)
}
function MobileRangeGroup({
label,
options,
activeKey,
onSelect,
}: {
label: string
options: { key: string; label: string }[]
activeKey?: string
onSelect: (key: string) => void
}) {
return (
<div className="mobile-filter-group">
<span className="mobile-filter-group__label">{label}</span>
<div className="mobile-filter-chips">
{options.map(option => (
<button
key={option.key}
type="button"
className={`mobile-filter-chip${activeKey === option.key ? ' is-active' : ''}`}
onClick={() => onSelect(option.key)}
>
{option.label}
</button>
))}
</div>
</div>
)
}
function MobileListingCard({ item }: { item: Listing }) {
const [coverFailed, setCoverFailed] = useState(false)
const online = onlineTimeText(item.asset_summary)
const rentalDays = listingRentalDays(item)
const faceOwner = faceOwnerText(item.asset_summary)
const banRecord = banRecordText(item.asset_summary)
const gameNameChange = gameNameChangeText(item.asset_summary)
const ratio = listingRatioText(item)
const resources = listingResources(item.asset_summary).slice(0, 2)
const specs = [
{ label: '保险', value: assetText(item, 'season_insurance') },
{ label: '体力', value: assetText(item, 'stamina_level') },
{ label: '负重', value: assetText(item, 'load_level') },
{ label: '区服', value: item.server_region },
{ label: '租期', value: rentalDays ? `${rentalDays}天` : '' },
{ label: '在线', value: online },
{ label: '人脸', value: faceOwner },
{ label: '封禁', value: banRecord },
{ label: '改名', value: gameNameChange },
]
.filter(spec => spec.value)
.slice(0, 5)
return (
<Link to={`/m/listings/${item.id}`} className="mobile-listing-card">
<div className="mobile-listing-card__cover">
{item.cover_url && !coverFailed ? (
<img
src={item.cover_url}
alt={item.title}
loading="lazy"
onError={() => setCoverFailed(true)}
/>
) : (
<div className="mobile-listing-card__fallback">
<BrandLogo height={36} variant="seal" />
<span>实拍图整理中</span>
</div>
)}
{item.is_premium ||
item.owner_is_quality_owner ||
item.compensation_plan === 'insurance' ? (
<div className="mobile-listing-card__badges">
{item.owner_is_quality_owner ? <span>优质号主</span> : null}
{item.is_premium ? <span className="is-premium">极品</span> : null}
{item.compensation_plan === 'insurance' ? (
<span className="is-insurance">保险</span>
) : null}
</div>
) : null}
</div>
<div className="mobile-listing-card__body">
<div className="mobile-listing-card__top">
<span className="mobile-listing-card__no">{item.listing_no}</span>
<Tag color={item.in_transaction ? 'default' : 'success'} fill="outline">
{item.in_transaction ? '租赁中' : '可租'}
</Tag>
</div>
<h3>{item.title}</h3>
<div className="mobile-listing-card__core">
<strong>{formatCoinM(item.haf_coin_amount)}</strong>
{ratio ? <span>1:{ratio}</span> : null}
</div>
<div className="mobile-listing-card__tags">
{specs.map(spec => (
<span key={`${spec.label}-${spec.value}`}>
<em>{spec.label}</em>
{spec.value}
</span>
))}
{resources.map(resource => (
<span key={resource.label}>
<em>{resource.label}</em>
{resource.quantity}
<i>{resourceBadgeText(resource, 'compact')}</i>
</span>
))}
</div>
<div className="mobile-listing-card__bottom">
<div>
<strong>{money(item.price_cent)}</strong>
<small>押金 {money(item.deposit_amount_cent)}</small>
</div>
<span className="mobile-listing-card__cta">
立即租 <RightOutline />
</span>
</div>
</div>
</Link>
)
}
function QuickService({
to,
icon,
label,
hint,
onClick,
}: {
to?: string
icon: ReactNode
label: string
hint: string
onClick?: () => void
}) {
const content = (
<>
<span className="mobile-quick-service__icon">{icon}</span>
<strong>{label}</strong>
<small>{hint}</small>
</>
)
if (to) {
return (
<Link to={to} className="mobile-quick-service">
{content}
</Link>
)
}
return (
<button type="button" className="mobile-quick-service" onClick={onClick}>
{content}
</button>
)
}
export function MobileHomePage() {
const navigate = useNavigate()
const [keyword, setKeyword] = useState('')
const [searchValue, setSearchValue] = useState('')
const [zone, setZone] = useState('all')
const [sort, setSort] = useState('')
const [filters, setFilters] = useState<ListingFilterState>(emptyListingFilters)
const [draft, setDraft] = useState<ListingFilterState>(emptyListingFilters)
const [filterOpen, setFilterOpen] = useState(false)
const [sortOpen, setSortOpen] = useState(false)
const [entryPreview, setEntryPreview] = useState<HomeEntryConfig | null>(null)
const homeConfig = useHomeConfig()
const publishOptions = useQuery({
queryKey: ['listing-publish-options'],
queryFn: fetchListingPublishOptions,
staleTime: 300_000,
})
const coin = coinRanges.find(range => range.key === filters.coinKey)
const price = priceRanges.find(range => range.key === filters.priceKey)
const ratio = ratioRanges.find(range => range.key === filters.ratioKey)
const awm = awmRanges.find(range => range.key === filters.awmKey)
const deposit = depositRanges.find(range => range.key === filters.depositKey)
const total = totalRanges.find(range => range.key === filters.totalKey)
const fireLevel = fireLevelRanges.find(range => range.key === filters.fireLevelKey)
const dailyLoss = dailyLossRanges.find(range => range.key === filters.dailyLossKey)
const secretKd = secretKdRanges.find(range => range.key === filters.secretKdKey)
const listingQuery = useMemo(
() => ({
page_size: 10,
keyword,
zone: zone === 'all' ? '' : zone,
sort,
min_coin: coin?.min,
max_coin: coin?.max,
min_price: price?.min,
max_price: price?.max,
min_ratio: ratio?.min,
max_ratio: ratio?.max,
min_deposit: deposit?.min,
max_deposit: deposit?.max,
min_total: total?.min,
max_total: total?.max,
min_fire_level: fireLevel?.min,
max_fire_level: fireLevel?.max,
min_daily_loss: dailyLoss?.min,
max_daily_loss: dailyLoss?.max,
min_secret_kd: secretKd?.min,
max_secret_kd: secretKd?.max,
resource_awmAmmo_min: awm?.min,
resource_awmAmmo_max: awm?.max,
insurance: filters.insurance.join(','),
stamina: filters.stamina.join(','),
load: filters.load.join(','),
login_method: filters.loginMethod.join(','),
rank: filters.ranks.join(','),
region: filters.regions.join(','),
skin_name: filters.skinNames.join(','),
}),
[
awm,
coin,
dailyLoss,
deposit,
filters,
fireLevel,
keyword,
price,
ratio,
secretKd,
sort,
total,
zone,
]
)
const listings = useInfiniteListings(listingQuery)
const items = listings.data?.pages.flatMap(page => page.items) ?? []
const totalListings = listings.data?.pages[0]?.total ?? 0
const zoneCounts = listings.data?.pages[0]?.zone_counts ?? {}
const quickSkinGroups = (publishOptions.data?.skin_groups ?? []).filter(group =>
['melee', 'operatorRed'].includes(group.key)
)
const rankOptions = publishOptions.data?.rank_options ?? []
const regionOptions = publishOptions.data?.region_options ?? []
const applyFilter = () => {
setFilters(draft)
setFilterOpen(false)
}
const resetFilters = () => {
setDraft(emptyListingFilters)
setFilters(emptyListingFilters)
setKeyword('')
setSearchValue('')
setZone('all')
setSort('')
}
const toggleDraft = (key: MultiFilterKey, option: string) => {
const current = draft[key]
setDraft({
...draft,
[key]: current.includes(option)
? current.filter(item => item !== option)
: [...current, option],
})
}
const toggleRange = (key: RangeFilterKey, nextKey: string) => {
setDraft({ ...draft, [key]: draft[key] === nextKey ? undefined : nextKey })
}
const activeCount =
filters.insurance.length +
filters.stamina.length +
filters.load.length +
filters.loginMethod.length +
filters.ranks.length +
filters.regions.length +
filters.skinNames.length +
[
filters.coinKey,
filters.priceKey,
filters.ratioKey,
filters.awmKey,
filters.depositKey,
filters.totalKey,
filters.fireLevelKey,
filters.dailyLossKey,
filters.secretKdKey,
].filter(Boolean).length
const sortLabel = sortOptions.find(option => option.value === sort)?.label ?? '综合排序'
const banners = (homeConfig.data?.banners ?? fallbackBanners)
.filter(banner => banner.enabled !== false)
.slice(0, 4)
const runBannerAction = (banner: HomeBannerItem) => {
const action = banner.mobile?.action
if (!action || action.type === 'none' || !action.target) return
if (action.type === 'route') {
navigate(action.target)
return
}
window.open(action.target, action.open_new_tab ? '_blank' : '_self')
}
const submitSearch = (value: string) => {
setKeyword(value.trim())
void listings.refetch()
}
const scrollToListings = () => {
document.getElementById('listings')?.scrollIntoView({ behavior: 'smooth', block: 'start' })
}
return (
<div className="mobile-home">
<section className="mobile-home-search">
<div className="mobile-home-search__heading">
<div>
<span>解忧柜选</span>
<strong>今天想租什么账号?</strong>
</div>
<Link to="/m/announcements">规则</Link>
</div>
<SearchBar
className="mobile-search"
value={searchValue}
onChange={setSearchValue}
onSearch={submitSearch}
placeholder="搜编号 / 区服 / 段位 / 资产"
searchIcon={<SearchOutline />}
/>
</section>
<section className="mobile-trust">
<span>
<CheckShieldOutline />
<em>实名审核</em>
</span>
<span>
<SmileOutline />
<em>找回包赔</em>
</span>
<span>
<PhoneFill />
<em>客服护航</em>
</span>
<span>
<BillOutline />
<em>账单透明</em>
</span>
</section>
<section className="mobile-banner">
<Swiper autoplay loop indicatorProps={{ color: 'white' }}>
{banners.map((banner, index) => {
const imageURL = banner.mobile?.image_url || banner.image_url
return (
<Swiper.Item key={`${banner.title || 'banner'}-${index}`}>
<button
type="button"
className={`mobile-banner__item tone-${banner.tone || 'green'}`}
onClick={() => runBannerAction(banner)}
>
{imageURL ? (
<img src={imageURL} alt={banner.mobile?.alt || banner.title || ''} />
) : (
<span className="mobile-banner__copy">
{banner.badge ? <em>{banner.badge}</em> : null}
<strong>{banner.title || '平台担保交易'}</strong>
<small>{banner.pill || banner.eyebrow || '实名审核 · 交接留痕'}</small>
</span>
)}
</button>
</Swiper.Item>
)
})}
</Swiper>
</section>
<section className="mobile-quick-services" aria-label="快捷服务">
<QuickService
icon={<ShopbagOutline />}
label="我要租号"
hint="海量账号"
onClick={scrollToListings}
/>
<QuickService
to="/m/seller/listings/new"
icon={<AddCircleOutline />}
label="我要出号"
hint="闲置账号出租"
/>
<QuickService to="/m/crash" icon={<FlagOutline />} label="撞车商城" hint="装备与现货" />
<QuickService
icon={<GiftOutline />}
label={homeConfig.data?.aw_recycle.title || 'AW回收'}
hint="查看回收说明"
onClick={() => setEntryPreview(homeConfig.data?.aw_recycle ?? null)}
/>
<QuickService to="/m/messages" icon={<PhoneFill />} label="联系客服" hint="问题留痕" />
</section>
<div id="listings" className="mobile-market">
<div className="mobile-market__head">
<div>
<span>放心购</span>
<strong>严选账号</strong>
</div>
<small>共 {totalListings} 个可租账号</small>
</div>
<div className="mobile-zone-tabs">
{zoneTabs.map(tab => (
<button
key={tab.key}
type="button"
className={zone === tab.key ? 'is-active' : ''}
onClick={() => setZone(tab.key)}
>
{tab.label}
{typeof zoneCounts[tab.key] === 'number' ? <em>{zoneCounts[tab.key]}</em> : null}
</button>
))}
</div>
<div className="mobile-list-toolbar">
<button type="button" onClick={() => setSortOpen(true)}>
{sortLabel} <DownOutline />
</button>
<button
type="button"
onClick={() => {
setDraft(filters)
setFilterOpen(true)
}}
>
筛选{activeCount > 0 ? ` ${activeCount}` : ''}
</button>
</div>
{listings.isError ? (
<div className="mobile-error">
<ErrorBlock
status="disconnected"
title="商品没有加载出来"
description="后端服务可能暂时不可用,你的账号和订单不受影响。"
/>
<Button color="primary" size="small" onClick={() => void listings.refetch()}>
重试
</Button>
</div>
) : null}
<PullToRefresh onRefresh={() => listings.refetch().then(() => undefined)}>
{listings.isPending ? (
<div className="mobile-skeleton-list">
{Array.from({ length: 3 }).map((_, index) => (
<div className="mobile-skeleton-card" key={index}>
<Skeleton animated className="mobile-skeleton-cover" />
<Skeleton.Paragraph lineCount={4} animated />
</div>
))}
</div>
) : items.length ? (
<>
<div className="mobile-listing-list">
{items.map(item => (
<MobileListingCard item={item} key={item.id} />
))}
</div>
<div className="mobile-list-more">
{listings.hasNextPage ? (
<Button
block
fill="outline"
loading={listings.isFetchingNextPage}
onClick={() => void listings.fetchNextPage()}
>
加载更多账号
</Button>
) : (
<span>已经看到全部账号</span>
)}
</div>
</>
) : (
<div className="mobile-empty">
<Empty description="还没有符合条件的商品" />
<Button size="small" color="primary" onClick={resetFilters}>
查看全部
</Button>
</div>
)}
</PullToRefresh>
</div>
<section className="mobile-rules">
<span className="mobile-eyebrow">RULES, IN PLAIN WORDS</span>
<h2>先把规则说明白</h2>
<p>押金、租金、额外消耗和退款规则都会在订单里逐项列出。</p>
</section>
<Popup
visible={filterOpen}
onMaskClick={() => setFilterOpen(false)}
bodyStyle={{
height: '82vh',
overflowY: 'auto',
borderTopLeftRadius: 16,
borderTopRightRadius: 16,
}}
>
<div className="mobile-filter-sheet">
<div className="mobile-filter-sheet__head">
<strong>筛选条件</strong>
<button type="button" onClick={() => setDraft(emptyListingFilters)}>
重置
</button>
</div>
<MobileRangeGroup
label="哈夫币"
options={coinRanges}
activeKey={draft.coinKey}
onSelect={key => toggleRange('coinKey', key)}
/>
<MobileRangeGroup
label="租金"
options={priceRanges}
activeKey={draft.priceKey}
onSelect={key => toggleRange('priceKey', key)}
/>
<MobileRangeGroup
label="比例"
options={ratioRanges}
activeKey={draft.ratioKey}
onSelect={key => toggleRange('ratioKey', key)}
/>
<MobileRangeGroup
label="AWM"
options={awmRanges}
activeKey={draft.awmKey}
onSelect={key => toggleRange('awmKey', key)}
/>
<MobileRangeGroup
label="押金"
options={depositRanges}
activeKey={draft.depositKey}
onSelect={key => toggleRange('depositKey', key)}
/>
<MobileRangeGroup
label="合计金额"
options={totalRanges}
activeKey={draft.totalKey}
onSelect={key => toggleRange('totalKey', key)}
/>
<MobileRangeGroup
label="等级"
options={fireLevelRanges}
activeKey={draft.fireLevelKey}
onSelect={key => toggleRange('fireLevelKey', key)}
/>
<MobileRangeGroup
label="日消耗"
options={dailyLossRanges}
activeKey={draft.dailyLossKey}
onSelect={key => toggleRange('dailyLossKey', key)}
/>
<MobileRangeGroup
label="绝密KD"
options={secretKdRanges}
activeKey={draft.secretKdKey}
onSelect={key => toggleRange('secretKdKey', key)}
/>
<MobileChipGroup
label="保险"
options={insuranceOptions}
selected={draft.insurance}
onToggle={option => toggleDraft('insurance', option)}
/>
<MobileChipGroup
label="体力"
options={levelOptions}
selected={draft.stamina}
onToggle={option => toggleDraft('stamina', option)}
/>
<MobileChipGroup
label="负重"
options={levelOptions}
selected={draft.load}
onToggle={option => toggleDraft('load', option)}
/>
<MobileChipGroup
label="登录"
options={loginOptions}
selected={draft.loginMethod}
onToggle={option => toggleDraft('loginMethod', option)}
/>
<MobileChipGroup
label="段位"
options={rankOptions}
selected={draft.ranks}
onToggle={option => toggleDraft('ranks', option)}
/>
<MobileChipGroup
label="IP地区"
options={regionOptions}
selected={draft.regions}
onToggle={option => toggleDraft('regions', option)}
/>
{quickSkinGroups.map(group => (
<MobileChipGroup
key={group.key}
label={group.title}
options={group.options}
selected={draft.skinNames}
onToggle={option => toggleDraft('skinNames', option)}
/>
))}
<div className="mobile-filter-sheet__actions">
<Button block onClick={() => setFilterOpen(false)}>
取消
</Button>
<Button block color="primary" onClick={applyFilter}>
确定
</Button>
</div>
</div>
</Popup>
<Popup
visible={sortOpen}
onMaskClick={() => setSortOpen(false)}
bodyStyle={{ borderTopLeftRadius: 16, borderTopRightRadius: 16 }}
>
<div className="mobile-sort-sheet">
<strong>排序方式</strong>
{sortOptions.map(option => (
<button
key={option.value}
type="button"
className={sort === option.value ? 'is-active' : ''}
onClick={() => {
setSort(option.value)
setSortOpen(false)
}}
>
{option.label}
</button>
))}
</div>
</Popup>
<Popup
visible={Boolean(entryPreview)}
onMaskClick={() => setEntryPreview(null)}
bodyStyle={{ borderTopLeftRadius: 16, borderTopRightRadius: 16 }}
>
{entryPreview ? (
<div className="mobile-entry-preview">
<strong>{entryPreview.title}</strong>
<small>{entryPreview.subtitle}</small>
{entryPreview.image_url ? (
<img src={entryPreview.image_url} alt={entryPreview.title} />
) : (
<p>暂无更多说明</p>
)}
</div>
) : null}
</Popup>
</div>
)
}