<template>
	<NavBar title="研习" />
	<view class="container">

		<view class="header" style="position: relative;">
			<view style="position: absolute; right: 32rpx; top: 32rpx;">
				<wd-button size="small" type="icon" icon="refresh" @click="refreshTime"></wd-button>
			</view>
			<wd-text text="当前时间" bold color="#333" />				
			<view class="header-time flex-row">
				<view class="flex-col gap-2">
					<wd-text text="公历" color="#999" />
					<wd-text :text="currentTime" bold color="#333" />
				</view>
				<view class="flex-col gap-2">
					<wd-text text="农历" color="#999" />
					<wd-text :text="lunarTime" bold color="#333" />
				</view>
			</view>
		</view>

		<view class="header flex-col gap-4" style="margin-top: 32rpx;">
			<wd-text text="当前困惑" bold color="#333" />
			<wd-input v-model="inputTxt" placeholder="请输入" :disabled="lines.length !== 0"/>

			<!-- 起卦按钮 & 进度提示 -->
			<!-- <view class="action-area"> -->
				<wd-button 
					type="warning" 
					size="large" 
					@click="handleCast" 
					:custom-style="{
						backgroundColor: '#145060',
						fontSize: '32rpx',
					}"
					:loading="coinLoading"
					block
					:disabled="showResponseText && !isDone"
				>
					{{ buttonText }}
				</wd-button>
			<!-- 铜钱区域：三个 view 标签显示正面/反面 -->
			<view v-if="lines.length" class="coins-area">
				<view 
					v-for="(coin, index) in coins" 
					:key="index" 
					class="coin"
				>
					<wd-img 
						:src="coin === '正面' ? coinPositiveImg : coinNegativeImg" 
						width="100%"
						height="100%"
						mode="aspectFill"
					/>
				</view>
			</view>
		</view>

		<!-- 底部主爻与动爻区域 -->
		<view class="result-content flex-col gap-4">
			
			<view class="result-area">
				<!-- 左侧：主爻（本卦六爻） -->
				<view class="main-lines">
					<view class="section-title">
						<wd-text text="当前" size="28rpx" bold color="#333" />
						<wd-button 
							v-if="本卦"
							@click="goTo(`/pages/ZhouYi/detail?name=${本卦}`)" 
							size="small"
							plain
							:custom-style="{
								border: '#4b3a2b 2px solid',
								color: '#4b3a2b',
								fontSize: '24rpx',
							}"
						>
							{{ 本卦 }}
						</wd-button>
					</view>
					<view v-if="lines.length === 0" class="empty-tip">暂无</view>
					<view v-else class="lines-list">
						<view v-for="(line, idx) in displayLines" :key="idx" class="line-item" :style="{
							backgroundImage: `url(${line.img})`
						}">
							<!-- <text class="line-position">{{ line.position }}</text> -->
							<!-- <view class="line-symbol">{{ line.symbol }}</view>-->
						</view>

					</view>
				</view>

				<!-- 右侧：变卦信息 -->
				<view class="moving-lines">
					<view class="section-title">
						<wd-text text="变化" size="28rpx" bold color="#333" />
						<wd-button 
							v-if="变卦"
							@click="goTo(`/pages/ZhouYi/detail?name=${变卦}`)" 
							size="small"
							plain
							:custom-style="{
								border: '#4b3a2b 2px solid',
								color: '#4b3a2b',
								fontSize: '24rpx',
							}"
						>
							{{ 变卦 }}
						</wd-button>
					</view>
					<view v-if="movingInfo.length === 0" class="empty-tip">
						{{ lines.length === 0 ? '暂无' : '无动爻' }}
					</view>
					<view v-else class="moving-list">
						<view v-for="(info, idx) in movingInfo" :key="idx" class="moving-item" :style="{
							backgroundImage: `url(${info.img})`
						}">
							<!-- {{ info }} -->
							<!-- <view v-if="info.isMoving" class="moving-symbol">{{ info.symbol }}</view>
							<view v-else >{{ info.symbol }}</view> -->
						</view>
					</view>
				</view>
			</view>

			<wd-text text="内容解析" bold color="#333" />
			<wd-text v-if="!isComplete" text="暂无" color="#333" />
			<wd-button 
				v-if="isComplete && showUserAgreeButton && !showCompleteLoading"
				@click="userAgree"
				block 
				size="large"
				:custom-style="{
					backgroundColor: '#145060',
					fontSize: '32rpx',
				}"
			>
				查看
			</wd-button>

			<view v-if="showResponse" class="result-desc flex-col gap-4">
				<view class="flex-col gap-2">
					<wd-text text="原文" bold color="#333" />
					<wd-text v-if="爻辞" :text="爻辞" color="#666" />
					<view class="empty-tip" v-else>
						<wd-text text="暂无" color="#666" />
					</view>
				</view>
				<view class="flex-col gap-2">
					<wd-text text="解析" bold color="#333" />
					<view class="empty-tip" v-if="!isComplete">
						<wd-text text="暂无" color="#666" />
					</view>
					<wd-text 
						v-if="showResponseText && responseText" 
						:text="responseText" 
						color="#666" 
					/>
				</view>
				<wd-button 
					v-if="isDone && showResponseText"
					@click="save" 
					block 
					size="large"
					:custom-style="{
						backgroundColor: '#145060',
						fontSize: '32rpx',
					}"
				>
						保存此次结果
				</wd-button>
			</view>
		</view>
	</view>

	<wd-message-box />

	<wd-overlay :show="showCompleteLoading" lock-scroll>
		<view class="overlay-content">
			<view class="tips">
				<view>
					<wd-text text="提示" size="32rpx" color="#333" />
				</view>
				<wd-text text="信息已生成，正在整理原文与相关资料....." size="28rpx" color="#333" />
			</view>
		</view>
	</wd-overlay>

	<wd-toast position="middle" />

