<template>
	<view class="ticket-order-page">
		<view class="status_bar" :style="navHeight"></view>
		<view class="tabs">
			<scroll-view ref="tabbar1" id="tab-bar" class="tab-bar" :scroll="false" :scroll-x="true"
				:scroll-into-view="scrollInto">
				<view class="tab-bar-list">
					<view class="tab-bar-list-wrapper">
						<view class="uni-tab-item" v-for="(tab,index) in tabList" :key="tab.id" :ref="'tabitem'+index">
							<text :id="tab.id" :data-id="index" :data-current="index" class="uni-tab-item-title"
								:class="{'uni-tab-item-title-active':tabIndex==index}"
								@click="ontabtap($event,tab.newsid)">{{tab.name}}</text>
						</view>
					</view>
					<view class="scroll-view-indicator">
						<view ref="underline" class="scroll-view-underline" :class="{'scroll-view-animation':isTap}"
							:style="underlineStyle"></view>
					</view>
				</view>
			</scroll-view>

			<!-- <view class="conditon-block" :style="conditionTop" :class="{'conditon-block-auto':ishowDetail}">
				<view class="filter-title">
					<button type="default" class="filter-btn filter-btn-active"><text
							class="filter-btn__text filter-btn-active__text">一周内</text></button>
					<button type="default" @click="handleFilter(item)"
						:class="{'filter-btn-active':item === filterActiveIndex}" class="filter-btn" v-for="item in 3"
						:key='item'>
						<text class="filter-btn__text" :class="{'filter-btn-active__text':item === filterActiveIndex}">{{item}}月内</text>
					</button>
					<image @click="handleShowDetail" class="icon-arrow" :class="{'icon-arrow-rotate':ishowDetail}"
						src="@/static/image/arrow_up@3x.png" mode="aspectFit"></image>
				</view>
				<view class="filter-content">
					<button type="default" @click="handleFilter(item+3)" class="filter-btn"
						:class="{'filter-btn-active':item+3 === filterActiveIndex}" v-for="item in 9" :key='item'>
						<text class="filter-btn__text" :class="{'filter-btn-active__text':item+3 === filterActiveIndex}">{{item+3}}月内</text>
					</button>
				</view>
			</view> -->
			<view class="conditon-block" :style="conditionTop" :class="{'conditon-block-auto':ishowDetail}">
				<view class="filter-title">
					<button type="default" class="filter-btn" :class="{'filter-btn-active':0 === filterActiveIndex}" @tap="handleFilter('week')">
						<text class="filter-btn__text" :class="{'filter-btn-active__text':0 === filterActiveIndex}">一周内</text>
					</button>
					<button type="default" @tap="handleFilter(item)" class="filter-btn"
						:class="{'filter-btn-active':item === filterActiveIndex}" v-for="item in 3" :key='item'>
						<text class="filter-btn__text" :class="{'filter-btn-active__text':item === filterActiveIndex}">{{item}}月内</text>
					</button>
					<image @tap="handleShowDetail" class="icon-arrow" :class="{'icon-arrow-rotate':ishowDetail}"
						src="@/static/image/arrow_up@3x.png" mode="aspectFit">
					</image>
				</view>
				<view class="filter-content">
					<button type="default" @tap="handleFilter(item+3)" class="filter-btn" :class="{'filter-btn-active':item+3 === filterActiveIndex}" v-for="item in 9" :key='item'>
						<text class="filter-btn__text" :class="{'filter-btn-active__text':item+3 === filterActiveIndex}">{{item+3}}月内</text>
					</button>
				</view>
			</view>
			<view class="empty"></view>
			<swiper ref="swiper1" disable-touch='true' class="tab-box" :current="tabIndex" :duration="300" @change="onswiperchange"
				@transition="onswiperscroll" @animationfinish="animationfinish" @onAnimationEnd="animationfinish">
				<swiper-item class="swiper-item" v-for="(page, index) in tabList" :key="index">
					<orderPage :ref="'page' + index" class="page-item" :nid="page.newsid" :conditions='condition'></orderPage>
				</swiper-item>
			</swiper>
			<!-- <swiper v-else ref="swiper2" class="tab-box" :current="tabIndex" :duration="300" @change="onswiperchange"
				@transition="onswiperscroll" @animationfinish="animationfinish" @onAnimationEnd="animationfinish">
				<swiper-item class="swiper-item" v-for="(page, index) in tabList" :key="index">
					<savePage :ref="'page' + index" class="page-item" :nid="page.newsid" :conditions='condition'></savePage>
				</swiper-item>
			</swiper> -->
		</view>
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex'
	
	import {
		timeRangeFormat
	} from '@/utils/date.js'
	
	// #ifdef APP-PLUS
	const dom = weex.requireModule('dom');
	// #endif

	import orderPage from './order-page.nvue';
	import savePage from './save-page.nvue';

	// 缓存每页最多
	const MAX_CACHE_DATA = 100;
	// 缓存页签数量
	const MAX_CACHE_PAGE = 3;
	const TAB_PRELOAD_OFFSET = 1;

	export default {
		components: {
			orderPage,
			savePage
		},
		data() {
			return {
				tabList: [{
					id: "tab01",
					name: '全部',
					newsid: 1
				}, {
					id: "tab02",
					name: '待审批',
					newsid: 2
				}, {
					id: "tab03",
					name: '已审批',
					newsid: 3
				}, {
					id: "tab04",
					name: '已保存',
					newsid: 4,
				}],
				tabIndex: 0,
				cacheTab: [],
				scrollInto: "",
				navigateFlag: false,
				indicatorLineLeft: 0,
				indicatorLineWidth: 0,
				isTap: false,
				// 测试使用观察变化
				_lastTabIndex: 0,
				swiperWidth: 0,
				tabbarWidth: 0,
				tabListSize: {},
				_touchTabIndex: 0,
				ishowDetail: false,
				filterActiveIndex: 0,
				condition: {
					"endDate": "",
					"page": 1,
					"pagesize": 20,
					"startDate": "",
					"status": "0"
				},
				savePageFlag: false
			}
		},
		computed: {
			underlineStyle() {
				return {
					left: this.indicatorLineLeft + 'px',
					width: this.indicatorLineWidth + 'px'
				}
			},
			navHeight() {
				return {
					'height': `${this.sysinfo.safeArea.top + 44}px`
				}
			},
			conditionTop() {
				return {
					'top': `${this.sysinfo.safeArea.top + 44 + 42}px`
				}
			},
			...mapState(['sysinfo'])
		},
		created() {
			this.handleFilter('week')
		},
		onReady() {
			this._lastTabIndex = 0;
			this.swiperWidth = 0;
			this.tabbarWidth = 0;
			this.tabListSize = {};
			this._touchTabIndex = 0;

			this.pageList = [];
			for (let i = 0; i < this.tabList.length; i++) {
				let item = this.$refs['page' + i]
				if (Array.isArray(item)) {
					this.pageList.push(item[0])
				} else {
					this.pageList.push(item)
				}
			}
			// this.condition.endDate = this.handleDate(timeRangeFormat('week'))
			// this.condition.startDate = this.handleDate(timeRangeFormat('now'))
			this.switchTab(this.tabIndex);

			this.selectorQuery();
		},
		methods: {
			ontabtap(e,type) {
				let index = e.target.dataset.current || e.currentTarget.dataset.current;
				this.condition.status = type
				//let offsetIndex = this._touchTabIndex = Math.abs(index - this._lastTabIndex) > 1;

				// #ifdef APP-PLUS || H5 || MP-WEIXIN || MP-QQ
				this.isTap = true;
				var currentSize = this.tabListSize[index];
				this.updateIndicator(currentSize.left, currentSize.width);
				this._touchTabIndex = index;
				// #endif
				if(type - 4 === 0){
					this.savePageFlag = true
					this.switchTab(index);
				}else{
					this.savePageFlag = false
					this.switchTab(index);
				}
			},
			onswiperchange(e) {
				// 注意：百度小程序会触发2次

				// #ifndef APP-PLUS || H5 || MP-WEIXIN || MP-QQ
				let index = e.target.current || e.detail.current;
				this.switchTab(index);
				// #endif
			},
			onswiperscroll(e) {
				if (this.isTap) {
					return;
				}

				var offsetX = e.detail.dx;
				var preloadIndex = this._lastTabIndex;
				if (offsetX > TAB_PRELOAD_OFFSET) {
					preloadIndex++;
				} else if (offsetX < -TAB_PRELOAD_OFFSET) {
					preloadIndex--;
				}
				if (preloadIndex === this._lastTabIndex || preloadIndex < 0 || preloadIndex > this.pageList.length - 1) {
					return;
				}
				if (this.pageList[preloadIndex].dataList.length === 0) {
					this.loadTabData(preloadIndex);
				}

				// #ifdef APP-PLUS || H5 || MP-WEIXIN || MP-QQ
				var percentage = Math.abs(this.swiperWidth / offsetX);
				var currentSize = this.tabListSize[this._lastTabIndex];
				var preloadSize = this.tabListSize[preloadIndex];
				var lineL = currentSize.left + (preloadSize.left - currentSize.left) / percentage;
				var lineW = currentSize.width + (preloadSize.width - currentSize.width) / percentage;
				this.updateIndicator(lineL, lineW);
				// #endif
			},
			animationfinish(e) {
				// #ifdef APP-PLUS || H5 || MP-WEIXIN || MP-QQ
				let index = e.detail.current;
				if (this._touchTabIndex === index) {
					this.isTap = false;
				}
				this._lastTabIndex = index;
				this.switchTab(index);
				this.updateIndicator(this.tabListSize[index].left, this.tabListSize[index].width);
				// #endif
			},
			selectorQuery() {
				// #ifdef APP-NVUE
				dom.getComponentRect(this.$refs.tabbar1, res => {
					this.tabbarWidth = res.size.width;
				});
				dom.getComponentRect(this.$refs['swiper1'], res => {
					this.swiperWidth = res.size.width;
				});

				// 因 nvue 暂不支持 class 查询
				let queryTabSize = uni.createSelectorQuery().in(this);
				for (let i = 0; i < this.tabList.length; i++) {
					queryTabSize.select('#' + this.tabList[i].id).boundingClientRect();
				}
				queryTabSize.exec(rects => {
					rects.forEach((rect) => {
						this.tabListSize[rect.dataset.id] = rect;
					})
					this.updateIndicator(this.tabListSize[this.tabIndex].left, this.tabListSize[this.tabIndex]
						.width);
					this.switchTab(this.tabIndex);
				});
				// #endif

				// #ifdef MP-WEIXIN || H5 || MP-QQ
				uni.createSelectorQuery().in(this).select('.tab-box').fields({
					dataset: true,
					size: true,
				}, (res) => {
					this.swiperWidth = res.width;
				}).exec();
				uni.createSelectorQuery().in(this).selectAll('.uni-tab-item-title').boundingClientRect((rects) => {
					rects.forEach((rect) => {
						this.tabListSize[rect.dataset.id] = rect;
					})
					this.updateIndicator(this.tabListSize[this.tabIndex].left, this.tabListSize[this.tabIndex]
						.width);
				}).exec();
				// #endif
			},
			updateIndicator(left, width) {
				this.indicatorLineLeft = left;
				this.indicatorLineWidth = width;
			},
			switchTab(index) {
				if (this.pageList[index].dataList.length === 0) {
					this.loadTabData(index);
				}

				if (this.tabIndex === index) {
					return;
				}

				// 缓存 tabId
				if (this.pageList[this.tabIndex].dataList.length > MAX_CACHE_DATA) {
					let isExist = this.cacheTab.indexOf(this.tabIndex);
					if (isExist < 0) {
						this.cacheTab.push(this.tabIndex);
					}
				}

				this.tabIndex = index;

				// #ifdef APP-NVUE
				// this.scrollTabTo(index);
				// #endif

				// #ifndef APP-NVUE
				this.scrollInto = this.tabList[index].id;
				// #endif

				// 释放 tabId
				if (this.cacheTab.length > MAX_CACHE_PAGE) {
					let cacheIndex = this.cacheTab[0];
					this.clearTabData(cacheIndex);
					this.cacheTab.splice(0, 1);
				}
			},
			scrollTabTo(index) {
				const el = this.$refs['tabitem' + index][0];
				let offset = 0;
				// TODO fix ios offset
				if (index > 0) {
					offset = this.tabbarWidth / 2 - this.tabListSize[index].width / 2;
					if (this.tabListSize[index].right < this.tabbarWidth / 2) {
						offset = this.tabListSize[0].width;
					}
				}
				dom.scrollToElement(el, {
					offset: -offset
				});
			},
			loadTabData(index) {
				this.pageList[index].loadData();
			},
			clearTabData(index) {
				this.pageList[index].clear();
			},
			handleShowDetail() {
				this.ishowDetail = !this.ishowDetail
			},
			handleFilter(item) {
				if (item === 'week') {
					this.filterActiveIndex = 0
					this.condition.startDate = this.handleDate(timeRangeFormat('week'))
				} else {
					this.filterActiveIndex = item
					this.condition.startDate = this.handleDate(timeRangeFormat(item))
				}
				this.condition.endDate = this.handleDate(timeRangeFormat('tomorrow'))
				this.pageList && this.pageList[this.tabIndex].refreshData()
			},
			handleDate(date){
				const str1 = date.slice(0,4)
				const str2 = date.slice(4,6)
				const str3 = date.slice(6,8)
				return str1+'-'+str2+'-'+str3
			},
		}
	}
