<template>
	<view class="want-page">
		<view class="fixed-header" :style="{ paddingTop: statusBarTop + 'px' }">
			<view class="nav-row">
				<view class="back" @tap="back"><uni-icons type="left" size="22" color="#15362f"></uni-icons></view>
				<view class="title-wrap">
					<view class="title">求购广场</view>
					<view class="subtitle">看看同学们正在找什么</view>
				</view>
			</view>
			<view class="search-bar">
				<uni-icons type="search" size="19" color="#8d9693"></uni-icons>
				<input
					v-model.trim="keyword"
					class="search-input"
					type="text"
					confirm-type="search"
					placeholder="按标题搜索求购"
					placeholder-class="search-placeholder"
					@confirm="handleSearch"
				/>
				<view class="search-button" @tap="handleSearch">搜索</view>
			</view>
			<view class="sort-row">
				<view class="sort-item" :class="{ active: sortType == item.key }" v-for="item in sortList" :key="item.key" @tap="changeSort(item.key)">
					{{item.name}}
				</view>
			</view>
			<scroll-view class="category-scroll" scroll-x :show-scrollbar="false">
				<view class="category-inner">
					<view
						class="category-item"
						:class="{ active: categoryIndex == index }"
						v-for="(item,index) in categoryOptions"
						:key="item.key"
						@tap="changeCategory(index)"
					>{{item.name}}</view>
				</view>
			</scroll-view>
		</view>

		<scroll-view
			class="want-scroll"
			scroll-y
			:style="{ paddingTop: headerHeight + 'px' }"
			:show-scrollbar="false"
			@scrolltolower="loadMore"
		>
			<view class="scroll-content">
				<view class="goods-grid" v-if="wantList.length">
					<view class="waterfall-column" v-for="(column,columnIndex) in waterfallColumns" :key="columnIndex">
						<view class="goods-card" v-for="item in column" :key="item.id" @tap="goDetail(item)">
							<view class="goods-image-box" :style="{ height: getImageHeight(item) + 'rpx' }">
								<image
									v-if="item.pic"
									class="goods-image"
									:src="item.pic"
									mode="aspectFill"
									:data-want-id="item.id"
									@load="onImageLoad"
								></image>
								<view v-else class="no-image">暂无图片</view>
								<view class="distance-tag">{{item.regionName}}</view>
							</view>
							<view class="goods-info">
								<view class="goods-title">{{item.text}}</view>
								<view class="goods-tags">
									<text v-if="item.category">{{item.category}}</text>
									<text>求购</text>
								</view>
								<view class="price-row">
									<view class="current-price"><text>预算 ¥</text>{{item.price}}</view>
								</view>
								<view class="seller-row">
									<image class="seller-avatar" :src="item.icon" mode="aspectFill"></image>
									<text class="seller-name">{{item.shopName}}</text>
									<view class="want-count">
										<uni-icons type="eye" size="16" color="#a5aeab"></uni-icons>
										<text>{{item.browseCount}}</text>
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>

				<view class="empty-state" v-else-if="!loading">
					<uni-icons type="search" size="38" color="#b8c2be"></uni-icons>
					<view>没有找到相关求购</view>
					<text>换个关键词试试吧</text>
				</view>
				<view class="load-more" v-if="loading">加载中...</view>
				<view class="load-more" v-else-if="wantList.length && pageNum >= totalPages">没有更多了</view>
				<view class="bottom-space"></view>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	import { pageFishWants, listFishCategories } from '@/common/fishMarketApi.js'

	export default {
		data() {
			return {
				statusBarTop: 24,
				keyword: '',
				sortType: 'latest',
				sortList: [
					{ key: 'latest', name: '最新' },
					{ key: 'hot', name: '热门' },
					{ key: 'priceAsc', name: '预算低到高' },
					{ key: 'priceDesc', name: '预算高到低' }
				],
				categoryIndex: 0,
				categoryList: [],
				wantList: [],
				pageNum: 1,
				pageSize: 10,
				totalPages: 1,
				loading: false,
				defaultCover: '/static/images/img/songshu.png'
			}
		},
		computed: {
			headerHeight() {
				return this.statusBarTop + uni.upx2px(302)
			},
			categoryOptions() {
				return [{ id: '', name: '全部', key: 'all' }].concat(this.categoryList.map(item => ({
					...item,
					key: item.id || item.name
				})))
			},
			waterfallColumns() {
				const columns = [[], []]
				const columnHeights = [0, 0]
				this.wantList.forEach(item => {
					const targetColumn = columnHeights[0] <= columnHeights[1] ? 0 : 1
					columns[targetColumn].push(item)
					columnHeights[targetColumn] += this.getImageHeight(item) + 190
				})
				return columns
			}
		},
		onLoad() {
			if (uni.getMenuButtonBoundingClientRect) {
				this.statusBarTop = uni.getMenuButtonBoundingClientRect().top || this.statusBarTop
			}
			this.loadCategories()
			this.reload()
		},
		methods: {
			back() {
				uni.navigateBack()
			},
			handleSearch() {
				uni.hideKeyboard()
				this.reload()
			},
			changeSort(key) {
				if (this.sortType == key) return
				this.sortType = key
				this.reload()
			},
			changeCategory(index) {
				if (this.categoryIndex == index) return
				this.categoryIndex = index
				this.reload()
			},
			loadCategories() {
				const area = this.getArea()
				listFishCategories(area.id || '').then(list => {
					this.categoryList = Array.isArray(list) ? list : []
				}).catch(() => {})
			},
			reload() {
				this.pageNum = 1
				this.totalPages = 1
				this.wantList = []
				this.loadWants()
			},
			loadMore() {
				if (this.loading || this.pageNum >= this.totalPages) return
				this.pageNum += 1
				this.loadWants()
			},
			loadWants() {
				if (this.loading) return
				this.loading = true
				const area = this.getArea()
				const category = this.categoryOptions[this.categoryIndex] || {}
				pageFishWants({
					pageNum: this.pageNum,
					pageSize: this.pageSize,
					titleKeyword: this.keyword,
					sortType: this.sortType,
					regionId: area.id || '',
					categoryId: category.id || '',
					status: 1,
					auditStatus: 1
				}).then(page => {
					const records = this.normalizeRecords(page && (page.records || page.content))
					this.totalPages = Number(page && (page.pages || page.totalPages)) || 1
					this.wantList = this.pageNum == 1 ? records : this.wantList.concat(records)
				}).finally(() => {
					this.loading = false
				})
			},
			normalizeRecords(records) {
				const area = this.getArea()
				const fallbackRegionName = area.title || area.name || uni.getStorageSync('schoolName') || '本校'
				return (Array.isArray(records) ? records : []).map(item => {
					const images = this.parseJsonList(item.images)
					const imageList = item.imageList && item.imageList.length ? item.imageList : images
					return {
						raw: item,
						id: item.id,
						pic: item.coverImage || imageList[0] || '',
						text: item.title || '',
						price: item.expectedPrice || 0,
						icon: item.userAvatar || this.defaultCover,
						shopName: item.userName || '校园同学',
						regionName: item.regionName || item.schoolName || item.areaName || fallbackRegionName,
						category: item.categoryName || '',
						browseCount: item.browseCount || 0
					}
				})
			},
			parseJsonList(value) {
				if (!value) return []
				if (Array.isArray(value)) return value
				try {
					const parsed = JSON.parse(value)
					return Array.isArray(parsed) ? parsed : []
				} catch (e) {
					return []
				}
			},
			getArea() {
				const area = uni.getStorageSync('area')
				if (!area) return {}
				if (typeof area === 'string') {
					try {
						return JSON.parse(area)
					} catch (e) {
						return {}
					}
				}
				return area
			},
			getImageHeight(item) {
				return Number(item.imageHeight) || 280
			},
			onImageLoad(event) {
				const detail = event && event.detail ? event.detail : {}
				const dataset = event && event.currentTarget ? event.currentTarget.dataset || {} : {}
				const wantId = String(dataset.wantId || '')
				const item = this.wantList.find(want => String(want.id) === wantId)
				const width = Number(detail.width)
				const height = Number(detail.height)
				if (!item || !width || !height) return
				const adaptedHeight = Math.max(220, Math.min(430, Math.round(342 * height / width)))
				if (item.imageHeight !== adaptedHeight) {
					this.$set(item, 'imageHeight', adaptedHeight)
				}
			},
			goDetail(item) {
				if (!item || !item.id) return
				uni.navigateTo({
					url: '/package2/IdleTrad/detail?type=want&id=' + item.id
				})
			}
		}
	}
