<template>
	<view class="publishPost">
		<navbar 
		leftClick
		@leftClick="$utils.navigateBack"
		title="发布动态"/>
		
		
		
		<!-- <view class="title-input box">
			<input type="text" placeholder="取个吸引人的标题吧" v-model="form.title"/>
		</view> -->
		
		
		<view class="content-input">
			<uv-textarea 
			v-model="form.title" 
			:maxlength="200" 
			autoHeight
			count
			style="min-height: 400rpx;"
			placeholder="说点什么吧"></uv-textarea>
		</view>
		
		
		<view class="images box">
			<uv-upload 
			:fileList="fileList" 
			:maxCount="imageMax" 
			multiple 
			width="150rpx" 
			height="150rpx"
			name="fileList"
			@delete="deleteImage"
			@afterRead="afterRead"
			:previewFullImage="true"
			accept="media"
			:sizeType="['original', 'compressed']"
			:sourceType="['album', 'camera']"></uv-upload>
		</view>
		
		<view class="category">
			<view class="title">
				选择分类
			</view>
			<view class="tagList">
				<view 
				:class="{act : t.id == form.classId}"
				@click="clickCategory(t, i)"
				v-for="(t, i) in category"
				:key="i">
					{{ t.title }}
				</view>
			</view>
		</view>
		
		<!-- <view class="category">
			<view class="title">
				选择地区
			</view>
			<view class="tagList">
				<view 
				:class="{act : t.name == form.address}"
				@click="clickAddress(t, i)"
				v-for="(t, i) in cityList"
				:key="i">
					{{ t.name }}
				</view>
			</view>
		</view> -->
		
		<view class="category"
		v-if="categoryRole.includes('code')">
			<view class="title">
				上传微信二维码（必填）
			</view>
			
			<view class="images box">
				<uv-upload 
				:fileList="codeFileList" 
				:maxCount="1" 
				multiple 
				width="150rpx" 
				height="150rpx"
				name="codeFileList"
				@delete="deleteImage"
				@afterRead="afterRead"
				:previewFullImage="true"></uv-upload>
			</view>
		</view>
		
		<view class="title-input box"
		v-if="categoryRole.includes('phone')">
			<input type="text" placeholder="手机号码（选填）" v-model="form.phone"/>
		</view>
		
		<view class="title-input box"
		v-if="categoryRole.includes('address')"
		@click="selectAddr">
			<input type="text"
			placeholder="选择位置（选填）"
			disabled
			v-model="form.address"/>
			<uv-icon
			size="40rpx"
			name="map"></uv-icon>
		</view>
		
		<view class="title-input box"
		@click="$refs.pickerHospital.open()"
		v-if="categoryRole.includes('shop')">
			<input type="text" 
			v-if="!form.shop"
			placeholder="关联店铺（选填）"/>
			
			<view class="shop-box"
			v-else>
				<view class="title">
					{{ form.shop.title }}
				</view>
				<view class="desc">
					{{ form.shop.address }}
				</view>
			</view>
		</view>
		
		
		<view class="configBtn"
		@click="$refs.configPopup.open()">
			《发布须知》
		</view>
		
		<view class="uni-color-btn"
		@click="submit">
			发布
		</view>
		

		<configPopup
		ref="configPopup"
		:text="headInfo.save_no && headInfo.save_no.keyDetails"
		/>
		
		<pickerHospital
		mixinsListApi="getStorePage"
		descKeyName="address"
		keyName="title"
		searchKey="title"
		ref="pickerHospital"
		@select="selectShop"
		/>
		
	</view>
</template>

