<template>
	<view class="content">

		<!-- 顶部大图 -->
		<view v-if="uid" class="zhuige-home-bg">
			<navigator v-if="IsLoginUser" url="/community/community/setting" style="color:#fff;z-index:8;position: absolute;right:30rpx;top:80rpx;">
				<view class="iconfont zc zc-shezhi i-type"></view>
			</navigator>
			<!-- 用户信息 -->
			<view v-if="uid" class="zhuige-user-card">
				<view class="zhuige-user-title">
					<!-- 头像及认证 -->
					<view class="zhuige-user-info-block">
						<view>
							<image mode="aspectFill" :src="UserInfo.user_avatar"></image>
						</view>
					</view>

					<view class="zhuige-user-count">
						<view @click="goToPage('/community/community/friend?tab=follow&user_id=' + uid)">
							<view>{{UserInfo.user_friend || 0}}</view>
							<text>{{__('关注')}}</text>
						</view>
						<view @click="goToPage('/community/community/friend?tab=fans&user_id=' + uid)">
							<view>{{UserInfo.user_fans || 0}}</view>
							<text>{{__('粉丝')}}</text>
						</view>
						<!-- 		<view>
							<view>3</view>
							<text>圈子</text>
						</view> -->
						<view>
							<view>{{UserInfo.user_story_like || 0}}</view>
							<text>{{__('获赞')}}</text>
						</view>
					</view>
				</view>

				<view class="zhuige-user-info-block-text">
					<text>{{UserInfo.user_nickname}}</text>
					<image mode="aspectFit" :src="UserInfo.user_level_logo"></image>
				</view>

				<view class="zhuige-user-line">
					<image mode="aspectFill" src="@/static/images/pen.png"></image>
					<text>{{__('签名：')}}</text>
					<text>{{UserInfo.user_sign}}</text>
				</view>
				<view class="zhuige-user-line" v-if="(false)">
					<image mode="aspectFill" src="https://q.zhuige.com/wp-content/uploads/2022/08/lvv.png"></image>
					<text>{{__('认证：')}}</text>
					<text>测试</text>
				</view>

				<!-- 操作相关 -->
				<view class="zhuige-user-info-btn">
					<template v-if="!IsLoginUser">
						<template v-if="UserInfo.IsFollow">
							<view class="follow active" :data-user_id="UserInfo.user_id + ''" @click="onUnFollow">{{__('已关注')}}</view>
						</template>
						<view v-else @click="onFollow" :data-user_id="UserInfo.user_id + ''" class="follow">{{__('+关注')}}</view>
					</template>

					<!-- 新增私信 -->
					<view v-if="hasLogin && !IsLoginUser">
						<navigator :url="'/im/chat/chat?uid='+  UserInfo.user_id">
							<text>{{__('私信')}}</text>
						</navigator>
					</view>

					<!-- 分享先隐藏 -->
					<!-- <button open-type="share">
						<uni-icons type="redo-filled" size="24"></uni-icons>
					</button> -->

				</view>
			</view>

			<view class="zhuige-home-cover"></view>
			<image class="zhuige-hover-bgimg" mode="aspectFill" :src="UserInfo.user_poster"></image>
		</view>

		<!-- 推荐 -->
		<view v-if="rec_ad" class="zhuige-user-market">
			<!-- 	<zhuige-scroll-ad ext-ad-class="zhuige-scroll-goods-mini" :title="rec_ad.title" :items="rec_ad.items">
			</zhuige-scroll-ad> -->
		</view>

		<!-- tab -->
		<view class="zhuige-home-tab">
			<view class="zhuige-block">
				<tab :tabs="tabs" :cur-tab="cur_tab" @clickTab="clickTab"></tab>
			</view>
		</view>

		<!-- 帖子列表 -->
		<view class="zhuige-home-list">
			<q-post-waterfall ref="pWaterfall" :type="cur_tab" @onRenew="onRenew" :list="PostsList" :loadStatus="loadPostStatus" :IsLoginUser="IsLoginUser" v-if="PostsList.length > 0"></q-post-waterfall>
			<view class="m-nullpage" v-else>
				<view class="m-nullpage-middle">
					<label class="iconfont icon-sousuo-sousuo"></label>
					<view class="m-null-tip">
						<text>{{ __('亲~找不到您想要的帖子') }}</text>
						<text>{{ __('再多点提示呗') }}</text>
					</view>
				</view>
			</view>
		</view>

		<!-- <uni-load-more v-if="PostsList && PostsList.length>0" :status="loadMore"></uni-load-more> -->
	</view>
