<template>
	<view class="my-fish-page">
		<view class="header" :style="{ paddingTop: statusBarTop + 'px' }">
			<view class="back" @tap="back"><uni-icons type="left" size="22"></uni-icons></view>
			<view class="title">我的校园二手</view>
		</view>
		<view class="tabs">
			<view class="tab" :class="{ active: activeTab == item.key }" v-for="item in visibleTabs" :key="item.key" @tap="switchTab(item.key)">
				{{item.name}}
			</view>
			<view class="tab tab-more" @tap="showTabActions">展开</view>
		</view>
		<view class="search-bar" v-if="canManageCurrentTab">
			<uni-icons type="search" size="18" color="#8d9693"></uni-icons>
			<input
				v-model.trim="titleKeyword"
				class="search-input"
				confirm-type="search"
				placeholder="按标题搜索"
				@confirm="handleSearch"
			/>
			<view class="search-clear" v-if="titleKeyword" @tap="clearSearch">清空</view>
			<view class="search-btn" @tap="handleSearch">搜索</view>
		</view>
		<scroll-view scroll-y class="list" :class="{ 'list--with-search': canManageCurrentTab }" @scrolltolower="loadMore">
			<u-swipe-action v-if="canManageCurrentTab">
				<u-swipe-action-item
					v-for="(item,index) in list"
					:key="item.id"
					:name="index"
					:options="swipeOptions(item)"
					@click="handleSwipeAction"
				>
					<view class="card" @tap="openItem(item)">
						<image class="cover" :src="coverText(item)" mode="aspectFill"></image>
						<view class="main">
							<view class="name">{{nameText(item)}}</view>
							<!-- <view class="desc">{{descText(item)}}</view> -->
							<view class="meta">
								<text v-if="priceText(item)">¥{{priceText(item)}}</text>
								<text>{{item.createTime || item.lastBrowseTime || item.lastChatTime || ''}}</text>
							</view>
						</view>
						<view class="status" :class="{ 'status--off': isOffShelf(item) }">{{statusText(item)}}</view>
					</view>
				</u-swipe-action-item>
			</u-swipe-action>
			<block v-if="!canManageCurrentTab">
				<view class="card" v-for="item in list" :key="item.id" @tap="openItem(item)">
					<image class="cover" :src="coverText(item)" mode="aspectFill"></image>
					<view class="main">
						<view class="name">{{nameText(item)}}</view>
						<view class="desc">{{descText(item)}}</view>
						<view class="meta">
							<text v-if="priceText(item)">¥{{priceText(item)}}</text>
							<text>{{item.createTime || item.lastBrowseTime || item.lastChatTime || ''}}</text>
						</view>
					</view>
					<view
						class="status"
						:class="{ 'status--off': isOffShelf(item), 'status--action': activeTab == 'favorites' || activeTab == 'comments' }"
						@tap.stop="handleCardAction(item)"
					>{{statusText(item)}}</view>
				</view>
			</block>
			<view class="empty" v-if="!list.length && !loading">暂无数据</view>
			<view class="load-more" v-if="loading">加载中...</view>
			<view class="bottom-space"></view>
		</scroll-view>
	</view>
</template>