</template>

<script setup lang="ts">
import NavBar from '@/components/NavBar.vue'
import { ref, computed } from 'vue'
import { useMessage, useToast } from '@/uni_modules/wot-design-uni'
import { AIChat, 获取易经爻辞, createQ } from '@/api/index'
import { useUserStore, useAIReponseStore } from '@/stores'
import { storeToRefs } from 'pinia'
import { watch } from 'vue'
import { formatDate, goTo, rateLimit, sleep } from '@/utils/common'
import { 六十四卦 } from '@/utils/gua_64'
import lunisolar from 'lunisolar'
import { BASE_URL } from '@/config/api.config'

const {
	responseText,
	showResponseText,
	isLoading,
	isDone
} = storeToRefs(useAIReponseStore())

const {
	yaoList
} = storeToRefs(useUserStore())

const message = useMessage()

const currentTime = ref(formatDate(new Date()))
const lunarTime = computed(() => {
	const d = lunisolar(currentTime.value.substring(0, 16))
	return d.lunar.toString()
})
const refreshTime = () => {
	currentTime.value = formatDate(new Date())
}

const YangImg = BASE_URL + '/uploads/mov_yang_d41e51fd83.png'
const YinImg = BASE_URL + '/uploads/yin_e32817a811.png'

const audio = uni.createInnerAudioContext()
audio.autoplay = false
audio.src = BASE_URL + '/uploads/01_b7107f6b3b.mp3'

const ding = uni.createInnerAudioContext()
ding.autoplay = false
ding.src = BASE_URL + '/uploads/ding_ae6e65af25.mp3'

const coinPositiveImg = BASE_URL + '/uploads/_52f5bd86b5.png'
const coinNegativeImg = BASE_URL + '/uploads/_5f46b99d48.png'

const toast = useToast()

// 铜钱状态：三个独立的正/反面，初始均为“正面”
const coins = ref(['正面', '正面', '正面'])
const 本卦 = ref('')
const 变卦 = ref('')

// 存储六爻结果，每个元素为 { type, isMoving, symbol }
// type: '少阳'/'少阴'/'老阳'/'老阴'
// isMoving: Boolean
// symbol: '—' (阳爻) 或 '- -' (阴爻)
const lines = ref<any>([])

// 辅助函数：随机生成正面/反面
const randomSide = () => {
	return Math.random() < 0.5 ? '正面' : '反面'
}

