<!-- 虚拟列表演示(不使用内置列表)(vue) -->
<!-- 写法较简单，在页面中对当前需要渲染的虚拟列表数据进行for循环，在vue3中兼容性良好 -->
<!-- 在各平台兼容性请查阅https://z-paging.zxlee.cn/module/virtual-list.html -->
<template>
	<view class="content">
		<!-- 如果页面中的cell高度是固定不变的，则不需要设置cell-height-mode，如果页面中高度是动态改变的，则设置cell-height-mode="dynamic" -->
		<!-- 原先的v-model修改为@virtualListChange="virtualListChange"并赋值处理后的虚拟列表 -->
		<z-paging ref="paging" :auto="false" :show-loading-more-no-more-view="showLoad" :show-default-loading-more-text="showLoad" use-virtual-list :force-close-inner-list="true" :paging-style="{ paddingTop: 0 + 'px', paddingBottom: paddingBottom + 'rpx' }" cell-height-mode="dynamic" @scroll="scroll" @virtualListChange="virtualListChange" @query="queryList">
			<!-- 需要固定在顶部不滚动的view放在slot="top"的view中，如果需要跟着滚动，则不要设置slot="top" -->
			<template #top>
				<nav-bar :title="title" :scrollTop="scrollTop" @onTab="change" @initNav="initNav"></nav-bar>
			</template>  
			   
			<view>  
				<user-box :clerk="user" :paddingTop="paddingTop"></user-box>
				<sticky-box :trendNum="total" @change="change"></sticky-box>
			</view>
			
			<!-- :id="`zp-id-${item.zp_index}`"和:key="item.zp_index" 必须写，必须写！！！！ -->
			<!-- 这里for循环的index不是数组中真实的index了，请使用item.zp_index获取真实的index -->
			<view class="data-box">
				<star-list v-if="currentTab == 0" @openGift="openGift" :virtualList="giftList"></star-list>
				<post-list v-if="currentTab == 1" :virtualList="virtualList"></post-list>
			</view>
			
			<template #bottom>
				<view v-if="isGift" class="bottom-box">
					<view class="order" @click="doGift">赠礼</view>
					<view class="gift" @click="chat">密聊</view>
				</view>
				<view v-else class="bottom-box">
					<view class="order-btn" @click="chat">密聊</view>
				</view>
			</template>  
			
		</z-paging>
		
		<gift-popup ref="giftPopup"></gift-popup>
		
	</view>
</template>

