<template>
	<view class="publish-page">
		<!-- 自定义导航栏 -->
		<view class="custom-navbar">
			<view class="navbar-left" @click="goBack">
				<text class="back-icon">← 返回</text>
			</view>
			<view class="navbar-title">发布动态</view>
			<view class="navbar-right"></view>
		</view>
		
		<!-- 内容区域 -->
		<scroll-view class="content-scroll" scroll-y>
			<view class="form-container">
				<!-- 内容输入 -->
				<view class="content-section">
					
					<textarea 
						v-model="content" 
						class="content-input" 
						placeholder="分享你的心动瞬间" 
						maxlength="1000"
						:show-count="true"
						auto-height
					/>
				</view>
				
				<!-- 图片上传区域 -->
				<view class="media-section">
					<view class="section-title">📷 图片</view>
                    <view class="media-grid">
                        <view v-for="(m,idx) in mediaList" :key="idx" class="media-item">
                            <image :src="m" mode="aspectFill" class="media-image"/>
                            <text class="remove-btn" @click="removeMedia(idx)">×</text>
                        </view>
                        <view v-if="mediaList.length < 9" class="add-media" @click="chooseImages">
							<text class="add-icon">+</text>
							<text class="add-text">添加图片</text>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>
		
		<!-- 底部发布栏 -->
		<view class="publish-bottom-bar">
			<button 
				class="publish-btn" 
				:disabled="uploading || !content.trim()"
				:class="{ disabled: uploading || !content.trim() }"
				@click="submit">
				<text class="btn-icon">💕</text>
				<text class="btn-text">发布</text>
			</button>
		</view>
	</view>
</template>

<script>
import api from '@/utils/api.js'

