<template>
	<view
		v-if="isShow"
		class="notice-bar-wrapper"
		:style="{
			background: backgroundColor,
			fontSize: fontSize + 'px',
			color: color
		}"
	>
		<Icons v-if="showIcon" class="sound" type="sound" :size="fontSize * 1.3" :color="color" />
		<view class="notice-content-wrapper">
			<view
				class="notice-content"
				:class="{ 'single-content': single, 'notice-content-animation': scrollable && contentOverflow }"
				>{{ text }}</view
			>
		</view>
		<Icons v-if="showGetMore" class="more" type="forward" :size="fontSize" :color="color" @click="emits('showMore')" />
		<Icons v-if="showClose" class="close" type="closeempty" :size="fontSize" :color="color" @click="isShow = false" />
	</view>
</template>

<script setup lang="ts">
import { Ref, onMounted, ref } from "vue";
import Icons from "../icons/index.vue";

const isShow: Ref<boolean> = ref(true);

defineProps({
	text: {
		type: String,
		default: ""
	},
	moreText: {
		type: String,
		default: ""
	},
	backgroundColor: {
		type: String,
		default: "#FFF9EA"
	},
	speed: {
		// 默认1s滚动100px
		type: Number,
		default: 100
	},
	color: {
		type: String,
		default: "#FF9A43"
	},
	fontSize: {
		type: Number,
		default: 14
	},
	moreColor: {
		type: String,
		default: "#FF9A43"
	},
	single: {
		// 是否单行
		type: Boolean,
		default: true
	},
	scrollable: {
		// 是否滚动，添加后控制单行效果取消
		type: Boolean,
		default: true
	},
	showIcon: {
		// 是否显示左侧icon
		type: Boolean,
		default: false
	},
	showGetMore: {
		// 是否显示右侧查看更多
		type: Boolean,
		default: false
	},
	showClose: {
		// 是否显示右侧关闭按钮
		type: Boolean,
		default: false
	}
});

const emits = defineEmits(["showMore"]);

const contentOverflow: Ref<boolean> = ref(false);

function getElementWidth(selector: string): Promise<number> {
	return new Promise<number>((resolve, reject) => {
		uni
			.createSelectorQuery()
			.select(selector)
			.boundingClientRect((res: any) => {
				resolve(res.width || 0);
			})
			.exec();
	});
}

onMounted(async () => {
	const width = await getElementWidth(".notice-content-wrapper");
	const contentWidth = await getElementWidth(".notice-content");
	contentOverflow.value = width < contentWidth;
});
</script>

<script lang="ts">
export default {
	name: "NoticeBar"
};
</script>

<style lang="scss" scoped>
.notice-bar-wrapper {
	box-sizing: border-box;
	display: flex;
	flex-direction: row;
	align-items: center;
	width: 100%;
	padding: 6px;
	.sound {
		flex-shrink: 0;
		margin-right: 3px;
	}
	.close {
		flex-shrink: 0;
	}
	.notice-content-wrapper {
		flex: 1;
		overflow: hidden;
		.notice-content {
			display: inline-block;
		}
	}
	.single-content {
		white-space: nowrap;
	}
	.notice-content-animation {
		animation: notice 10s 0s linear infinite both;
	}
}

@keyframes notice {
	0% {
		transform: translate3d(600rpx, 0, 0);
	}
	100% {
		transform: translate3d(-100%, 0, 0);
	}
}
</style>
