<template>
	<view class="xingmalabpublishpage ">
		<!-- <span class="xingmalabpublishpagebg"
			:style="{ backgroundImage: `url(${$baseUrl}${getImageUrl(config.images.background)})` }"></span> -->

		<span class="xingmalabpublishpagebackbtn"
			:style="{ backgroundImage: `url(${$baseUrl}${getImageUrl(config.images.backBtn)})` }"
			@click="handleGoBack"></span>

		<!-- 主内容区域 -->
		<div class="xingmalabpublishpagenosel" v-if="currentState !== config.states.SUC">
			<!-- 文案输入框 -->
			<textarea v-model="description" class="xingmalabpublishpagenoseltextplaceholder"
				:placeholder="hasContent ? config.texts.sel.descriptionPlaceholder : config.texts.noSel.placeholder"
				:maxlength="config.upload.maxWords" @input="handleDescriptionInput"></textarea>

			<!-- 底部按钮区域 -->
			<div class="xingmalabpublishpagenoselbottomcon" v-if="!hasContent">
				<span class="xingmalabpublishpagenoselbottomconbg"
					:style="{ backgroundImage: `url(${$baseUrl}${getImageUrl(config.images.noSel.bottomConBg)})` }"></span>
				<span class="xingmalabpublishpagenoselbottomconbtn"
					:style="{ backgroundImage: `url(${$baseUrl}${getImageUrl(config.images.noSel.bottomConBtn)})` }"></span>
			</div>

			<div class="xingmalabpublishpageselbottomcon" v-if="hasContent">
				<span class="xingmalabpublishpageselbottomconpublishbtnbg"
					:style="{ backgroundImage: `url(${$baseUrl}${getImageUrl(config.images.sel.bottomConPublishBtnBg)})` }"></span>
				<span class="xingmalabpublishpageselbottomconpublishbtn"
					:style="{ backgroundImage: `url(${$baseUrl}${getImageUrl(config.images.sel.bottomConPublishBtn)})` }"
					@click="handlePublishBtnClick"></span>
			</div>

			<!-- 上传按钮 -->
			<span class="xingmalabpublishpagenoselbtn" v-if="!hasContent"
				:style="{ backgroundImage: `url(${$baseUrl}${getImageUrl(config.images.noSel.btn)})` }"
				@click="handleImageUpload"></span>

			<!-- 已上传图片显示 -->
			<image v-if="uploadedImage" :src="uploadedImage" class="xingmalabpublishpageselpic" mode="aspectFit" />
			<span class="xingmalabpublishpageselcpver" v-if="uploadedImage"
				:style="{ backgroundImage: `url(${$baseUrl}${getImageUrl(config.images.sel.cpver)})` }"></span>
			<span class="xingmalabpublishpageselretry" v-if="uploadedImage"
				:style="{ backgroundImage: `url(${$baseUrl}${getImageUrl(config.images.sel.retry)})` }"
				@click="handleImageUpload"></span>
		</div>

		<!-- 成功状态 -->
		<div class="xingmalabpublishpagesuc" v-if="currentState === config.states.SUC">
			<span class="xingmalabpublishpagesucbottomconicon"
				:style="{ backgroundImage: `url(${$baseUrl}${getImageUrl(config.images.suc.bottomConIcon)})` }"></span>
			<div class="xingmalabpublishpagesucbottomcon">
				<span class="xingmalabpublishpagesucbottomconbg"
					:style="{ backgroundImage: `url(${$baseUrl}${getImageUrl(config.images.suc.bottomConBg)})` }"></span>
				<span class="xingmalabpublishpagesucbottomconbtn"
					:style="{ backgroundImage: `url(${$baseUrl}${getImageUrl(config.images.suc.bottomConBtn)})` }"
					@click="handleSuccessBtnClick"></span>
			</div>
			<span class="xingmalabpublishpagesucdesc">
				{{ successMessage }}
			</span>
			<span class="xingmalabpublishpagesucpicbg"
				:style="{ backgroundImage: `url(${$baseUrl}${getImageUrl(config.images.suc.picBg)})` }"></span>
			<image v-if="uploadedImage" :src="uploadedImage" class="xingmalabpublishpagesucpic" mode="aspectFit" />
			<span class="xingmalabpublishpagesucnum">{{ config.texts.suc.numberPrefix }}{{ publishNumber }}</span>
		</div>

		<!-- 确认发布弹窗 - 使用 Xingmalabconfirmpop 组件 -->
		<Xingmalabconfirmpop :visible="showConfirmPopup" title="确认发布" confirm-text="确认发布" cancel-text="取消"
			@confirm="handleConfirmPublish" @cancel="handleCancelPublish" @close="showConfirmPopup = false" />

		<!-- 无次数弹窗 - 使用 Xingmalabnotimepop 组件 -->
		<Xingmalabnotimepop :visible="showNoTimePopup" title="发布次数已用完" @button-click="handleNoTimeButtonClick"
			@close="showNoTimePopup = false" />

		<!-- 用户信息授权弹窗 -->
		<uni-popup ref="userInfoPopup" type="bottom" :mask-click="false">
			<view class="user-info-popup">
				<view class="user-info-header">
					<view class="header-left">
						<image :src="$baseUrl + getImageUrl(config.images.xingmaLogo)" class="xingma-logo" />
						<text class="app-name">星妈会</text>
					</view>
				</view>

				<view class="user-info-title">获取你的昵称、头像</view>

				<view class="user-info-content">
					<view class="user-profile">
						<view class="avatar-section">
							<button class="avatar-btn" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
								<image v-if="tempUserInfo.avatarUrl" :src="tempUserInfo.avatarUrl" class="avatar-image"
									mode="aspectFit" />
								<view v-else class="avatar-placeholder">
									<image :src="$baseUrl + getImageUrl(config.images.xingmaDefaultAvatar)"
										class="avatar-icon" />
								</view>
							</button>
						</view>

						<view class="nickname-section">
							<input type="nickname" class="nickname-input" :value="tempUserInfo.nickName"
								@input="onNicknameInput" placeholder="请输入昵称" />
							<view class="nickname-label">微信昵称头像</view>
						</view>
					</view>
				</view>

				<view class="user-info-actions">
					<button class="action-btn reject-btn" @click="handleRejectAuth">拒绝</button>
					<button class="action-btn allow-btn" @click="handleAllowAuth">允许</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { xingmaLabConfig, getImageUrl, getRandomSuccessMessage } from './config.js'
