<template>
	<view class="content" :style="getBackgroundImg()">
		<!-- 使用 z-paging 组件实现分页功能 -->
		<z-paging ref="pagePaging" v-model="dataList" @query="queryList" :refresher-enabled="true"
			:loading-more-enabled="true" :auto="true" :empty-view-text="'暂无麻将局数据'" :empty-view-img="'/static/empty.png'"
			:refresher-threshold="80" :loading-more-threshold="50" style="flex: 1; width: 95%; margin-top: 10rpx;">
			<template #top>
				<view style="z-index: 100;position: sticky;top :0;">
					<view :style="{ height: statusBarHeight + 'px' }" style="background-color: #fff;"
						class="status-bar">
					</view>
				</view>
			</template>
			<template #empty>
				<com-index-NoEmpty></com-index-NoEmpty>
			</template>

			<view style="z-index: 100;margin-top:10rpx;height:532rpx;">
				<view style="width: 100%;width:100%;display:flex;justify-content: center;"
					v-if="homeData != null && homeData.advertList != null && homeData.advertList.length > 0">
					<view class="" style="width:97%; height: 386rpx;border-radius: 25rpx;">
						<swiper class="img-swiper" :indicator-dots="false" circular autoplay interval="3000">
							<swiper-item v-for="(item, index) in homeData.advertList" :key="index">
								<image :src="item.imageUrl" mode="scaleToFill" class="slide-img"
									style="border-radius:25rpx;">
								</image>
							</swiper-item>
						</swiper>
					</view>
				</view>
				<view style="height: 10rpx;"></view>
			</view>
			<view class="grid-container">
				<MahjongCard v-for="(item, index) in dataList" :key="index" :item="item" @click="openPop"
					@join="handleJoin" />
			</view>
		</z-paging>


		<!-- 预约信息弹窗组件 -->
		<ReservationPopup ref="reservationPopup" @openUserPop="openUserPop" @refreshList="refreshData" />



		<uni-popup ref="userInfo_popup" type="center">

			<view class="column" style="width: 500rpx; background-color: white; padding: 20rpx;">

				<image @click="closeUserPop()" src="/static/ic_close.png"
					style="width: 20rpx; height: 20rpx; margin-left: auto;" mode="">
				</image>

				<view class="row" style="align-items: center;">

					<image src="" style="width: 80rpx; height: 80rpx; background-color: aquamarine; border-radius: 50%;"
						mode="">
					</image>

					<view class="column" style="font-size: 24rpx; margin-left: 20rpx;">

						<text>树下的胖子</text>
						<text style="margin-top: 10rpx;">男，30岁，已参与20次，信誉5.0</text>

					</view>
				</view>

				<view class="row" style="align-items: center; margin-top: 20rpx;">
					<text style="font-size: 24rpx;">Ta的评分 </text>
					<text style="font-size: 40rpx; color: #ED3535; margin-left: 10rpx;">4.6</text>
				</view>

				<view class="row" style="align-items: center; margin-top: 20rpx;">
					<text style="font-size: 24rpx;">牌品</text>
					<uni-rate style="margin-left: 20rpx;" :readonly="true" v-model="rateValue" @change="onChange" />
				</view>

				<view class="row" style="align-items: center; margin-top: 20rpx;">
					<text style="font-size: 24rpx;">牌技</text>
					<uni-rate style="margin-left: 20rpx;" :readonly="true" v-model="rateValue" @change="onChange" />
				</view>

				<text style="font-size: 24rpx; margin-top: 20rpx;">鸽子数 0次</text>


			</view>

		</uni-popup>


	</view>
</template>

<script setup>
import {
	ref,
	reactive,
	onMounted
} from 'vue'
import { onShareAppMessage } from '@dcloudio/uni-app';

import zPaging from '@/uni_modules/z-paging/components/z-paging/z-paging.vue'
import MahjongCard from '@/components/index/MahjongCard.vue'
import ReservationPopup from '@/components/com/index/ReservationPopup.vue'
import {
	homeData,
	preloadHomeData,
	getReservation,
	getDetail
} from '@/common/server/index'

import {
	configData,
	getConfigData,
	getShareConfig,
	preloadConfigData
} from '@/common/server/config'
import { userInfo, loadUserInfo } from '@/common/server/user'
import { sleep } from '../../uni_modules/uview-plus/libs/function';
const statusBarHeight = ref(uni.getSystemInfoSync().statusBarHeight);
const getBackgroundImg = () => {
	return {
		background: `url(${configData.value.config.defaultImage}) 100% 100% `,
		backgroundSize: '100%',
		backgroundRepeat: "no-repeat",
		backgroundRepeatX: "0px",
		backgroundSize: "100%",
		backgroundRepeatY: "0px",
		backgroundPositionX: "0px",
		backgroundPositionY: statusBarHeight.value + "px",
	};
}
// 响应式数据
const title = ref('Hello')
const imgList = ref([1, 2, 3, 4, 5])
const dataList = ref([]) // 分页数据列表
const rateValue = ref(3.5)
const mockData = ref([]) // 模拟数据源

