<template>
	<view class="min-body">
		<view class="Tabs-List">
			<u-tabs itemStyle="height:88rpx;padding:0 18rpx" inactiveStyle="font-size:28rpx;color:#333"
				:current="current" :activeStyle="tabActive" keyName="title" lineColor="#FF7700" @click="clickTab"
				:list="list">
			</u-tabs>
		</view>
		<view class="scroll-List" :style="{height:`${scrollHeight}rpx`}">
			<scroll-view @scroll="scroll" :scroll-top="scrolltop" :scroll-into-view="intoView" scroll-y="true"
				class="scroll-Y" :style="{height:`${scrollHeight}rpx`,'padding': '32rpx','box-sizing': 'border-box'}">
				<template v-for="(item,index) in list">
					<view class="scroll-List-scroll-Item" :id="`scroll-List-scroll-Item-${index}`" :key="index">
						<view class="scroll-List-scroll-Item-Title">
							{{item['title']}}
						</view>
						<view class="scroll-List-scroll-Item-Commodity-List"
							:style="{'--height':`${(scrollHeight - 120)}rpx`}">
							<u-grid :border="false" col="4">
								<u-grid-item v-for="(baseListItem,baseListIndex) in baseList[index]"
									:key="baseListIndex" @click="goGoods(baseListItem)">
									<u-image width="140rpx" height="140rpx" radius="50%"
										:customStyle="{paddingTop:20+'rpx'}" :src="baseListItem.b_goods_img"></u-image>
									<u-gap height="10rpx"></u-gap>
									<text class="lit-333">{{baseListItem.b_goods_name}}</text>
									<u-gap height="30rpx"></u-gap>
								</u-grid-item>
							</u-grid>
						</view>
					</view>
				</template>
			</scroll-view>
		</view>
	</view>
</template>

