<template>
	<view>
		<view class="huiyuan" v-if="TabList.length > 0">
			<swiper class="swiper" next-margin="15rpx" @change="swiperChange">
				<swiper-item :class="'li li' + index" v-for="(item, index) in TabList" :key="index">
					<image :src="item.pic ? item.pic : '../static/mine/images/vip_bg' + index + '.png'" class="vipbg"></image>
					<view class="userinfo">
						<view class="infos dflex">
							<image :src="userinfo.avatar ? userinfo.avatar : '../../static/pages/images/userimg.png'" mode="aspectFill" class="user-img"></image>
							<view class="flex">
								<view class="username">{{ userinfo.nickName }}</view>
								<image :src="item.icon ? item.icon : '../static/mine/images/level' + index + '.png'" mode="heightFix" class="level-img"></image>
							</view>
						</view>

						<view class="times" v-if="userinfo.level == item.id && userinfo.level != 0 && !userinfo.end">
							<view class="expire">
								<view class="v-price" v-if="vip.money > 0">
									<text>￥</text>
									{{ vip.money }}
								</view>
								<view class="v-price" v-else>免费领取</view>
								<view class="ddflex">
									{{ userinfo.expireTime }}到期
									<image :src="'../static/mine/images/rico' + index + '.png'"></image>
								</view>
							</view>
							<view class="vipid">NO.{{ userinfo.level }}</view>
						</view>
						<block v-else>
							<view class="v-times"> 
								<view class="v-price" v-if="vip.money > 0">
									<text>￥</text>
									{{ vip.money }}
								</view>
								<view class="v-price" v-else>免费领取</view>
								<view class="invi">有效期：{{ vip.day }}天</view>
							</view>
						</block>

						<view class="obtn" @tap="openVip(item,index)" :data-index="index">
							<block v-if="vip.money > 0">{{ userinfo.level == item.id && userinfo.level != 0 && !userinfo.end ? '立即续费' : '立即开通' }}</block>
							<block v-else>{{ userinfo.level == item.id && userinfo.level != 0 && !userinfo.end ? '已领取' : '立即领取' }}</block>
						</view>
					</view>
				</swiper-item>
			</swiper>
			<view class="dots dflex">
				<block v-for="(item, index) in TabList" :key="index"><view :class="['dot', index == swiperCurrent ? 'active' : '']"></view></block>
			</view>
		</view>
		<view class="quanyi">
			<view class="quanyi-tit dflex">会员权益</view>
			<view class="ziyou">
				<block v-if="nodes[idx]"><!-- <mp-html :content="nodes[idx]" @imgtap="choose" /> --><rich-text :nodes="nodes[idx]"></rich-text></block>
				<block v-else>无</block>
			</view>
		</view>
		<block v-if="couponCount>0">
		<view class="cai-tit">
			会员优惠券
			
		</view>
		<view class="quan">
			<scroll-view scroll-x="true" :class="'quans' + (couponCount == 1 ? ' quans1':'')">
				<view class="li" v-for="(item, index) in couponList" :key="index" @click="recieveCoupon(index)">
					<view class="q-info ddflex">
						<view class="fflex">
							<view class="q-title tover">{{item.couponType === 3 ? '通用券' : item.couponType === 1 ? '满减券' :  item.couponType === 4 ? '免除券':'代金券'}}-{{item.couponTitle}}</view>
							<view class="q-time ddflex"><view>{{timeFormat(item.couponStart)}}</view><text>至</text><view>{{timeFormat(item.couponEnd)}}</view></view>
						</view>
						<view class="info-r">
							<view class="q-money"><text>￥</text>{{item.couponAmount}}</view>
							<view class="q-man">{{item.couponBrief}}</view>
						</view>
					</view>
					<view class="li-bot ddflex">
						<view class="check ddflex fflex" @click.stop="checks(item,index)">查看详情
							<image src="../static/mine/images/bico.png"></image>
						</view>
						<view class="yong ddflex">{{item.userCount >= item.userReceive&&item.userCount!=0&&item.userReceive!=-1 ? '已领取' : '领取'}}</view>
					</view>
					<view class="q-infos" v-if="item.isShow">
						<view>1.使用时间：{{timeFormat(item.couponStart)}}至{{timeFormat(item.couponEnd)}}</view>
						<view v-if="item.couponBrief">2.使用范围：{{item.couponBrief}}</view>
						<view v-if="item.useActionsList && item.useActionsList.length > 0" class="i-pro">{{item.couponBrief?'3':'2'}}.指定产品：
							<text v-for="(it,idx) in item.useActionsList" :key="idx" @click="toDetail(it)">{{it.name}}</text>
						</view>
					</view>
				</view>
			</scroll-view>
		</view>
		</block>
		<view class="cai">
			<view class="cai-tit">
				会员专区
				<text>专属折扣享不停</text>
			</view>
			<view class="tabcon pdlr20 dflex">
				<block v-for="(item, index) in likeList" :key="index">
					<view class="li">
						<view class="jsdimgs" @tap="toDetail" :data-id="item.id">
							<image :src="item.pic + '?x-oss-process=style/w375'" mode="aspectFit" class="jsdpro"></image>
							<image src="/static/pages/images/jishida.png" v-if="item.isTimely === 1" class="jsdimg"></image>
						</view>
						<view class="jsdinfo">
							<view class="proname" @tap="toDetail" :data-id="item.id">{{ item.title }}</view>
							<view class="xiaol dflex">
								<block v-if="item.isOtc != 5 && about.is_open_shop == 1 && (isDistriUser == 2 || ascription)">
									<view class="zhuan dflex" v-if="item.commission > 0">
										<block>
											<text>赚</text>
											<view class="dflex">￥{{ item.commission }}</view>
										</block>
									</view>
								</block>
								<view class="yishou">{{ item.sellStock }}件已售</view>
							</view>
							<view class="operate dflex">
								<view class="price proprice">
									￥
									<text>{{ show_membership_price == 1 && item.actualPrice < item.salePrice ? item.actualPrice : item.salePrice }}</text>
									<text class="vip" v-if="show_membership_price == 1 && item.membersPrice < item.salePrice">
										<text class="sale">VIP</text>
										<text class="members">{{ item.membersPrice }}</text>
									</text>
									<text class="del" v-else>￥{{ item.marketPrice }}</text>
								</view>
								<view class="add-cart">
									<view class="nums dflex" v-if="item.count > 0">
										<image src="/static/pages/images/jian.png"></image>
										<view class="num">{{ item.count }}</view>
										<image src="/static/pages/images/jia1.png"></image>
									</view>
									<image
										src="/static/pages/images/jia.png"
										@tap="addShopCart"
										:data-id="item.id"
										:data-skuid="item.skuId"
										:data-index="index"
										:data-state="item.state"
										v-else
									></image>
								</view>
							</view>
						</view>
					</view>
				</block>
			</view>
		</view>
		<!-- 开通会员弹窗 -->
		<view class="mask" @tap="eliminate" v-if="show"></view>
		<view class="purchaseVip" v-if="show">
			<view class="timg dflex">
				<image :src="userinfo.avatar" mode="aspectFit"></image>
				<text>{{ userinfo.nickName }}</text>
			</view>
			<view class="cont">
				<view class="tab">
					<scroll-view class="scroll-box" scroll-x style="height:100rpx">
						<view
							v-for="(item, index) in TabList"
							:key="index"
							:class="'li ' + (item.active ? 'active' : '')"
							:style="
								TabList.length == 4
									? 'width:25%'
									: TabList.length == 3
									? 'width:33%'
									: TabList.length == 2
									? 'width:50%'
									: TabList.length == 1
									? 'width:100%'
									: 'width:20%'
							"
							:data-index="index"
							:data-level="item.level"
							@tap="switchTab"
							v-if="item.price != 0"
						>
							{{ item.title }}
						</view>
					</scroll-view>
				</view>

				<view class="jiage dflex">
					<scroll-view class="scroll-box" scroll-x style="height:400rpx">
						<view
							v-for="(item, index) in money"
							:key="index"
							class="li"
							@tap="selectOpen"
							:data-index="index"
							:data-id="item.id"
							:data-price="item.price"
							:data-day="item.day"
						>
							<view :class="'month ' + (item.active ? 'act' : '')">{{ item.day }}天</view>
							<view :class="'money ' + (item.active ? 'actbor' : '')">
								<text class="txt">￥</text>
								{{ item.price }}
							</view>
						</view>
					</scroll-view>
				</view>
				<view class="title">开通{{ day }}天会员，享尊贵特权</view>
				<view class="confirm mbglinear" @tap="buy">立即支付{{ price }}元</view>
			</view>
		</view>
		<view class="placeholder-view" :style="'height:' + (bottomBlankHeight + 115) + 'rpx'"></view>
	</view>
