<template>
	<view>
		<view class="naming_bg" :style="{backgroundImage: `url(${$baseUrl}aiNaming/bg.jpg)`}">
			<!-- <view class="page-top">
				<image @tap="backHandler" class="btnback" :src="$baseUrl+'aiNaming/back_btn.png'"></image>
				<view class="page_title">星妈起名</view>
			</view> -->

			<view class="top_con">
				<!--出生状态-->
				<view class="cs_status">
					<view class="item_top">
						<span class="title_txt"><span :style="{color: '#b27c1e'}">*</span>出生状态</span>
						<view class="val_view">
							<view class="radio-group" :style="{display: 'flex'}">
								<label class="radio-item" :class="{ active: birthStatus === '已出生' }"
									@click="birthStatus = '已出生'">
									<radio :style="{opacity: 0}" :checked="birthStatus === '已出生'" color="#4a90e2" />
									<view class="custom-radio" :style="{display: 'flex','margin-top': '-41rpx'}">
										<image class="radio-icon"
											:src="birthStatus === '已出生' ? `${$baseUrl}aiNaming/sel.png` : `${$baseUrl}aiNaming/no_sel.png`"
											mode="aspectFit" />
										<text class="radio-label" :style="{'margin': '-6rpx 0 0 10rpx'}">已出生</text>
									</view>
								</label>
								<label class="radio-item" :class="{ active: birthStatus === '未出生' }"
									@click="birthStatus = '未出生'">
									<radio :style="{opacity: 0}" :checked="birthStatus === '未出生'" color="#4a90e2" />
									<view class="custom-radio" :style="{display: 'flex','margin-top': '-41rpx'}">
										<image class="radio-icon"
											:src="birthStatus === '未出生' ? `${$baseUrl}aiNaming/sel.png` : `${$baseUrl}aiNaming/no_sel.png`"
											mode="aspectFit" />
										<text class="radio-label" :style="{'margin': '-6rpx 0 0 10rpx'}">未出生</text>
									</view>
								</label>
							</view>
						</view>
					</view>
					<view class="item_line"></view>
				</view>

				<!--出生时间-->
				<view class="cs_time">
					<view class="item_top">
						<span class="title_txt"><span :style="{color: '#b27c1e'}">*</span>出生时间</span>
						<view class="val_view">
							<view class="time-picker-container" @click="openPicker">
								<!-- 隐藏的时间选择器 -->
								<view class="datetime-picker" :style="{'margin-left': '0rpx', 'width':'480rpx'}">
									<uni-datetime-picker class="custom-picker" ref="pickerRef" v-model="birthTime">
										<!-- 时间显示部分 -->
										<view class="time-display">
											<text class="date_txt">{{ formattedDate }}</text>
											<view class="time-separator">
												<image :src="`${$baseUrl}aiNaming/line.png`" mode="aspectFit"
													class="time-icon" />时
											</view>
											<view class="time-separator">
												<image :src="`${$baseUrl}aiNaming/line.png`" mode="aspectFit"
													class="time-icon" />分
											</view>
											<!-- 右侧箭头图标 -->
											<view class="time-separator">
												<image :src="`${$baseUrl}aiNaming/jt.png`" mode="aspectFit"
													class="arrow-icon" />
											</view>
											<text class="hh">{{ formattedTime.hour }}</text>
											<text class="ss">{{ formattedTime.minute }}</text>
										</view>

									</uni-datetime-picker>
								</view>
							</view>

						</view>
					</view>
					<view class="item_line"></view>
				</view>

				<!--姓氏-->
				<view class="surname_box">
					<view class="item_top">
						<span class="title_txt"><span :style="{color: '#b27c1e'}">*</span>姓氏</span>
						<input class="name_input" v-model="surname" @input="setNameInput" @blur="forceCorrection" />
					</view>
					<view class="item_line"></view>
				</view>


				<!--性别-->
				<view class="cs_sex">
					<view class="item_top">
						<span class="title_txt"><span :style="{color: '#b27c1e'}">*</span>性别</span>
						<view class="val_view">
							<view class="radio-group" :style="{display: 'flex'}">
								<label class="radio-item" :class="{ active: gender === '男' }" @click="gender = '男'">
									<radio :style="{opacity: 0}" :checked="gender === '男'" color="#4a90e2" />
									<view class="custom-radio" :style="{display: 'flex','margin-top': '-41rpx'}">
										<image class="radio-icon"
											:src="gender === '男' ? `${$baseUrl}aiNaming/sel.png` : `${$baseUrl}aiNaming/no_sel.png`"
											mode="aspectFit" />
										<text class="radio-label" :style="{'margin': '-6rpx 0 0 10rpx'}">男</text>
									</view>
								</label>
								<label class="radio-item" :class="{ active: gender === '女' }" @click="gender = '女'">
									<radio :style="{opacity: 0}" :checked="gender === '女'" color="#4a90e2" />
									<view class="custom-radio" :style="{display: 'flex','margin-top': '-41rpx'}">
										<image class="radio-icon"
											:src="gender === '女' ? `${$baseUrl}aiNaming/sel.png` : `${$baseUrl}aiNaming/no_sel.png`"
											mode="aspectFit" />
										<text class="radio-label" :style="{'margin': '-6rpx 0 0 10rpx'}">女</text>
									</view>
								</label>
							</view>
						</view>
					</view>
					<view class="item_line"></view>
				</view>

				<!--数字要求-->
				<view class="name_len">
					<view class="item_top">
						<span class="title_txt"><span :style="{color: '#b27c1e'}">*</span>数字要求</span>
						<view class="val_view">
							<view class="radio-group" :style="{display: 'flex'}">
								<label class="radio-item" :class="{ active: wordCount === '单字' }"
									@click="wordCount = '单字'">
									<radio :style="{opacity: 0}" :checked="wordCount === '单字'" color="#4a90e2" />
									<view class="custom-radio" :style="{display: 'flex','margin-top': '-41rpx'}">
										<image class="radio-icon"
											:src="wordCount === '单字' ? `${$baseUrl}aiNaming/sel.png` : `${$baseUrl}aiNaming/no_sel.png`"
											mode="aspectFit" />
										<text class="radio-label" :style="{'margin': '-6rpx 0 0 10rpx'}">单字</text>
									</view>
								</label>
								<label class="radio-item" :class="{ active: wordCount === '双字' }"
									@click="wordCount = '双字'">
									<radio :style="{opacity: 0}" :checked="wordCount === '双字'" color="#4a90e2" />
									<view class="custom-radio" :style="{display: 'flex','margin-top': '-41rpx'}">
										<image class="radio-icon"
											:src="wordCount === '双字' ? `${$baseUrl}aiNaming/sel.png` : `${$baseUrl}aiNaming/no_sel.png`"
											mode="aspectFit" />
										<text class="radio-label" :style="{'margin': '-6rpx 0 0 10rpx'}">双字</text>
									</view>
								</label>
								<!-- <label class="radio-item" :class="{ active: wordCount === '三字' }"
									@click="wordCount = '三字'">
									<radio :style="{opacity: 0}" :checked="wordCount === '三字'" color="#4a90e2" />
									<view class="custom-radio" :style="{display: 'flex','margin-top': '-41rpx'}">
										<image class="radio-icon"
											:src="wordCount === '三字' ? `${$baseUrl}aiNaming/sel.png` : `${$baseUrl}aiNaming/no_sel.png`"
											mode="aspectFit" />
										<text class="radio-label" :style="{'margin': '-6rpx 0 0 10rpx'}">三字</text>
									</view>
								</label> -->
							</view>
						</view>
					</view>
					<view class="item_line"></view>
				</view>

				<!--必有字-->
				<view class="shall_be_word">
					<view class="item_top">
						<span class="title_txt">必有字</span>
						<input class="shall_be_input" :placeholder="showPlaceholder ? '示例：多、浩、雨' : ''"
							v-model="requiredChars" @blur="e => enforceSeparator(e, 1)"
							@click="showPlaceholder = false" />
					</view>
					<view class="item_line"></view>
				</view>

				<!--避免字-->
				<view class="taboo_word">
					<view class="item_top">
						<span class="title_txt">避免字</span>
						<input class="taboo_input" :placeholder="showPlaceholder2 ? '示例：然、萌' : ''" v-model="avoidChars"
							@blur="e => enforceSeparator(e, 2)" @click="showPlaceholder2 = false" />
					</view>
					<view class="item_line"></view>
				</view>

				<!--期望风格-->
				<view class="hope_style">
					<view class="item_top">
						<span class="title_txt">期望风格</span>
						<view class="val_view">
							<view class="radio-group">
								<view :style="{display: 'flex'}">
									<label class="radio-item" :class="{ active: expectedStyle === '古风诗词' }"
										@click="(expectedStyle === '古风诗词')? expectedStyle = '' : expectedStyle = '古风诗词'">
										<radio :style="{opacity: 0}" :checked="expectedStyle === '古风诗词'"
											color="#4a90e2" />
										<view class="custom-radio" :style="{display: 'flex','margin-top': '-41rpx'}">
											<image class="radio-icon"
												:src="expectedStyle === '古风诗词' ? `${$baseUrl}aiNaming/sel.png` : `${$baseUrl}aiNaming/no_sel.png`"
												mode="aspectFit" />
											<text class="radio-label" :style="{'margin': '-6rpx 0 0 10rpx'}">古风诗词</text>
										</view>
									</label>
									<label class="radio-item" :class="{ active: expectedStyle === '蛇年生肖' }"
										@click="(expectedStyle === '蛇年生肖')? expectedStyle = '' : expectedStyle = '蛇年生肖'">
										<radio :style="{opacity: 0}" :checked="expectedStyle === '蛇年生肖'"
											color="#4a90e2" />
										<view class="custom-radio" :style="{display: 'flex','margin-top': '-41rpx'}">
											<image class="radio-icon"
												:src="expectedStyle === '蛇年生肖' ? `${$baseUrl}aiNaming/sel.png` : `${$baseUrl}aiNaming/no_sel.png`"
												mode="aspectFit" />
											<text class="radio-label" :style="{'margin': '-6rpx 0 0 10rpx'}">蛇年生肖</text>
										</view>
									</label>
								</view>
								<view :style="{display: 'flex'}">
									<label class="radio-item" :class="{ active: expectedStyle === '龙年生肖' }"
										@click="(expectedStyle === '龙年生肖')? expectedStyle = '' : expectedStyle = '龙年生肖'">
										<radio :style="{opacity: 0}" :checked="expectedStyle === '龙年生肖'"
											color="#4a90e2" />
										<view class="custom-radio" :style="{display: 'flex','margin-top': '-41rpx'}">
											<image class="radio-icon"
												:src="expectedStyle === '龙年生肖' ? `${$baseUrl}aiNaming/sel.png` : `${$baseUrl}aiNaming/no_sel.png`"
												mode="aspectFit" />
											<text class="radio-label" :style="{'margin': '-6rpx 0 0 10rpx'}">龙年生肖</text>
										</view>
									</label>
									<label class="radio-item" :class="{ active: expectedStyle === '马年生肖' }"
										@click="(expectedStyle === '马年生肖')? expectedStyle = '' : expectedStyle = '马年生肖'">
										<radio :style="{opacity: 0}" :checked="expectedStyle === '马年生肖'"
											color="#4a90e2" />
										<view class="custom-radio" :style="{display: 'flex','margin-top': '-41rpx'}">
											<image class="radio-icon"
												:src="expectedStyle === '马年生肖' ? `${$baseUrl}aiNaming/sel.png` : `${$baseUrl}aiNaming/no_sel.png`"
												mode="aspectFit" />
											<text class="radio-label" :style="{'margin': '-6rpx 0 0 10rpx'}">马年生肖</text>
										</view>
									</label>
								</view>
							</view>
						</view>
					</view>
					<view class="item_line"></view>
				</view>

			</view>

			<view class="naming_btn" :style="{backgroundImage: `url(${$baseUrl}aiNaming/naming_btn.png)`}"
				@click="onNaming">
			</view>
		</view>
		<CustomLoading :show="globalStore.isShowLoading" :text="'起名中...'"
			:imgPath="$baseUrl+'aiNaming/loading_icon.png'">
		</CustomLoading>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		onMounted,
		computed,
		nextTick,
		getCurrentInstance
	} from 'vue'
	import {
		onLoad,
		onShow,
		onShareAppMessage
	} from '@dcloudio/uni-app'
	import {
		jump,
		JumpType,
		throttleTap
	} from '@/utils/index.js';
	import {
		aiNaming
	} from '../../api/naming.js';
	import CustomLoading from '../../components/CustomLoading.vue';
	import {
		useGlobalStore
	} from "@/stores/global.js";

	const globalStore = useGlobalStore();

	// 出生状态
	const birthStatus = ref('');
	//姓氏
	const surname = ref('');
	// 性别选择
	const gender = ref('');
	// 字数要求
	const wordCount = ref('');
	const showPlaceholder = ref(true);
	//必有字
	const requiredChars = ref('');
	const showPlaceholder2 = ref(true);
	//避免字
	const avoidChars = ref('');
	//期望风格
	const expectedStyle = ref('');

	const back_btn = ref('');
	const {
		proxy
	} = getCurrentInstance();
	const $baseUrl = proxy.$baseUrl;

	onShareAppMessage(() => ({
		title: '好名字是给宝宝独一无二的礼物',
		path: `/pages/naming/naming?back_btn='hide'`,
		imageUrl: $baseUrl + 'aiNaming/single.png'
	}));
	
	onLoad((options) => {
		back_btn.value = options.back_btn
		console.log('接收到的参数:', back_btn.value)
	});

	onShow(() => {
		console.log('onShow')
	});

	// 页面加载
	onMounted(() => {

	});

	// 转换为目标格式
	const getDefaultTime = () => {
		const date = new Date(Date.now())
		const year = date.getFullYear()
		const month = String(date.getMonth() + 1).padStart(2, '0')
		const day = String(date.getDate()).padStart(2, '0')
		const hours = String(date.getHours()).padStart(2, '0')
		const minutes = String(date.getMinutes()).padStart(2, '0')

		return `${year}-${month}-${day} ${hours}:${minutes}`
	}

	//出生时间
	const birthTime = ref(getDefaultTime()) // 默认时间
	const pickerRef = ref(null)

	// 格式化日期显示
	const formattedDate = computed(() => {
		return birthTime.value.split(' ')[0]
	})

	// 格式化时间显示
	const formattedTime = computed(() => {
		const timePart = birthTime.value.split(' ')[1] || '00:00'
		const [hour, minute] = timePart.split(':')
		return {
			hour,
			minute
		}
	})

	// 打开时间选择器
	const openPicker = () => {
		uni.nextTick(() => {
			if (pickerRef.value?.show) {
				pickerRef.value.show()
			} else {
				console.error('时间选择器初始化失败')
			}
		})
	}

	// 计算中文字符数
	// const chineseCount = computed(() => {
	// 	// 方法1：正则匹配中文
	// 	const chineseChars = surname.value.match(/[\u4e00-\u9fa5]/g) || []
	// 	return chineseChars.length

	// })
	// const setNameInput = (e) => {
	// 	const text = e.detail.value

	// 	// 如果超过2个中文，截取前2个
	// 	if (chineseCount.value > 2) {
	// 		// 找到第二个中文字符的位置
	// 		const chineseMatches = [...text.matchAll(/[\u4e00-\u9fa5]/g)]
	// 		if (chineseMatches.length >= 2) {
	// 			const secondCharEndPos = chineseMatches[chineseMatches.length - 1].index + 1
	// 			surname.value = text.slice(0, 2);
	// 		}
	// 	}
	// }

	const realText = ref('') // 实际存储的中文
	// 核心输入处理
	const setNameInput = (e) => {
		const inputVal = e.detail.value

		// 1. 移除非中文字符（包括标点、英文、数字等）
		const chineseOnly = inputVal.replace(/[^\u4e00-\u9fa5]/g, '').slice(0, 17);


		// 3. 更新实际值
		realText.value = chineseOnly

		// 4. 延迟同步显示（避免打断输入法组合）
		if (shouldSyncDisplay(inputVal, chineseOnly)) {
			surname.value = chineseOnly
		}
	}

	// 失焦时强制修正
	const forceCorrection = () => {
		surname.value = realText.value
	}

	// 判断是否需要立即同步显示
	const shouldSyncDisplay = (input, filtered) => {
		// 如果内容变短或完全匹配，立即同步
		return input.length <= filtered.length || input === filtered
	}

	//设置必有字和避免字，用、隔开每一个字
	const enforceSeparator = (e, idx) => {
		let text = e.detail.value
		// 1. 移除所有现有分隔符（避免干扰）
		text = text.replace(/、/g, '')
		// 2. 在每个字符后插入分隔符（最后一个字符除外）
		const formatted = [...text].join('、')
		if (idx == 1) {
			showPlaceholder.value = true; // 获取焦点时隐藏占位符
			requiredChars.value = formatted.slice(0, 5)
		} else if (idx == 2) {
			showPlaceholder2.value = true; // 获取焦点时隐藏占位符
			avoidChars.value = formatted.slice(0, 5)
		}
	}

	//ai取名
	const onNaming = (data) => {
		let param = {
			birthStatus: birthStatus.value,
			birthTime: birthTime.value.split(' ')[0],
			surname: surname.value,
			gender: gender.value,
			wordCount: wordCount.value,
			requiredChars: requiredChars.value,
			avoidChars: avoidChars.value,
			expectedStyle: expectedStyle.value
		}
		// console.log('开始取名：：', param)
		// if (!param.birthStatus || !param.birthTime || !param.surname || !param.gender || !param.wordCount) {
		// 	uni.showToast({
		// 		title: '还有信息没填写哦',
		// 		icon: 'none'
		// 	})
		// 	return;
		// }
		if (!param.birthStatus) {
			uni.showToast({
				title: '请选择出生状态',
				icon: 'none'
			})
			return;
		}
		if (!param.birthTime) {
			uni.showToast({
				title: '请选择出生时间',
				icon: 'none'
			})
			return;
		}
		if (!param.surname) {
			uni.showToast({
				title: '请输入姓氏',
				icon: 'none'
			})
			return;
		}
		if (!param.gender) {
			uni.showToast({
				title: '请选择性别',
				icon: 'none'
			})
			return;
		}
		if (!param.wordCount) {
			uni.showToast({
				title: '请选择数字要求',
				icon: 'none'
			})
			return;
		}

		//验证通过，调接口
		onAiNaming(param);
	};

	//生成or重新生成名字
	const onAiNaming = throttleTap(async (param) => {
		// 显示加载中
		// uni.showLoading({
		// 	title: '生成中...',
		// 	mask: true // 是否显示透明蒙层（防止触摸穿透）
		// })
		globalStore.setIsShowLoading(true);
		let d = await aiNaming(param);
		// 隐藏
		// uni.hideLoading()
		globalStore.setIsShowLoading(false);
		if (d) {
			let nameList = d?.data;
			console.log('取名回调:', nameList)
			if (nameList[0].meaning == "未获取解释") {
				uni.showToast({
					title: '生成失败，请检查你输入的内容',
					icon: 'none'
				})
				return
			}

			jump({
				type: JumpType.INNER,
				url: `/pages/naming/namingResult?param=${encodeURIComponent(JSON.stringify(param))}&nameList=${encodeURIComponent(JSON.stringify(nameList))}`
			})
		}
	}, 5000)

	// 首页组件逻辑
	const backHandler = () => {
		if (!back_btn) {
			uni.navigateBack();
		} else {
			jump({
				type: JumpType.INNER,
				url: `/pages/index/index`
			})
		}
	}
