<template>
	<view class="xingmalabpublishpage modal_center">
		<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>

		<!-- 确认发布弹窗 -->
		<uni-popup ref="confirmPopup" type="center" :mask-click="false">
			<view class="confirm-popup">
				<view class="confirm-title">确认发布</view>
				<view class="confirm-content">
					<view class="confirm-image" v-if="uploadedImage">
						<image :src="uploadedImage" mode="aspectFill" />
					</view>
					<view class="confirm-description">
						{{ description || '暂无文案介绍' }}
					</view>
				</view>
				<view class="confirm-actions">
					<button class="confirm-btn cancel" @click="handleCancelPublish">取消</button>
					<button class="confirm-btn confirm" @click="handleConfirmPublish">确认发布</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { xingmaLabConfig, getImageUrl, getRandomSuccessMessage } from './config.js'

// 组件名称
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 confirmPopup = ref(null) // 确认弹窗引用
const successMessage = ref('') // 成功文案

// 配置对象
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) {
	await requestUserInfo()
	return
	// }

	// 显示确认弹窗
	confirmPopup.value.open()
}

// 请求用户信息授权
const requestUserInfo = () => {
	return new Promise((resolve, reject) => {
		// 使用新的授权方式
		uni.getUserInfo({
			success: (res) => {
				console.log('获取用户信息成功:', res)
				// 保存用户信息
				uni.setStorageSync('userInfo', res.userInfo)
				// 显示确认弹窗
				confirmPopup.value.open()
				resolve(res)
			},
			fail: (err) => {
				console.log('获取用户信息失败:', err)
				// 如果获取失败，尝试使用按钮授权
				uni.showModal({
					title: '授权提示',
					content: '需要获取您的头像和昵称信息才能发布内容',
					confirmText: '去授权',
					success: (modalRes) => {
						if (modalRes.confirm) {
							// 引导用户到设置页面授权
							uni.openSetting({
								success: (settingRes) => {
									if (settingRes.authSetting['scope.userInfo']) {
										// 用户已授权，重新获取用户信息
										uni.getUserInfo({
											success: (userRes) => {
												uni.setStorageSync('userInfo', userRes.userInfo)
												confirmPopup.value.open()
												resolve(userRes)
											},
											fail: () => {
												uni.showToast({
													title: '授权失败，请重试',
													icon: 'none'
												})
												reject()
											}
										})
									} else {
										uni.showToast({
											title: '需要授权才能发布',
											icon: 'none'
										})
										reject()
									}
								}
							})
						} else {
							uni.showToast({
								title: '需要授权才能发布',
								icon: 'none'
							})
							reject()
						}
					}
				})
			}
		})
	})
}

// 取消发布
const handleCancelPublish = () => {
	confirmPopup.value.close()
}

// 确认发布
const handleConfirmPublish = async () => {
	confirmPopup.value.close()

	try {
		// 检查发布次数限制
		const canPublish = await checkPublishLimit()
		if (!canPublish) {
			uni.showToast({
				title: '发布次数已达上限',
				icon: 'none'
			})
			return
		}

		// 执行发布
		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 checkPublishLimit = async () => {
	// 这里应该调用后端接口检查发布次数
	// 暂时返回true作为示例
	return new Promise((resolve) => {
		setTimeout(() => {
			resolve(true)
		}, 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>