export default {
	data() {
        return {
            content: '',
            mediaList: [],
            uploading: false
        }
	},
	methods: {
		// 返回上一页
		goBack() {
			uni.navigateBack()
		},
		
        
		isImage(url) { 
			if (!url || typeof url !== 'string') return false
			console.log('检查文件类型:', url)
			
			// 1. 检查文件扩展名
			const hasImageExtension = /(\.png|\.jpg|\.jpeg|\.gif|\.webp|\.bmp)$/i.test(url)
			
			// 2. 检查是否是微信小程序的临时图片路径
			const isTempImagePath = url.includes('tmp_') || 
			                       url.includes('wxfile://tmp_') ||
			                       url.includes('tempFilePath') ||
			                       url.startsWith('http://tmp/') ||
			                       /\/tmp_[a-zA-Z0-9_]+\.(png|jpg|jpeg|gif|webp|bmp)$/i.test(url)
			
			// 3. 检查是否是MinIO的图片URL
			const isMinioImageUrl = url.includes('dynamic-comments/dynamics/') && 
			                       /(\.png|\.jpg|\.jpeg|\.gif|\.webp|\.bmp)(\?|$)/i.test(url)
			
			const result = hasImageExtension || isTempImagePath || isMinioImageUrl
			console.log('文件类型检查结果:', {
				url: url,
				hasImageExtension,
				isTempImagePath,
				isMinioImageUrl,
				result
			})
			
			return result
		},
        removeMedia(i) { this.mediaList.splice(i,1) },
        async chooseImages() {
            const maxCount = Math.max(0, 9 - this.mediaList.length)
            if (maxCount <= 0) {
                uni.showToast({ title: '最多选择9张图片', icon: 'none' })
                return
            }
            uni.chooseImage({
                count: maxCount,
                sizeType: ['compressed'],
                success: async (res) => {
                    const filePaths = res.tempFilePaths || []
                    if (filePaths.length === 0) return
                    // 立即预览
                    this.mediaList.push(...filePaths)
                    this.uploading = true
                    uni.showLoading({ title: `正在上传 ${filePaths.length} 张图片...` })
                    try {
                        for (const filePath of filePaths) {
                            try {
                                const url = await api.dynamic.uploadSingle(filePath)
                                const idx = this.mediaList.indexOf(filePath)
                                if (idx !== -1) this.mediaList.splice(idx, 1, url)
                            } catch (e) {
                                const idx = this.mediaList.indexOf(filePath)
                                if (idx !== -1) this.mediaList.splice(idx, 1)
                            }
                        }
                    } finally {
                        this.uploading = false
                        uni.hideLoading()
                    }
                },
                fail: () => {
                    uni.showToast({ title: '选择图片失败', icon: 'none' })
                }
            })
        },
		async submit() {
			if (!this.content.trim()) {
				uni.showToast({ title: '请分享你的心动瞬间吧～', icon: 'none' })
				return
			}
			if (this.content.length > 1000) {
				uni.showToast({ title: '内容过长，请精简到1000字以内', icon: 'none' })
				return
			}
			
			if (this.uploading) {
				uni.showToast({ title: '图片还在上传中，请稍等', icon: 'none' })
				return
			}
			
			// 简单敏感词检测
			const badWords = ['傻', '坏词', '违规']
			if (badWords.some(w => this.content.includes(w))) {
				uni.showToast({ title: '内容包含敏感词，请修改后发布', icon: 'none' })
				return
			}
			
			uni.showLoading({ title: '正在发布...' })
			
			try {
				const payload = {
					userId: 1,
					content: this.content,
					mediaList: this.mediaList,
					mediaType: this.mediaList.length > 0 ? 2 : 1, // 自动检测：有图片为2，纯文本为1
					visibility: 1 // 默认公开
				}
				const dynamicId = await api.dynamic.publish(payload)
				uni.hideLoading()
				uni.showToast({ title: '发布成功！开始你的缘分旅程～', icon: 'success' })
				
				// 直接插入到广场页数据头部，避免全量刷新
				uni.$emit('dynamic-insert', {
					dynamicId,
					userId: 1,
					content: this.content,
					mediaUrls: this.mediaList,
					mediaType: this.mediaList.length > 0 ? 2 : 1,
					visibility: 1,
					likeCount: 0,
					commentCount: 0,
					favoriteCount: 0,
					shareCount: 0,
					viewCount: 0,
					isLiked: false,
					isFavorited: false,
					createdAt: new Date().toISOString(),
					user: { userId: 1, nickname: '我', avatarUrl: '' }
				})
				
				setTimeout(() => {
					// 发布成功后回到动态列表页面
					uni.switchTab({
						url: '/pages/plaza/index',
						fail: () => {
							uni.redirectTo({ url: '/pages/plaza/index' })
						}
					})
				}, 1500)
			} catch (e) {
				uni.hideLoading()
				uni.showToast({ title: '发布失败，请重试', icon: 'none' })
				console.error('发布失败:', e)
			}
		}
	}
}
</script>