import Xingmalabconfirmpop from '@/components/xingmaLab/Xingmalabconfirmpop.vue'
import Xingmalabnotimepop from '@/components/xingmaLab/Xingmalabnotimepop.vue'
import { useXingmaLabStore } from '@/stores/xingmaLab.js'
import { uploadImage } from '@/api/common.js'
import { fetchRecordPublish } from '@/api/xingmaLab.js'
import md from '../../md';

// 组件名称
defineOptions({
	name: 'XingmaLabPublishPage'
})

// 使用 store
const xingmaLabStore = useXingmaLabStore()

// 响应式数据
const currentState = ref(xingmaLabConfig.states.NOSEL) // nosel, sel, suc
const publishNumber = ref('')
const uploadedImage = ref('') // 上传的图片
const description = ref('') // 藏品文案介绍
const isUploading = ref(false) // 上传状态
const userInfoPopup = ref(null) // 用户信息授权弹窗引用
const successMessage = ref('') // 成功文案
const tempUserInfo = ref({ // 临时用户信息
	avatarUrl: '',
	nickName: ''
})

// 弹窗显示状态
const showConfirmPopup = ref(false) // 确认发布弹窗
const showNoTimePopup = ref(false) // 无次数弹窗

// 配置对象
const config = xingmaLabConfig

// 计算属性 - 判断是否有内容（图片和文案都要有）
const hasContent = computed(() => {
	return uploadedImage.value && description.value.trim()
})

// 计算属性 - 根据 store 中的信息判断
const isFirstTimePublish = computed(() => {
	// 通过头像昵称判断是否为首次发布
	// 如果没有头像昵称信息，则为首次发布
	return !hasUserInfo.value
})

const hasUserInfo = computed(() => {
	// 只检查 store 中的 xingmaInfo
	const { xingmaInfo } = xingmaLabStore
	console.log('🔍 hasUserInfo 检查:', {
		xingmaInfo,
		avatar: xingmaInfo?.avatar,
		nickname: xingmaInfo?.nickname,
		avatarType: typeof xingmaInfo?.avatar,
		nicknameType: typeof xingmaInfo?.nickname
	})

	if (xingmaInfo && xingmaInfo.avatar && xingmaInfo.nickname) {
		console.log('✅ Store 中有头像昵称信息')
		return true
	}

	return false
})

const canPublish = computed(() => {
	// 根据 store 中的 remainingPublishCount 判断是否还有发布次数
	const { xingmaInfo } = xingmaLabStore
	if (!xingmaInfo) return false
	const { remainingPublishCount, isReachedLimit } = xingmaInfo
	return remainingPublishCount > 0 && !isReachedLimit
})

