<template>
	<view class="el-tabs" :style="{ background: bgColor }">
		<view :id="id">
			<view v-if="isLeft" class="tabs-left">
				<slot name="left"></slot>
			</view>
			<scroll-view scroll-x class="el-scroll-view" :scroll-left="scrollLeft" scroll-with-animation>
				<view class="el-scroll-box" :class="{'el-tabs-scorll-flex': !isScroll}">
					<view class="el-tab-item" :id="'el-tab-item-' + index" v-for="(item, index) in list" :key="index" @click="clickTab(index)" :style="[tabItemStyle(index)]">
						{{ item[name] || item['name']}}
					</view>
					<view v-if="isRight" class="el-tab-item" :style="[tabItemStyle(index), { width: unit(rightStyle.width,'rpx') }]"></view>
					<view v-if="showBar" class="el-tab-bar" :style="[tabBarStyle]"></view>
				</view>
			</scroll-view>
			<view v-if="isRight" class="tabs-right" style="padding: 0 10rpx;" :style="{ width: unit(props.itemWidth,'rpx'), height: unit(props.height + props.barHeight,'rpx'), lineHeight: unit(props.height,'rpx'), background: bgColor }">
				<slot name="right"></slot>
			</view>
		</view>
	</view>
</template>

<script setup>
	import { ref,watch,nextTick,computed, onMounted,getCurrentInstance } from "vue";
	import { deepMerge,rpx2px,sleep,guid,unit } from "../../libs/utils.js";
	import { addStyle,getClientRect } from "../../libs/style.js";
	
	const props = defineProps({
		// 导航菜单是否需要滚动，如只有2或者3个的时候，就不需要滚动了，此时使用flex平分tab的宽度
		isScroll: {
			type: Boolean,
			default: true
		},
		//需循环的标签列表
		list: {
			type: Array,
			default () {
				return [];
			}
		},
		// 当前活动tab的索引
		current: {
			type: [Number, String],
			default: 0
		},
		// 导航栏的高度和行高
		height: {
			type: [String, Number],
			default: 80
		},
		// 字体大小
		fontSize: {
			type: [String, Number],
			default: 30
		},
		// 过渡动画时长, 单位ms
		duration: {
			type: [String, Number],
			default: 0.5
		},
		// 选中项的主题颜色
		activeColor: {
			type: String,
			default: '#2979ff'
		},
		// 未选中项的颜色
		inactiveColor: {
			type: String,
			default: '#303133'
		},
		// 菜单底部移动的bar的宽度，单位rpx
		barWidth: {
			type: [String, Number],
			default: 40
		},
		// 移动bar的高度
		barHeight: {
			type: [String, Number],
			default: 6
		},
		// 单个tab的左或有内边距（左右相同）
		gutter: {
			type: [String, Number],
			default: 30
		},
		// 导航栏的背景颜色
		bgColor: {
			type: String,
			default: '#ffffff'
		},
		// 读取传入的数组对象的属性(tab名称)
		name: {
			type: String,
			default: 'name'
		},
		// 读取传入的数组对象的属性(徽标数)
		count: {
			type: String,
			default: 'count'
		},
		// 徽标数位置偏移
		offset: {
			type: Array,
			default: () => {
				return [5, 20]
			}
		},
		// 活动tab字体是否加粗
		bold: {
			type: Boolean,
			default: true
		},
		itemStyle: {
			type: Object,
			default() {
				return {}
			}
		},
		// 当前活动tab item的样式
		activeItemStyle: {
			type: Object,
			default() {
				return {}
			}
		},
		// 是否显示底部的滑块
		showBar: {
			type: Boolean,
			default: true
		},
		// 底部滑块的自定义样式
		barStyle: {
			type: Object,
			default() {
				return {}
			}
		},
		// 标签的宽度
		itemWidth: {
			type: [Number, String],
			default: 'auto'
		},
		isLeft: {
			type: Boolean,
			default: false
		},
		isRight: {
			type: Boolean,
			default: false
		}
	});
	
	const emits  		 = defineEmits(["change"]);
	let instance 		 = getCurrentInstance();
	let scrollLeft 		 = ref(0); // 滚动scroll-view的左边滚动距离
	let tabQueryInfo 	 = ref([]); // 存放对tab菜单查询后的节点信息
	let componentWidth 	 = ref(0); // 屏幕宽度，单位为px
	let scrollBarLeft  	 = ref(0); // 移动bar需要通过translateX()移动的距离
	let parentLeft     	 = ref(0); // 父元素(tabs组件)到屏幕左边的距离
	let id             	 = ref(guid()); // id值
	let currentIndex   	 = ref(props.current);
	let barFirstTimeMove = ref(true); // 滑块第一次移动时(页面刚生成时)，无需动画，否则给人怪异的感觉
	let rightStyle		 = ref({ width: 0, height: 0 });
	
	const scrollByIndex = ()=>{
		let tabInfo = tabQueryInfo.value[currentIndex.value];
		if (!tabInfo) return;
		let tabWidth = tabInfo.width;
		let offsetLeft = tabInfo.left - parentLeft.value;
		let iScrollLeft = offsetLeft - (componentWidth.value - tabWidth) / 2;
		scrollLeft.value = iScrollLeft < 0 ? 0 : iScrollLeft;
		let left = tabInfo.left + tabInfo.width / 2 - parentLeft.value;
		scrollBarLeft.value = left - uni.upx2px(props.barWidth) / 2;
		if(barFirstTimeMove.value == true) {
			setTimeout(() => {
				barFirstTimeMove.value = false;
			}, 100);
		}
	}
	
	const clickTab = (index)=>{
		if(index == currentIndex.value) return ;
		emits('change', index);
	}
	
	const getTabRect = ()=>{
		let query = uni.createSelectorQuery().in(instance);
		for (let i = 0; i < props.list.length; i++) {
			query.select(`#el-tab-item-${i}`).fields({ size: true, rect: true });
		}
		
		query.exec(
			function(res) {
				tabQueryInfo.value = res;
				// 初始化滚动条和移动bar的位置
				scrollByIndex();
			}.bind(instance)
		);
	}
	
	const init = ()=>{
		getClientRect('#' + id.value).then(res=>{
			parentLeft.value 	 = res.left;
			componentWidth.value = res.width;
			getTabRect();
		});
		
		getClientRect('.tabs-right',false).then(res=>{
			rightStyle.value.width = res.width;
			rightStyle.value.height = res.height;
		});
	}
	
	onMounted(()=>{
		nextTick(()=>{
			init();
		})
	})
	
	watch(()=>props.list,(newValue,oldValue)=>{
		if(newValue.length !== oldValue.length) currentIndex.value = 0;
		nextTick(() => {
			init();
		});
	});
	
	watch(()=>props.current,(newValue,oldValue)=>{
		nextTick(() => {
			currentIndex.value = newValue;
			scrollByIndex();
		});
	},{ deep: true, immediate: true });
	
	const tabBarStyle = computed(()=>{
		let style = {
			width: props.barWidth + 'rpx',
			transform: `translate(${scrollBarLeft.value}px, -100%)`,
			// 滑块在页面渲染后第一次滑动时，无需动画效果
			'transition-duration': `${barFirstTimeMove.value ? 0 : props.duration }s`,
			'background-color': props.activeColor,
			height: props.barHeight + 'rpx',
			opacity: barFirstTimeMove.value ? 0 : 1,
			// 设置一个很大的值，它会自动取能用的最大值，不用高度的一半，是因为高度可能是单数，会有小数出现
			'border-radius': `${props.barHeight / 2}px`
		};
		return Object.assign(style, props.barStyle);
	});
	
	const tabItemStyle = computed(()=>{
		return (index) => {
			let style = {
				height: props.height + 'rpx',
				'line-height': props.height + 'rpx',
				'font-size': props.fontSize + 'rpx',
				'transition-duration': `${props.duration}s`,
				padding: props.isScroll ? `0 ${props.gutter}rpx` : '',
				flex: props.isScroll ? 'auto' : '1',
				width: rpx2px(props.itemWidth,true)
			};
			
			style = deepMerge(style,props.itemStyle);
			if (index == currentIndex.value && props.bold) style.fontWeight = 'bold';
			if (index == currentIndex.value) {
				style.color = props.activeColor;
				// 给选中的tab item添加外部自定义的样式
				style = Object.assign(style, props.activeItemStyle);
			} else {
				style.color = props.inactiveColor;
			}
			
			return style;
		}
	});
	