<style scoped lang="scss">
.publish-page {
    min-height: 100vh;
    background: #FFF0F5; // 与广场一致淡粉背景
	
	// 自定义导航栏
    .custom-navbar {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
        height: 96rpx; // 提高高度以便垂直居中
        background: transparent; // 透明，标题用粉色
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 32rpx;
        padding-top: constant(safe-area-inset-top);
        padding-top: env(safe-area-inset-top);
		z-index: 1000;
        box-shadow: none;
		
        .navbar-left,
        .navbar-right {
			width: 120rpx;
            height: 96rpx; // 与导航高度一致
			display: flex;
			align-items: center;
		}
		
        .back-icon {
            color: #E91E63;
			font-size: 36rpx;
			font-weight: bold;
		}
		
        .navbar-title {
			flex: 1;
			text-align: center;
            color: #D81B60;
			font-size: 32rpx;
			font-weight: 600;
		}
		
        .publish-text {
            color: #FFFFFF;
			font-size: 28rpx;
			font-weight: 500;
            background: linear-gradient(135deg, #E91E63, #FF6B9D);
			padding: 12rpx 24rpx;
			border-radius: 24rpx;
            border: none;
		}
	}
	
	// 内容滚动区域
.content-scroll {
    padding-top: calc(96rpx + constant(safe-area-inset-top));
    padding-top: calc(96rpx + env(safe-area-inset-top));
    height: calc(100vh - 100rpx); // 预留底部发布栏空间
    padding-bottom: 0;
}
	
	.form-container {
		padding: 32rpx;
	}

// 底部发布栏
.publish-bottom-bar {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background: #FFFFFF;
    padding: 20rpx 24rpx;
    box-shadow: 0 -2rpx 10rpx rgba(0,0,0,0.06);
    padding-bottom: constant(safe-area-inset-bottom);
    padding-bottom: env(safe-area-inset-bottom);
    z-index: 1001;

    .publish-btn {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 10rpx;
        padding: 18rpx 28rpx;
        border-radius: 999rpx;
        background: linear-gradient(135deg, #E91E63, #FF6B9D);
        color: #FFFFFF;
        border: none;

        &.disabled {
            background: #E0E0E0;
            color: #AAAAAA;
        }

        .btn-icon { font-size: 30rpx; }
        .btn-text { font-size: 28rpx; font-weight: 600; }
    }
}
	
	// 内容输入区域
	.content-section {
		background: #FFFFFF;
		border-radius: 20rpx;
		padding: 32rpx;
		margin-bottom: 24rpx;
		box-shadow: 0 4rpx 24rpx rgba(0,0,0,0.06);
		
		.content-input {
			width: 100%;
			min-height: 240rpx;
			font-size: 28rpx;
			line-height: 1.6;
			color: #333333;
			background: transparent;
			border: none;
			outline: none;
		}
	}
	
	// 媒体上传区域
    .media-section {
		background: #FFFFFF;
		border-radius: 20rpx;
        padding: 24rpx;
		margin-bottom: 24rpx;
		box-shadow: 0 4rpx 24rpx rgba(0,0,0,0.06);
		
		.section-title {
			font-size: 30rpx;
			font-weight: 600;
			color: #333333;
			margin-bottom: 24rpx;
		}
		
		.media-grid {
			display: grid;
			grid-template-columns: repeat(3, 1fr);
			gap: 20rpx;
		}
		
		.media-item {
			position: relative;
			width: 100%;
			height: 200rpx;
			border-radius: 16rpx;
			overflow: hidden;
			
			.media-image {
				width: 100%;
				height: 100%;
			}
			
			.video-placeholder {
				width: 100%;
				height: 100%;
				background: #F5F5F5;
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				
				.video-icon {
					font-size: 32rpx;
					margin-bottom: 8rpx;
				}
				
				.video-text {
					font-size: 24rpx;
					color: #666666;
				}
			}
			
			.remove-btn {
				position: absolute;
				top: 8rpx;
				right: 8rpx;
				width: 36rpx;
				height: 36rpx;
				background: rgba(0,0,0,0.7);
				color: #FFFFFF;
				border-radius: 50%;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 24rpx;
				font-weight: bold;
			}
		}
		
		.add-media {
			width: 100%;
			height: 200rpx;
			background: #F8F9FA;
			border: 2rpx dashed #D0D7DE;
			border-radius: 16rpx;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			transition: all 0.3s ease;
			
			&:active {
				background: #F0F0F0;
				border-color: #E91E63;
			}
			
			.add-icon {
				font-size: 48rpx;
				color: #8C8C8C;
				margin-bottom: 8rpx;
			}
			
			.add-text {
				font-size: 24rpx;
				color: #8C8C8C;
			}
		}
	}
	
	// 设置区域
	.settings-section {
		background: #FFFFFF;
		border-radius: 20rpx;
		padding: 32rpx;
		margin-bottom: 24rpx;
		box-shadow: 0 4rpx 24rpx rgba(0,0,0,0.06);
		
		.section-title {
			font-size: 30rpx;
			font-weight: 600;
			color: #333333;
			margin-bottom: 24rpx;
		}
		
		.setting-item {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 20rpx 0;
			border-bottom: 1rpx solid #F0F0F0;
			
			&:last-child {
				border-bottom: none;
			}
			
			.setting-label {
				font-size: 28rpx;
				color: #333333;
			}
			
			.setting-value {
				display: flex;
				align-items: center;
				font-size: 26rpx;
				color: #666666;
				
				.arrow {
					margin-left: 12rpx;
					color: #CCCCCC;
				}
			}
		}
	}
	
	// 上传方式弹窗
	.upload-modal {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		z-index: 9999;
		
		.modal-mask {
			position: absolute;
			top: 0;
			left: 0;
			right: 0;
			bottom: 0;
			background: rgba(0,0,0,0.5);
		}
		
		.modal-content {
			position: absolute;
			bottom: 0;
			left: 0;
			right: 0;
			background: #FFFFFF;
			border-radius: 32rpx 32rpx 0 0;
			padding: 40rpx;
			padding-bottom: calc(40rpx + constant(safe-area-inset-bottom));
			padding-bottom: calc(40rpx + env(safe-area-inset-bottom));
			
			.modal-title {
				text-align: center;
				font-size: 32rpx;
				font-weight: 600;
				color: #333333;
				margin-bottom: 32rpx;
			}
			
			.upload-options {
				display: flex;
				gap: 24rpx;
			}
			
			.upload-option {
				flex: 1;
				background: #F8F9FA;
				border-radius: 20rpx;
				padding: 40rpx 20rpx;
				display: flex;
				flex-direction: column;
				align-items: center;
				transition: all 0.3s ease;
				
				&:active {
					background: #E91E63;
					transform: scale(0.95);
					
					.option-icon,
					.option-text {
						color: #FFFFFF;
					}
				}
				
				.option-icon {
					font-size: 48rpx;
					margin-bottom: 16rpx;
				}
				
				.option-text {
					font-size: 28rpx;
					color: #333333;
					font-weight: 500;
				}
			}
		}
	}
	
	// 温馨提示区域
	.tips-section {
		background: linear-gradient(145deg, #FFF5F7 0%, #FFE8EC 100%);
		border-radius: 24rpx;
		padding: 32rpx;
		margin-bottom: 24rpx;
		box-shadow: 0 8rpx 24rpx rgba(233, 30, 99, 0.08);
		border: 2rpx solid rgba(255, 182, 193, 0.15);
		position: relative;
		overflow: hidden;
		
		&::before {
			content: '';
			position: absolute;
			top: 0;
			left: 0;
			right: 0;
			height: 4rpx;
			background: linear-gradient(90deg, #FFB3BA, #FF8A95, #FFC0CB);
		}
		
		&::after {
			content: '💕';
			position: absolute;
			top: 20rpx;
			right: 20rpx;
			font-size: 40rpx;
			opacity: 0.1;
			animation: pulse-love 3s ease-in-out infinite;
		}
		
		.section-header {
			text-align: center;
			margin-bottom: 24rpx;
			
			.header-decoration {
				margin-bottom: 12rpx;
				
				.feather-tiny {
					font-size: 24rpx;
					opacity: 0.6;
					margin: 0 8rpx;
					animation: float 3s ease-in-out infinite;
					
					&:first-child {
						animation-delay: 0s;
					}
					
					&:last-child {
						animation-delay: 1.5s;
					}
				}
				
				.section-icon {
					font-size: 32rpx;
					margin: 0 12rpx;
				}
			}
			
			.section-title {
				font-size: 32rpx;
				font-weight: 600;
				color: #2D1B69;
				margin-bottom: 8rpx;
			}
			
			.section-desc {
				font-size: 24rpx;
				color: #8B5A96;
				opacity: 0.8;
			}
		}
		
		.tips-content {
			.tip-item {
				display: flex;
				align-items: center;
				margin-bottom: 16rpx;
				padding: 16rpx 20rpx;
				background: rgba(255, 255, 255, 0.6);
				border-radius: 16rpx;
				border: 1rpx solid rgba(255, 182, 193, 0.2);
				transition: all 0.3s ease;
				
				&:last-child {
					margin-bottom: 0;
				}
				
				.tip-icon {
					font-size: 28rpx;
					margin-right: 16rpx;
					animation: float 2s ease-in-out infinite;
				}
				
				.tip-text {
					flex: 1;
					font-size: 26rpx;
					color: #2D1B69;
					line-height: 1.4;
					font-weight: 500;
				}
			}
		}
	}
}
</style>


