<template>
	<view>
		<!--mine/vip/vip.wxml-->
		<!-- <view class="top">
  <image src="/pages/images/vip_bg1.png" class="vipbg"></image>
  <view class="bg"><image src="{{userinfo.pic?userinfo.pic:'/pages/images/vip_bg1.png'}}" class="vipbg" style="{{userinfo.pic?'border-radius: 35rpx':''}}"></image></view>
  <image src="/pages/images/vip_bg2.png" class="vipbg1"></image>
  <view class="topc dflex" wx:if="{{userinfo.level!=0 && !userinfo.end}}">
    <view style="flex:0.9">
      <view class="card-id">{{userinfo.levelName}}<text>{{userinfo.level}}</text></view>
      <view class="level dflex">
        <image src="{{userinfo.icon}}"></image>
      </view>
      <view class="cheng">会员到期时间：{{userinfo.expireTime}}</view>
    </view>
    <view class="btn mbglinear" bindtap="openVip" data-index="{{userinfo.levelGrade==0?'0':userinfo.levelGrade-1}}">续费</view>
  </view>
  <view class="topc dflex notTopc" wx:else>
    <view class="card-id">柚荚M店会员卡<text>1558145805</text></view>
    <view class="level dflex"><image src="/pages/images/hg_icon1.png"></image>1</view>
    <view class="cheng">当前成长值为0，距离下一成长值差5001</view>
    <view class="notOpen">VIP<text>未开通</text></view>
    <view class="btn mbglinear" bindtap="openVip" data-index="0">立即开通</view>
  </view>
