<template>
	<a-input v-model:value="subtitleVal" allowClear placeholder="请输入" />
	<div style="height: 98%; overflow-y: auto" class="mt-2 pb-4">
		<div v-if="subtitle">{{ subtitle }}</div>
		<div v-for="(item, idx) in subtitleList" :key="idx">
			<div>{{ item.startTimeStr }}~{{ item.endTimeStr }}</div>
			<div style="cursor: pointer; padding: 10px 0" @click="videoSpeed(item)">{{ item.text }}</div>
		</div>
	</div>
</template>

<script setup>
	import axios from 'axios'
	const props = defineProps({
		url: {
			type: String,
			default: ''
		}
	})
	watch(
		() => props.url,
		(newVal, oldVal) => {
			if (newVal) {
				nextTick(() => {
					GetSrtInfo(newVal)
				})
			}
		},
		{ immediate: true }
	)
	const emit = defineEmits({ videoSpeed: null })
	const videoSpeed = (e) => {
		emit('videoSpeed', e)
	}
	// 模糊查询函数
	const subtitleVal = ref()
	const srtInfoList = ref([])
	const subtitleList = computed(() => {
		return srtInfoList.value.filter((item) => {
			if (subtitleVal.value) {
				return item.text.includes(subtitleVal.value)
			} else {
				return true
			}
		})
	})
	function getFileExtension(filename) {
		return filename.substring(filename.lastIndexOf('.') + 1).toLowerCase()
	}
	//获取字幕内容，发送一个get请求
	const subtitle = ref()
	const GetSrtInfo = (srtUrl) => {
		subtitle.value = ''
		if(getFileExtension(srtUrl) != 'srt'){
			subtitle.value = '字幕解析失败'
			return
		}
		axios
			.get(`${srtUrl}`)
			.then(function (response) {
				try {
					let textList = response.data
						.split(/\n\s\n/)
						.filter((item) => item != '')
						.map((item, index) => {
							let textItem = item.split(/\n/)
							return {
								index: index,
								sort: textItem[0],
								text: textItem[2],
								startTime: ToSeconds(textItem[1].split(' --> ')[0]),
								endTime: ToSeconds(textItem[1].split(' --> ')[1]),
								startTimeStr: toStrTime(textItem[1].split(' --> ')[0]),
								endTimeStr: toStrTime(textItem[1].split(' --> ')[1]),
								timeLine: textItem[1]
							}
						})
					subtitle.value = false
					srtInfoList.value = textList
				} catch (error) {
					subtitle.value = '字幕解析失败'
				}
			})
			.catch(function (error) {
				console.log(error)
			})
	}
	function toStrTime(t){
		return t.split(',')[0]
	}
	//将时间转化为秒
	function ToSeconds(t) {
		var s = 0.0
		if (t) {
			var p = t.split(':')
			for (let i = 0; i < p.length; i++) {
				s = s * 60 + parseFloat(p[i].replace(',', '.'))
			}
		}
		return s
	}
	defineExpose({
		GetSrtInfo
	})
</script>
<style scoped lang="less"></style>