// 根据三个铜钱结果计算爻的类型、是否动爻、符号
const analyzeYao = (coinResults) => {
	console.log(coinResults)
	const positiveCount = coinResults.filter(v => v === '正面').length
	// 正面为阴，反面为阳
	if (positiveCount === 3) {
		// 三个正面 → 老阳（动爻）
		return { type: '老阳', isMoving: true, symbol: '阳', img: YangImg, number: '9' }
	} else if (positiveCount === 0) {
		// 三个反面 → 老阴（动爻）
		return { type: '老阴', isMoving: true, symbol: '阴', img: YinImg, number: '6' }
	} else if (positiveCount === 2) {
		// 两正一反 → 少阴（不动）
		return { type: '少阴', isMoving: false, symbol: '阴', img: YinImg, number: '8' }
	} else {
		// 两反一正 → 少阳
		return { type: '少阳', isMoving: false, symbol: '阳', img: YangImg, number: '7' }
	}
}

// 重置所有状态（清空卦象，重置铜钱为默认正面）
const resetState = () => {
	lines.value = []
	coins.value = ['正面', '正面', '正面']
	本卦.value = ''
	变卦.value = ''
	体卦.value = ''
	用卦.value = ''
	爻辞.value = ''
	动爻列表.value = []
	静爻列表.value = []
	inputTxt.value = ''
	showUserAgreeButton.value = true
	showResponse.value = false
	audio.pause()
	useAIReponseStore().reset()
}

// 执行一次摇卦（增加一爻）
const performCast = () => {
	// 随机生成三个铜钱的正反面
	const newCoins = [randomSide(), randomSide(), randomSide()]
	coins.value = [...newCoins]

	// 根据铜钱结果计算爻象
	const yao = analyzeYao(newCoins)
	// 存入 lines（从下往上，初爻索引0）
	lines.value.unshift(yao)
}


const showDialog = ref(false)
const inputTxt = ref<string>('')

// const isLoading = ref(false)
const resultContent = ref<string>('卦象结果生成中')
const 本卦数字 = ref('')
const 体卦 = ref('')
const 用卦 = ref('')
const 动爻列表 = ref<string[]>([])
const 动爻数量 = ref<number>(0)
const 爻辞 = ref('')
const 动爻名称 = ['初九', '九二', '九三', '九四', '九五', '上九', '初六', '六二', '六三', '六四', '六五', '上六']
const 静爻列表 = ref<string[]>([])
// const 静爻名称 = ['初爻', '二爻', '三爻', '四爻', '五爻', '上爻']

const 获取爻辞名称 = async () => {
	const len = 动爻列表.value.length

	if (len === 0) {
		return {
			pos: '本卦',
			name: '无',
		}
	}

	// 取动爻的爻辞
	if (len === 1) {
		return {
			pos: '本卦',
			name: 动爻列表.value[0],
		}
	}

	// 取上面
	if (len === 2) {
		return {
			pos: '本卦',
			name: 动爻列表.value[1],
		}
	}

	// 取中间
	if (len === 3) {
		return {
			pos: '本卦',
			name: 动爻列表.value[1],
		}
	}

	// 取静爻靠下
	if (len === 4) {
		return {
			pos: '变卦',
			name: 静爻列表.value[0],
		}
	}

	// 取静爻
	if (len === 5) {
		return {
			pos: '变卦',
			name: 静爻列表.value[0],
		}
	}

	if (len === 6) {
		if (本卦.value === '乾为天') {
			return {
				pos: '本卦',
				name: '用九',
			}
		} else if (本卦.value === '坤为地') {
			return {
				pos: '本卦',
				name: '用六',
			}
		} else {
			return {
				pos: '本卦',
				name: '无',
			}
		}
	}

	return {
		pos: '本卦',
		name: '无',
	}
}