</script>

<style lang="scss" scoped>
	view, scroll-view {
		box-sizing: border-box;
	}
	
	::-webkit-scrollbar {
		display: none;
		width: 0 !important;
		height: 0 !important;
		-webkit-appearance: none;
		background: transparent;
	}
	
	/* #ifdef H5 */
	// 通过样式穿透，隐藏H5下，scroll-view下的滚动条
	scroll-view ::v-deep ::-webkit-scrollbar {
		display: none;
		width: 0 !important;
		height: 0 !important;
		-webkit-appearance: none;
		background: transparent;
	}
	/* #endif */
	
	.el-tabs {
		position: relative;
		.tabs-left {
			
		}
		.tabs-right {
			position: absolute;
			top: 0;
			right: 0;
			padding: 0 10rpx;
		}
	}
	
	.el-scroll-box {
		position: relative;
	}
	
	.el-scroll-view {
		width: 100%;
		white-space: nowrap;
		position: relative;
	}
	
	.el-tab-item {
		position: relative;
		display: inline-block;
		text-align: center;
		transition-property: background-color, color;
		overflow: hidden;
		white-space: nowrap;
		text-overflow: ellipsis;
	}
	
	.el-tab-bar {
		position: absolute;
		bottom: 0;
	}
	
	.el-tabs-scorll-flex {
		display: flex;
		flex-direction: row;
		justify-content: space-between;
	}
</style>