// 组件引用
const pagePaging = ref(null)
const reservationPopup = ref(null)
const userInfo_popup = ref(null)

// 初始化模拟数据
const initMockData = () => {
	mockData.value = []
	for (let i = 1; i <= 20; i++) {
		// 随机生成不同人数的麻将局
		const personCount = [2, 3, 4][Math.floor(Math.random() * 3)]
		const joinedCount = Math.floor(Math.random() * (personCount + 1))

		// 生成已加入的玩家
		const joinPerson = []
		for (let j = 0; j < joinedCount; j++) {
			joinPerson.push({
				id: j + 1,
				name: `玩家${j + 1}`,
				avatar: 'https://admin-1308826010.cos.ap-shanghai.myqcloud.com/app/static/userlogo.png',
				phone: `138****${String(j + 1).padStart(4, '0')}`
			})
		}

		mockData.value.push({
			id: i,
			title: `麻将局 ${i}`,
			status: joinedCount >= personCount ? '已满员' : '组局中',
			time: '20：00 ~ 04：30 共8小时30分钟',
			room: `304包厢-大包，${personCount}人`,
			description: '休闲局，随便来',
			requirements: '麻将、斗地主、不可吸烟、性别不限、信誉≧4.0',
			personCount: personCount,
			joinPerson: joinPerson
		})
	}
}

// 分页查询方法
const queryList = (pageNo, pageSize) => {
	console.log(`加载第${pageNo}页，每页${pageSize}条数据333`)
	getReservation(pageNo, pageSize).then(res => {
		if (res != null && res.length > 0) {
			pagePaging.value.complete(res)
		} else {
			pagePaging.value.complete([])
		}
	});

}

// 手动刷新
const refreshData = () => {
	if (pagePaging.value != null) {
		pagePaging.value.reload()
	}
}

// 清空数据
const clearData = () => {
	pagePaging.value.clear()
}



onShareAppMessage(({ from, target, webViewUrl }) => {
	// console.log('onShareAppMessage', from, target, webViewUrl);
	var resid = 0;
	if (target != null) {
		var item = target.dataset.item;
		console.log('item', item);
		resid = item.id;
	}
	var obj = getShareConfig("pages/index/loading?id=" + resid);
	return obj
});


// 弹窗相关方法
const openPop = (item) => {
	reservationPopup.value.show(item.data)
}

const openUserPop = () => {
	userInfo_popup.value.open()
}

const closeUserPop = () => {
	userInfo_popup.value.close()
}

const onChange = (e) => {
	console.log('rate发生改变:' + JSON.stringify(e))
}

// 处理加入麻将局事件
const handleJoin = (item) => {
	console.log('加入麻将局:', item)
	// 这里可以添加加入逻辑，比如调用API
	uni.showToast({
		title: '加入成功',
		icon: 'success',
		duration: 1500
	})
	// 关闭弹窗
	reservationPopup.value.close()
}

// 生命周期
onMounted(() => {
	// 初始化模拟数据

})
onShow(async () => {
	refreshData();
});
onLoad(async (option) => {
	// console.log('INDEX-option', option);
	if (!homeData.value) preloadHomeData();
	if (!configData.value) preloadConfigData();
	await loadUserInfo();
	var share_id = uni.getStorageSync('share_id');
	console.log('share_id', share_id);
	if (share_id != null && share_id != "0" && share_id != "") {
		uni.removeStorageSync('share_id')
		var share_data = await getDetail(share_id);
		// console.log("share_data321321", share_data.data);
		if (reservationPopup.value != null) {
			// await sleep()
			openPop(share_data);
		}

	}
	// initMockData();
	// initMockData();
});
</script>

<style lang="scss">
.content {
	height: 100vh;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: flex-start;

}

.img-swiper {
	width: 100%;
	height: 386rpx;
}

.slide-img {
	width: 100%;
	height: 100%;

}

/* 网格容器 - 2列布局 */
.grid-container {
	display: grid;
	grid-template-columns: repeat(2, 1fr);
	/* 2列，每列宽度相等 */
	gap: 20rpx;
	/* 网格间距（行列间距相同） */
	padding: 0 15rpx;
}

/* 网格项内容 */
.item-content {
	height: 630rpx;
	// background-color: #E6E6E6;
	color: white;
	border-radius: 10rpx;
	font-size: 32rpx;
}
</style>