const showCompleteLoading = ref<boolean>(false)
const showUserAgreeBox = ref<boolean>(false)
// 监听 lines 变化，当长度为 6 时，执行 AI 回答
watch(
	() => lines.value,
	async (newVal) => {
		// console.log(newVal)
		if (newVal.length === 6) {
			
			showCompleteLoading.value = true
			await sleep(3000)
			showCompleteLoading.value = false

			setTimeout(() => {
				uni.pageScrollTo({
					scrollTop: 999999,
				})
			})

			// 本卦结果
			let result1 = ''
			let arr1 = JSON.parse(JSON.stringify(lines.value))
			arr1.reverse().map(line => {
				result1 += line.symbol
				本卦数字.value += line.number
			})
			// 变卦结果
			let result2 = ''
			let arr2 = JSON.parse(JSON.stringify(movingInfo.value))
			arr2.reverse().map(line => {
				result2 += line.symbol
			})
			// 动爻及静爻结果
			// let result3 = ''
			let arr3 = JSON.parse(JSON.stringify(movingInfo.value))
			arr3.reverse().map((line, i) => {
				if (line.isMoving) {
					if (line.number === '6') {
						动爻列表.value.push(动爻名称[6 + i])
					}
					if (line.number === '9') {
						动爻列表.value.push(动爻名称[i])
					}
				} else {
					if (line.number === '8') {
						静爻列表.value.push(动爻名称[6 + i])
					}
					if (line.number === '7') {
						静爻列表.value.push(动爻名称[i])
					}
				}
			})
			// console.log(动爻列表.value, 静爻列表.value)

			for (let i = 0; i < 64; i++) {
				if (六十四卦[i].symbol === result1) {
					本卦.value = 六十四卦[i].name
					体卦.value = 六十四卦[i].bottom
					用卦.value = 六十四卦[i].top
				}
				if (六十四卦[i].symbol === result2) {
					变卦.value = 六十四卦[i].name
				}
			}

			let _爻辞名称 = await 获取爻辞名称()
			if (_爻辞名称.name === '无') {
				爻辞.value = '无动爻'
			} else {
				if (_爻辞名称.pos === '本卦') {
					爻辞.value = await 获取易经爻辞(本卦.value, _爻辞名称.name)
				}
				if (_爻辞名称.pos === '变卦') {
					爻辞.value = await 获取易经爻辞(变卦.value, _爻辞名称.name)
				}
			}

			// // AI 回答
			await AIChat(
				inputTxt.value,
				本卦.value,
				变卦.value,
				爻辞.value,
				// count
			).then(res => {
				if (res.code) {
				    toast.error(res.message)
				}
			})
		}
	},
	{
		deep: true
	}
)
// watch(
// 	() => isLoading.value,
// 	(newVal) => {
// 		if (!newVal) {
// 			audio.seek(0)
// 			audio.play()
// 		}
// 	},
// 	{
// 		deep: true
// 	}
// )

// 用户同意查看占卜结果并播放音乐
const showUserAgreeButton = ref<boolean>(true)
const agreeMsg = '本程序系免费的数字化研习辅助工具，所形成的内容及原文解读，仅供学习参考之用，不提供现实事务预测、运势分析等服务。'
const showResponse = ref<boolean>(false)
const userAgree = () => {
	// showUserAgreeBox.value = true
	message
		.confirm({
			title: '提示',
			msg: agreeMsg,
		})
		.then(async () => {
			audio.seek(0)
			audio.play()
			showResponse.value = true
			showResponseText.value = true
			isLoading.value = true
			showUserAgreeButton.value = false
		})
}

const agreeCancel = () => {
	showUserAgreeBox.value = false
}

const agreeConfirm = () => {
	showUserAgreeBox.value = false
	audio.seek(0)
	audio.play()
	showResponse.value = true
	showResponseText.value = true
	isLoading.value = true
	showUserAgreeButton.value = false
}



// 保存占卜结果
const save = () => {
    yaoList.value.unshift({
		time: new Date().getTime(),
		q: inputTxt.value,
		symbol1: 本卦.value,
		symbol2: 变卦.value,
		symbolNum: 本卦数字.value,
		result: responseText.value
	})
	responseText.value = ''
	isDone.value = false
	toast.success('保存成功')

	resetState()
}

const coinLoading = ref<boolean>(false)

// 起卦逻辑
const handleCast = async () => {

	ding.play()

	// 如果已完成六爻，则先重置
	if (lines.value.length === 6) {
		resetState()
	} else if (lines.value.length === 0) {

		if (inputTxt.value === '') {
			toast.error('请输入当前困惑')
			return
		}

		await createQ(inputTxt.value)
		const func = await rateLimit(
			30 * 60 * 1000,
			3
		)
		if (!func()) {
			toast.error('您短时间内解惑次数过多，请稍后再试')
			return
		}
		
		coinLoading.value = true
		// 未满六爻，正常摇卦
		toast.info({
			msg: '请静心片刻，默念困惑之事',
			closed: () => {
				performCast()
				coinLoading.value = false
			}
		})
	} else {
		coinLoading.value = true
		performCast()
		await sleep(1000)
		coinLoading.value = false
	}
}


