<template>
	<view class="container clearfix">
		<view class="coupon-tabs">
			<coupon-tabs
				:tabs="navbar"
				:currentTab="currentTab > 2 ? 0 : currentTab"
				@change="change"
				:itemWidth="100 / navbar.length + '%'"
				selectedColor="#FF5B00"
				sliderBgColor="#FF5B00"
			>
			</coupon-tabs>
		</view>
		<view
			class="container-list"
			:style="{
				overflow: 'auto',
				paddingBottom: isIphoneX ? '140rpx' : '0rpx',
				height: coupinList.length > 6 ? windowHeight + 'px' : 'auto'
			}"
			v-show="isRequest"
		>
			<view class="empty-container" v-if="showEmpty">
				<image class="empty-container-image" :src="StaticUrl + '/icon/icon-coupon-empty@2x.png'"></image>
				<text class="error-text">暂无优惠券~</text>
			</view>
			<template v-else>
				<view :style="{ height: coupinList.length > 5 ? scrollHeight + 'px' : 'auto' }">
					<view
						v-for="(coupon, index) in coupinList"
						:key="index"
						:id="coupon.id"
						class="coupon-list"
						:class="listClass"
					>
						<view class="list-cell-le">
							<view class="coupon-maxMoney">
								<text class="small">￥</text> {{ coupon.couponAmount }}
							</view>
							<view class="coupon-minMoney"> 满{{ coupon.touchPrice }}可用 </view>
						</view>
						<view class="list-cell-ri">
							<view class="list-cell-top">
								<view class="list-cell-type">
									<view class="list-cell-tags">
										<template v-if="coupon.moneyCouponFlag == 1">
											<text
												class="tags"
												v-if="coupon.moneyCouponType == 1"
												:class="coupon.useStatus == 2 || coupon.useStatus == 3 ? 'none' : ''"
												>意向{{ coupon.couponType | TypeFormat }}</text
											>
											<text class="tags" v-else>定向{{ coupon.couponType | TypeFormat }}</text>
										</template>
										<template v-else>
											<text
												class="tags"
												:class="coupon.useStatus == 2 || coupon.useStatus == 3 ? 'none' : ''"
												>{{ coupon.couponType | TypeFormat }}</text
											>
										</template>
									</view>
									<view
										class="list-cell-texts"
										:class="coupon.useStatus == 2 || coupon.useStatus == 3 ? 'none' : ''"
									>
										<text v-if="coupon.couponType == 0">
											{{
												coupon.productType && coupon.productType == 1
													? '全商城商品通用'
													: '仅可购买指定商品'
											}}
										</text>
										<text v-if="coupon.couponType == 1">
											{{ coupon.categoryType == 1 ? '仅限购买产品类商品' : '仅限购买仪器类商品' }}
										</text>
										<text v-if="coupon.couponType == 3"
											>仅限购买店铺【{{ coupon.shopName }}】的商品</text
										>
										<text v-if="coupon.couponType == 4 || coupon.couponType == 2"
											>全商城商品通用</text
										>
									</view>
								</view>
								<view class="list-cell-btn">
									<view class="icon-used" v-if="coupon.useStatus == 1">
										<view class="icon-used-btn" @click="toUseCoupon(coupon)">去使用</view>
									</view>
									<view class="icon-use" v-if="coupon.useStatus == 2"></view>
									<view class="icon-invalid" v-if="coupon.useStatus == 3"></view>
								</view>
							</view>
							<view class="list-cell-time">{{ coupon.startDate }} - {{ coupon.endDate }}</view>
                           <button open-type="share" class="list-cell-share" :data-coupon="coupon" v-if="coupon.useStatus == 1">
                               <text class="iconfont icon-fenxiang"></text>
                           </button>
						</view>
					</view>
					<!--加载loadding-->
					<tui-loadmore :visible="loadding" :index="3" type="black"></tui-loadmore>
					<tui-nomore :visible="!pullUpOn" :backgroundColor="'#F7F7F7'" :text="nomoreText"></tui-nomore>
					<!--加载loadding-->
				</view>
			</template>
		</view>
		<view class="button-bottom" :style="{ paddingBottom: isIphoneX ? '68rpx' : '20rpx' }">
			<view class="button-exchange" @click="navigator('/pages/user/coupon/coupon-exchange')"> 兑换优惠券 </view>
			<view class="button-receive" @click="navigator('/pages/user/coupon/coupon-collection')"> 领更多好券 </view>
		</view>
	</view>