</script>

<style lang="scss">
	page {
		width: 100%;
		height: 100%;
		background: #f7f9f7;
		color: #17241f;
	}

	.want-page {
		width: 100%;
		height: 100%;
		overflow: hidden;
		background: linear-gradient(180deg, rgba(224, 250, 241, 0.78) 0, rgba(247, 249, 247, 0) 340rpx), #f7f9f7;
	}

	.fixed-header {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		z-index: 20;
		padding-left: 26rpx;
		padding-right: 26rpx;
		padding-bottom: 18rpx;
		background: linear-gradient(180deg, #e4faf1 0%, rgba(247, 249, 247, 0.96) 100%);
		box-shadow: 0 8rpx 24rpx rgba(22, 85, 66, 0.06);
	}

	.nav-row {
		height: 72rpx;
		display: flex;
		align-items: center;
	}

	.back {
		width: 64rpx;
		height: 64rpx;
		display: flex;
		align-items: center;
	}

	.title-wrap {
		flex: 1;
	}

	.title {
		color: #17362f;
		font-size: 34rpx;
		font-weight: 900;
	}

	.subtitle {
		margin-top: 2rpx;
		color: #739187;
		font-size: 20rpx;
	}

	.search-bar {
		height: 68rpx;
		margin-top: 10rpx;
		display: flex;
		align-items: center;
		padding: 0 16rpx 0 22rpx;
		border-radius: 38rpx;
		background: #fff;
		box-shadow: 0 10rpx 30rpx rgba(31, 73, 58, 0.08);
	}

	.search-input {
		flex: 1;
		height: 68rpx;
		margin-left: 10rpx;
		font-size: 25rpx;
		color: #21342e;
	}

	.search-placeholder {
		color: #9ba7a3;
	}

	.search-button {
		min-width: 88rpx;
		height: 52rpx;
		line-height: 52rpx;
		text-align: center;
		border-radius: 28rpx;
		color: #fff;
		font-size: 23rpx;
		font-weight: 800;
		background: linear-gradient(135deg, #37c990, #19af7e);
	}

	.sort-row {
		margin-top: 18rpx;
		display: flex;
		gap: 14rpx;
		overflow: hidden;
	}

	.sort-item {
		padding: 12rpx 18rpx;
		border-radius: 999rpx;
		background: rgba(255, 255, 255, 0.72);
		color: #62736e;
		font-size: 23rpx;
		font-weight: 800;
		white-space: nowrap;
	}

	.sort-item.active {
		color: #15362f;
		background: #c8f7e2;
	}

	.category-scroll {
		margin-top: 16rpx;
		width: 100%;
		white-space: nowrap;
	}

	.category-inner {
		display: inline-flex;
		align-items: center;
		gap: 14rpx;
		padding-right: 10rpx;
	}

	.category-item {
		padding: 12rpx 22rpx;
		border-radius: 999rpx;
		background: rgba(255, 255, 255, .76);
		color: #6f817c;
		font-size: 23rpx;
		font-weight: 800;
	}

	.category-item.active {
		background: linear-gradient(135deg, #37c990, #19af7e);
		color: #fff;
		box-shadow: 0 8rpx 18rpx rgba(25, 175, 126, .16);
	}

	.want-scroll {
		height: 100%;
		box-sizing: border-box;
	}

	.scroll-content {
		padding: 24rpx 24rpx 0;
		box-sizing: border-box;
	}

	.goods-grid {
		display: flex;
		gap: 18rpx;
		align-items: flex-start;
	}

	.waterfall-column {
		flex: 1;
		min-width: 0;
	}

	.goods-card {
		overflow: hidden;
		margin-bottom: 18rpx;
		border-radius: 26rpx;
		background: #fff;
		box-shadow: 0 10rpx 28rpx rgba(20, 60, 48, 0.06);
	}

	.goods-image-box {
		position: relative;
		width: 100%;
		min-height: 220rpx;
		background: #edf4f1;
	}

	.goods-image {
		width: 100%;
		height: 100%;
		display: block;
	}

	.no-image {
		width: 100%;
		height: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
		color: #92a39d;
		background: linear-gradient(135deg, #eef6f2, #f8fbf9);
		font-size: 25rpx;
		font-weight: 900;
	}

	.distance-tag {
		position: absolute;
		left: 14rpx;
		bottom: 14rpx;
		padding: 6rpx 14rpx;
		border-radius: 20rpx;
		color: #fff;
		background: rgba(17, 39, 32, 0.58);
		font-size: 20rpx;
		font-weight: 700;
	}

	.goods-info {
		padding: 18rpx 18rpx 20rpx;
	}

	.goods-title {
		color: #17241f;
		font-size: 27rpx;
		line-height: 38rpx;
		font-weight: 800;
	}

	.goods-tags {
		margin-top: 12rpx;
		display: flex;
		flex-wrap: wrap;
		gap: 8rpx;
	}

	.goods-tags text {
		padding: 5rpx 12rpx;
		border-radius: 14rpx;
		color: #3bb68a;
		background: #e8fbf3;
		font-size: 19rpx;
		font-weight: 800;
	}

	.price-row {
		margin-top: 14rpx;
		display: flex;
		align-items: baseline;
	}

	.current-price {
		color: #ef4c3f;
		font-size: 32rpx;
		font-weight: 900;
	}

	.current-price text {
		font-size: 21rpx;
	}

	.seller-row {
		margin-top: 14rpx;
		display: flex;
		align-items: center;
		color: #86928e;
		font-size: 21rpx;
	}

	.seller-avatar {
		width: 34rpx;
		height: 34rpx;
		margin-right: 8rpx;
		border-radius: 50%;
		background: #edf4f1;
	}

	.seller-name {
		flex: 1;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.want-count {
		display: flex;
		align-items: center;
		gap: 4rpx;
	}

	.empty-state,
	.load-more {
		padding: 90rpx 0;
		color: #9aa8a4;
		text-align: center;
		font-size: 24rpx;
	}

	.empty-state view {
		margin-top: 18rpx;
		color: #65736f;
		font-size: 27rpx;
		font-weight: 900;
	}

	.empty-state text {
		display: block;
		margin-top: 8rpx;
		font-size: 22rpx;
	}

	.bottom-space {
		height: 80rpx;
	}
</style>
