<template>
	<view>
		<view class="con">
			<editor id="editor" @input="descInput" class="ql-container" :placeholder="placeholderText"></editor>
			<!-- <view class="upload ddflex" @tap="uploadVodChangeHandle"><image src="../static/images/upload.png"></image>上传视频</view> -->
			<view class="imgbox ddflex">
				<view class="imgs" v-for="(item, index) in zhiPicUrls" :key="index">
					<image :src="item" class="img" @tap="previewImg(zhiPicUrls, index)" mode="aspectFill"></image>
					<image src="../static/images/close.png" class="del" @tap="cleanimages(index)"></image>
				</view>
				<view class="video" :hidden="!videoInfo">
					<video :src="videoInfo" :show-center-play-btn="false" :controls="isCotrols" :autoplay="isCotrols" :id="'myVideo'"></video>
					<view class="video-play ddflex" @click="videoPlay()" v-if="isShowPlayBtn"><image src="../../static/images/play.png"></image></view>
					<image src="../static/images/close.png" class="del" @click="clearVideo"></image>
				</view>
				<block v-if="zhiPicUrls.length < picCount && !videoInfo">
					<view class="upload ddflex" @click="uploadImgs" v-if="config.open_community_video != 1 || zhiPicUrls.length > 0"><image src="../static/images/upload.png"></image>上传图片</view>
					<view class="upload ddflex" @click="showPop" v-if="config.open_community_video == 1&&zhiPicUrls.length == 0"><image src="../static/images/upload.png"></image>上传图片或视频</view>
				</block>
			</view>
		</view>
		<view class="other">
			<view class="li ddflex" @click="isDaka?'':jumpUrl('/office/topic/topic')">
				<image src="../static/images/tj_htico.png" class="o-ico"></image>
				<view class="fflex">话题</view>
				<view class="sel-ht" v-if="htObj"><text>#{{htObj.title}}</text><!-- <text>#张丹丹推荐绘本</text> --></view>
				<image src="../../static/pages/images/more.png" class="rico"></image>
			</view>
			<!-- <view class="li ddflex" @click="jumpUrl(productList.length>0 ? '/office/product/product':'/office/add/add')">
				<image src="../static/images/tj_spico.png" class="o-ico"></image>
				<view class="fflex">商品</view>
				<view class="sel-ht" v-if="productList.length>0">{{productList.length}}件商品</view>
				<image src="../../static/pages/images/more.png" class="rico"></image>
			</view> -->
			<view class="li ddflex" @click="jumpUrl('/office/addActivity/addActivity')">
				<image src="../static/images/tj_spico.png" class="o-ico"></image>
				<view class="fflex">链接</view>
				<view class="sel-ht" v-if="productList.length>0&&newsType==11">{{productList.length}}个活动</view>
				<image src="../../static/pages/images/more.png" class="rico"></image>
			</view>
			<view class="li ddflex" @click="jumpUrl('/office/vote/vote' + (pollObj ? '?pollId=' + pollObj.id : ''))">
				<image src="../static/images/tj_tpico.png" class="o-ico"></image>
				<view class="fflex">投票</view>
				<view class="sel-ht" v-if="pollObj">发起投票</view>
				<image src="../../static/pages/images/more.png" class="rico"></image>
			</view>
			<view class="li ddflex" @click="chooseLocation" v-if="showArea"><!-- @click="jumpUrl('/office/location/index')" -->
				<image src="../static/images/tj_wzico.png" class="o-ico"></image>
				<view class="fflex">位置</view>
				<view class="sel-ht" v-if="location">{{location.poiName}}</view>
				<image src="../../static/pages/images/more.png" class="rico"></image>
			</view>
			<view class="li ddflex" v-else><!-- @click="jumpUrl('/office/location/index')" -->
				<image src="../static/images/tj_wzico.png" class="o-ico"></image>
				<view class="fflex">位置</view>
				<switch style="scale: 0.7;transform-origin: right;" color="var(--main)" @click="openArea()"></switch>
			</view>
		</view>
		<view class="loca" v-if="showArea">
			<scroll-view scroll-x="true" class="locas">
				<view class="lis" @click="closeArea()" >不开启定位</view>
				<view :class="'lis'+(poiIndex == index ? ' active':'')" @click="checkLocation(item,index)" v-for="(item,index) in poiList" :key="index">{{item.title}}</view>
			</scroll-view>
		</view>
		<view style="height: 160rpx"></view>
		<view class="btn-after" @click="submit()">发布帖子</view>
		
		<view class="ceng" @click="hidePop" v-if="isShowPop"></view>
		<view class="popup savepadding" :style="'bottom:'+popBottom">
			<view class="pop-list">
				<view class="li" @tap="uploadImgs">图片</view>
				<view class="li" @tap="uploadVodChangeHandle">视频</view>
			</view>
			<view class="pop-cancel" @click="hidePop">取消</view>
		</view>
	</view>