</template>

<script>
import { mapState, mapMutations } from 'vuex'
import couponTabs from '@/components/cm-module/coupon/tui-tabs.vue'
import { COUPON_TEXT_MAP } from '@/utils/coupon.share.js'
export default {
	components: {
		couponTabs
	},
	data() {
		return {
			isRequest: false,
			listClass: 'list-used',
			StaticUrl: this.$Static,
			isIphoneX: this.$store.state.isIphoneX,
			currentTab: 0,
			listQuery: {
				userId: 0,
				pageNum: 1,
				pageSize: 10,
				status: 1
			},
			navbar: [{ name: '未使用', num: 0 }, { name: '已使用', num: 0 }, { name: '已失效', num: 0 }],
			coupinList: [],
			windowHeight: '',
			scrollHeight: '',
			showEmpty: false,
			nomoreText: '上拉显示更多',
			hasNextPage: false,
			loadding: false,
			pullUpOn: true,
			pullFlag: true
		}
	},
	onLoad() {},
	filters: {
		TypeFormat(value) {
			switch (value) {
				case 0:
					return '活动券'
					break
				case 1:
					return '品类券'
					break
				case 2:
					return '用户专享券'
					break
				case 3:
					return '店铺券'
					break
				case 4:
					return '新用户券'
					break
			}
		}
	},
	computed: {
		...mapState(['hasLogin', 'userInfo', 'identity', 'isActivity'])
	},
	methods: {
		setScrollHeight() {
			const { windowHeight, pixelRatio } = wx.getSystemInfoSync()
			this.windowHeight = windowHeight - 1
			this.scrollHeight = windowHeight - 1
		},
		QueryCouponList() {
			// 获取优惠券列表
			this.coupinList = []
			this.listQuery.pageNum = 1
			this.ProductService.QueryCouponCenter(this.listQuery)
				.then(response => {
					let data = response.data
					if (data.list && data.list.length > 0) {
						this.showEmpty = false
						this.hasNextPage = data.hasNextPage
						this.coupinList = data.list
						this.pullFlag = false
						setTimeout(() => {
							this.pullFlag = true
						}, 500)
						if (this.hasNextPage) {
							this.pullUpOn = false
							this.nomoreText = '上拉显示更多'
						} else {
							if (this.coupinList.length < 8) {
								this.pullUpOn = true
							} else {
								this.pullUpOn = false
								this.loadding = false
								this.nomoreText = '已至底部'
							}
						}
					} else {
						this.showEmpty = true
					}
					this.isRequest = true
				})
				.catch(error => {
					this.$util.msg(error.msg, 2000)
				})
		},
		getOnReachBottomData() {
			// 上滑加载分页
			this.listQuery.pageNum += 1
			this.ProductService.QueryCouponCenter(this.listQuery)
				.then(response => {
					let data = response.data
					if (data.list && data.list.length > 0) {
						this.hasNextPage = data.hasNextPage
						this.coupinList = this.coupinList.concat(data.list)
						this.pullFlag = false // 防上拉暴滑
						setTimeout(() => {
							this.pullFlag = true
						}, 500)
						if (this.hasNextPage) {
							this.pullUpOn = false
							this.nomoreText = '上拉显示更多'
						} else {
							this.pullUpOn = false
							this.loadding = false
							this.nomoreText = '已至底部'
						}
					}
				})
				.catch(error => {
					this.$util.msg(error.msg, 2000)
				})
		},
		getQueryCouponsCount() {
			// 获取优惠券数量
			this.ProductService.QueryCouponsCount({
				userId: this.listQuery.userId
			})
				.then(response => {
					let data = response.data
					this.navbar[0].num = data.unusedNum
					this.navbar[1].num = data.usedNum
					this.navbar[2].num = data.expiredNum
				})
				.catch(error => {
					this.$util.msg(error.msg, 2000)
				})
		},
		toUseCoupon(coupon) {
			// 去使用跳转路径,友盟埋点收集去使用优惠券
			if (process.env.NODE_ENV != 'development') {
				this.$uma.trackEvent('Um_Event_userCouponToUseCoupon', {
					Um_Key_PageName: '机构优惠券列表',
					Um_Key_EvenName: '使用优惠券',
					Um_Key_CouponId: `${coupon.couponId}`,
				})
			}
			switch (coupon.couponType) {
				case 0: // 活动券：跳转到商城首页 / 或者活动页（看是否指定了商品）
					if (coupon.productType == 1) {
						// 1 全商城通用 2 指定商品
						console.log('asdasdasda', coupon.productType)
						this.$api.switchTabTo('/pages/tabBar/home/index')
					} else {
						this.$api.navigateTo('/pages/user/coupon/coupon-product?couponId=' + coupon.couponId)
					}
					break
				case 1: // 品类券：跳转到产品 287 / 仪器页 286
					this.$api.navigateTo(`/pages/goods/good-floor?linkId=${coupon.categoryType == 1 ? 287 : 286}`)
					break
				case 2: // 用户专享券：跳转到商城首页
					this.$api.switchTabTo('/pages/tabBar/home/index')
					break
				case 3: // 店铺券：跳转到店铺首页
					this.$api.navigateTo('/pages/supplier/user/my-shop?shopId=' + coupon.shopId)
					break
				case 4: // 新用户券：跳转到商城首页
					this.$api.switchTabTo('/pages/tabBar/home/index')
					break
			}
		},
		change(e) {
			this.currentTab = e.index
			this.isRequest = false
			this.listQuery.pageNum = 1
			switch (this.currentTab) {
				case 0:
					this.listClass = 'list-used'
					this.listQuery.status = 1
					break
				case 1:
					this.listClass = 'list-none'
					this.listQuery.status = 2
					break
				case 2:
					this.listClass = 'list-none'
					this.listQuery.status = 3
					break
			}
			this.QueryCouponList()
		},
		navigator(url) {
			this.$api.navigateTo(url)
		}
	},
    onShareAppMessage(res) {
        //分享购买优惠券
        const coupon = res.target.dataset.coupon
        if (res.from === 'button') {
            const randomIndex = Math.floor(Math.random() * COUPON_TEXT_MAP.length)
            const shareTitle = coupon.moneyCouponFlag === 1 ?
                `${coupon.moneyCouponPrice}抵${coupon.couponAmount}，限时优惠券等您抢购~` :
                COUPON_TEXT_MAP[randomIndex]
            return {
                title: shareTitle,
                path: `pages/user/coupon/coupon-details?couponId=${coupon.couponId}&shareUserId=${this.listQuery.userId}`,
                imageUrl: 'https://static.caimei365.com/app/img/icon/icon-shareCoupon@2x.png'
            }
        }
    },
	onPullDownRefresh() {
		setTimeout(() => {
			this.QueryCouponList()
			uni.stopPullDownRefresh()
		}, 200)
	},
	onReachBottom() {
		if (this.hasNextPage) {
			this.loadding = true
			this.pullUpOn = true
			this.getOnReachBottomData()
		}
	},
	onShow() {
		this.setScrollHeight()
		this.$api.getComStorage('userInfo').then(resolve => {
			this.listQuery.userId = resolve.userId ? resolve.userId : 0
			this.getQueryCouponsCount()
			this.QueryCouponList()
		})
	}
}
</script>