// 当前已摇的爻数（1-6）
const currentStep = computed(() => lines.value.length)
// 是否已完成六爻
const isComplete = computed(() => lines.value.length === 6)

// 按钮动态文本
const buttonText = computed(() => {
	if (currentStep.value === 0) {
		return '开始演示'
	} else if (currentStep.value === 6) {
		return '重新演示'
	} else {
		return `继续演示`
	}
})

// 主爻显示：将 lines 数组转为从下往上（初爻在下）展示，并配上爻位名称
// 传统卦象显示习惯：初爻在下，上爻在上，因此列表顺序为从初爻到上爻（上爻在最后）
const displayLines = computed(() => {
	const positionNames = ['初爻', '二爻', '三爻', '四爻', '五爻', '上爻']
	return lines.value.map((line, index) => ({
		position: positionNames[index],
		symbol: line.symbol,
		img: line.img,
		number: line.number
	}))
})

// 动爻信息：根据 lines 中 isMoving 为 true 的爻，生成描述文本
const movingInfo = computed(() => {
	const movingIndices = <any>[]
	// return movingIndices
	lines.value.forEach((line, idx) => {
		let item = {
			...line,
			img: line.img
		}
		if (line.isMoving) {
			item.position = `第${6 - idx}爻动`
			item.symbol = line.symbol === '阴' ? '阳' : '阴'
			if (line.type === '老阴') item.img = YangImg
			if (line.type === '老阳') item.img = YinImg
		}
		movingIndices.push(item)
	})
	return movingIndices

	// if (movingIndices.length === 0) return []

	// const positionNames = ['初爻', '二爻', '三爻', '四爻', '五爻', '上爻']
	// return movingIndices.map(idx => {
	// 	const line = lines.value[idx]
	// 	// return `${positionNames[idx]}动 (${line.type})`
	// 	return line.symbol
	// })
	// return lines.value
})

</script>

<style lang="scss" scoped>
.container {
	// background: linear-gradient(145deg, #f7f3e9 0%, #e8e0d3 100%);
	display: flex;
	flex-direction: column;
	align-items: center;
	padding: 32rpx;
	box-sizing: border-box;
	height: auto;
	width: 100%;
	// font-family: 'Segoe UI', '思源黑体', system-ui, -apple-system, BlinkMacSystemFont, 'Helvetica Neue', sans-serif;
}

/* 头部 */
.header {
	// text-align: center;
	// margin-bottom: 60rpx;
	background-color: #fff;
	width: 100%;
	height: auto;
	padding: 32rpx;
	box-sizing: border-box;
	border-radius: 32rpx;
	box-shadow: 0 8rpx 20rpx rgba(0, 0, 0, 0.08);

	.title {
		font-size: 32rpx;
		font-weight: bold;
		color: #3a2c1f;
		letter-spacing: 4rpx;
		display: block;
		text-shadow: 2rpx 2rpx 0 rgba(0, 0, 0, 0.05);
	}

	.header-time {
		margin-top: 32rpx;
		gap: 32rpx;
		font-size: 28rpx;
	}

	.subtitle {
		font-size: 26rpx;
		color: #7f6b4f;
		margin-top: 12rpx;
		display: block;
	}
}

/* 三枚铜钱区域 */
.coins-area {
	display: flex;
	justify-content: space-between;
	gap: 32rpx;
	margin: 16rpx 0;
	flex-wrap: wrap;

	.coin {
		width: 160rpx;
		height: 160rpx;
		// border-radius: 50%;
		filter: drop-shadow(0 8rpx 10rpx rgba(0, 0, 0, 0.25));
	}
}

:deep(.cast-btn) {
	width: 400rpx;
	background: #4b3a2b;
	color: #fef1df;
	border-radius: 100rpx;
	font-size: 36rpx;
	font-weight: bold;
	padding: 24rpx 0;
	box-shadow: 0 6rpx 0 #2b2118;
	transition: all 0.1s linear;
	margin-bottom: 20rpx;
	border: none;
}