<script>
	import UserBox from '@/pages/user/detail/components/userBox.vue';
	import StickyBox from '@/pages/user/detail/components/stickyBox.vue';
	import StarList from '@/pages/user/detail/components/starList.vue';
	import PostList from '@/pages/user/detail/components/postList.vue';
	import NavBar from '@/pages/user/detail/components/navBar.vue';
	import GiftPopup from '@/pages/user/detail/components/giftPopup.vue';
	import UserApi from '@/sheep/api/member/user';
	import TrendApi from '@/sheep/api/worker/trend'; 
	import RewardApi from '@/sheep/api/worker/reward'; 
	import ImConversationApi from '@/sheep/api/im/memberConversation';
	import { WxaSubscribeTemplate } from '@/sheep/util/const';
	import { showAuthModal } from '@/sheep/hooks/useModal';
	import dayjs from 'dayjs';
	import relativeTime from "dayjs/plugin/relativeTime";
	dayjs.extend(relativeTime);
	import sheep from '@/sheep';
	export default {
		components: {
			UserBox,
			StickyBox,
			StarList,
			PostList,
			NavBar, 
			GiftPopup,
		},
		props: {
			title: {
				type: String,
				default: '',
			}
		},
		data() {
			return {
				// 虚拟列表数组，通过@virtualListChange监听获得最新数组
				virtualList: [],
				scrollTop: 0,
				paddingTop: 0,
				paddingBottom: 0,
				height: 0,
				
				user: {},
				userId: 0,
				giftList: [],
				
				total: 0,
			}
		},
		computed: {
			currentTab() {
				return sheep.$store('sys').userTabIndex;
			},
			showLoad() {
				return sheep.$store('sys').userTabIndex > 1;
			},
			isLogin: {
				get() {
				  return sheep.$store('user').isLogin;
				},
			},
			userInfo: {
			    get() {
			      return sheep.$store('user').userInfo;
			    },
			},
			isGift() {
				return sheep.$store('user').tradeConfig.giftEnabled;
			},
		},
		methods: {
			initNav(e) {
				this.height = e.height;
				this.paddingTop = this.height;
			},
			initData(options) {
				this.userId = options.id;
				this.getUserInfo();
				
				RewardApi.getRewardGiftList({
					workerUserId: options.id,
				}).then(res => {
					this.giftList = res.data;
				});
			},
			getUserInfo() {
				UserApi.getUserInfoById(this.userId).then(res => {
					this.user = res.data;
					this.user.time = this.showDayTime(this.user.updateTime);
					sheep.$store('sys').setUser(this.user);
					
					this.$refs.paging.reload();
				});
			},
			showDayTime(datetime) {
			  if (!datetime) return "";
			  return dayjs(datetime).fromNow();
			},
			scroll(e) {
				this.scrollTop = e.detail.scrollTop;
			},
			// 监听虚拟列表数组改变并赋值给virtualList进行重新渲染
			virtualListChange(vList) {
				this.virtualList = vList;
			},
			queryList(pageNo, pageSize) {
				// 组件加载时会自动触发此方法，因此默认页面加载时会自动触发，无需手动调用
				// 这里的pageNo和pageSize会自动计算好，直接传给服务器即可
				// 模拟请求服务器获取分页数据，请替换成自己的网络请求
				const params = {
					pageNo: pageNo,
					pageSize: pageSize,
					queryType: '2',
					workerUserId: this.userId,
				}
				
				TrendApi.getTrendPage(params).then(res => {
					this.total = res.data.total;
					// 将请求的结果数组传递给z-paging
					this.$refs.paging.complete(res.data.list);
				}).catch(res => {
					// 如果请求失败写this.$refs.paging.complete(false);
					// 注意，每次都需要在catch中写这句话很麻烦，z-paging提供了方案可以全局统一处理
					// 在底层的网络请求抛出异常时，写uni.$emit('z-paging-error-emit');即可
					this.$refs.paging.complete(false);
				})
			},
			change(e) {
				sheep.$store('sys').setUserTabIndex(e);
				this.scrollTop = 0;
				this.$refs.paging.reload();
			},
			chat() {
				const isLogin = sheep.$store('user').isLogin;
				if(!isLogin) {
					showAuthModal();
					return;
				}
				
				const userInfo = sheep.$store('user').userInfo;
				// 如果用户已经有头像和昵称,不要每次登录都要重新上传头像。
				if(userInfo.visible) {
					// #ifdef MP-WEIXIN
					this.subscribeMessage();
					// #endif
					
					ImConversationApi.createMemberConversation({
						userId: this.userId,
						groupType: 1,
						lastMessageContentType: 1,
					}).then(res => {
						if(res.data){
							sheep.$router.go('/pages/im/index',{groupId: res.data, receiveUserId: this.userId});
						}
					});
					return;
				}
				// 触发小程序授权信息弹框
				// #ifdef MP-WEIXIN
				showAuthModal('mpAuthorization');
				// #endif
				
				// #ifndef MP-WEIXIN
				showAuthModal('h5Authorization');
				// #endif
			},
			subscribeMessage() {
			  const event = [WxaSubscribeTemplate.UNREAD_MESSAGE];
			  sheep.$platform.useProvider('wechat').subscribeMessage(event, () => {
			    // 订阅后记录一下订阅状态
			    uni.removeStorageSync(WxaSubscribeTemplate.UNREAD_MESSAGE);
			    uni.setStorageSync(WxaSubscribeTemplate.UNREAD_MESSAGE, '已订阅');
			  });
			},
			doGift() {
				if(this.isLogin){
					this.$refs.giftPopup.showPopup();
				}else{
					showAuthModal();
				}
			},
			openGift(e) {
				if(this.isLogin){
					this.$refs.giftPopup.showGiftPopup(e);
				}else{
					showAuthModal();
				}
			},
		}
	}
</script>

<style lang="scss" scoped>
	.data-box {
		padding: 0 15px;
	}
	.bottom-box {
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 10px 30px;
		box-shadow: 0 0 6px 0 #ccc;
		
		.order {
			background-color: var(--ui-BG-Main);
			padding: 10px;
			border-top-left-radius: 40px;
			border-bottom-left-radius: 40px;
			color: #fff;
			width: 50%;
			display: flex;
			justify-content: center;
			align-items: center;
			height: 88rpx;
			font-size: 28rpx;
		}
		
		.order-btn {
			background-color: var(--ui-BG-Main);
			padding: 10px;
			border-radius: 40px;
			color: #fff;
			flex: 1;
			display: flex;
			justify-content: center;
			align-items: center;
			height: 88rpx;
			font-size: 28rpx;
		}
		
		.gift {
			background-color: #eef3f2;
			padding: 10px;
			border-top-right-radius: 40px;
			border-bottom-right-radius: 40px;
			width: 50%;
			display: flex;
			justify-content: center;
			align-items: center;
			height: 88rpx;
			color: #aaa;
			font-size: 28rpx;
		}
	}
</style>
