<template>
	<view class="reviews-page">
		<scroll-view
			class="reviews-scroll"
			scroll-y
			:style="{ height: scrollHeight }"
			@scrolltolower="onLoadMore"
		>
			<view v-if="loading && !list.length" class="reviews-loading">
				<u-loading-icon mode="circle" text="加载中" />
			</view>
			<view v-else-if="list.length" class="reviews-list">
				<review-card v-for="item in list" :key="item.reviewId" :item="item" />
			</view>
			<view v-else class="reviews-empty">
				<u-empty mode="list" text="暂无评价" icon-size="80" />
			</view>
			<view v-if="list.length" class="reviews-footer">
				<text v-if="loadingMore">加载中...</text>
				<text v-else-if="finished">没有更多了</text>
			</view>
		</scroll-view>
	</view>
</template>

<script setup>
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { getGoodsReviews } from '@/api/goods'
import { mapReviewList } from '@/utils/goodsDetail'
import ReviewCard from '@/components/goods/ReviewCard.vue'

const goodsId = ref('')
const list = ref([])
const loading = ref(false)
const loadingMore = ref(false)
const finished = ref(false)
const pageNum = ref(1)
const pageSize = 10
const scrollHeight = ref('600px')

function calcScrollHeight() {
	try {
		const sys = uni.getSystemInfoSync()
		scrollHeight.value = `${sys.windowHeight || 600}px`
	} catch (e) {
		scrollHeight.value = '600px'
	}
}

async function fetchPage(isReset) {
	if (!goodsId.value) return
	if (isReset) {
		loading.value = true
		pageNum.value = 1
		finished.value = false
	} else {
		if (finished.value || loadingMore.value) return
		loadingMore.value = true
	}
	try {
		const res = await getGoodsReviews(goodsId.value, {
			pageNum: pageNum.value,
			pageSize
		})
		const rows = mapReviewList(res.rows || [])
		const total = Number(res.total) || 0
		if (isReset) {
			list.value = rows
		} else {
			list.value = list.value.concat(rows)
		}
		finished.value =
			rows.length < pageSize || (total > 0 && list.value.length >= total)
		if (!finished.value) {
			pageNum.value += 1
		}
	} catch (e) {
		if (isReset) list.value = []
	} finally {
		loading.value = false
		loadingMore.value = false
	}
}

function onLoadMore() {
	if (!loading.value && !loadingMore.value && !finished.value) {
		fetchPage(false)
	}
}

onLoad((options) => {
	goodsId.value = options.goodsId || ''
	calcScrollHeight()
	fetchPage(true)
})
</script>

<style lang="scss" scoped>
.reviews-page {
	min-height: 100vh;
	background: #fff;
}
.reviews-scroll {
	box-sizing: border-box;
}
.reviews-list {
	padding: 0 24rpx;
}
.reviews-loading,
.reviews-empty {
	min-height: 50vh;
	display: flex;
	align-items: center;
	justify-content: center;
}
.reviews-footer {
	padding: 24rpx;
	text-align: center;
	font-size: 24rpx;
	color: #999;
}
</style>
