<template>
	<view class="page">
		<navbar title="创建群组" bgColor="#5baaff" color="#fff" leftClick @leftClick="$utils.navigateBack" />
		
		<view class="form-container">
			<!-- 群组头像 -->
			<view class="avatar-section">
				<view class="avatar-title">群组头像</view>
				<view class="avatar-upload" @click="chooseAvatar">
					<image v-if="groupForm.image" :src="groupForm.image" class="avatar-preview" mode="aspectFill"></image>
					<view v-else class="avatar-placeholder">
						<uv-icon name="camera" size="60rpx" color="#ccc"></uv-icon>
						<text>点击上传头像</text>
					</view>
				</view>
			</view>
			
			<!-- 群组信息表单 -->
			<view class="form-section">
				<view class="form-item">
					<view class="form-label">群组名称</view>
					<uv-input 
						v-model="groupForm.title"
						placeholder="请输入群组名称"
						:border="false"
						:clearable="true"
					></uv-input>
				</view>
				
				<view class="form-item">
					<view class="form-label">群组描述</view>
					<uv-textarea 
						v-model="groupForm.titleText"
						placeholder="请输入群组描述"
						:border="false"
						:maxlength="200"
						height="120"
					></uv-textarea>
				</view>
				
				<view class="form-item">
					<view class="form-label">所属区域</view>
					<view class="category">
						<view class="tagList">
							<view 
								:class="{act : t.id == groupForm.classId}"
								@click="clickCategory(t, i)"
								v-for="(t, i) in cityList"
								:key="i">
								{{ t.name }}
							</view>
						</view>
					</view>
				</view>
				
				<view class="form-item">
					<view class="form-label">群组公告</view>
					<uv-textarea 
						v-model="groupForm.notice"
						placeholder="请输入群组公告（可选）"
						:border="false"
						:maxlength="500"
						height="120"
					></uv-textarea>
				</view>
				
				<view class="form-item">
					<view class="form-label">预计人数</view>
					<uv-input 
						v-model="groupForm.num"
						placeholder="请输入预计人数"
						type="number"
						:border="false"
						:clearable="true"
					></uv-input>
				</view>
				
				<!-- 群二维码上传 -->
				<view class="form-item">
					<view class="form-label">群二维码（必填）</view>
					<view class="qrcode-upload">
						<uv-upload 
							:fileList="qrCodeFileList" 
							:maxCount="1" 
							width="200rpx" 
							height="200rpx"
							name="qrCodeFileList"
							@delete="deleteQrCode"
							@afterRead="afterReadQrCode"
							:previewFullImage="true"
							:accept="'image'"
							:sizeType="['original', 'compressed']"
							:sourceType="['album', 'camera']">
						</uv-upload>
						<view class="qrcode-tip">请上传群聊二维码，用户可通过此二维码加入群聊</view>
					</view>
				</view>
			</view>
			
			<!-- 创建按钮 -->
			<view class="submit-section">
				<uv-button 
					type="primary" 
					text="创建群组"
					:loading="submitting"
					@click="createGroup"
				></uv-button>
			</view>
		</view>
	</view>
</template>