</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" 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'" 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">
									<text>￥</text>
									{{ vip.money }}
								</view>
								<view class="dflex">
									{{ 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" v-if="vip.money">
								<view class="v-price">
									<text>￥</text>
									{{ vip.money }}
								</view>
								<view class="invi">有效期：{{ vip.day }}天</view>
							</view>
						</block>

						<view class="obtn" @tap="openVip" :data-index="index">
							{{ userinfo.level == item.id && userinfo.level != 0 && !userinfo.end ? '立即续费' : '立即开通' }}
						</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>
			<!-- <scroll-view class="scroll-box" scroll-x style="height:400rpx" :scroll-into-view="bottomId"
				scroll-with-animation="true">
				<view v-for="(item, index) in TabList" :key="index" :class="'openvip ' + (item.active?'active':'')"
					@tap="showVipd" :data-index="index" :id="'bottomView' + index">
					<image v-if="userinfo.level==item.id&&userinfo.level!=0 && !userinfo.end"
						:src="userinfo.pic?userinfo.pic:'vip'" class="openvipbg"
						mode="aspectFill"></image>
					<image :src="item.pic?item.pic:'/static/pages/images/vip_bg1.png'" class="openvipbg"
						mode="aspectFill" v-else></image>
					<view class="dflex viptitle">
						<image :src="userinfo.avatar" class="userimg"
							v-if="userinfo.level==item.id&&userinfo.level!=0 && !userinfo.end"></image>
						<image :src="item.icon" class="icon" v-else></image>
						<view v-if="userinfo.level==item.id&&userinfo.level!=0 && !userinfo.end">
							<view class="username">{{userinfo.nickName}} <text>{{item.title}}</text></view>
							<view class="usercont">NO:{{userinfo.level}}</view>
						</view>
						<view v-else>
							<view class="vipname">{{item.title}}</view>
							<view class="vipcont">{{item.brief}}</view>
						</view>
					</view>

					<view class="go dflex">
						<view class="expireTime dflex"
							v-if="userinfo.level==item.id&&userinfo.level!=0 && !userinfo.end">
							{{userinfo.expireTime}}<text>到期</text>
							<image src="/mine/static/mine/images/jianqu.png" class="jianquimg"></image>
						</view>
						<view
							:class="'btn ' + (userinfo.level==item.id&&userinfo.level!=0 && !userinfo.end?'':'btnleft')"
							@tap="openVip" :data-index="index">
							{{userinfo.level==item.id&&userinfo.level!=0 && !userinfo.end?'立即续费':'立即开通'}}</view>
					</view>
				</view>
			</scroll-view> -->
		</view>

		<view class="quanyi">
			<view class="quanyi-tit dflex">
				会员权益
				<!-- <image src="/static/pages/images/quanyi_l.png"></image>
				<image src="/static/pages/images/quanyi.png" class="quanyi_c"></image>
				<image src="/static/pages/images/quanyi_r.png"></image> -->
			</view>
			<!-- <view class="qylist dflex">
    <view class="li">
      <image src="/pages/images/qy_ico1.png"></image>
      <text>专享客服</text>
    </view>
    <view class="li">
      <image src="/pages/images/qy_ico1.png"></image>
      <text>专享客服</text>
    </view>
    <view class="li">
      <image src="/pages/images/qy_ico1.png"></image>
      <text>专享客服</text>
    </view>
    <view class="li">
      <image src="/pages/images/qy_ico1.png"></image>
      <text>专享客服</text>
    </view>
  </view> -->
			<view class="ziyou">
				<!--    <rich-text :nodes="nodes[idx]"></rich-text>
    <block v-for="(item, index) in vipList[idx].imgs" :key="index">
      <image class="img" :src="item" mode="widthFix" :data-src="item"></image>
    </block> -->
				<block v-if="nodes[idx]"><mp-html :content="nodes[idx]" @imgtap="choose" /></block>
				<block v-else>无</block>
				<!-- <image src="{{item}}" mode="widthFix" wx:for="{{imgs}}" wx:key="{{index}}"></image> -->
			</view>
		</view>
		<!-- <view class="huiyuan " wx:if="{{TabList.length>1}}">
  <scroll-view class="scroll-box" scroll-x style="height:400rpx">
    <view class="openvip {{item.active?'active':''}}" wx:for="{{TabList}}" wx:key="index" bindtap="showVipd" data-index="{{index}}">

      <image src="{{item.pic?item.pic:'/pages/images/vip_bg1.png'}}" class="openvipbg" mode="aspectFit"></image>

      <view class="dflex viptitle">
        <image src="{{item.icon}}" class="icon"></image>
        <view>
          <view class="vipname">{{item.title}}</view>
          <view class="vipcont">{{item.brief}}</view>
        </view>
      </view>
      <view class="btn go" bindtap="openVip" data-index="{{index}}">立即开通</view>
    </view>
  </scroll-view>
</view> -->
		<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" 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="list-tag ddflex">
								<block v-if="item.label">
								<view class="tover" v-for="(it,idx) in item.label.split(',')" :key="idx" v-if="idx < 2">{{it}}</view>
								</block>
							</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>
								<block v-else>
									<view class="vip-news ddflex" v-if="show_membership_price==1&&item.actualPrice < item.salePrice"><text class="vip-sale">会员价</text><text class="vip-members">￥{{item.actualPrice}}</text></view>
									<view class="vip-news ddflex" v-if="show_membership_price==1&&item.membersPrice<item.salePrice"><text class="vip-sale">会员价</text><text class="vip-members">￥{{item.membersPrice}}</text></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">
										<block v-if="item.marketPrice!=0&&item.marketPrice>item.salePrice">
											￥{{item.marketPrice}}
										</block>
									</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"
						>
							{{ 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 class="chufangy" >
  <button class="submit" bindtap="openVip" data-index="{{userinfo.end?'0':userinfo.levelGrade==0?'0':userinfo.levelGrade-1}}">{{userinfo.end?'快来点我开通会员，享尊贵特权':'快来点我续费会员，享尊贵特权'}}</button></view> -->
	</view>
</template>

<script>
// mine/vip/vip.js
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: {
				maney: 0,
				day: 0
			}, //默认的会员价格
			about: {},
			isDistriUser: 0, // 判断用户是否是分销员 2为分销员
			ascription: false //是否开启小店
		};
	},

	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: {
		swiperChange(e) {
			this.swiperCurrent = e.detail.current;
			this.idx = e.detail.current;
			this.vip.money = '';
			this.vip.day = '';
			this.getVipMoneyT(this.TabList[this.idx].level);
		},
		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;
			// console.log(id);
			app.globalData.openPage('product/detail/detail?id=' + id);
		},

		openVip(e) {
			this.setData({
				money: []
			});
			let index = e.currentTarget.dataset.index;
			let def = this.TabList.findIndex(it => it.active);
			let d = {};
			// console.log(def, index);
			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
			});
		},

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

		switchTab(event) {
			this.setData({
				money: []
			});
			let index = event.currentTarget.dataset.index;
			let level = event.currentTarget.dataset.level;
			// console.log(this.TabList);
			let def = this.TabList.findIndex(it => it.active);
			let d = {};
			// console.log(def, index);
			d['TabList[' + def + '].active'] = false;
			d['TabList[' + index + '].active'] = true;
			d['pageList'] = []; // this.data.form.states=this.data.TabList[index].state.toString();
			// this.data.form.state = this.data.TabList[index].state;

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

		 getVip() {
			req.getRequest('/api/levelStrategy/userLevelList', {},data => {
				// data=data.map(it=>{
				//   it.active=false
				//   return it})
				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 => {
					// console.log(it);
				});
				// console.log(arr, node, data);

				this.setData({
					vipList: data,
					TabList: data,
					['TabList[' + 0 + '].active']: true,
					imags: arr
				});
				this.getVipMoneyT(this.TabList[0].level);
				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);
						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); // var expireTime= new Date(data.expireTime)
				// var time1=expireTime.getTime();

				// console.log(times, endTime, nowTime);
				this.setData({
					userinfo: data,
					['userinfo.expireTime']: expireTime[0]
				});

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

				this.getVipListOrg();
				// console.log(data);
			});
		},

		getVipMoney(index) {
			// let idx=index
			this.setData({
				price: 0,
				day: 0,
				id: ''
			});
			let from = {
				level: index
			};
			req.getRequest('/api/levelStrategy/list', from, data => {
				// console.log(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
					});
				}
			});
		},
		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;
					}
				});
				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;
			// console.log(this.money);
			let def = this.money.findIndex(it => it.active);
			let d = {};
			// console.log(def, index);
			d['money[' + def + '].active'] = false;
			d['money[' + index + '].active'] = true;
			d['pageList'] = []; // this.data.form.states=this.data.TabList[index].state.toString();
			// this.data.form.state = this.data.TabList[index].state;
			// this.setData({index:index})

			this.setData(d);
			this.setData({
				price: price,
				day: day,
				id: id
			});
			// console.log(this.money, price); // this.getVipMoney(level)
		},

		//购买
		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');
						} // wx.requestPayment({
						//   timeStamp: res.timeStamp,
						//   nonceStr: res.nonceStr,
						//   package: res.packages,
						//   signType: res.signType,
						//   paySign: res.sign,
						//   success: function () {
						//     let i = 0;
						//     let timer = setInterval(() => {
						//       req.postRequest('/api/levelStrategy/check', {
						//         strategyId: data.id
						//       }, res => {
						//         console.log(i, res)
						//         if (res.isSuccess || i === 4) {
						//           clearInterval(timer);
						//           app.navigateTo('product/pay/pay?isSuccess=true&vip=true')
						//           that.setData({show:false})
						//         } else {
						//           i++;
						//         }
						//       }, true)
						//     }, 200);
						//     console.log(res)
						//   },
						//   fail: function (res) {
						//     req.postRequest('/api/levelStrategy/check', { strategyId: data.id }, res => {
						//       app.navigateTo('product/pay/pay?isSuccess=false&vip=true&money='+that.data.price+'&id='+data.id)
						// that.setData({show:false})
						//     })
						//   }
						// })

						// console.log(res);
					});
				}
			);
		}
	}
};
</script>
<style>
@import './vip.css';
</style>
