<template>
	<mobile-frame>
		<view class="main">
			<view class="one">
				<scroll-view scroll-y="true" class="scroll-view" @scrolltolower="toPage">
					<view class="list-scroll-view">
						<discount :Style="Style" :couponList="list" @toReceive="toReceive"></discount>
					</view>
				</scroll-view>
			</view>
		</view>
	</mobile-frame>
</template>

<script>
	import discount from '@/components/discount/index.vue';
	export default {
		components: {
			discount
		},
		data() {
			return {
				Style: {
					receive: true
				},
				user: {},
				list: [],
				total: 0,
				skip: 0,
				limit: 5,
				page: 0
			};
		},
		onLoad: function(e) {
			const that = this;
			// 监听用户是否登录
			that.watchLogin();
		},
		methods: {
			// 领取优惠劵
			async toReceive(e) {
				const that = this;
				uni.showModal({
					title: '提示',
					content: '确定领取该优惠券?',
					success: async function(res) {
						if (res.confirm) {
							const arr = await that.$api(`/userCoupon/getCoupon/${e._id}`, 'POST');
							if (arr.errcode == '0') {
								uni.showToast({
									title: `领取成功`,
									icon: 'none',
									duration: 3000
								})
								that.clearPage();
								that.search();
							} else {
								uni.showToast({
									title: arr.errmsg,
									icon: 'none',
									duration: 2000
								});
							}
						}
					}
				});
			},
			// 监听用户是否登录
			watchLogin() {
				const that = this;
				uni.getStorage({
					key: 'token',
					success: function(res) {
						let user = that.$jwt(res.data);
						if (user) that.$set(that, `user`, user);
						that.search();
					},
					fail: function(err) {
						uni.navigateTo({
							url: `/pages/login/index`
						})
					}
				});
			},
			// 查询列表
			async search() {
				const that = this;
				let user = that.user;
				let info = {
					skip: that.skip,
					limit: that.limit,
				}
				const res = await that.$api(`/coupon/userView`, 'GET', {
					...info
				})
				if (res.errcode == '0') {
					let list = [...that.list, ...res.data];
					that.$set(that, `list`, list)
					that.$set(that, `total`, res.total)
				} else {
					uni.showToast({
						title: res.errmsg,
					});
				}
			},
			// 分页
			toPage(e) {
				const that = this;
				let list = that.list;
				let limit = that.limit;
				if (that.total > list.length) {
					uni.showLoading({
						title: '加载中',
						mask: true
					})
					let page = that.page + 1;
					that.$set(that, `page`, page)
					let skip = page * limit;
					that.$set(that, `skip`, skip)
					that.search();
					uni.hideLoading();
				} else uni.showToast({
					title: '没有更多数据了'
				});
			},
			// 清空列表
			clearPage() {
				const that = this;
				that.$set(that, `list`, [])
				that.$set(that, `skip`, 0)
				that.$set(that, `limit`, 5)
				that.$set(that, `page`, 0)
			}
		}
	}
</script>

<style lang="scss">
	.main {
		background-color: var(--f5Color);
	}
</style>