<script>
	let self;
	import {
		consumerCard,
		GetUserInvitationCode
	} from '@/static/js/share.js';
	import {
		benclassAPI,
		benClssGoodsAPI
	} from '@/request/pay/index.js'
	export default {
		data() {
			return {
				tabActive: {
					color: "#FF7700",
					'font-weight': 'bold',
					'font-size': '28rpx'
				},
				b_class_id: 0,
				baseList: [],
				code: '',
				list: [],
				// scroll高度
				scrollHeight: 0,
				// tabs高度
				tabsh: 0,
				// 内部scroll滚动距离
				scrolltop: 0,
				intoView: 'scroll-List-scroll-Item-0',
				// 记录高度数组
				arr: [],
				// 当前滑块激活索引
				current: 0

			}
		},
		methods: {
			async clickTab(e) {

				// 点击的时候判断当前记录高度数组是否以及执行完毕,如果数组没有记录则重新执行获取高度逻辑
				if (this.arr.length == 0) {
					await this.getMenuItemTop();
				};
				// 点击时判断是否点击的是当前激活的
				if (e['index'] == this['current']) return;
				this.$nextTick(function() {
					self['scrolltop'] = self['arr'][e['index']]['top'];
					self['current'] = e['index'];
				})
				// console.log(e['index'], '当前点击索引');
				// let id = `scroll-List-scroll-Item-${e['index']}`;
				// this['intoView'] = id;
				// const query = uni.createSelectorQuery().in(this);
				// query.select(id).boundingClientRect(data => {
				// 	console.log(data['top']);
				// 	if (data['top'] >= 0) {
				// 		self['scrolltop'] = data['top'] - self['tabsh'] - 16;
				// 		console.log(self['scrolltop'])
				// 	}
				// }).exec();
			},
			// async getData() {
			// 	await this.GetTabsList()
			// },

			/**
			 * @获取右边菜单每个item到顶部的距离
			 * */
			getMenuItemTop() {
				return new Promise(resolve => {
					let selectorQuery = uni.createSelectorQuery();
					selectorQuery.selectAll('.scroll-List-scroll-Item').boundingClientRect((rects) => {
						// 如果节点尚未生成，rects值为[](因为用selectAll，所以返回的是数组)，循环调用执行
						if (!rects.length) {
							setTimeout(() => {
								this.getMenuItemTop();
							}, 10);
							return;
						};
						rects.forEach((rect, index) => {
							// console.log(rect, 'rect');
							// 这里减去rects[0].top，是因为第一项顶部可能不是贴到导航栏(比如有个搜索框的情况)
							// console.log(rect.top - rects[0].top);
							// console.log(rects[0].top, 'rects[0]')
							this.arr.push({
								top: rect.top - rects[0].top,
								index: index,
								height: rect['height'] - 16
							});
							// resolve();
							resolve();
						});

					}).exec()
				})
			},
			goGoods(item) {
				console.log(item['b_id'], '渠道')
				/**
				 * @接口返回b_id根据b_id来判断跳入那个页面
				 * @b_id1 渠道一（充值会员等）
				 * @b_id2 渠道二（淮鱼充值电费）
				 * @b_id3 渠道三（粘鱼充值话费/电费）
				 * @b_id4 渠道四（芯达-话费快充）
				 * @b_id4 渠道五（中鼎云-话费电费）
				 * @param { b_id }  后台用来区分
				 * */
				switch (item['b_id']) {
					// 渠道一
					case 1:
						uni.navigateTo({
							url: `/pages/goods/goods_Info/index?goods_id=${item['b_goods_id']}&b_id=${item['b_id']}`
						});
						break;
						// 惟鱼和粘鱼都是充值电费渠道,因为电费充值不稳定,零一个做备用,而且提要提交的数据逻辑不一样所以写了两个页面
						// 惟鱼
						// 电费充值
					case 2:
						uni.navigateTo({
							url: `/sub_card/goods/b_id2/b_id2?goods_id=${item['b_goods_id']}&b_id=${item['b_id']}`
						});
						break;
						// 粘鱼
						// 电费充值
					case 3:
						// [b_id3,goods3,goods4]
						// 渠道3下的商品3和商品4
						// 粘鱼话费慢充/粘鱼话费快充
						if (item['b_goods_id'] == 3 || item['b_goods_id'] == 4) {
							uni.navigateTo({
								url: `/pages/goods/b_id3/b_id3_hua?goods_id=${item['b_goods_id']}&b_id=${item['b_id']}`
							});
							break;
						};
						// 粘鱼电费
						uni.navigateTo({
							url: `/pages/goods/b_id3/b_id3_dian?goods_id=${item['b_goods_id']}&b_id=${item['b_id']}`
						});
						break;
					case 4:
						// 芯达渠道4下的商品
						// 话费快充
						if (item['b_goods_id'] == 1) {
							uni.navigateTo({
								url: `/pages/goods/b_id4/b_id4_hua?goods_id=${item['b_goods_id']}&b_id=${item['b_id']}`
							});
							break;
						};
					case 5:
						// 话费
						if (item['type_id'] == 1) {
							uni.navigateTo({
								url: `/pages/goods/b_id5/b_id5_hua?goods_id=${item['b_goods_id']}&b_id=${item['b_id']}`
							});
						}else if(item['type_id'] == 3){
							// 电费
							uni.navigateTo({
								url: `/pages/goods/b_id3/b_id3_dian?goods_id=${item['b_goods_id']}&b_id=${item['b_id']}`
							});
						}
						
						break;
				}

			},
			/**
			 * @获取顶部tabs列表
			 * */
			GetTabsList() {
				let parameter = {

					// 联调线下接口时防止影响线上用户使用,多传入一个type为1告诉接口现在调用是线下,这样接口就会返回线下数据
					// 1 正式版
					// 0 测试版
					// type: 1
				};
				benclassAPI(parameter).then(res => {
					// 先获取到顶部tabs列表用于计算
					this.list = res['data'];
					if (this.list.length > 0) {
						return this.initScrollView();
					}
				}).then(async res => {
					self['scrollHeight'] = res;
					// 获取玩顶部tabs列表之后再递归获取每一项tabs中的数据
					this.GetCommodityList()
				})
			},
			/**
			 * @递归获取
			 * @因为后台是按照id返回的前端不通知后台情况下自行做递归获取
			 * */
			GetCommodityList(index = 0) {
				benClssGoodsAPI({
					b_class_id: this.list[index]['id'],
					// TODO 正式删除
					// t: 1
				}).then(res => {
					this['baseList'][index] = [];
					if (res['data']['length'] > 0) {
						this.$set(this['baseList'], index, res['data']);
					}
					// console.log(index, this.list['length'] - 1);
					// 获取数据是否完毕
					if (index >= this.list['length'] - 1) {
						// console.log('进入');
						// 必须保证获取完毕tabs数据之后再执行getMenuItemTop方法,因为getMenuItemTop方法是用来做滚动逻辑处理的
						// 完毕之后获取高度数组
						self.getMenuItemTop()
						return
					}
					if (index < this.list['length'] - 1) {
						index += 1;
						this.GetCommodityList(index);
					};
				})
			},

			/**
			 * @获取可滚动区域
			 * */
			initScrollView() {
				return new Promise((resolve, reject) => {
					setTimeout(() => {
						// 获取屏幕高度
						uni.getSystemInfo({
							success: (window) => {
								let wh = window['windowHeight'];
								let ww = window['windowWidth'];
								// console.log(window, 'window');
								uni.createSelectorQuery().in(self).select(".Tabs-List")
									.boundingClientRect(
										data => {
											self['tabsh'] = data['height']
											// 注意这里获得的高度宽度都是px，需要转换rpx
											// 可使用窗口高度，将px转换rpx
											let scrollHeight = ((wh - data['height']) * (750 /
												ww));
											resolve(scrollHeight);
										}).exec()
							}
						})
					}, 500)
				});
			},

			async scroll(e) {
				// console.log('滚动');
				this.$u.debounce(() => {
					let selectorQuery = uni.createSelectorQuery();
					selectorQuery.selectAll('.scroll-List-scroll-Item').boundingClientRect((rects) => {
						for (let i = 0; i < self['arr']['length']; i++) {
							// console.log(e['detail']['scrollTop'], self['arr'][i]['top']);
							if (e['detail']['scrollTop'] <= (self['arr'][i]['top'] + self['arr'][i][
									'height'
								])) {
								self['current'] = self['arr'][i]['index']
								break;
							}
						}
					}).exec();
				}, 200, false)
			}
		},
		onLoad() {
			self = this;
			this.GetTabsList();
			this['UserInfr'] = GetUserInvitationCode();
			// this.getData();
		},
		onReady() {

		},
		onShareAppMessage() {
			return consumerCard(this['UserInfor']['userInfo']['invite_code']);
		}
	}
</script>

<style lang="scss">
	.white-box {
		background-color: #fff;
		min-height: 100vh;
		border-top-left-radius: 20rpx;
		border-top-right-radius: 20rpx;

		.Tabs-List {
			border-bottom: 2rpx solid #EDEDED;
			padding-left: 20rpx;
		}


	}

	.scroll-List {
		// padding: 32rpx;
		// box-sizing: border-box;

		&-scroll-Item {

			&-Title {
				width: 100%;
				height: 80rpx;
				font-size: 32rpx;
				font-weight: 700;
				line-height: 80rpx;

			}

			&:last-child .scroll-List-scroll-Item-Commodity-List {
				min-height: var(--height);
			}

			&-Commodity-List {
				padding: 32rpx 0;
				box-sizing: border-box;
			}
		}
	}
</style>
