<template>
	<view class="ranking">
		<custom-nav :title="pageTitle"></custom-nav>
		<view class="content">
			<view class="top_container">
				<view class="day-title">
					<text @tap="switchDay(0)" :class="day === 0 ? 'active' : ''">总榜单</text>
					<text @tap="switchDay(1)" :class="day === 1 ? 'active' : ''">昨日榜单</text>
				</view>
			</view>
			<view class="my_rank_container">
				<view class="my_rank" v-if="userServerInfo">
					<text class="num">{{ userServerInfo.rank }}</text>
					<image :src="avatarUrl" mode="" class="userImg"></image>
					<text class="name">{{ nickName }}</text>
					<text class="score">{{ userServerInfo.score }}</text>
				</view>
			</view>
			<view class="list_container">
				<view class="type-title" v-if="typeList.length > 0">
					<text v-for="(item, index) in typeList" :key="index" @tap="switchType(index)" :class="type === index ? 'active' : ''">{{ item }}</text>
				</view>
				<view class="rank_list_fixed_title">
					<view class="text1">排名</view>
					<view class="text3">
						<view class="text5">头像</view>
						<view class="text6">昵称</view>
					</view>
					<view class="text4">学分</view>
				</view>
				<view class="list">
					<scroll-view
						v-if="scrollview"
						show-scrollbar="true"
						:scroll-top="scrollTop"
						scroll-with-animation="true"
						:scroll-y="true"
						:style="{ height: scrollViewHeight + 'px' }"
						@scrolltolower="scrolltolower"
						@scrolltoupper="scrolltoTop"
					>
						<ranking-item
							v-for="(item, index) in list"
							:key="item.id"
							:index="item.rank || index + 1"
							:item="item"
							:rank="user.rank"
							:type="type"
							:bg="user.id === item.id && userServerInfo.type !== 3 && day === 0 && type + 1 === userServerInfo.type"
						></ranking-item>
						<custom-reach-bottom v-if="nomore || list.length" :nomore="nomore"></custom-reach-bottom>
					</scroll-view>
				</view>
			</view>
			<view class="share_btn">
				<!-- <button open-type="share">点我晒一晒排名</button> -->
				<button @click="toShare">点我晒一晒排名</button>
			</view>
		</view>
		<page-toast :is-show="is_float" :is-close="false">
			<view class="toast_container shangsheng_toast" @click="is_float = 0">
				<image class="bg" src="https://api.jiuweiyun.cn/public/uploads/icon/toast9.png"></image>
				<view class="text">
					<view>上升了</view>
					<view>{{ is_float }}名</view>
				</view>
			</view>
		</page-toast>
	</view>
</template>

<script>
import rankingItem from '../../components/ranking-item.vue';
import { api_todayPerson, api_todayCrown, api_todayTeam, api_todayWar, api_yesterdayPerson, api_yesterdayCrown, api_yesterdayTeam, api_yesterdayWar } from '../../api.js';

var rank_prev_scroll = 0,
	prev_flag = true,
	location_flag = false,
	load_prev_scrolltop = 0;
let ONE_H = 70;
let PAGE_SIZE = 20;