/* 按钮区域 */
.action-area {
	display: flex;
	flex-direction: column;
	align-items: center;
	margin: 30rpx 0 40rpx;
	width: 100%;

	.progress-text {
		font-size: 28rpx;
		color: #5c4a34;
		background: rgba(255, 245, 225, 0.8);
		padding: 8rpx 24rpx;
		border-radius: 60rpx;
	}

	.complete-text {
		color: #9b6e3e;
		font-weight: 500;
	}
}

/* 底部结果区域 (主爻 | 动爻) */
.result-area {
	display: flex;
	width: 100%;
	// margin-top: 32rpx;
	gap: 32rpx;
	min-height: 348rpx;
	// flex: 1;

	.main-lines,
	.moving-lines {
		flex: 1;
		background: #f3f4f6;
		backdrop-filter: blur(4px);
		border-radius: 16rpx;
		padding: 24rpx;
		box-shadow: 0 8rpx 20rpx rgba(0, 0, 0, 0.08);
		position: relative;
		// min-height: 400rpx;
	}

	.section-title {
		display: flex;
		justify-content: space-between;
		align-items: center;
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		// border-left: 8rpx solid #5d3f1e;
		// padding-left: 20rpx;
		margin-bottom: 24rpx;
	}

	.empty-tip {
		text-align: center;
		color: #4b3a2b;
		font-size: 28rpx;
		padding: 40rpx 0;
	}

	.lines-list {
		display: flex;
		flex-direction: column;
		position: absolute;
    	width: calc(100% - 48rpx);
		bottom: 24rpx;
		// gap: 16rpx;
	}

	.line-item {
		// display: flex;
		// justify-content: center;
		// font-family: monospace;
		margin: 8rpx 0;
		padding: 12rpx 20rpx;
		border-radius: 40rpx;
		font-size: 28rpx;
		font-weight: bold;
		text-align: center;
		align-items: baseline;
		// background: #fef7e8;
		background-size: contain;
		background-repeat: no-repeat;
		background-position: center;
		// margin: 4rpx 0;

		.line-position {
			width: 80rpx;
			font-size: 28rpx;
			font-weight: 600;
			color: #b87c3a;
		}

		.line-symbol {
			font-size: 32rpx;
			// font-family: monospace;
			letter-spacing: 6rpx;
			font-weight: 500;
			color: #333;
		}
	}

	.moving-list {
		display: flex;
		flex-direction: column;
		position: absolute;
    	width: calc(100% - 48rpx);
		bottom: 24rpx;

		.moving-item {
			// background: #fff0e0;
			margin: 8rpx 0;
			padding: 12rpx 20rpx;
			border-radius: 40rpx;
			font-size: 28rpx;
			// color: #ff0000;
			font-weight: bold;
			text-align: center;
			background-size: contain;
			background-repeat: no-repeat;
			background-position: center;
			// box-shadow: inset 0 1rpx 2rpx rgba(0, 0, 0, 0.02), 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
		}

		.moving-symbol {
			color: #ff0000;
		}
	}

	.guaxiang {
		position: absolute;
		width: calc(100% - 64rpx);
		bottom: 32rpx;
		// width: 100%;
		color: #4b3a2b;
		text-align: center;
	}
}

.result-content {
	width: 100%;
	margin-top: 32rpx;
	padding: 32rpx;
	gap: 32rpx;
	height: auto;
	background-color: #fff;
	box-shadow: 0 8rpx 20rpx rgba(0, 0, 0, 0.08);
	border-radius: 32rpx;
	box-sizing: border-box;

	.result-desc {
		// mar
	}
}

/* 图例说明 */
.overlay-content {
	// position: absolute;
	display: flex;
	align-items: center;
	justify-content: center;
	height: 100%;
	.tips {
		display: flex;
		flex-flow: column nowrap;
		align-items: center;
		gap: 32rpx;
		width: 300px;
		padding: 48rpx;
		border-radius: 32rpx;
		background-color: #fff;
		box-sizing: border-box;
	}

	.user-agree-tips {
		display: flex;
		flex-flow: column nowrap;
		align-items: center;
		justify-content: center;
		gap: 64rpx;
		width: 100%;
		height: 100%;
		background-color: #B8AD70;
		box-sizing: border-box;
		padding: 120rpx;
	}
}
</style>