const publishCountInfo = computed(() => {
	const { xingmaInfo } = xingmaLabStore
	if (!xingmaInfo) {
		return {
			current: 0,
			max: 0,
			remaining: 0
		}
	}
	const { currentMonthPublishCount, maxPublishCount, remainingPublishCount } = xingmaInfo
	return {
		current: currentMonthPublishCount,
		max: maxPublishCount,
		remaining: remainingPublishCount
	}
})


// 图片上传处理
const handleImageUpload = () => {


	if (uploadedImage.value) {
		// 重新上传
		md.sensorComponentLogTake({
			xcxComponentClick: "true",
			pageName: "星妈lab-内容发布页",
			componentName: "内容发布",
			componentContent: "重新上传"
		});
	} else {
		md.sensorComponentLogTake({
			xcxComponentClick: "true",
			pageName: "星妈lab-内容发布页",
			componentName: "内容发布",
			componentContent: "点击添加图片"
		});
	}

	if (isUploading.value) return

	uni.chooseImage({
		count: 1,
		sizeType: ['original', 'compressed'],
		sourceType: ['album', 'camera'],
		success: (res) => {
			md.sensorComponentLogTake({
				xcxComponentExposure: "true",
				pageName: "星妈lab-内容发布页",
				componentName: "内容发布",
				componentContent: "重新上传"
			});
			const tempFilePath = res.tempFilePaths[0]

			// 检查文件大小
			uni.getFileInfo({
				filePath: tempFilePath,
				success: (fileInfo) => {
					if (fileInfo.size > config.upload.maxSize) {
						uni.showToast({
							title: config.upload.maxSizeText,
							icon: 'none',
							duration: 2000
						})
						return
					}

					// 检查文件格式
					const fileExtension = tempFilePath.split('.').pop().toLowerCase()
					if (!config.upload.allowedTypes.includes(fileExtension)) {
						uni.showToast({
							title: '请选择jpg、png或jpeg格式的图片',
							icon: 'none',
							duration: 2000
						})
						return
					}

					// 保存临时文件路径，等待发布时上传
					uploadedImage.value = tempFilePath
					console.log('🖼️ 图片已选择，等待发布时上传:', tempFilePath)
				},
				fail: () => {
					uni.showToast({
						title: '获取文件信息失败',
						icon: 'none'
					})
				}
			})
		},
		fail: (err) => {
			console.log('选择图片失败:', err)
		}
	})
}

// 上传图片到服务器
const uploadImageFunc = async (tempFilePath) => {
	isUploading.value = true
	uni.showLoading({
		title: '上传中...',
		mask: true
	})

	try {
		console.log('📤 开始上传图片:', tempFilePath)
		const fs = uni.getFileSystemManager();
		const base64 = "data:image/jpeg;base64," + fs.readFileSync(tempFilePath, "base64");

		const uploadRes = await uploadImage(base64);

		if (uploadRes.success) {
			// 保存接口返回的url，用于发布
			const uploadedUrl = uploadRes.data?.url
			isUploading.value = false
			uni.hideLoading()
			console.log('✅ 图片上传成功，url:', uploadedUrl)
			return uploadedUrl
		} else {
			throw new Error(uploadRes.message || '图片上传失败')
		}
	} catch (error) {
		isUploading.value = false
		uni.hideLoading()
		console.error('❌ 图片上传失败:', error)
		uni.showToast({
			title: error.message || '图片上传失败',
			icon: "none",
		});
		throw error
	}
}

// 文案输入处理
const handleDescriptionInput = (e) => {
	const value = e.detail.value
	if (value.length > config.upload.maxWords) {
		uni.showToast({
			title: config.upload.maxWordsText,
			icon: 'none',
			duration: 2000
		})
		description.value = value.substring(0, config.upload.maxWords)
	} else {
		description.value = value
	}
}

// 发布按钮点击处理
const handlePublishBtnClick = async () => {


	md.sensorComponentLogTake({
		xcxComponentClick: "true",
		pageName: "星妈lab-内容发布页",
		componentName: "内容发布",
		componentContent: "发布"
	});

	console.log('点击发布按钮', {
		isFirstTimePublish: isFirstTimePublish.value,
		hasUserInfo: hasUserInfo.value,
		canPublish: canPublish.value,
		publishCountInfo: publishCountInfo.value
	})

	// 检查是否首次发布且需要授权
	if (isFirstTimePublish.value && !hasUserInfo.value) {
		// 重置临时用户信息
		tempUserInfo.value = {
			avatarUrl: '',
			nickName: ''
		}
		// 显示用户信息授权弹窗
		userInfoPopup.value.open()
		return
	}

	// 检查发布次数限制
	if (!canPublish.value) {
		// 显示无次数弹窗
		showNoTimePopup.value = true
		return
	}

	// 显示确认发布弹窗
	showConfirmPopup.value = true
}