<style lang="scss">
page {
	background-color: #f7f7f7;
}
.coupon-tabs {
	width: 100%;
	height: 80rpx;
	position: fixed;
	top: 0;
	left: 0;
	z-index: 99;
}
.container {
	width: 100%;
	height: auto;
	padding-top: 80rpx;
}
.container-list {
	box-sizing: border-box;
	padding: 24rpx;
	scroll-view {
		height: 100%;
		overflow: scroll;
	}
	.empty-container-image {
		width: 260rpx;
		height: 260rpx;
		margin-top: -300rpx;
	}
	.toIndexPage {
		bottom: 390rpx;
	}
	.coupon-list {
		width: 100%;
		height: 200rpx;
		margin-bottom: 24rpx;
		box-sizing: border-box;
		&.list-used {
			background: url(https://static.caimei365.com/app/img/icon/icon-coupon-uesb@2x.png);
			background-size: cover;
		}
		&.list-none {
			background: url(https://static.caimei365.com/app/img/icon/icon-coupon-none@2x.png);
			background-size: cover;
		}
		.list-cell-le {
			width: 224rpx;
			height: 100%;
			box-sizing: border-box;
			padding: 37rpx 0;
			float: left;
			.coupon-maxMoney {
				width: 100%;
				height: 78rpx;
				line-height: 78rpx;
				font-size: 56rpx;
				color: #ffffff;
				text-align: center;
				.small {
					font-size: $font-size-24;
				}
			}
			.coupon-minMoney {
				width: 100%;
				height: 33rpx;
				line-height: 33rpx;
				font-size: $font-size-24;
				color: #ffffff;
				text-align: center;
			}
		}
		.list-cell-ri {
			width: 478rpx;
			height: 100%;
			box-sizing: border-box;
			padding: 20rpx 24rpx 0 24rpx;
			float: right;
            position: relative;
            .list-cell-share{
                width: 60rpx;
                height: 60rpx;
                line-height: 60rpx;
                text-align: center;
                position: absolute;
                right: 0;
                top: 0;
                box-sizing: border-box;
                display: block;
                background: transparent;
                border-radius: 0;
                border: 0;
                margin: 0;
                .iconfont{
                    font-size: 40rpx;
                    color: #07c160;
                }
            }
			.list-cell-top {
				width: 100%;
				height: 121rpx;
				float: left;
				border-bottom: 1px solid #e1e1e1;
				.list-cell-type {
					width: 286rpx;
					height: 100%;
					float: left;
					.list-cell-tags {
						width: 100%;
						height: 32rpx;
						margin-bottom: 7rpx;
						.tags {
							display: inline-block;
							padding: 0 10rpx;
							height: 32rpx;
							line-height: 32rpx;
							background-color: #ffdcce;
							color: #f94b4b;
							font-size: $font-size-20;
							border-radius: 8rpx;
							text-align: center;
							float: left;
							&.none {
								background-color: #dbdbdb;
								color: #ffffff;
							}
						}
					}
					.list-cell-texts {
						width: 100%;
						height: auto;
						line-height: 35rpx;
						text-overflow: ellipsis;
						display: -webkit-box;
						word-break: break-all;
						-webkit-box-orient: vertical;
						-webkit-line-clamp: 2;
						overflow: hidden;
						font-size: 26rpx;
						color: #333333;
						&.none {
							color: #999999;
						}
					}
				}
				.list-cell-btn {
					width: 128rpx;
					height: 100%;
					float: right;
					.icon-used {
						width: 100%;
						height: 100%;
						box-sizing: border-box;
						padding-top: 57rpx;
						.icon-used-btn {
							width: 128rpx;
							height: 48rpx;
							border-radius: 28rpx;
							border: solid 1px #f94b4b;
							line-height: 48rpx;
							font-size: $font-size-26;
							color: #f94b4b;
							text-align: center;
						}
					}
					.icon-use {
						width: 92rpx;
						height: 92rpx;
						box-sizing: border-box;
						background: url(https://static.caimei365.com/app/img/icon/icon-coupon-use@2x.png);
						background-size: cover;
						float: right;
					}
					.icon-invalid {
						width: 92rpx;
						height: 92rpx;
						box-sizing: border-box;
						background: url(https://static.caimei365.com/app/img/icon/icon-coupon-invalid@2x.png);
						background-size: cover;
						float: right;
					}
				}
			}
			.list-cell-time {
				width: 100%;
				height: 58rpx;
				line-height: 58rpx;
				text-align: left;
				font-size: $font-size-20;
				color: #999999;
			}
		}
	}
}
.button-bottom {
	width: 100%;
	position: fixed;
	background-color: #ffffff;
	bottom: 0;
	left: 0;
	box-sizing: border-box;
	padding: 8rpx 24rpx;
	z-index: 999;
	.button-exchange {
		width: 280rpx;
		height: 84rpx;
		line-height: 84rpx;
		background-color: #ffe6dc;
		border-radius: 50rpx;
		text-align: center;
		font-size: $font-size-30;
		color: #FF5B00;
		float: left;
	}
	.button-receive {
		width: 408rpx;
		height: 84rpx;
		line-height: 84rpx;
		background: $btn-confirm;
		border-radius: 50rpx;
		text-align: center;
		font-size: $font-size-30;
		color: #ffffff;
		float: right;
	}
}
</style>