</template>

<script>
const app = getApp();
const req = require('../../utils/request.js');
const route = require('../../utils/route');
const utils = require('../../utils/util.js');
import mpHtml from '../../components/mp-html/components/mp-html/mp-html';
export default {
	components: {
		mpHtml
	},
	data() {
		return {
			swiperCurrent: 0,
			page: 1,
			likeList: [],
			isLikeLoad: true,
			TabList: [],
			show: false,
			index: 0,
			idx: 0,
			bottomBlankHeight: app.globalData.isIPhoneX ? 68 : 0,
			bottomId: '',
			searchTitle: '',
			show_membership_price: 0,
			money: [],
			level: '',
			imgs: '',
			vipList: '',
			nodes: '',
			imags: '',
			userinfo: '',
			price: 0,
			day: 0,
			id: '',
			freshen: true,
			vip: {
				money: 0,
				day: 0
			}, //默认的会员价格
			about: {},
			isDistriUser: 0, // 判断用户是否是分销员 2为分销员
			ascription: false ,//是否开启小店
			couponList: [],//会员优惠券
			couponCount: 0
		};
	},

	components: {},
	props: {},

	onLoad(options) {
		this.getConfig();
		this.getMy();
		this.getLikeList();
		if (options.searchTitle) {
			this.setData({
				searchTitle: options.searchTitle
			});
		}
	},

	onShow() {
		if (this.freshen) {
			this.getuserVip();
			if (req.getStorage('userInfo')) {
				this.getVip();
			}
		}
	},

	methods: {
		timeFormat(time){
			if(time.indexOf('00:00:00')>-1){
				let newTime = /\d{4}-\d{1,2}-\d{1,2}/g.exec(time);
				return newTime[0].split('-').join('.');
			}else{
				return time.substring(0,16).replace(/\-/g, '.');
			}
		},
		loadCoupon(id) {
			let that = this;
			req.getRequest('/api/userLevel/coupon', {id: id}, data => {
				data.map(it=>{
					it.isShow = false;
					return it;
				})
				that.couponList = data;
				that.couponCount = data.length;
			});
		},
		recieveCoupon(index) {
			let _ts = this;
			if(_ts.userinfo.level !== _ts.TabList[_ts.idx].id){
				// '该优惠券仅限' + _ts.TabList[_ts.idx].title + '领取，
				req.msgConfirmText('请先升级成为' + _ts.TabList[_ts.idx].title,'升级',suc=>{
					_ts.openVip(_ts.idx);
				})
				return false;
			}
			const coupon = _ts.couponList[index];
			if (coupon.userReceive > -1 && coupon.userCount >= coupon.userReceive) {
				return req.msg('超出优惠券领取限制，无法领取');
			}
			req.postRequest('/api/coupon/receive', {
				id: coupon.id
			}, res => {
				coupon.userCount++
				req.msg('领取成功', () => {});
			});
		},
		checks(item,index){
			let pageList = this.couponList;
			if(pageList[index].isShow){
				pageList[index].isShow = false;
			}else{
				pageList.map(it=>{
					it.isShow = false;
					return it;
				});
				pageList[index].isShow = true;
			}
		},
		swiperChange(e) {
			let source = e.detail.source
			if (source == 'autoplay' || source == 'touch') {
			    this.swiperCurrent = e.detail.current;
			    this.idx = e.detail.current;
			    this.vip.money = '';
			    this.vip.day = '';
			    this.getVipMoneyT(this.TabList[this.idx].level);
				this.loadCoupon(this.TabList[this.idx].id)
			}
		},
		choose() {
			this.setData({
				freshen: false
			});
		},
		getMy() {
			let that = this;
			req.getRequest('/api/user/my', {}, data => {
				that.isDistriUser = data.isDistriUser;
				if (data && data.listShopBase && data.listShopBase != null && data.listShopBase.length > 0) {
					if (data.listShopBase[0].merchant_id == that.merchant.id && that.merchant.type != 5) {
						that.ascription = true;
					}
				}
			});
		},
		getConfig() {
			var _this = this;
			return new Promise((resolve, reject) => {
				req.getRequest('/api/config', {}, function(res) {
					_this.about = res;
					if (res && res.show_membership_price == 1) {
						_this.setData({
							show_membership_price: 1
						});
					}

					resolve();
				});
			});
		},

		showVipd(e) {
			let index = e.currentTarget.dataset.index;
			let d = {};
			let def = this.TabList.findIndex(it => it.active);
			d['TabList[' + def + '].active'] = false;
			d['TabList[' + index + '].active'] = true;
			d['pageList'] = [];
			this.setData(d);
			this.setData({
				idx: index,
				bottomId: 'bottomView' + index
			});
		},

		addShopCart(e) {
			let state = e.currentTarget.dataset.state;
			let skuId = e.currentTarget.dataset.skuid;
			let id = e.currentTarget.dataset.id;
			let defaultMerchant = req.getStorage('defaultMerchant');
			// console.log(skuId, id);
			let params = {
				skuId: skuId,
				quantity: 1,
				productId: id,
				merchantId: defaultMerchant.id
			}; // if(state!=1){
			//   return req.msg('您来晚了，商品已经下架')
			// }

			if (this.merchant) {
				params.merchantId = this.merchant.id;
			}

			req.postRequest('/api/purchase/cart', params, res => {
				req.msg('加入购物车成功');
			});
		},

		getLikeList() {
			//Recommend
			if (!this.isLikeLoad) return false;
			this.isLikeLoad = false;
			let that = this;
			req.getRequest(
				'/api/product/list',
				{
					page: that.page,
					limit: 10,
					attr: 'sell_well'
				},
				res => {
					if (res && res.length >= 10) that.isLikeLoad = true;
					if (that.page > 1) res = that.likeList.concat(res);
					res = res.map(it => {
						if (it.deliverWay && JSON.parse(it.deliverWay).indexOf(3) != -1) it.isJs = true;
						return it;
					});
					that.setData({
						likeList: res
					});
				}
			);
		},

		toDetail(e) {
			let id = e.currentTarget.dataset.id;
			app.globalData.openPage('product/detail/detail?id=' + id);
		},

		jumpUrl(url) {
			uni.navigateTo({
				url: url
			});
		},

		openVip(item,idx) {
			// if (this.vip.money <= 0) {
				// if (this.userinfo.level == this.item.id && this.userinfo.level != 0 && !this.userinfo.end) {
				// } else {
					//未领取
					// this.jumpUrl('/topic/card/index');
					this.freshen = false;
					this.jumpUrl('/open/index/index?levelId='+item.id);
				// }
				return;
			// }

			this.setData({
				money: []
			});
			let index = e.currentTarget.dataset.index;
			let def = this.TabList.findIndex(it => it.active);
			let d = {};
			d['TabList[' + def + '].active'] = false;
			d['TabList[' + index + '].active'] = true;
			d['pageList'] = [];
			this.setData(d);
			this.getVipMoney(this.TabList[index].level);
			this.setData({
				show: true,
				level: this.TabList[index].level
			});
			
			console.log('会员等级>>>>>>>',this.TabList);
		},

		eliminate() {
			this.setData({
				show: false
			});
		},

		switchTab(event) {
			this.setData({
				money: []
			});
			let index = event.currentTarget.dataset.index;
			let level = event.currentTarget.dataset.level;
			let def = this.TabList.findIndex(it => it.active);
			let d = {};
			d['TabList[' + def + '].active'] = false;
			d['TabList[' + index + '].active'] = true;
			d['pageList'] = [];

			this.setData({
				index: index,
				level: level
			});
			this.setData(d);
			this.getVipMoney(level);
		},

		getVip() {
			req.getRequest('/api/levelStrategy/userLevelList', {}, data => {
				let that = this;
				let arr = [];
				let node = [];
				data.forEach(it => {
					var nodes = it.editorContent;
					node.push(nodes);
					return it;
				});
				this.nodes = node;
				arr.forEach(it => {});
				this.setData({
					vipList: data,
					TabList: data,
					['TabList[' + 0 + '].active']: true,
					imags: arr
				});
				this.getVipMoneyT(this.TabList[0].level);
				this.loadCoupon(this.TabList[0].id)
				this.getVipListOrg();
			});
		},

		getVipListOrg() {
			if (this.TabList && this.userinfo) {
				for (var i = 0; i < this.TabList.length; i++) {
					var item = this.TabList[i];
					if (this.userinfo.level == item.id) {
						this.TabList = this.TabList.slice(i, this.TabList.length);
						this.getVipMoneyT(this.TabList[0].level);
						this.loadCoupon(this.TabList[0].id)
						let node = [];
						this.TabList.forEach(it => {
							var nodes = it.editorContent;
							node.push(nodes);
							return it;
						});
						this.nodes = node;
						return;
					}
				}
			}
		},

		getuserVip() {
			req.getRequest('/api/user/levelDetails', {}, data => {
				let expireTime = Array;
				if (data.expireTime) {
					expireTime = data.expireTime.split(' ');
					data.expireTime = data.expireTime.replace(/-/g, '/');
				}
				let nowTime = new Date().getTime();
				let endTime = new Date(data.expireTime).getTime();
				let times = parseInt((endTime - nowTime) / 1000);
				this.setData({
					userinfo: data,
					['userinfo.expireTime']: expireTime[0]
				});

				if (times <= 0) {
					this.setData({
						['userinfo.end']: true
					});
				} else {
					this.setData({
						['userinfo.end']: false
					});
				}
				this.getVipListOrg();
			});
		},

		/**
		 * 获取每个会员的销售价格
		 * @param {Object} index
		 */
		getVipMoney(index) {
			this.setData({
				price: 0,
				day: 0,
				id: ''
			});
			let from = {
				level: index
			};
			req.getRequest('/api/levelStrategy/list', from, data => {
				if (data && data.length > 0) {
					this.setData({
						money: data,
						['money[' + 0 + '].active']: true,
						price: data[0].price,
						day: data[0].day,
						id: data[0].id
					});
					//设置等级的价格
					this.TabList[index-1].price = data[0].price;
				}
			});
		},
		getVipMoneyT(index) {
			let from = {
				level: index
			};
			return new Promise((resolve, reject) => {
				req.getRequest('/api/levelStrategy/list', from, data => {
					if (data && data.length > 0) {
						this.vip.money = data[0].price;
						this.vip.day = data[0].day;
					}
					this.TabList[index-1].price = data[0].price;
				});
				resolve();
			});
		},

		// 选择开通时长
		selectOpen(event) {
			let index = event.currentTarget.dataset.index;
			let id = event.currentTarget.dataset.id;
			let price = event.currentTarget.dataset.price;
			let day = event.currentTarget.dataset.day;
			let def = this.money.findIndex(it => it.active);
			let d = {};
			d['money[' + def + '].active'] = false;
			d['money[' + index + '].active'] = true;
			d['pageList'] = [];

			this.setData(d);
			this.setData({
				price: price,
				day: day,
				id: id
			});
		},

		//购买
		buy() {
			let that = this;
			if (!this.id || this.id == undefined || this.id == null) return req.msg('请选择开通类型');
			if (this.userinfo.levelGrade > this.level && !this.userinfo.end) return req.msg('您不能购买低于现在等级会员');
			that.setData({
				show: false
			});
			route.vip(
				{
					strategyId: this.id,
					scene: req.getStorage('scene')
				},
				data => {
					route.vipPay(data.id, data.status, this.price, res => {
						if (res) {
							app.globalData.navigateTo('product/pay/pay?isSuccess=true&vip=true');
						}
					});
				}
			);
		}
	}
};
</script>
<style>
@import './vip.css';
</style>