// 选择头像
const onChooseAvatar = (e) => {
	console.log('选择头像:', e.detail.avatarUrl)
	tempUserInfo.value.avatarUrl = e.detail.avatarUrl
}

// 输入昵称
const onNicknameInput = (e) => {
	console.log('输入昵称:', e.detail.value)
	tempUserInfo.value.nickName = e.detail.value
}


// 拒绝授权
const handleRejectAuth = () => {
	userInfoPopup.value.close()
	uni.showToast({
		title: '需要授权才能发布',
		icon: 'none'
	})
}

// 允许授权
const handleAllowAuth = () => {
	console.log('允许授权', tempUserInfo.value)

	if (!tempUserInfo.value.avatarUrl) {
		uni.showToast({
			title: '请输入头像',
			icon: 'none'
		})
		return
	}
	if (!tempUserInfo.value.nickName) {
		uni.showToast({
			title: '请输入昵称',
			icon: 'none'
		})
		return
	}


	// 关闭授权弹窗
	userInfoPopup.value.close()

	// 检查发布次数限制并显示确认弹窗
	checkPublishLimitAndShowConfirm()
}

// 检查发布次数限制并显示确认弹窗
const checkPublishLimitAndShowConfirm = () => {
	// 直接使用计算属性判断
	if (!canPublish.value) {
		// 显示无次数弹窗
		showNoTimePopup.value = true
		return
	}

	// 显示确认发布弹窗
	showConfirmPopup.value = true
}

// 取消发布
const handleCancelPublish = () => {
	showConfirmPopup.value = false
}

// 确认发布
const handleConfirmPublish = async () => {

	showConfirmPopup.value = false

	try {
		console.log('🚀 开始发布，当前状态:', {
			isFirstTimePublish: isFirstTimePublish.value,
			hasUserInfo: hasUserInfo.value,
			imgUrl: uploadedImage.value,
			content: description.value
		})

		// 执行发布
		const publishResult = await performPublish()

		// 如果是首次授权发布成功，记录日志
		if (isFirstTimePublish.value) {
			console.log('✅ 首次授权发布成功，用户信息:', {
				avatar: tempUserInfo.value.avatarUrl,
				nickname: tempUserInfo.value.nickName
			})
		}

		// 发布成功后重新获取最新信息（如果需要的话）
		// await xingmaLabStore.loadXingmaInfo()

		// 切换到成功状态
		currentState.value = config.states.SUC
		successMessage.value = getRandomSuccessMessage()
		// 使用发布接口返回的 bizNo 作为发布编号
		publishNumber.value = publishResult.data?.bizNo

		md.sensorComponentLogTake({
			xcxComponentExposure: "true",
			pageName: "星妈lab-内容发布页",
			componentName: "内容发布",
			componentContent: "返回星妈会lab首页"
		});

	} catch (error) {
		console.error('发布失败:', error)
		uni.showToast({
			title: '发布失败，请重试',
			icon: 'none'
		})
	}
}

// 无次数弹窗按钮点击处理
const handleNoTimeButtonClick = () => {
	showNoTimePopup.value = false

	// 显示更详细的发布次数信息
	// const { current, max, remaining } = publishCountInfo.value
	// uni.showToast({
	// 	title: `本月已发布${current}次，剩余${remaining}次`,
	// 	icon: 'none',
	// 	duration: 3000
	// })
}

// 移除不再需要的 checkPublishLimit 函数
// const checkPublishLimit = async () => {
// 	// 这里应该调用后端接口检查发布次数
// 	// 暂时返回true作为示例，实际使用时应该根据后端返回结果判断
// 	return new Promise((resolve) => {
// 		setTimeout(() => {
// 			// 模拟检查结果，这里可以改为实际的接口调用
// 			const hasRemainingCount = Math.random() > 0.3 // 70% 概率有剩余次数
// 			resolve(hasRemainingCount)
// 		}, 500)
// 	})
// }

// 返回上一页
const handleGoBack = () => {
	// 检查是否有上一页
	const pages = getCurrentPages()

	console.log('pages', pages)
	if (pages.length > 1) {
		// 有上一页，直接返回上一页（收藏状态已在更新时同步）
		uni.navigateBack({
			delta: 1
		})
	} else {
		// 没有上一页，跳转到星妈实验室页面，并传递index参数
		uni.redirectTo({
			url: `/pages/xingmaLab/xingmaLab`
		})
	}
}