</script>

<style lang="scss">
	.ticket-order-page {
		flex-direction: column;
		flex: 1;
	}

	/* #ifndef APP-PLUS */
	page {
		width: 100%;
		min-height: 100%;
		display: flex;
		background: $background-color-1;
	}

	.status_bar {
		height: var(--status-bar-height);
	}

	/* #endif */

	.tabs {
		flex: 1;
		flex-direction: column;
		overflow: hidden;
		background-color: #ffffff;
	}

	.tab-bar {
		width: 750rpx;
		height: 42px;
		flex-direction: row;
		/* #ifndef APP-PLUS */
		white-space: nowrap;
		/* #endif */
		border-bottom: 0.5px solid #eeeeee;
	}

	/* #ifndef APP-NVUE */
	.tab-bar ::-webkit-scrollbar {
		display: none;
		width: 0 !important;
		height: 0 !important;
		-webkit-appearance: none;
		background: transparent;
	}

	/* #endif */

	.tab-bar-list {
		flex-direction: column;
	}

	.tab-bar-list-wrapper {
		width: 750rpx;
		flex-direction: row;
	}

	.scroll-view-indicator {
		position: relative;
		height: 2px;
		border-radius: 1px;
		background-color: transparent;
	}

	.scroll-view-underline {
		position: absolute;
		top: 0;
		bottom: 0;
		width: 0;
		background-color: $tabbar-color;
	}

	.scroll-view-animation {
		transition-duration: 0.2s;
		transition-property: left;
	}
	
	.conditon-block {
		position: fixed;
		left: 0;
		top: 172rpx;
		right: 0;
		bottom: 0;
		z-index: 10;
		width: 750rpx;
		height: 124rpx;
		overflow: hidden;
		background-color: #fff;
		display: flex;
		flex-direction: column;
		padding: 40rpx 32rpx 0 16rpx;
	}

	.conditon-block-auto {
		height: 460rpx;
		overflow: auto;
		max-height: 230px;
	}

	.icon-arrow {
		width: 32rpx;
		height: 20rpx;
		margin-top: 24rpx;
		transition-property: transform;
		transition-duration: 0.15s;
		transform: rotate(0deg);
	}

	.icon-arrow-rotate {
		transform: rotate(180deg);
	}


	.filter-btn {
		width: 148rpx;
		height: 68rpx;
		line-height: 64rpx;
		background-color: #f8f8f8;
		border-radius: 8px;
		margin-right: 20rpx;
		margin-bottom: 20rpx;
		margin-left: 0;
		border: 2rpx solid transparent;
		overflow: hidden;
		padding: 0;
	}

	.filter-btn__text {
		display: inline-block;
		width: 148rpx;
		height: 68rpx;
		border-radius: 8px;
		line-height: 68rpx;
		color: #8e8e8e;
		text-align: center;
		font-size: 24rpx;
	}

	.filter-btn-active {
		background: #f61d30;
	}

	.filter-btn-active__text {
		color: #fff;
		background: #f61d30;
	}

	.filter-content {
		display: flex;
		flex-wrap: wrap;
	}

	uni-button:after {
		border: 0
	}

	.empty {
		height: 124rpx;
	}

	.tab-box {
		flex: 1;
		background: $background-color-1;
		padding: 0 16rpx;
	}

	.uni-tab-item {
		/* #ifndef APP-PLUS */
		display: inline-block;
		/* #endif */
		flex-wrap: nowrap;
		padding-left: 6px;
		padding-right: 6px;
		flex: 1;
		justify-content: center;
		text-align: center;
	}

	.uni-tab-item-title {
		color: $text-base-color;
		font-size: 28rpx;
		height: 40px;
		line-height: 40px;
		font-weight: 400;
		flex-wrap: nowrap;
		/* #ifndef APP-PLUS */
		white-space: nowrap;
		/* #endif */
	}

	.uni-tab-item-title-active {
		color: $tabbar-color;
		font-weight: 500;
	}

	.swiper-item {
		flex: 1;
		flex-direction: column;
	}

	.page-item {
		flex: 1;
		flex-direction: row;
		position: absolute;
		left: 16rpx;
		top: 0;
		right: 16rpx;
		bottom: 0;
	}
</style>