</template>

<script>
const app = getApp();
const req = require('../../utils/request.js');
const QQMapWX = require("../../utils/qqmap.js");
const requsetmessage = require('../../utils/requestmessage.js');
import VODUpload from '@/utils/aliyun-upload-sdk-1.0.1.min.js'
const api = require('../../utils/api.js');
export default {
	data() {
		return {
			placeholderText: '请输入内容',
			picCount: 9,
			title: 'Hello',
			desc: '', //描述
			zhiPicUrls: [],
			newsType: 1, //1 聊一聊 ，2 提问
			htObj: '', //选中的话题对象
			pollObj: '', //投票对象
			productList: [] ,//选中的商品list
			treeObj: '',//社区类型
			topicId: '',//圈子ID
			isVideo: false,//是否上传视频
			uploader: '',
			isStart: false,
			videoInfo: '',
			fileName: '',//视频名称
			popBottom: '-100%',
			isShowPop: false,
			isShowPlayBtn: true,
			isCotrols: false,
			config: {},
			location: {},
			poiIndex: -1,
			poiList: [],
			userGroupId: '',//团队id
			
			isShowPopCenter:false,
			
			isDaka:false,
			isOpenWeRunData:false,
			
			showArea:true,//是否选择定位
		};
	},
	onLoad(opt) {
		this.newsType = opt.newsType;
		if(opt.isVideo){
			this.isVideo = true;
		}
		if(opt.userGroupId) this.userGroupId = opt.userGroupId;
		this.topicId = opt.topicId
		uni.setNavigationBarTitle({
			title: '编辑动态'
		});
		
		this.placeholderText = '请输入内容';
		QQMapWX.initMap();
		let location = {
			latitude: req.getStorage('loctionAddressMap').location.lat,
			longitude: req.getStorage('loctionAddressMap').location.lng
		}
		QQMapWX.reverseGeocoder(location, data => {
			this.poiList = data.pois;
			this.checkLocation(this.poiList[0],0)
		});
	},
	onShow() {
		this.isOpenWeRunData = req.getStorage('isOpenWeRunData')
		this.config = JSON.parse(req.getStorage('configRes'))
	},
	methods: {
		descInput(event) {
			this.desc = event.detail.html;
			console.log('desc数据>>>>>>', this.desc);
			if (this.desc) {
				this.descLength = event.detail.text.length - 1;
			} else {
				this.descLength = 0;
			}
		},
		uploadImgs() {
			let that = this;
			that.hidePop()
			uni.chooseImage({
				count: that.picCount - that.zhiPicUrls.length,
				sizeType: ['original', 'compressed'],
				sourceType: ['album', 'camera'],
				success: function({ tempFilePaths }) {
					uni.showLoading({
						title: '上传中'
					});
					var promise = Promise.all(
						tempFilePaths.map(tempFilePath => {
							return new Promise(function(resolve, reject) {
								req.uploadFile('/api/nocheck/upload', tempFilePath, res => {
									let picUrls = that.zhiPicUrls;
									that.zhiPicUrls = picUrls.concat(res.src);
									resolve()
								});
							});
						})
					);
					promise
						.then(function(results) {
							uni.hideLoading()
							console.log(results);
						})
						.catch(function(err) {
							uni.hideLoading()
							console.log(err);
						});
				}
			});
		},
		//预览图片
		previewImg(picUrls, index) {
			//预览合同图片
			var src = picUrls[index];
			let imgs = picUrls;
			uni.previewImage({
				current: src, // 当前显示图片的http链接
				urls: imgs
			});
		},

		cleanimages(index) {
			// 删除图片
			let arr = this.zhiPicUrls;
			arr.splice(index, 1);
			this.zhiPicUrls = arr;
		},
		chooseLocation(){
			let that = this;
			uni.chooseLocation({//choosePoi不返回经纬度
				success: function (res) {
					console.log('位置名称：' , res);
					that.location = {
						poiName: res.name,
						poiAddress: res.address,
						poiLongitude: res.longitude,
						poiLatitude: res.latitude
					}
					that.reverseGeocoder(res);
				}
			});
		},
		reverseGeocoder(location) {
			QQMapWX.initMap();
			QQMapWX.reverseGeocoder(location, data => {
				this.location.poiRegionalism = data.ad_info.adcode.substring(0, 2) + "0000," + data.ad_info.adcode.substring(0, 4) +"00," + data.ad_info.adcode
				console.log('解析后的地址地址数据：', data,this.location.poiRegionalism);
			});
		},
		checkLocation(item,index){
			if(this.poiIndex == index) return false;
			this.poiIndex = index;
			this.location = {
				poiName: item.title,
				poiAddress: item.address,
				poiLongitude: item.location.lng,
				poiLatitude: item.location.lat,
				poiRegionalism: item.ad_info.adcode.substring(0, 2) + "0000," + item.ad_info.adcode.substring(0, 4) +"00," + item.ad_info.adcode
			}
		},

		async submit() {
			var dataPream = {};
			dataPream.type = this.newsType;
			if (!this.desc) {
				return req.msg('请输入内容');
			}
			dataPream.content = this.desc;
			//图片
			if (this.zhiPicUrls.length > 0) {
				dataPream.url = this.zhiPicUrls.join(',');
			}
			//视频
			if (this.videoInfo) {
				dataPream.url = this.videoInfo;
			}
			//话题
			if(this.topicId){
				dataPream.dialogueId = this.topicId;
			}
			if (this.htObj) {
				dataPream.dialogueId = this.htObj.id;
			}
			if (this.treeObj) {
				dataPream.treeId = this.treeObj.id;
			}
			//投票
			if (this.pollObj) {
				dataPream.pollId = this.pollObj.id;
			}
			//产品
			if (this.productList && this.productList.length > 0) {
				if(this.newsType==10||this.newsType==11){
					dataPream.productIds = this.productList[0].id
				}else{
					let idList = [];
					this.productList.map(it => {
						let obj={
							productId: it.id
						}
						idList.push(obj);
					});
					dataPream.productsList = idList;
				}
			}
			// 位置
			if(this.location&&this.location.poiName){
				dataPream.poiName = this.location.poiName;
				dataPream.poiAddress = this.location.poiAddress;
				dataPream.poiLongitude = this.location.poiLongitude;
				dataPream.poiLatitude = this.location.poiLatitude;
				dataPream.poiRegionalism = this.location.poiRegionalism
			}
			if(this.userGroupId) dataPream.userGroupId = this.userGroupId;
			// await requsetmessage.remindIntegral().then(res => {});
			uni.showLoading({
				mask: true
			})
			req.postRequest('/api/v3/moments/save', dataPream, data => {
				uni.hideLoading();
				if (this.newsType == 2) {
					req.msg('提问发表成功');
				} else {
					req.msg('动态发表成功');
				}
				let pages = getCurrentPages(); //获取所有页面栈实例列表
				let prevPage = pages[pages.length - 2]; //上一页页面实例
				prevPage.$vm.isRefresh = true;
				setTimeout(() => {
					uni.navigateBack();
				}, 1500);
			});
		},
		showPop(){
			this.isShowPop = true
			this.popBottom = 0
		},
		hidePop(){
			this.isShowPop = false
			this.isShowPopCenter = false
			this.popBottom = '-100%'
		},
		uploadVodChangeHandle: function (e) {
			let self = this;
			self.hidePop()
			wx.chooseMedia({
			  count: 1,  //上传视频的个数
			  mediaType:['video'],  //限制上传的类型为video
			  sourceType:['album', 'camera'], //视频选择来源
			  maxDuration: 58, //拍摄限制时间
			  camera: 'back',  //采用后置摄像头
			  success:function(res){
				//获取临时存放的视频资源
				// let tempFilePath=res.tempFiles[0]
				console.log('视频文件==',res)
				var file = {url: res.tempFiles[0].tempFilePath, coverUrl: res.tempFiles[0].thumbTempFilePath};
				self.fileName = res.tempFiles[0].tempFilePath.substring(res.tempFiles[0].tempFilePath.lastIndexOf('/') + 1)
				uni.showLoading({
					title: '视频上传中'
				})
				self.upLoadVideo(res.tempFiles[0].tempFilePath)
			  },
		  })
		},
		upLoadVideo(tempFilePath){
			req.uploadFile('/api/nocheck/upload',tempFilePath,res=>{
				this.videoInfo = res.src
				uni.hideLoading()
			})
		},
		clearVideo(){
			this.videoInfo = ''
		},
		videoPlay(){
		    var that = this;
			this.isShowPlayBtn = false;
			this.isCotrols = true;
			var videoContext = uni.createVideoContext('myVideo') // 对应的视频id
			videoContext.play()
		},
		jumpUrl(url){
			this.isShowPopCenter = false
			uni.navigateTo({
				url: url
			})
		},
		
		onEditorReady(text) {
		    var that = this;
		    uni.createSelectorQuery().select('#editor').context((res) => {
				let editorCtx = res.context;
				editorCtx.setContents({//赋值
					html:text
		        });
		    }).exec()
		  },
		  
		// 发帖隐藏定位
		closeArea(){
			this.showArea = false
			this.poiIndex = -1;
			this.location = {}
		},
		// 开启发帖定位
		openArea(){
			this.showArea = true
			this.checkLocation(this.poiList[0],0)
		}
	}
};
</script>

<style>
@import './news.css';
</style>