// 执行发布
const performPublish = async () => {
	try {
		// 调用实际的发布接口
		const params = {
			imgUrl: uploadedImage.value, // 初始时是临时文件路径，将在下面上传
			content: description.value
		}

		// 上传内容图片
		if (uploadedImage.value) {
			try {
				const uploadedUrl = await uploadImageFunc(uploadedImage.value)
				params.imageUrl = uploadedUrl
				console.log('✅ 内容图片上传成功，更新 imgUrl:', uploadedUrl)
			} catch (uploadError) {
				console.error('❌ 内容图片上传失败:', uploadError)
				throw new Error('内容图片上传失败，请重试')
			}
		}

		// 如果是首次授权，需要传递nickname和avatar
		if (isFirstTimePublish.value) {
			// 直接从临时用户信息中读取，不存储到本地
			console.log('🔍 检查临时用户信息:', tempUserInfo.value);
			if (tempUserInfo.value && tempUserInfo.value.avatarUrl && tempUserInfo.value.nickName) {
				params.nickname = tempUserInfo.value.nickName

				// 上传头像到服务器，使用返回的URL
				try {
					console.log('🖼️ 开始上传头像:', tempUserInfo.value.avatarUrl)

					// 将临时文件路径转换为base64
					const fs = uni.getFileSystemManager()
					const avatarBase64 = "data:image/jpeg;base64," + fs.readFileSync(tempUserInfo.value.avatarUrl, "base64")

					const avatarUploadRes = await uploadImage(avatarBase64)

					if (avatarUploadRes.success) {
						params.avatar = avatarUploadRes.data?.url
						console.log('✅ 头像上传成功，avatar URL:', params.avatar)
					} else {
						throw new Error(avatarUploadRes.message || '头像上传失败')
					}
				} catch (avatarError) {
					console.error('❌ 头像上传失败:', avatarError)
					throw new Error('头像上传失败，请重试')
				}
			} else {
				console.warn('⚠️ 临时用户信息不完整，无法上传头像:', tempUserInfo.value);
			}
		}

		console.log('🚀 发布参数:', params)

		// 使用 fetchRecordPublish 调用发布接口
		const result = await fetchRecordPublish(params)

		console.log('📤 发布接口返回:', result)

		if (result.success) {
			console.log('✅ 发布成功')
			return result
		} else {
			throw new Error(result.message || '发布失败')
		}

	} catch (error) {
		console.error('❌ 发布失败:', error)
		throw error
	}
}

// 生成发布编号
const generatePublishNumber = () => {
	return Math.random().toString().slice(2, 11)
}

const handleSuccessBtnClick = () => {
	console.log('点击成功状态按钮')

	md.sensorComponentLogTake({
		xcxComponentClick: "true",
		pageName: "星妈lab-内容发布页",
		componentName: "内容发布",
		componentContent: "返回星妈会lab首页"
	});

	// 这里可以添加完成后的跳转逻辑
	// uni.navigateBack()
	uni.redirectTo({
		url: '/pages/xingmaLab/xingmaLab'
	})
}

// 生命周期
onMounted(async () => {
	console.log('星妈实验室发布页面已加载')

	md.sensorComponentLogTake({
		xcxComponentExposure: "true",
		pageName: "星妈lab-内容发布页",
		componentName: "内容发布",
		componentContent: "点击添加图片"
	});
	md.sensorComponentLogTake({
		xcxComponentExposure: "true",
		pageName: "星妈lab-内容发布页",
		componentName: "内容发布",
		componentContent: "发布"
	});

	// 获取最新的星妈实验室信息
	await xingmaLabStore.loadXingmaInfo()

	// 调试信息：查看加载后的数据状态
	console.log('🚀 页面加载完成后的状态:', {
		xingmaInfo: xingmaLabStore.xingmaInfo,
		hasUserInfo: hasUserInfo.value,
		isFirstTimePublish: isFirstTimePublish.value,
		canPublish: canPublish.value,
		publishCountInfo: publishCountInfo.value
	})

	// 生成随机成功文案
	successMessage.value = getRandomSuccessMessage()


	// 重置临时用户信息
	// tempUserInfo.value = {
	// 	avatarUrl: '',
	// 	nickName: ''
	// }
	// // 显示用户信息授权弹窗
	// userInfoPopup.value.open()
})
</script>

<style lang="less" scoped>
@import './XingmaLabPublishPage.less';
</style>