</template>

<script>
	/*
	 * 追格小程序
	 * 作者: 追格
	 * 文档: https://www.zhuige.com/docs/zg.html
	 * gitee: https://gitee.com/zhuige_com/zhuige_xcx
	 * github: https://github.com/zhuige-com/zhuige_xcx
	 * Copyright © 2022-2023 www.zhuige.com All rights reserved.
	 */



	import {
		mapState,
		mapMutations
	} from 'vuex'
	import dateUtil from '../../helpers/util_date';
	import Tab from '../components/tab.vue'
	import QPostWaterfall from '../components/q-post-waterfall/q-post-waterfall.vue';
	export default {
		components: {
			Tab,
			QPostWaterfall,
		},


		data() {
			this.user_id = undefined;

			this.loginReload = false;

			return {
				options: {},
				uid: 0,
				UserInfo: {},
				page: 1,
				ispage: true,
				flag: true,
				PostsList: [],
				loadPostStatus: 'loadmore',
				IsLoginUser: false,

				user: undefined,
				stat: undefined,
				rec_ad: undefined,

				tabs: [{
						id: 'publish',
						title: '作品'
					}, {
						id: 'like',
						title: '点赞'
					},
					{
						id: 'fav',
						title: '收藏'
					},
					{
						id: 'comment',
						title: '评论'
					}

				],
				cur_tab: 'publish',

				posts: [],
				loadMore: 'more',
				loaded: false,

				noDataTip: '哇哦，什么也没有',

				// 是否显示私信按钮
				btn_message: false,

				nav_opacity: 0,
				statusBarHeight: 0,
			}
		},
		computed: mapState(['Config', 'StateCode', 'notice', 'plantformInfo', 'shopInfo', 'userInfo', 'hasLogin']),
		onLoad(options) {
			var that = this;
			that.setData({
				uid: options.uid || that.userInfo.user_id
			});
			this.uid == that.userInfo.user_id && that.setData({
				IsLoginUser: true
			});


			if (options.tab) {
				this.cur_tab = options.tab;
			}

			this.statusBarHeight = uni.getSystemInfoSync().statusBarHeight;

			//如果没有用户id，且未登录
			if (!that.$.isUndefined(that.uid)) {
				that.GetUserSpace();
				that.GetMemberPostsByUserId()
			}

			// this.refresh();

			// uni.$on('zhuige_event_follow_user', this.onFlollowUser);
			// uni.$on('zhuige_event_user_like', this.onUserLike);
		},

		onUnload() {

		},

		onShow() {
			if (this.loginReload) {
				this.loadData();
			}
		},

		onReachBottom() {
			this.scrollbottom()
		},

		onPullDownRefresh() {
			this.setData({
				PostsList: [],
				page: 1,
				ispage: true,
				flag: true,
			})
			this.clickTab({
				id: this.cur_tab
			});
		},

		onPageScroll(e) {
			this.nav_opacity = (e.scrollTop > 255 ? 255 : e.scrollTop) / 255;
			if (e.scrollTop > 20) {
				uni.setNavigationBarColor({
					frontColor: '#000000',
					backgroundColor: '#ffffff',
				})
			} else {
				uni.setNavigationBarColor({
					frontColor: '#000000',
					backgroundColor: '#ffffff'
				})
			}



		},

		onShareAppMessage() {

		},

		// #ifdef MP-WEIXIN
		onShareTimeline() {
			return {
				title: '个人主页-' + getApp().globalData.appName,
			};
		},
		// #endif

		methods: {
			...mapMutations(['logout', 'getPlantformInfo', 'forceUserInfo', 'getStoreInfo']),
			onRenew: function() {
				this.setData({
					PostsList: [],
					page: 1,
					ispage: true,
					flag: true,
				})
				this.GetMemberPostsByUserId();
			},
			goToPage: function(url) {
				this.$.navigateTo({
					url: url
				})
			},
			GetUserSpace: function() {
				var that = this,
					params = {
						UserId: that.userInfo.user_id,
						user_id: that.uid,
						operateId: that.cf.storeId
					};

				that.$.request({
					url: this.Config.URL.sns.user_space,
					data: params,
					success: function(data, status, msg, code) {
						that.setData({
							UserInfo: data,
						})
					}
				});
			},

			GetLikePost: function() {
				var that = this,
					params = {
						user_id: that.uid,
						page: that.page,
						'sidx': 'like_time',
						'sord': 'DESC'
					};
				1 == that.page && that.setData({
					PostsList: []
				});

				that.$.request({
					url: this.Config.URL.sns.story_like_lists,
					data: params,
					success: function(data, status, msg, code) {

						if (data.items.length > 0) {
							for (var r = 0; r < data.items.length; r++) {
								data.items[r]['story_time_str'] = dateUtil.dateUtils.format(that.$
									.datetimeFormatter(data.items[r]['story_time']));
							}

							if (data.page >= data.total) {
								that.setData({
									PostsList: that.PostsList.concat(data.items),
									flag: false,
									ispage: false,

								});
							} else {
								that.setData({
									PostsList: that.PostsList.concat(data.items),
									flag: true,
									ispage: true,

								})
							}

						} else {
							that.setData({
								flag: false,
								ispage: false,

							})
						}
						that.$.stopPullDownRefresh()
					}
				});
			},

			GetMemberPostsByUserId: function() {
				var that = this,
					params = {
						user_id: that.uid,
						page: that.page,
						'sidx': 'story_time',
						'sord': 'DESC'
					};
				1 == that.page && that.setData({
					PostsList: []
				});

				that.$.request({
					url: this.Config.URL.sns.user_story,
					data: params,
					success: function(data, status, msg, code) {

						if (data.items.length > 0) {
							for (var r = 0; r < data.items.length; r++) {
								data.items[r]['story_time_str'] = dateUtil.dateUtils.format(that.$
									.datetimeFormatter(data.items[r]['story_time']));
							}

							if (data.page >= data.total) {
								that.setData({
									PostsList: that.PostsList.concat(data.items),
									flag: false,
									ispage: false,

								});
							} else {
								that.setData({
									PostsList: that.PostsList.concat(data.items),
									flag: true,
									ispage: true,

								})
							}

						} else {
							that.setData({
								flag: false,
								ispage: false,

							})
						}
						that.$.stopPullDownRefresh()
					}
				});
			},

			GetCommentPostsByUserId: function() {
				var that = this;
				let params = {
					user_id: that.uid,
					page: that.page
				};
				1 == that.page && that.setData({
					PostsList: []
				});

				that.$.request({
					url: this.Config.URL.sns.user_comment_story,
					data: params,
					success: function(data, status, msg, code) {

						if (data.items.length > 0) {
							for (var r = 0; r < data.items.length; r++) {
								data.items[r]['story_time_str'] = dateUtil.dateUtils.format(that.$.datetimeFormatter(data.items[r]['story_time']));
							}

							if (data.page >= data.total) {
								that.setData({
									PostsList: that.PostsList.concat(data.items),
									flag: false,
									ispage: false,

								});
							} else {
								that.setData({
									PostsList: that.PostsList.concat(data.items),
									flag: true,
									ispage: true,

								})
							}

						} else {
							that.setData({
								flag: false,
								ispage: false,
							})
						}

						that.$.stopPullDownRefresh()
					}
				});
			},

			GetCollectionPostsByUserId: function() {
				var that = this;
				let params = {
					user_id: that.uid,
					page: that.page
				};
				1 == that.page && that.setData({
					PostsList: []
				});

				that.$.request({
					url: this.Config.URL.sns.user_collect_story,
					data: params,
					success: function(data, status, msg, code) {

						if (data.items.length > 0) {
							for (var r = 0; r < data.items.length; r++) {
								data.items[r]['story_time_str'] = dateUtil.dateUtils.format(that.$.datetimeFormatter(data.items[r]['story_time']));
							}

							if (data.page >= data.total) {
								that.setData({
									PostsList: that.PostsList.concat(data.items),
									flag: false,
									ispage: false,
								});
							} else {
								that.setData({
									PostsList: that.PostsList.concat(data.items),
									flag: true,
									ispage: true,
								})
							}

						} else {
							that.setData({
								flag: false,
								ispage: false,
							})
						}

						that.$.stopPullDownRefresh()
					}
				});
			},
			scrollbottom: function() {
				if (this.flag) {
					var that = this;
					that.setData({
						flag: false
					});

					clearTimeout(t);
					var t = setTimeout(function() {
						that.setData({
							flag: false,
							page: parseInt(that.page) + 1,
						});
						if (that.cur_tab == 'publish') {
							//帖子
							that.GetMemberPostsByUserId()
						} else if (that.cur_tab == 'comment') {
							//评论
							that.GetCommentPostsByUserId()
						} else if (that.cur_tab == 'fav') {
							//收藏
							that.GetCollectionPostsByUserId()
						} else if (that.cur_tab == 'like') {
							//喜欢
							that.GetLikePost()
						} else {
							that.GetMemberPostsByUserId()
						}
					}, 100)
				}
			},
			//----- event start -----
			/**
			 * 关注用户事件
			 */
			onFollow: function(a) {
				let that = this;
				that.forceUserInfo(function(user) {
					that.AddFollow(a.currentTarget.dataset.user_id)
				});
			},
			AddFollow: function(friend_id) {
				var that = this,
					params = {
						friend_id: friend_id
					};

				that.$.request({
					url: this.Config.URL.user.friend_agree,
					data: params,
					success: function(data, status, msg, code) {
						if (200 == status) {
							that.$.showToast({
								title: that.__("关注成功"),
								icon: "success",
								duration: 2e3
							}), clearTimeout(t);
							var t = setTimeout(function() {
								that.GetUserSpace();
							}, 1500)
						} else {}
					}
				});
			},
			onUnFollow: function(a) {

				let that = this;
				that.forceUserInfo(function(user) {
					that.cancelFollow(a.currentTarget.dataset.user_id)
				});
			},
			cancelFollow: function(friend_id) {
				var that = this;
				that.$.confirm(that.__("是否取消关注?"), function(a) {
						if (a.confirm) {
							var params = {
								friend_id: friend_id
							};

							that.$.request({
								url: that.Config.URL.user.friend_refuse,
								data: params,
								success: function(data, status, msg, code) {
									if (200 == status) {
										that.$.showToast({
											title: that.__("取消关注成功"),
											icon: "success",
											duration: 2e3
										}), clearTimeout(t);
										var t = setTimeout(function() {
											that.GetUserSpace();
										}, 1500)
									} else {}
								}
							});
						}
					},
					true)
			},

			/**
			 * 点赞事件
			 */
			onUserLike(data) {
				if (this.posts && this.posts.length > 0) {
					this.posts.forEach((topic) => {
						if (topic.id == data.post_id) {
							topic.like_count = data.like_count;
						}
					})
				}
			},
			// ------- event end ---------


			/**
			 * 刷新
			 */
			refresh() {
				this.loadData();
				this.loadPosts(true);
			},





			/**
			 * 点击切换TAB
			 */
			clickTab(tab) {
				this.setData({
					cur_tab: tab.id,
					page: 1,
				})
				if (tab.id == 'publish') {
					//帖子
					this.GetMemberPostsByUserId()
				} else if (tab.id == 'comment') {
					//评论
					this.GetCommentPostsByUserId()
				} else if (tab.id == 'fav') {
					//收藏
					this.GetCollectionPostsByUserId()
				} else if (tab.id == 'like') {
					//喜欢
					this.GetLikePost()
				} else {
					this.GetMemberPostsByUserId()
				}

			},

			/**
			 * 点击关注作者
			 */
			clickFollowUser() {
				Rest.post(Api.URL('user', 'follow_user'), {
					user_id: this.user_id
				}).then(res => {
					if (res.code == 0) {
						uni.$emit('zhuige_event_follow_user', {
							user_id: this.user_id,
							is_follow: res.data.is_follow,
							from: 'user_home'
						});
					} else {
						Alert.toast(res.message);
					}
				}, err => {
					console.log(err)
				});
			},




			/**
			 * 删除帖子
			 */
			onDeleteTopic(topic) {
				Rest.post(Api.URL('bbs', 'topic_delete'), {
					topic_id: topic.id
				}).then(res => {
					if (res.code != 0) {
						Alert.error(res.message);
						return;
					}

					let newPosts = [];
					this.posts.forEach(ele => {
						if (topic.id != ele.id) {
							newPosts.push(ele);
						}
					})
					this.posts = newPosts;
				}, err => {
					console.log(err)
				});
			},

			/**
			 * 删除投票
			 */
			clickDeleteVote(vote) {
				Rest.post(Api.URL('vote', 'delete'), {
					vote_id: vote.id
				}).then(res => {
					if (res.code != 0) {
						Alert.error(res.message);
						return;
					}

					let newPosts = [];
					this.posts.forEach(ele => {
						if (vote.id != ele.id) {
							newPosts.push(ele);
						}
					})
					this.posts = newPosts;
				}, err => {
					console.log(err)
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	@import "@/styles/_variables.scss";

	page {
		background: #f5f5f5;
	}

	.zhuige-nav-back {
		position: fixed;
		top: 0;
		padding: 0 20rpx;
		z-index: 99;
	}

	.zhuige-home-bg {
		width: 100%;
		position: relative;
		overflow: hidden;
		padding-bottom: 50rpx;
	}

	.zhuige-home-bg .zhuige-home-cover {
		position: absolute;
		z-index: 3;
		height: 820rpx;
		top: 0rpx;
		width: 100%;
		background: linear-gradient(to bottom, #4b9ffb, #00438d);
	}

	.zhuige-home-bg image.zhuige-hover-bgimg {
		height: 100%;
		width: 100%;
		position: absolute;
		z-index: 2;
		top: 0;
	}

	.zhuige-user-card {
		padding: 30rpx 30rpx 20rpx;
		position: inherit;
		z-index: 5;
		color: #FFFFFF;
	}

	.zhuige-user-title {
		display: flex;
		justify-content: space-between;
		align-items: center;
		position: relative;
		padding: 10rpx;
	}

	.zhuige-user-info-block {
		position: relative;
		z-index: 6;
		display: inherit;
	}

	.zhuige-user-info-block view:nth-child(1) {
		position: relative;
		display: inherit;
	}

	.zhuige-user-info-block view:nth-child(1) image:nth-child(1) {
		height: 140rpx;
		width: 140rpx;
		border-radius: 50%;
		border: 8rpx solid rgba(255, 255, 255, 0.7)
	}

	.zhuige-user-info-block view:nth-child(1) image:nth-child(2) {
		height: 64rpx;
		width: 64rpx;
		position: absolute;
		z-index: 9;
		right: 10rpx;
		bottom: 20rpx;
	}

	.zhuige-user-info-btn {
		display: flex;
		align-items: center;
		padding: 20rpx 0;
	}

	.zhuige-user-info-btn view,
	.zhuige-user-info-btn button {
		height: 80rpx;
		line-height: 80rpx;
		text-align: center;
		width: 180rpx;
		padding: 0;
		border-radius: 40rpx;
		background: #F3F2F3;
		margin-left: 12rpx;
		font-size: 28rpx;
		font-weight: 400;
	}

	.zhuige-user-info-btn view text {
		color: #333333;
	}

	.zhuige-user-info-btn button::after {
		border: none;
	}

	.zhuige-user-info-btn view.follow {
		background: #363B50;
		color: #ffffff;
		width: 320rpx;
	}

	.zhuige-user-info-btn view.active {
		background: $default-skin-bg;
		color: #ffffff;
	}

	.zhuige-user-count {
		display: flex;
		align-items: center;
		justify-content: flex-end;
		width: 70%;
	}

	.zhuige-user-count>view {
		width: 25%;
		display: flex;
		align-items: center;
		text-align: center;
		flex-wrap: wrap;
	}

	.zhuige-user-count>view text {
		font-size: 26rpx;
		font-weight: 300;
		display: block;
		width: 100%;
	}

	.zhuige-user-count>view view {
		font-size: 46rpx;
		font-weight: 600;
		line-height: 1em;
		width: 100%;
	}

	.zhuige-user-line {
		padding: 10rpx;
		display: flex;
		align-items: center;
	}

	.zhuige-user-line image {
		height: 28rpx;
		width: 28rpx;
		margin-right: 8rpx;
	}

	.zhuige-user-line text {
		font-size: 26rpx;
		font-weight: 400;
		margin-left: 4rpx;
		white-space: nowrap;
	}

	.zhuige-user-line text:last-of-type {
		white-space: normal;
		max-width: 80%;
	}

	.zhuige-home-tab .zhuige-block {
		margin-bottom: 0;
		border-radius: 24rpx 24rpx 0 0;
		padding: 10px;
		border-radius: 6px;
		background: #FFFFFF;
		margin-bottom: 12px;
	}

	.zhuige-home-tab .zhuige-tab {
		border-bottom: 1rpx solid #DDDDDD !important;
		padding-bottom: 20rpx !important;
	}

	.zhuige-user-market {
		padding-bottom: 20rpx;
	}

	.zhuige-user-info-block-text {
		display: flex;
		align-items: center;
		flex-wrap: nowrap;
		padding: 10rpx;
	}

	.zhuige-user-info-block-text text {
		font-size: 36rpx;
		font-weight: 600;
		height: 1.4em;
		line-height: 1.4em;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.zhuige-user-info-block-text image {
		height: 28rpx;
		width: 56rpx;
		min-width: 56rpx;
		margin-left: 12rpx;
	}

	.zhuige-home-tab {
		z-index: 19;
		position: relative;
		margin-top: -40rpx;
	}

	.zhuige-home-list .zhuige-block {
		padding: 20rpx 40rpx !important;
	}
</style>