<script>
	import {
		pageMyFishGoods,
		pageMyFishWants,
		updateMyFishGoodsStatus,
		updateMyFishWantStatus,
		pageMyFishFavorites,
		pageMyFishComments,
		pageMyFishLikes,
		pageMyFishComplaints,
		toggleFishFavorite,
		deleteFishComment
	} from '@/common/fishMarketApi.js'

	export default {
		data() {
			return {
				statusBarTop: 24,
				activeTab: 'goods',
				list: [],
				pageNum: 1,
				pageSize: 10,
				totalPages: 1,
				loading: false,
				loadedOnce: false,
				titleKeyword: '',
				defaultCover: '/static/images/img/songshu.png',
				tabs: [
					{ key: 'goods', name: '我的发布' },
					{ key: 'wants', name: '我的求购' },
					{ key: 'favorites', name: '我的收藏' },
					{ key: 'comments', name: '我的评论' },
					{ key: 'likes', name: '我的点赞' },
					{ key: 'complaints', name: '我的举报' }
				]
			}
		},
		computed: {
			canManageCurrentTab() {
				return this.activeTab == 'goods' || this.activeTab == 'wants'
			},
			visibleTabs() {
				const firstTabs = this.tabs.slice(0, 4)
				if (firstTabs.some(item => item.key == this.activeTab)) return firstTabs
				const active = this.tabs.find(item => item.key == this.activeTab)
				return active ? this.tabs.slice(0, 3).concat(active) : firstTabs
			}
		},
		onLoad() {
			if (uni.getMenuButtonBoundingClientRect) {
				this.statusBarTop = uni.getMenuButtonBoundingClientRect().top || this.statusBarTop
			}
			this.load()
		},
		onShow() {
			if (this.loadedOnce) {
				this.reload()
			}
		},
		methods: {
			back() {
				uni.navigateBack()
			},
			showTabActions() {
				uni.showActionSheet({
					itemList: this.tabs.map(item => item.name),
					success: (res) => {
						const item = this.tabs[res.tapIndex]
						if (item) this.switchTab(item.key)
					}
				})
			},
			swipeOptions(item) {
				const offShelf = this.isOffShelf(item)
				return [{
					text: '编辑',
					style: {
						backgroundColor: '#24b979',
						color: '#fff',
						fontSize: '26rpx'
					}
				}, {
					text: offShelf ? '上架' : '下架',
					style: {
						backgroundColor: offShelf ? '#24b979' : '#ff9f2d',
						color: '#fff',
						fontSize: '26rpx'
					}
				}, {
					text: '删除',
					style: {
						backgroundColor: '#ef4c3f',
						color: '#fff',
						fontSize: '26rpx'
					}
				}]
			},
			handleSwipeAction(e) {
				const item = this.list[Number(e.name)]
				if (!item) return
				if (e.index == 0) {
					this.editItem(item)
					return
				}
				if (e.index == 1) {
					this.toggleShelf(item)
					return
				}
				this.deleteItem(item)
			},
			editItem(item) {
				if (!item || !item.id) return
				const type = this.activeTab == 'wants' ? 'want' : 'sell'
				uni.navigateTo({
					url: `/package1/tabbar/fishRelease?mode=edit&type=${type}&id=${item.id}`
				})
			},
			isOffShelf(item) {
				return Number(item.status) == 2 || Number(item.offShelf) == 1
			},
			updateItemStatus(item, status) {
				const request = this.activeTab == 'goods'
					? updateMyFishGoodsStatus({ goodsId: item.id, status })
					: updateMyFishWantStatus({ wantId: item.id, status })
				return request.then(res => {
					if (!res && res !== true) return
					uni.showToast({ title: status == 3 ? '已删除' : (status == 2 ? '已下架' : '已上架'), icon: 'none' })
					this.reload()
				})
			},
			toggleShelf(item) {
				const nextStatus = this.isOffShelf(item) ? 1 : 2
				this.updateItemStatus(item, nextStatus)
			},
			deleteItem(item) {
				uni.showModal({
					title: '删除确认',
					content: '删除后不可恢复，确定删除吗？',
					confirmText: '删除',
					confirmColor: '#ef4c3f',
					success: (res) => {
						if (!res.confirm) return
						this.updateItemStatus(item, 3)
					}
				})
			},
			switchTab(key) {
				this.activeTab = key
				this.titleKeyword = ''
				this.reload()
			},
			handleSearch() {
				uni.hideKeyboard()
				this.reload()
			},
			clearSearch() {
				this.titleKeyword = ''
				this.reload()
			},
			reload() {
				this.pageNum = 1
				this.totalPages = 1
				this.list = []
				this.load()
			},
			loadMore() {
				if (this.loading || this.pageNum >= this.totalPages) return
				this.pageNum += 1
				this.load()
			},
			load() {
				this.loading = true
				const query = {
					pageNum: this.pageNum,
					pageSize: this.pageSize,
					titleKeyword: this.canManageCurrentTab ? this.titleKeyword : ''
				}
				const map = {
					goods: pageMyFishGoods,
					wants: pageMyFishWants,
					favorites: pageMyFishFavorites,
					comments: pageMyFishComments,
					likes: pageMyFishLikes,
					complaints: pageMyFishComplaints
				}
				map[this.activeTab](query).then(page => {
					const records = page && (page.records || page.content) ? (page.records || page.content) : []
					this.totalPages = Number(page && (page.pages || page.totalPages)) || 1
					this.list = this.pageNum == 1 ? records : this.list.concat(records)
				}).finally(() => {
					this.loading = false
					this.loadedOnce = true
				})
			},
			openItem(item) {
				if (this.activeTab == 'wants') {
					uni.navigateTo({ url: '/package2/IdleTrad/detail?type=want&id=' + item.id })
					return
				}
				const goodsId = item.goodsId || (this.activeTab == 'goods' ? item.id : '')
				if (goodsId) uni.navigateTo({ url: '/package2/IdleTrad/detail?id=' + goodsId })
			},
			statusText(item) {
				if (this.activeTab == 'favorites') return '取消收藏'
				if (this.activeTab == 'comments') return '删除评价'
				if (this.activeTab == 'likes') return item.likeType == 'comment' ? '评论点赞' : '商品点赞'
				if (this.activeTab == 'complaints') return item.targetTypeText || (item.status == 1 ? '已通过' : (item.status == 2 ? '已驳回' : '待处理'))
				if (item.saleStatus == 2) return '已预定'
				if (item.saleStatus == 3) return '已卖出'
				if (item.status == 2) return '已下架'
				return '正常'
			},
			handleCardAction(item) {
				if (this.activeTab == 'favorites') {
					this.cancelFavorite(item)
					return
				}
				if (this.activeTab == 'comments') {
					this.deleteCommentItem(item)
				}
			},
			cancelFavorite(item) {
				if (!item || !item.goodsId) return
				uni.showModal({
					title: '取消收藏',
					content: '确定取消收藏这件商品吗？',
					confirmText: '取消收藏',
					confirmColor: '#ef4c3f',
					success: (res) => {
						if (!res.confirm) return
						toggleFishFavorite(item.goodsId).then(result => {
							if (!result && result !== false) return
							uni.showToast({ title: '已取消收藏', icon: 'none' })
							this.reload()
						})
					}
				})
			},
			deleteCommentItem(item) {
				if (!item || !item.id) return
				uni.showModal({
					title: '删除评价',
					content: '确定删除这条评价吗？',
					confirmText: '删除',
					confirmColor: '#ef4c3f',
					success: (res) => {
						if (!res.confirm) return
						deleteFishComment(item.id).then(() => {
							uni.showToast({ title: '已删除', icon: 'none' })
							this.reload()
						})
					}
				})
			},
			nameText(item) {
				if (item.displayTitle) return item.displayTitle
				if (item.title) return item.title
				if (this.activeTab == 'comments') return '我发表的评论'
				if (this.activeTab == 'likes') return item.likeType == 'comment' ? '我点赞的评论' : '我点赞的商品'
				if (this.activeTab == 'complaints') return '我的举报记录'
				return item.goodsId || item.id || '校园二手'
			},
			descText(item) {
				if (this.activeTab == 'favorites') return '收藏的商品'
				if (this.activeTab == 'comments') return item.content || '评论内容'
				if (this.activeTab == 'likes') return item.likeType == 'comment' ? (item.commentContent || '点赞了评论') : '点赞了商品'
				if (this.activeTab == 'complaints') {
					const prefix = item.targetTypeText ? item.targetTypeText + '：' : ''
					const detail = item.commentContent || item.reason || '举报内容'
					return prefix + detail
				}
				return this.plainText(item.content || '')
			},
			coverText(item) {
				return item.displayCover || item.coverImage || item.pic || this.firstImage(item.images) || this.defaultCover
			},
			priceText(item) {
				if (item.displayPrice !== undefined && item.displayPrice !== null && item.displayPrice !== '') return item.displayPrice
				if (this.activeTab == 'wants') return item.expectedPrice || ''
				return item.price || ''
			},
			firstImage(value) {
				if (!value) return ''
				if (Array.isArray(value)) return value[0] || ''
				try {
					const parsed = JSON.parse(value)
					return Array.isArray(parsed) ? (parsed[0] || '') : ''
				} catch (e) {
					return ''
				}
			},
			plainText(value) {
				return String(value || '')
					.replace(/<img[^>]*>/gi, '[图片]')
					.replace(/<[^>]+>/g, '')
					.replace(/&nbsp;/g, ' ')
					.replace(/&lt;/g, '<')
					.replace(/&gt;/g, '>')
					.replace(/&amp;/g, '&')
					.trim()
			}
		}
	}