<script>
	import { mapState } from 'vuex'
	
	export default {
		data() {
			return {
				submitting: false,
				groupId: '', // 编辑时的群组ID
				groupForm: {
					title: '',
					titleText: '',
					image: '',
					classId: '',
					notice: '',
					num: '',
					qrCode: ''
				},
				qrCodeFileList: [] // 二维码文件列表
			}
		},
		computed: {
			...mapState(['cityList'])
		},
		onLoad(options) {
			// 获取城市列表
			this.$store.commit('getCityList')
			
			// 如果有ID参数，说明是编辑模式
			if (options.id) {
				this.groupId = options.id
				this.getGroupDetail()
			}
		},
		methods: {
			// 获取群组详情（编辑模式）
			getGroupDetail() {
				this.$api('groupDetail', { id: this.groupId }, res => {
					if (res.code === 200 && res.result) {
						this.groupForm = {
							title: res.result.title || '',
							titleText: res.result.titleText || '',
							image: res.result.image || '',
							classId: res.result.classId || '',
							notice: res.result.notice || '',
							num: res.result.num || '',
							qrCode: res.result.qrCode || ''
						}
						
						// 如果有二维码，添加到文件列表
						if (res.result.qrCode) {
							this.qrCodeFileList = [{
								url: res.result.qrCode
							}]
						}
					} else {
						uni.showToast({
							title: res.message || '获取群组详情失败',
							icon: 'none'
						})
					}
				})
			},
			
			// 选择头像
			chooseAvatar() {
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['album', 'camera'],
					success: (res) => {
						this.uploadAvatar(res.tempFilePaths[0])
					}
				})
			},
			
			// 上传头像
			uploadAvatar(filePath) {
				if (this.$Oss && this.$Oss.ossUpload) {
					this.$Oss.ossUpload(filePath).then(url => {
						this.groupForm.image = url
					}).catch(err => {
						console.error('头像上传失败:', err)
						uni.showToast({
							title: '头像上传失败',
							icon: 'none'
						})
					})
				} else {
					// 如果没有OSS上传，直接使用本地路径
					this.groupForm.image = filePath
				}
			},
			
			// 区域选择
			clickCategory(item, index) {
				this.groupForm.classId = item.id
			},
			
			// 删除二维码
			deleteQrCode(e) {
				this.qrCodeFileList = []
				this.groupForm.qrCode = ''
			},
			
			// 二维码上传完成
			afterReadQrCode(e) {
				const file = e.file
				if (this.$Oss && this.$Oss.ossUpload) {
					this.$Oss.ossUpload(file.url).then(url => {
						this.qrCodeFileList = [{
							url: url
						}]
						this.groupForm.qrCode = url
					}).catch(err => {
						console.error('二维码上传失败:', err)
						uni.showToast({
							title: '二维码上传失败',
							icon: 'none'
						})
					})
				} else {
					// 如果没有OSS上传，直接使用本地路径
					this.qrCodeFileList = [{
						url: file.url
					}]
					this.groupForm.qrCode = file.url
				}
			},
			
			// 创建群组
			createGroup() {
				// 表单验证
				if (!this.groupForm.title.trim()) {
					uni.showToast({
						title: '请输入群组名称',
						icon: 'none'
					})
					return
				}
				
				if (!this.groupForm.titleText.trim()) {
					uni.showToast({
						title: '请输入群组描述',
						icon: 'none'
					})
					return
				}
				
				if (!this.groupForm.classId) {
					uni.showToast({
						title: '请选择所属区域',
						icon: 'none'
					})
					return
				}
				
				if (!this.groupForm.qrCode) {
					uni.showToast({
						title: '请上传群二维码',
						icon: 'none'
					})
					return
				}
				
				if (!this.groupForm.num || this.groupForm.num <= 0) {
					uni.showToast({
						title: '请输入有效的预计人数',
						icon: 'none'
					})
					return
				}
				
				this.submitting = true
				
				const apiMethod = this.groupId ? 'groupSaveOrUpdate' : 'groupSaveOrUpdate'
				const params = this.groupId ? { ...this.groupForm, id: this.groupId } : this.groupForm
				
				this.$api(apiMethod, params, res => {
					this.submitting = false
					
					if (res.code === 200) {
						uni.showToast({
							title: this.groupId ? '修改成功' : '创建成功',
							icon: 'success'
						})
						
						// 跳转到群组详情页
						setTimeout(() => {
							const groupId = this.groupId || res.result?.id || 'new'
							this.$utils.navigateTo('/pages_order/group/groupDetail?id=' + groupId)
						}, 1500)
					} else {
						uni.showToast({
							title: res.message || (this.groupId ? '修改失败' : '创建失败'),
							icon: 'none'
						})
					}
				})
			}
		}
	}
</script>

<style scoped lang="scss">
.page {
	background-color: #f5f5f5;
	min-height: 100vh;
	
	.form-container {
		padding: 20rpx;
		
		.avatar-section {
			background-color: #fff;
			padding: 30rpx;
			border-radius: 20rpx;
			margin-bottom: 20rpx;
			
			.avatar-title {
				font-size: 30rpx;
				font-weight: bold;
				color: #333;
				margin-bottom: 20rpx;
			}
			
			.avatar-upload {
				display: flex;
				justify-content: center;
				
				.avatar-preview {
					width: 120rpx;
					height: 120rpx;
					border-radius: 20rpx;
				}
				
				.avatar-placeholder {
					width: 120rpx;
					height: 120rpx;
					border: 2rpx dashed #ddd;
					border-radius: 20rpx;
					display: flex;
					flex-direction: column;
					align-items: center;
					justify-content: center;
					
					text {
						font-size: 20rpx;
						color: #999;
						margin-top: 10rpx;
					}
				}
			}
		}
		
		.form-section {
			background-color: #fff;
			padding: 30rpx;
			border-radius: 20rpx;
			margin-bottom: 20rpx;
			
			.form-item {
				margin-bottom: 30rpx;
				
				&:last-child {
					margin-bottom: 0;
				}
				
				.form-label {
					font-size: 28rpx;
					color: #333;
					margin-bottom: 15rpx;
					font-weight: bold;
				}
				
				.picker-trigger {
					display: flex;
					justify-content: space-between;
					align-items: center;
					padding: 20rpx 0;
					border-bottom: 1rpx solid #f0f0f0;
					
					text {
						font-size: 28rpx;
						color: #333;
					}
				}
				
				.radio-item {
					margin-bottom: 15rpx;
					
					&:last-child {
						margin-bottom: 0;
					}
				}
				
				// 区域选择样式
				.category {
					.tagList {
						display: flex;
						flex-wrap: wrap;
						padding: 10rpx 0;
						
						view {
							background: rgba(91, 170, 255, 0.1);
							padding: 10rpx 20rpx;
							margin: 10rpx;
							border-radius: 10rpx;
							font-size: 26rpx;
							color: #5baaff;
							
							&.act {
								color: #fff;
								background: #5baaff;
							}
						}
					}
				}
				
				// 二维码上传样式
				.qrcode-upload {
					.qrcode-tip {
						font-size: 24rpx;
						color: #999;
						margin-top: 15rpx;
						line-height: 1.4;
					}
				}
			}
		}
		
		.submit-section {
			padding: 40rpx 0;
			
			.uv-button {
				width: 100%;
				height: 80rpx;
				border-radius: 40rpx;
				font-size: 32rpx;
			}
		}
	}
}
</style>