<template>
	<view class="xingmalabpublishpage ">
		<span class="xingmalabpublishpagebg"
			:style="{ backgroundImage: `url(${$baseUrl}${getImageUrl(config.images.background)})` }"></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)})` }"
					@click="handleImageUpload"></span>
				<span class="xingmalabpublishpagenoselbottomconbtn"
					:style="{ backgroundImage: `url(${$baseUrl}${getImageUrl(config.images.noSel.bottomConBtn)})` }"
					@click="handleImageUpload"></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="aspectFill" />
			<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="aspectFill" />
			<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="aspectFill" />
								<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"
						:disabled="!tempUserInfo.avatarUrl || !tempUserInfo.nickName">允许</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'

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

// 响应式数据
const currentState = ref(xingmaLabConfig.states.NOSEL) // nosel, sel, suc
const publishNumber = ref('123456789')
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()
})

// 计算属性
const isFirstTimePublish = computed(() => {
	// 检查用户是否首次发布（这里需要根据实际业务逻辑判断）
	// 可以通过本地存储或用户信息来判断
	const hasPublished = uni.getStorageSync('hasPublished')
	return !hasPublished
})

const hasUserInfo = computed(() => {
	// 检查用户是否已有头像昵称信息
	const userInfo = uni.getStorageSync('userInfo')
	return userInfo && userInfo.avatarUrl && userInfo.nickName
})

// 图片上传处理
const handleImageUpload = () => {
	if (isUploading.value) return

	uni.chooseImage({
		count: 1,
		sizeType: ['original', 'compressed'],
		sourceType: ['album', 'camera'],
		success: (res) => {
			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
					}

					// 上传图片
					uploadImage(tempFilePath)
				},
				fail: () => {
					uni.showToast({
						title: '获取文件信息失败',
						icon: 'none'
					})
				}
			})
		},
		fail: (err) => {
			console.log('选择图片失败:', err)
		}
	})
}

// 上传图片到服务器
const uploadImage = (filePath) => {
	isUploading.value = true

	// 这里应该调用实际的上传接口
	// 暂时使用本地路径作为示例
	setTimeout(() => {
		uploadedImage.value = filePath
		isUploading.value = false
		uni.showToast({
			title: '图片上传成功',
			icon: 'success'
		})
	}, 1000)
}

// 文案输入处理
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 () => {
	console.log('点击发布按钮', isFirstTimePublish.value, hasUserInfo.value)

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

	// 检查发布次数限制
	const canPublish = await checkPublishLimit()
	if (!canPublish) {
		// 显示无次数弹窗
		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 handleUseOtherInfo = () => {
	// 这里可以添加自定义头像昵称的逻辑
	uni.showToast({
		title: '可以使用自定义头像昵称',
		icon: 'none'
	})
}

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

// 允许授权
const handleAllowAuth = () => {
	if (!tempUserInfo.value.avatarUrl || !tempUserInfo.value.nickName) {
		uni.showToast({
			title: '请选择头像和输入昵称',
			icon: 'none'
		})
		return
	}

	// 保存用户信息
	uni.setStorageSync('userInfo', {
		avatarUrl: tempUserInfo.value.avatarUrl,
		nickName: tempUserInfo.value.nickName
	})

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

	// 检查发布次数限制
	checkPublishLimitAndShowConfirm()
}

// 检查发布次数限制并显示确认弹窗
const checkPublishLimitAndShowConfirm = async () => {
	const canPublish = await checkPublishLimit()
	if (!canPublish) {
		// 显示无次数弹窗
		showNoTimePopup.value = true
		return
	}

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

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

// 确认发布
const handleConfirmPublish = async () => {
	showConfirmPopup.value = false

	try {
		// 执行发布
		await performPublish()

		// 标记用户已发布过
		uni.setStorageSync('hasPublished', true)

		// 切换到成功状态
		currentState.value = config.states.SUC
		successMessage.value = getRandomSuccessMessage()
		publishNumber.value = generatePublishNumber()

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

// 无次数弹窗按钮点击处理
const handleNoTimeButtonClick = () => {
	showNoTimePopup.value = false
	uni.showToast({
		title: '发布次数已用完，请明天再试',
		icon: 'none'
	})
}

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

// 执行发布
const performPublish = async () => {
	// 这里应该调用后端发布接口
	return new Promise((resolve) => {
		setTimeout(() => {
			console.log('发布成功')
			resolve()
		}, 1000)
	})
}

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

const handleSuccessBtnClick = () => {
	console.log('点击成功状态按钮')
	// 这里可以添加完成后的跳转逻辑
	uni.navigateBack()
}

// 生命周期
onMounted(() => {
	console.log('星妈实验室发布页面已加载')
	// 生成随机成功文案
	successMessage.value = getRandomSuccessMessage()
})
</script>

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