</script>

<style lang="less" scoped>
	::v-deep .uni-datetime-picker--btn {
		background-color: #d3a358 !important;
	}

	::v-deep .uni-calendar-item--checked {
		background-color: #d3a358 !important;
	}

	::v-deep .uni-datetime-picker-btn-text {
		color: #d3a358 !important;
	}

	.naming_bg {
		// position: absolute;
		width: 100%;
		height: 1624rpx;
		background-size: 100% 100%;
	}

	.top_con {
		position: absolute;
		width: 686rpx;
		height: 1044rpx;
		top: 43rpx;
		left: 32rpx;
		background: #fff;
		border-radius: 28rpx;
	}

	.cs_status,
	.cs_time,
	.surname_box,
	.cs_sex,
	.name_len,
	.shall_be_word,
	.taboo_word,
	.hope_style {
		margin-top: 40rpx;
		margin-left: 30rpx;
		font-size: 28rpx;
	}

	.item_top {
		display: flex;
	}

	.title_txt {
		width: 150rpx;
	}

	.val_view {
		display: flex;
		flex-direction: column;
		align-items: flex-end;
		color: #6f6d67;
		font-size: 28rpx;
		font-weight: 400;
		width: 480rpx;
		text-align: right;
	}

	.example-body {
		background-color: #fff;
		padding: 10px;
	}

	.radio-item {
		margin-left: 40rpx;
	}

	.radio-icon {
		width: 26rpx;
		height: 26rpx !important;
	}

	.name_input,
	.shall_be_input,
	.taboo_input {
		width: 480rpx;
		text-align: right;
	}

	.item_line {
		width: 620rpx;
		height: 2rpx;
		margin-top: 30rpx;
		background: #999;
		opacity: 0.15;
	}

	.time-picker-container {
		display: flex;
		width: 470rpx;
		margin-top: 0rpx;
		color: #999;
	}

	.time-display {
		flex: 1;
		display: flex;
		align-items: center;
		// font-size: 20rpx;
		color: #999;
	}

	.date_txt {
		width: 200rpx;
	}

	.time-separator {
		display: flex;
		align-items: center;
		margin-left: 10rpx;
		color: #666;
	}

	.time-icon {
		width: 76rpx;
		height: 15rpx;
		margin-right: 8rpx;
		margin-top: 30rpx;
	}

	.hh {
		margin-left: -232rpx;
	}

	.ss {
		margin-left: 88rpx;
	}

	.arrow-icon {
		width: 11rpx;
		height: 19rpx;
		margin-left: 5rpx;
	}

	.naming_btn {
		position: absolute;
		width: 686rpx;
		height: 94rpx;
		top: 1230rpx;
		left: 32rpx;
		background-size: 100% 100%;
	}

	.page-top {
		width: 100%;
	}

	.btnback {
		width: 20rpx;
		height: 32rpx;
		margin-top: 110rpx;
		margin-left: 48rpx;
	}

	.page_title {
		width: 100%;
		font-size: 34rpx;
		font-weight: 500;
		text-align: center;
		color: #1d1e25;
		margin-top: -46rpx;
		margin-left: 0rpx;
	}
</style>