export default {
	onShareAppMessage: function(res) {
		uni.showLoading({ title: '加载中', mask: true }); //显示loading
		if (res.from === 'button') {
			return {
				title: '我的排名',
				path: `/pages/crownshare/crownshare?top=${JSON.stringify(this.list.slice(0, 3))}&list=${JSON.stringify(this.shareList)}&season=${this.userServerInfo.season}`
			};
		}
		return {
			title: '大卫博士商学院卖货争霸',
			path: '/pages/index/index'
		};
	},
	components: {
		rankingItem
	},
	data() {
		return {
			pageTitle: '排行榜',
			typeList: [], //个人/批发商/团队/服务 导航栏显示内容
			day: 0, //今日/昨日
			type: 0, //个人/批发商/团队/服务
			page: 1, //
			list: [],
			user: {}, //用户当前排名和浮动情况
			scrollViewHeight: 0, //scrollview 高
			requesting: false, //是否正在请求
			nomore: false, //没得更多了
			apis: [
				//用二维数组来表示 今日昨日一共八个 api
				[api_todayPerson, api_todayTeam, api_todayCrown, api_todayWar],
				[api_yesterdayPerson, api_yesterdayTeam, api_yesterdayCrown, api_yesterdayWar]
			],
			scrollview: true, // 显示隐藏 scrollvew 解决切换后 scrolltop 不回到顶部的BUG
			shareList: [], //批发商分享列表
			scrollTop: 0, //设置竖向滚动条位置,
			is_float: 0,
			rankData: [],
			isClickLocation: false,
			avatarUrl: '',
			nickName: ''
		};
	},
	computed: {
		userWeixinInfo() {
			//用户微信信息
			return this.$store.state.userWeixinInfo;
		},
		userServerInfo() {
			//用户信息
			return this.$store.state.userServerInfo;
		},
		showFiexed() {
			//是否在屏幕下方显示显示个人信息
			return this.userServerInfo.type === this.type + 1 && this.userServerInfo.type !== 3 && this.day === 0;
		}
	},
	methods: {
		toShare() {
			uni.navigateTo({
				url: '../share/share'
			});
		},
		scrolltoTop() {
			if (this.isClickLocation) {
				let _this = this;
				this.getPageData(
					() => {
						_this.isClickLocation = false;
						_this.scrollTop = 0;
						_this.page = 1;
					},
					0,
					1
				);
			}
		},
		// 快速定位到我的位置
		locationMe(my) {
			this.isClickLocation = true;
			let max_one_screen_len = Math.ceil(this.scrollViewHeight / ONE_H);
			let toscroll;
			if (my % PAGE_SIZE < max_one_screen_len && my % PAGE_SIZE > 0) {
				toscroll = 0;
			} else if (my % PAGE_SIZE > PAGE_SIZE - max_one_screen_len || my % PAGE_SIZE === 0) {
				toscroll = (PAGE_SIZE - max_one_screen_len) * ONE_H;
			} else {
				toscroll = ((my % PAGE_SIZE) - 1) * ONE_H;
			}
			let you_page = Math.ceil(my / PAGE_SIZE);
			// 如果我的排名小于第一页的个数
			if (my < PAGE_SIZE) {
				this.scrollTop = toscroll;
			} else {
				if (!this.rankData.some(a => a.page === you_page)) {
					this.page = you_page;
					location_flag = true;
					let _this = this;
					this.getPageData(() => {
						// 计算出向下滚动距离
						if (toscroll > 0) {
							_this.scrollTop = toscroll;
						}
					}, 0);
				}
			}
		},
		switchDay(day) {
			//切换天
			this.day = day;
			this.switched();
		},
		switchType(index) {
			//切换类型
			this.type = index;
			this.switched();
		},
		getPageData(cb, isMy = 1, page) {
			page = page ? page : this.page;
			this.requesting = true;
			uni.showLoading({ title: '加载中', mask: true });
			this.$ajax.get(`${this.apis[this.day][this.type]}?page=${page}&season=${this.userServerInfo.season}`).then(
				([, { data: res }]) => {
					res.data.list.length < 20 ? (this.nomore = true) : ''; //如果返回的数据长度小于20，说明没得更多了
					this.requesting = false;
					if (isMy !== 1) {
						this.rankData = [];
					}
					this.rankData.push({
						page: page,
						data: res.data.list
					});
					this.rankData.sort((a, b) => a.page - b.page);
					cb && cb(res.data);
					uni.hideLoading();
				},
				() => {
					uni.hideLoading();
					this.requesting = false;
				}
			);
		},
		switched() {
			//切换数据
			uni.showLoading({ title: '加载中', mask: true }); //显示loading
			this.scrollViewHeight = 0; //将 scrollview 变为高变为零
			this.scrollview = false; // 隐藏 scrollvew 解决切换后 scrolltop 不回到顶部的BUG
			this.page = 1; //恢复页码
			this.nomore = false; //恢复没得更多了
			this.isClickLocation = false;
			this.scrollTop = 0;
			this.rankData = [];
			let _this = this;
			this.getPageData(data => {
				_this.scrollview = true; // 显示 scrollvew 解决切换后 scrolltop 不回到顶部的BUG
				data.per_data ? (_this.user = data.per_data) : ''; //是否有用户排名信息传过来，有就赋给 user
				_this.$scrollViewHeight('.list'); //设置页面内 scroll view 的高度
				if (_this.userServerInfo.type === 2 && _this.type === 1 && _this.day === 0) {
					//如果是批发商点击了批发商榜
					_this.makeCrownShareList();
				} else {
					_this.$hideLoading(); //异步操作结束，停止 loading
				}
			});
		},
		scrolltolower() {
			//下拉 scroll view 触底函数
			if (this.userServerInfo.type === 1 && this.type === 1) {
				//普通客户查看批发商榜时不会触发
				return;
			}
			if (!this.requesting && !this.nomore) {
				//防抖
				this.page = this.rankData[this.rankData.length - 1].page + 1;
				this.getPageData();
			}
		},
		async makeCrownShareList() {
			//生成批发商分享页面的列表数据
			const user = Object.assign(
				{
					//生成用户信息
					name: this.userServerInfo.name,
					avatar: this.userWeixinInfo.avatarUrl,
					self: true
				},
				this.user
			);
			const rank = start => {
				this.shareList.forEach((e, i) => {
					e.rank = i + start;
				});
			};
			if (this.user.rank < 5) {
				//前四名的处理方式
				this.shareList = this.list.slice(0, 4);
				this.shareList.splice(this.user.rank - 1, 1, user);
				rank(1); //为分享数组里面的对象添加排名
				this.$hideLoading(); //异步操作结束，停止 loading
			} else if (this.user.rank > 4 && this.user.rank < 20) {
				//5 - 19 名的处理方式
				this.shareList = this.list.slice(this.user.rank - 3, this.user.rank + 1);
				this.shareList.splice(2, 1, user);
				rank(this.user.rank - 2); //为分享数组里面的对象添加排名
				this.$hideLoading(); //异步操作结束，停止 loading
			} else if (this.user.rank === 20) {
				//第 20 名的处理方式
				this.shareList = this.list.slice(17, 19);
				this.$ajax.get(`${api_todayCrown}?page=2&season=${this.userServerInfo.season}`).then(([, { data: res }]) => {
					this.shareList.push(user);
					this.shareList.push(res.data.list[0]);
					rank(this.user.rank - 2); //为分享数组里面的对象添加排名
					this.$hideLoading(); //异步操作结束，停止 loading
				});
			} else {
				this.$hideLoading();
				if (this.user.rank) {
					const page = Math.floor(this.user.rank / 20) + 1; //自己排名所处的页数（第几页）
					const index = this.user.rank % 20; //自己在自己那页的下标（第几个）
					const [, { data: res1 }] = await this.$ajax.get(`${api_todayCrown}?page=${page - 1}&season=${this.userServerInfo.season}`);
					const [, { data: res2 }] = await this.$ajax.get(`${api_todayCrown}?page=${page}&season=${this.userServerInfo.season}`);
					const [, { data: res3 }] = await this.$ajax.get(`${api_todayCrown}?page=${page + 1}&season=${this.userServerInfo.season}`);
					const totalList = [...res1.data.list, ...res2.data.list, ...res3.data.list];
					this.shareList = totalList.slice(20 + index - 3, 20 + index + 1);
					this.shareList.splice(2, 1, user);
					rank(this.user.rank - 2); //为分享数组里面的对象添加排名
					this.$hideLoading(); //异步操作结束，停止 loading
				}
			}
		}
	},
	created() {
		this.avatarUrl = this.userServerInfo.avatar
		this.nickName = this.userServerInfo.name
		uni.showLoading({ title: '加载中', mask: true }); //显示loading
		if (this.userServerInfo.type == 1) {
			//根据用户类型生成要展示的数据列表
			this.typeList = ['个人排行榜'];
			this.apis = [
				//用二维数组来表示 今日昨日一共八个 api
				[api_todayPerson, api_todayTeam],
				[api_yesterdayPerson, api_yesterdayTeam]
			];
		} else if (this.userServerInfo.type == 2) {
			// this.typeList = ['个人排行榜', '团队排行榜'];
			this.typeList = ['个人排行榜', '总排行榜'];
		} else if (this.userServerInfo.type == 3) {
			// this.typeList = ['个人排行榜', '团队排行榜'];
			this.typeList = ['个人排行榜', '总排行榜'];
		}
		this.$scrollViewHeight('.list'); //设置页面内 scroll view 的高度
		let _this = this;
		this.getPageData(data => {
			_this.$hideLoading(); //异步操作结束，停止 loading
			data.per_data ? (_this.user = data.per_data) : ''; //是否有用户排名信息传过来，有就赋给 user
			_this.is_float = (data.per_data && data.per_data.float) || 0;
		});
	},
	watch: {
		rankData: {
			handler(a, b) {
				if (a.length > 0) {
					this.list = [];
					a.forEach(item => {
						this.list = this.list.concat(item.data);
					});
				}
			},
			deep: true
		}
	}
};
</script>