</script>

<style lang="scss">
	page {
		background: #f7f9f7;
	}
	.my-fish-page {
		min-height: 100vh;
		background: #f7f9f7;
		color: #17362f;
	}
	.header {
		padding-left: 26rpx;
		padding-right: 26rpx;
		background: linear-gradient(180deg, #e5fbf3, #f7f9f7);
	}
	.back {
		width: 68rpx;
		height: 68rpx;
		display: flex;
		align-items: center;
	}
	.title {
		padding: 10rpx 0 24rpx;
		font-size: 40rpx;
		font-weight: 900;
	}
	.tabs {
		display: flex;
		align-items: center;
		overflow: visible;
		padding: 0 22rpx 18rpx;
		white-space: nowrap;
	}
	.tab {
		flex-shrink: 0;
		margin-right: 12rpx;
		padding: 13rpx 18rpx;
		border-radius: 28rpx;
		background: #fff;
		color: #758782;
		font-size: 22rpx;
	}
	.tab.active {
		background: #24b979;
		color: #fff;
		font-weight: 900;
	}
	.tab-more {
		margin-left: auto;
		margin-right: 0;
		background: #e8fbf3;
		color: #18a878;
		font-weight: 900;
	}
	.search-bar {
		height: 70rpx;
		margin: 0 24rpx 16rpx;
		padding: 0 12rpx 0 22rpx;
		display: flex;
		align-items: center;
		border-radius: 38rpx;
		background: #fff;
		box-shadow: 0 8rpx 22rpx rgba(20, 60, 48, 0.045);
		box-sizing: border-box;
	}
	.search-input {
		flex: 1;
		height: 68rpx;
		margin-left: 10rpx;
		color: #293632;
		font-size: 24rpx;
		line-height: 68rpx;
	}
	.search-clear {
		padding: 0 12rpx;
		color: #9aa8a4;
		font-size: 22rpx;
	}
	.search-btn {
		width: 86rpx;
		height: 54rpx;
		border-radius: 28rpx;
		background: linear-gradient(135deg, #38c897, #19af7e);
		color: #fff;
		font-size: 23rpx;
		font-weight: 800;
		line-height: 54rpx;
		text-align: center;
	}
	.list {
		height: calc(100vh - 210rpx);
	}
	.list--with-search {
		height: calc(100vh - 296rpx);
	}
	.card {
		margin: 18rpx 24rpx 0;
		padding: 18rpx;
		display: flex;
		align-items: center;
		border-radius: 24rpx;
		background: #fff;
		box-shadow: 0 8rpx 22rpx rgba(20, 60, 48, 0.05);
	}
	.cover {
		width: 126rpx;
		height: 126rpx;
		border-radius: 18rpx;
		background: #edf3ef;
	}
	.main {
		flex: 1;
		min-width: 0;
		margin-left: 18rpx;
	}
	.name {
		overflow: hidden;
		font-size: 28rpx;
		font-weight: 900;
		text-overflow: ellipsis;
		white-space: nowrap;
	}
	.desc {
		margin-top: 8rpx;
		overflow: hidden;
		color: #71817c;
		font-size: 23rpx;
		text-overflow: ellipsis;
		white-space: nowrap;
	}
	.meta {
		margin-top: 8rpx;
		display: flex;
		gap: 14rpx;
		color: #a0aaa6;
		font-size: 20rpx;
	}
	.meta text:first-child {
		color: #ef4c3f;
		font-weight: 900;
	}
	.status {
		margin-left: 12rpx;
		color: #22a879;
		font-size: 22rpx;
		font-weight: 800;
		white-space: nowrap;
	}
	.status--off {
		color: #9aa8a4;
	}
	.status--action {
		padding: 8rpx 14rpx;
		border-radius: 18rpx;
		background: #fff2f2;
		color: #ef4c3f;
		font-size: 20rpx;
	}
	.empty,
	.load-more {
		padding: 80rpx 0;
		color: #9aa8a4;
		text-align: center;
	}
	.bottom-space {
		height: 120rpx;
	}
</style>