<script>
	import { mapState } from 'vuex'
	import Position from '@/utils/position.js'
	import pickerHospital from '@/components/base/pickerHospital.vue'
	import { subscribeBeforePublish } from '@/utils/subscribeMessage.js'
	export default {
		components : {
			pickerHospital,
		},
		data() {
			return {
				form : {
					title : '',
					classId : 0,
					address : '',
					phone : '',
					shop : '',
				},
				id : 0,
				fileList : [],
				codeFileList : [],
				imageMax : 9,
			};
		},
		computed : {
			...mapState(['cityList', 'category', 'headInfo']),
			categoryRole(){
				if(!this.form.classId){
					return []
				}
				for(let i = 0;i < this.category.length;i++){
					let c = this.category[i]
					if(c.id == this.form.classId){
						return c.linkType ? c.linkType.split(',') : []
						// return 'code,phone,address,shop'.split(',')
					}
				}
				return []
			},
		},
		onLoad(args) {
			this.id = args.id
			this.form.classId = this.category[0].id
			// this.form.address = this.cityList[0].name
			this.imageMax = args.imageMax || 9
			this.getDateil()
		},
		onShow() {
			this.$store.commit('getCategory')
		},
		methods : {
			clickCategory(item, index){
				this.form.classId = item.id
			},
			clickAddress(item, index){
				this.form.address = item.name
			},
			getDateil(){
				if(!this.id){
					return
				}
				
				let self = this
				
				this.$api('getPostDetail', {
					id : this.id
				}, res => {
					if (res.code == 200) {
						self.form.id = res.result.id
						self.form.title = res.result.title
						self.form.address = res.result.address || self.form.address
						self.form.classId = res.result.classId || self.form.classId
						self.form.latitude = res.result.latitude || self.form.latitude
						self.form.longitude = res.result.longitude || self.form.longitude
						self.form.shop = res.result.shop || self.form.shop
						self.form.shopId = res.result.shopId || self.form.shopId
						
						if(res.result.wxImage){
							self.codeFileList = [
								{
									url : res.result.wxImage
								}
							]
						}
						
						if(res.result.image){
							res.result.image.split(',')
							.forEach(url => {
								if(url.trim()){
									// 根据文件扩展名判断类型
									const isVideo = this.isVideoFile(url.trim())
									self.fileList.push({
										url: url.trim(),
										type: isVideo ? 'video' : 'image'
									})
								}
							})
						}
					}
				})
			},
			deleteImage(e){
				this[e.name].splice(e.index, 1)
			},
			afterRead(e){
				let self = this
				e.file.forEach(file => {
					// 检测文件类型
					const isVideo = this.isVideoFile(file.url || file.path)
					
					self.$Oss.ossUpload(file.url).then(url => {
						self[e.name].push({
							url,
							type: isVideo ? 'video' : 'image'
						})
					})
				})
			},
			
			// 检测是否为视频文件
			isVideoFile(filePath) {
				const videoExtensions = ['.mp4', '.avi', '.mov', '.wmv', '.flv', '.webm', '.m4v', '.3gp']
				const fileName = filePath.toLowerCase()
				return videoExtensions.some(ext => fileName.includes(ext))
			},
			
			// 提交
			async submit(){
				
				// if(this.fileList.length == 0){
				// 	return uni.showToast({
				// 		title: '请上传图片',
				// 		icon : 'none'
				// 	})
				// }
				
				if (this.$utils.verificationAll(this.form, {
						title: '说点什么吧',
					})) {
					return
				}
				
				if(this.categoryRole.includes('code') && this.codeFileList.length == 0){
					return uni.showToast({
						title: '请上传微信二维码',
						icon : 'none'
					})
				}
				
				// 在发布前订阅消息通知
				await subscribeBeforePublish()
				
				delete this.form.shop
				
				// 将所有文件（图片和视频）合并到 image 字段
				this.form.image = this.fileList.map((item) => item.url).join(",")
				this.form.wxImage = this.codeFileList.map((item) => item.url).join(",")
				
				this.$api('publishPost', this.form, res => {
					if(res.code == 200){
						uni.showToast({
							title: '发布成功!',
							icon: 'none'
						})
						
						setTimeout(uni.navigateBack, 1000, -1)
					}
				})
			},
			//地图上选择地址
			selectAddr() {
				Position.selectAddress(success => {
					this.setAddress(success)
				})
			},
			
			//提取用户选择的地址信息复制给表单数据
			setAddress(res) {
				
				//经纬度信息
				this.form.latitude = res.latitude
				this.form.longitude = res.longitude
			
				if (res.name) { //用户直接选择城市的逻辑
				// if (!res.address && res.name) { //用户直接选择城市的逻辑
					return this.form.address = res.name
				}
				// if (res.address || res.name) {
				// 	return this.form.address = res.address + res.name
				// }
				this.form.address = '' //用户啥都没选就点击勾选
				this.form.latitude = ''
				this.form.longitude = ''
			},
			// 选择关联的店铺
			selectShop(shop){
				this.form.shop = shop
				this.form.shopId = shop.id
				this.$refs.pickerHospital.close()
			},
		}
	}
</script>

<style lang="scss" scoped>
.publishPost{
	background-color: #fff;
	min-height: 100vh;
	font-size: 28rpx;
	padding-bottom: 150rpx;
	/deep/ .uv-textarea{
		background-color: transparent;
		border: none;
	}
	/deep/ .uv-textarea__count{
		background-color: transparent !important;
	}
	.box{
		padding: 0 20rpx;
	}
	.images{
		display: flex;
		flex-wrap: wrap;
		padding: 20rpx;
	}
	.title-input{
		margin: 10rpx;
		border-bottom: 1px solid #00000015;
		padding-bottom: 25rpx;
		margin-bottom: 15rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		input{
			width: 100%;
		}
		.shop-box{
			
			.title{
				font-size: 28rpx;
			}
			.desc{
				margin-top: 10rpx;
				color: #888;
				font-size: 24rpx;
			}
		}
	}
	.content-input{
		min-height: 400rpx;
		/deep/ .uv-textarea{
			min-height: 400rpx;
		}
	}
	.upTop{
		.title{
			padding-top: 20rpx;
			padding-left: 20rpx;
			border-top: 1px solid #00000015;
			display: flex;
			align-items: center;
		}
		.list{
			padding-top: 30rpx;
			width: 100%;
			.item{
				display: flex;
				padding: 20rpx;
				padding-left: 80rpx;
				justify-content: space-between;
				width: 600rpx;
				border-bottom: 1px solid #00000015;
				align-items: center;
			}
		}
	}
	
	.configBtn{
		padding: 20rpx;
		color: #777;
		padding-top: 40rpx;
		font-size: 28rpx;
	}
	
	.confirmationPopup{
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		width: 100%;
		height: 300rpx;
		image{
			margin-top: 40rpx;
		}
		.info{
			margin-top: 40rpx;
			font-size: 26rpx;
		}
	}
}
.category{
	padding: 20rpx;
	.title{
		// font-weight: 900;
		// font-size: 30rpx;
	}
	.tagList{
		display: flex;
		flex-wrap: wrap;
		padding: 10rpx 0;
		view{
			background: rgba($uni-color, 0.1);
			padding: 10rpx 20rpx;
			margin: 10rpx;
			border-radius: 10rpx;
			font-size: 26rpx;
		}
		.act{
			color: #fff;
			background: $uni-color;
		}
	}
}
</style>