<style lang="scss" scoped>
.ranking {
	@include page();

	.shangsheng_toast {
		width: 750rpx;
		height: 811rpx;
		.text {
			color: #e46b00;
			font-size: 60rpx;
			position: absolute;
			width: 200rpx;
			left: 50%;
			margin-left: -100rpx;
			bottom: 227rpx;
			text-align: center;
			line-height: 90rpx;
		}
	}

	.content {
		border-top: $custom-nav-borderbot-height solid $custom-nav-borderbot-color;
		display: flex;
		flex-direction: column;
		background-color: #f2f4f5;
		.top_container {
			width: 100%;
			height: 265rpx;
			background-image: url(../../static/new/rank_bg.png);
			background-repeat: no-repeat;
			background-size: 100% 100%;
			.day-title {
				width: 100%;
				display: flex;
				justify-content: space-between;
				align-items: center;
				box-sizing: border-box;
				padding: 0 50rpx;
				margin: 34rpx 0 28rpx 0;
				text {
					height: 64rpx;
					width: 300rpx;
					line-height: 64rpx;
					text-align: center;
					box-sizing: border-box;
					border: 2rpx solid #ffffff;
					font-size: 36rpx;
					color: #ffffff;
					border-radius: 64rpx;
					&.active {
						color: #fa6342;
						background-color: #ffffff;
					}
				}
			}
		}
		.my_rank_container {
			width: 100%;
			padding: 0 30rpx;
			position: relative;
			height: 40rpx;
			margin-bottom: 30rpx;
			.my_rank {
				height: 120rpx;
				position: absolute;
				top: -80rpx;
				left: 30rpx;
				right: 30rpx;
				background-color: #ffffff;
				border-radius: 10rpx;
				box-sizing: border-box;
				padding: 0 42rpx;
				display: flex;
				justify-content: space-between;
				align-items: center;
				.num {
					color: #2a2a2a;
					font-size: 40rpx;
				}
				.userImg {
					width: 64rpx;
					height: 64rpx;
					border-radius: 50%;
				}
				.name {
					font-size: 28rpx;
					color: #2a2a2a;
				}
				.score {
					color: #fa6342;
					font-size: 28rpx;
				}
			}
		}
		.share_btn {
			margin-top: 15rpx;
			padding: 0 30rpx;
			button {
				width: 100%;
				height: 76rpx;
				border: 2rpx solid #ffffff;
				border-radius: 24rpx;
				padding: 0;
				background: #fa6342;
				line-height: 76rpx;
				text-align: center;
				font-size: 28rpx;
				color: #ffffff;
				border-radius: 76rpx;
			}
		}
		.title-bar {
			height: 4rpx;
			width: 100%;
			background: #dedede;
			position: relative;
			.title-drog {
				width: 50%;
				height: 100%;
				background: #fa6342;
				position: absolute;
				top: 0;
				left: 0;
				&::after {
					content: '';
					display: block;
					width: 0;
					height: 0;
					border-style: solid;
					border-width: 8rpx 12rpx;
					border-color: transparent transparent red transparent;
					transform: translate(175.5rpx, -100%);
				}
			}
		}
		image {
			display: block;
			width: 100%;
			height: 240rpx;
		}
		.type-title {
			height: 83rpx;
			width: 100%;
			display: flex;
			justify-content: space-around;
			text {
				height: 83rpx;
				flex: 1;
				color: #999999;
				font-size: 36rpx;
				line-height: 83rpx;
				text-align: center;
				box-sizing: border-box;
				position: relative;
				border: 2rpx solid #ffffff;
				font-weight: 500;
				&.active {
					background-color: #ffffff;
					color: #fa6342;
				}
			}
		}
		.list_container {
			margin: 0 30rpx;
			flex: 1;
			display: flex;
			justify-content: space-between;
			flex-direction: column;
			box-shadow: 0 0 21rpx 3rpx rgba(255, 90, 11, 0.2);
		}
		.rank_list_fixed_title {
			width: 100%;
			height: 64rpx;
			line-height: 64rpx;
			color: #666666;
			font-size: 32rpx;
			padding: 0 30rpx;
			box-sizing: border-box;
			display: flex;
			justify-content: space-between;
			align-items: center;
			.text1 {
				width: 76rpx;
			}
			.text3 {
				width: calc(100% - 206rpx);
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-left: 40rpx;
			}
			.text4 {
				width: 130rpx;
				text-align: center;
			}
			.text5 {
				width: 64rpx;
				text-align: center;
			}
			.text6 {
				width: calc(100% - 104rpx);
				// text-align: center;
				text-align: left !important;
			}
		}
		.list {
			flex: 1;
			height: calc(100% - 91rpx - 64rpx);
		}
		.fiexed {
			height: 100rpx;
			bottom: 0;
			background: #fa6342;
			display: flex;
			padding: 0 30rpx;
			.left {
				height: 100%;
				width: 136rpx;
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				text {
					color: #ffffff;
					font-size: 26rpx;
					&.rank {
						font-size: 32rpx;
					}
				}
			}
			.center {
				width: 380rpx;
				margin-left: 10rpx;
				height: 100%;
				display: flex;
				align-items: center;
				color: #ffffff;
				position: relative;
				image {
					width: 64rpx;
					height: 64rpx;
					border-radius: 50%;
					&.hat {
						position: absolute;
						top: 6rpx;
						left: -5rpx;
						width: 72rpx;
						height: 88rpx;
					}
				}
				text {
					margin-left: 30rpx;
					font-size: 24rpx;
				}
			}
			.right {
				flex: 1;
				display: flex;
				align-items: center;
				color: #ffffff;
				button {
					width: 146rpx;
					height: 48rpx;
					border: 2rpx solid #ffffff;
					border-radius: 24rpx;
					padding: 0;
					background: transparent;
					line-height: 48rpx;
					text-align: center;
					font-size: 24rpx;
					color: #ffffff;
				}
				.score {
					width: 130rpx;
					height: 100%;
					display: flex;
					align-items: center;
					color: #fa6342;
					image {
						width: 30rpx;
						height: 30rpx;
					}
					text {
						font-size: 24rpx;
						margin-left: 10rpx;
					}
				}
				.float {
					flex: 1;
					display: flex;
					align-items: center;
					image {
						width: 24rpx;
						height: 30rpx;
					}
					text {
						margin-left: 10rpx;
						font-size: 24rpx;
					}
				}
			}
		}
	}
}
</style>
