<template>
	<view class="settings-container">
		<!-- 设置选项组 -->
		<view class="settings-section">
			<u-cell-group :border="false">
				<!-- 语音播报设置 -->
				<u-cell title="语音播报" label="控制除app启动提示外所有语音播报的开关" :border-bottom="true">
					<template #right-icon>
						<u-switch v-model="settings.voiceBroadcast" activeColor="#4cd964"></u-switch>
					</template>
				</u-cell>

				<!-- 点击音效设置 -->
				<u-cell title="点击音效" :border-bottom="true">
					<template #right-icon>
						<u-switch v-model="settings.clickSound" activeColor="#4cd964"></u-switch>
					</template>
				</u-cell>

				<!-- 启动提示语设置 -->
				<u-cell title="启动提示语" :border-bottom="true">
					<template #right-icon>
						<u-switch v-model="settings.startupPrompt" activeColor="#4cd964"></u-switch>
					</template>
				</u-cell>
			</u-cell-group>

			<!-- 启动提示语输入框 -->
			<view class="input-section">
				<u-textarea v-model="settings.startupText" placeholder="输入启动时要说的内容，比如：欢迎使用书嗨/很开心又见到你啦"
					height="100"></u-textarea>
			</view>

			<!-- 语速设置 -->
			<view class="slider-section">
				<view class="slider-title">
					<text>设置语速</text>
					<text class="subtitle">(部分机型不支持)</text>
				</view>
				<u-slider v-model="settings.speechRate" :min="0" :max="10" :step="1" showValue></u-slider>
			</view>

			<!-- 音调设置 -->
			<view class="slider-section">
				<view class="slider-title">
					<text>设置音调</text>
					<text class="subtitle">(部分机型不支持)</text>
				</view>
				<u-slider v-model="settings.pitch" :min="0" :max="10" :step="1" showValue></u-slider>
			</view>

			<!-- 操作按钮 -->
			<view class="button-group">
				<u-button type="primary" text="保存设置并试听" @click="saveAndTest"></u-button>
				<u-button type="warning" text="停止播放" @click="stopPlayback" :plain="true"></u-button>
				<u-button type="error" text="重启app" @click="restartApp" :plain="true"></u-button>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		reactive,
		onMounted
	} from 'vue'

	// TTS 引擎实例
	let innerAudioContext = null;

	// 设置状态
	const settings = reactive({
		voiceBroadcast: true,
		clickSound: true,
		startupPrompt: true,
		startupText: '书嗨，不辜负每一个爱书的人',
		speechRate: 10,
		pitch: 10
	})

	// 检查并请求权限
	async function checkAndRequestPermissions() {
		// #ifdef APP-PLUS
		try {
			const status = await requestPermissions()
			if (!status) {
				uni.showModal({
					title: '提示',
					content: '请在系统设置中允许应用访问麦克风等权限，以便使用语音功能',
					confirmText: '去设置',
					success: (res) => {
						if (res.confirm) {
							// 跳转到应用设置页面
							if (uni.getSystemInfoSync().platform === 'android') {
								const main = plus.android.runtimeMainActivity()
								const Intent = plus.android.importClass('android.content.Intent')
								const Settings = plus.android.importClass('android.provider.Settings')
								const Uri = plus.android.importClass('android.net.Uri')
								const intent = new Intent()
								intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
								intent.setData(Uri.fromParts('package', main.getPackageName(), null))
								main.startActivity(intent)
							} else {
								// iOS
								const UIApplication = plus.ios.import("UIApplication")
								const NSURL = plus.ios.import("NSURL")
								const setting = NSURL.URLWithString("app-settings:")
								const application = UIApplication.sharedApplication()
								application.openURL(setting)
							}
						}
					}
				})
				return false
			}
			return true
		} catch (error) {
			console.error('权限请求失败:', error)
			return false
		}
		// #endif

		// #ifdef H5
		// H5端检查Web Speech API权限
		if ('speechSynthesis' in window) {
			return true
		}
		uni.showToast({
			title: '当前浏览器不支持语音功能',
			icon: 'none'
		})
		return false
		// #endif

		// #ifdef MP-WEIXIN
		// 微信小程序一般不需要特殊权限
		return true
		// #endif
	}

	// 请求权限
	function requestPermissions() {
		return new Promise((resolve, reject) => {
			// #ifdef APP-PLUS
			plus.android.requestPermissions(
				[
					'android.permission.RECORD_AUDIO',
					'android.permission.MODIFY_AUDIO_SETTINGS',
					'android.permission.WRITE_EXTERNAL_STORAGE',
					'android.permission.READ_EXTERNAL_STORAGE'
				],
				function(resultObj) {
					if (resultObj.granted.length === 4) {
						resolve(true)
					} else {
						resolve(false)
					}
				},
				function(error) {
					reject(error)
				}
			)
			// #endif

			// 其他平台直接返回true
			resolve(true)
		})
	}

	// 初始化 TTS 时检查权限
	async function initTTS() {
		const hasPermission = await checkAndRequestPermissions()
		if (!hasPermission) {
			return
		}

		// 检查平台是否支持 TTS
		if (!uni.createInnerAudioContext) {
			uni.showToast({
				title: '当前设备不支持语音功能',
				icon: 'none'
			})
			return
		}

		try {
			// 创建音频实例
			innerAudioContext = uni.createInnerAudioContext()

			// 监听错误
			innerAudioContext.onError((res) => {
				console.error('音频播放错误:', res.errMsg)
				uni.showToast({
					title: '语音播放失败',
					icon: 'none'
				})
			})
		} catch (error) {
			console.error('TTS初始化失败:', error)
		}
	}

	// 文字转语音
	async function textToSpeech(text) {
		const hasPermission = await checkAndRequestPermissions()
		if (!hasPermission) {
			return
		}

		if (!settings.voiceBroadcast) return

		try {
			// 构建 TTS 参数
			const ttsParams = {
				lang: 'zh-CN',
				speed: settings.speechRate / 10, // 将 0-10 转换为 0-1
				pitch: settings.pitch / 10, // 将 0-10 转换为 0-1
				volume: 1,
				text: text
			}

			// #ifdef APP-PLUS
			// App 端使用原生 TTS
			const TTSModule = uni.requireNativePlugin('nrb-tts-plugin')
			TTSModule && TTSModule.init({
				"lang": "ZH",
				"country": "CN"
			}, res => {
				if (res.success == 0) {
					TTSModule.speak(text, ttsParams, (e) => {
						console.log(e, 'dsadsads')
					})
				}
			})
			// #endif

			// #ifdef H5
			// H5端使用Web Speech API
			if ('speechSynthesis' in window) {
				const utterance = new SpeechSynthesisUtterance(text)
				utterance.lang = ttsParams.lang
				utterance.rate = ttsParams.speed
				utterance.pitch = ttsParams.pitch
				utterance.volume = ttsParams.volume
				speechSynthesis.speak(utterance)
			}
			// #endif

			// #ifdef MP-WEIXIN
			// 微信小程序使用微信同声传译插件
			const plugin = requirePlugin("WechatSI")
			plugin.textToSpeech({
				lang: "zh_CN",
				tts: text,
				success: function(res) {
					innerAudioContext.src = res.filename
					innerAudioContext.play()
				},
				fail: function(res) {
					console.error("转换失败", res)
				}
			})
			// #endif
		} catch (error) {
			console.error('TTS播放错误:', error)
			uni.showToast({
				title: '语音播放失败',
				icon: 'none'
			})
		}
	}

	// 保存设置并试听
	function saveAndTest() {
		// 保存设置到本地存储
		uni.setStorageSync('tts_settings', settings)

		// 试听当前设置
		textToSpeech(settings.startupText)

		uni.showToast({
			title: '设置已保存',
			icon: 'success'
		})
	}

	// 停止播放
	function stopPlayback() {
		// #ifdef APP-PLUS
		const TTSModule = uni.requireNativePlugin('nrb-tts-plugin')
		if (TTSModule && TTSModule.stop) {
			TTSModule.stop()
		}
		// #endif

		// #ifdef H5
		if ('speechSynthesis' in window) {
			speechSynthesis.cancel()
		}
		// #endif

		// #ifdef MP-WEIXIN
		if (innerAudioContext) {
			innerAudioContext.stop()
		}
		// #endif

		uni.showToast({
			title: '已停止播放',
			icon: 'none'
		})
	}

	// 重启应用
	function restartApp() {
		uni.showModal({
			title: '提示',
			content: '确定要重启应用吗？',
			success: function(res) {
				if (res.confirm) {
					// #ifdef APP-PLUS
					plus.runtime.restart()
					// #endif

					// #ifdef H5 || MP-WEIXIN
					uni.reLaunch({
						url: '/pages/index/index'
					})
					// #endif
				}
			}
		})
	}

	// 加载保存的设置
	function loadSettings() {
		try {
			const savedSettings = uni.getStorageSync('tts_settings')
			if (savedSettings) {
				Object.assign(settings, savedSettings)
			}
		} catch (error) {
			console.error('加载设置失败:', error)
		}
	}

	// 播放点击音效
	function playClickSound() {
		if (!settings.clickSound) return

		const audio = uni.createInnerAudioContext()
		audio.src = '/static/audio/click.mp3' // 确保添加点击音效文件
		audio.play()
	}

	// 生命周期钩子
	onMounted(async () => {
		await initTTS()
		loadSettings()
	})
</script>

<style lang="scss" scoped>
	.settings-container {
		min-height: 100vh;
		background-color: #f5f5f5;
		padding-bottom: 40rpx;

		.card-head {
			display: flex;
			align-items: center;
			padding: 10rpx 0;

			.head-title {
				margin-left: 10rpx;
				font-size: 32rpx;
				font-weight: bold;
			}
		}

		.settings-section {
			margin: 20rpx;
			background-color: #ffffff;
			border-radius: 12rpx;
			padding: 20rpx;
			box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
		}

		.input-section {
			margin: 30rpx 0;
			padding: 0 20rpx;
		}

		.slider-section {
			margin: 30rpx 0;
			padding: 0 20rpx;

			.slider-title {
				margin-bottom: 20rpx;
				font-size: 28rpx;
				color: #333;

				.subtitle {
					font-size: 24rpx;
					color: #999;
					margin-left: 10rpx;
				}
			}
		}

		.button-group {
			margin-top: 50rpx;
			padding: 0 20rpx;

			:deep(.u-button) {
				margin-bottom: 20rpx;
			}
		}
	}
</style>