<template>
	<div>
		<div v-if="drag" class="wrap tab-bar-scroll">
			<scroller class="scroll" scrollDirection="horizontal" showScrollbar="false">
				<div
					class="tab-bar-item tab-bar-scroll-width"
					v-for="(tabBar, t) in tabBars"
					:key="t"
					:ref="tabBar.id + t"
					@click="change(t)"
				>
					<text class="tab-bar-title" :class="[tabIndex === t ? 'active' : '']">{{
						tabBar.name
					}}</text>
				</div>
			</scroller>
		</div>
		<div v-else class="wrap tab-bar">
			<div
				class="tab-bar-item"
				v-for="(tabBar, t) in tabBars"
				:key="t"
				:ref="tabBar.id + t"
				@click="change(t)"
			>
				<text class="tab-bar-title" :class="[tabIndex === t ? 'active' : '']">{{
					tabBar.name
				}}</text>
			</div>
		</div>
	</div>
</template>

<script>
const dom = weex.requireModule('dom');

export default {
	props: {
		drag: {
			type: Boolean,
			default: true
		},
		tabBars: {
			type: Array,
			default: function(e) {
				return [];
			}
		},
		tabIndex: {
			type: Number,
			default: 0
		}
	},
	watch:{
		tabIndex(newVal){
			this.change(newVal)
		}
	},
	methods: {
		async change(index, e) {

			let ret = {
				index: index
			};

			this.$emit('tabChange', ret);
			const el = this.$refs[this.tabBars[index].id + index][0]
			let elSize = await this.getElSize(el);
			if (elSize.left + elSize.width > 750) {
			    let idx = index - 4;
			    let newEl = this.$refs[this.tabBars[idx].id + idx][0]
			    dom.scrollToElement(newEl, {});
			    return;
			}
			if (elSize.left < 0) {
			    dom.scrollToElement(el, {});
			}
			
		},
		getElSize(el) { //得到元素的size
		    return new Promise((res, rej) => {
		        const result = dom.getComponentRect(el, option => {
		            res(option.size);
		        })
		    })
		}
	}
};
</script>
<style>
.wrap {
	height: 90px;
	width: 750px;
	flex-direction: row;
	font-size: 30px;
	border-bottom-width: 1px;
	border-color: #eee;
}
.tab-bar {
	justify-content: space-between;
	padding-left: 30px;
	padding-right: 30px;
}
.scroll {
	height: 90px;
	width: 750px;
	flex-direction: row;
}
.tab-bar-item {
	height: 90px;
	flex-direction: column;
	align-items: center;
	justify-content: center;
}
.tab-bar-scroll-width {
	width: 150px;
}
.tab-bar-title {
	height: 90px;
	line-height: 90px;
	font-size: 30px;
	color: #303133;
	border-bottom-width: 4px;
	border-color: transparent;
}
.active {
	color: #ec706b;
	border-color: #ec706b;
}
</style>
