<style >
	.release {
		width: 100%;
		height: 100vh;
		background: #FFF;
	}

	.release .release-box {
		width: 100%;
		padding: 15px;
	}

	.release .option-box {
		width: 100%;
		height: 40px;
		padding: 0 10px;
		display: flex;
		flex-direction: row;
		align-items: center;
		font-size: 14px;
		color: #333333;
		border-bottom: 1px soild #DFDFDF;
	}

	.release .ob-l {
		display: flex;
		flex-direction: row;
		align-items: center;
	}

	.release .ob-r {
		display: flex;
		flex: 1;
		justify-content: flex-end;
		display: flex;
		flex-direction: row;
		align-items: center;
		padding-left: 10px;
	}

	.release .releasebtn {
		width: 100%;
		height: 45px;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 16px;
		color: #FFFFFF;
		background: #40766E;
		margin-top: 83px;
		margin-bottom: 80px;
		border-radius: 22.5px;
	}
	.release .slot-btn{
		width: 200rpx;
		height: 200rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		flex-direction: column;
		background: rgb(244, 245, 246);
		border-radius: 10rpx;
		margin-left: 5px;
	}
	.release .slot-btn .mian-title {
		font-size: 28rpx;
		color: #888;
		font-weight: 600;
		margin: 10rpx 0;
	}
	.release .audio{
		width: 100%;
		margin: 10px 0;
		height: 40px;
		background: #F9F9F9;
		border-radius: 4px;
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: center;
		padding: 0 10px;
	}
	.release .audio-o{
		display: flex;
		flex-direction: row;
		align-items: center;
		font-size: 12px;
		color: #333333;
		width: 100%;
		height: 100%;
		justify-content: center;
	}
	.release .as-box{
		width: 100%;
		height: 240px;
		background: #FFFFFF;
		position: relative;
		display: flex;
		flex-direction: column;
		align-items: center;
		border-top-left-radius: 10px;
		border-top-right-radius: 10px;
	}
	.release .as-yuyin{
		margin-top: 20px;
		width: 90px;
		height: 90px;
		border: 3px solid #4F877F;
		background: #40766E;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	.release .now-date {
	  font-size: 28rpx;
	  color: #666;
	  padding: 20rpx 0;
	 
	}
	.release .as-btn{
		width: 100%;
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: space-around;
		margin-top: 5px;
	}
	.release .as-btn-item{
		width: 85px;
		height: 40px;
		border-radius: 20px;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 16px;
		color: #40766E;
		border: 1px solid #40766E;
	}
	.release  .audio-ot{
		width: 1;flex:1;margin-right: 20px;display: flex;flex-direction: row;align-items: center;padding: 0 10px;justify-content: space-between;
		height: 30px;
		background: #EBEBEB;
		border-radius: 4px;
	}
	.release .videostyle{
		width: 100px;
		height: 100px;
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 4px;
		background: #F9F9F9;
		border: 1px dashed #D2D2D2;
	}
	#myVideo{
		width: 150px; height: 200px;
	}
</style>
<template>
	<view class="release">
		<view class="release-box">
			<textarea placeholder="今天又什么可以给大家分享呢？" style="width: 100%;height: 100px;" maxlength='-1' confirm-type='done' v-model="addMsg.Content">

			</textarea>
			<text v-if='addMsg.FileType==1 ' style="font-size: 12px;color: #333333">上传图片<span style='color: ;#A9A9A9'>(图片无上限）</span> </text>
			<text v-if=' addMsg.FileType==2' style="font-size: 12px;color: #333333">上传视频 </text>
			<view style="width: 100%;margin-top: 15px;">
				<u-upload :action="action" :file-list="fileList" @on-remove="onRemove1"  :custom-btn="true"
				v-if='addMsg.FileType==1'
				 @on-success="uploadSuccessHandler">
					<view slot="addBtn" class="slot-btn">
						<u-icon name="photograph" size="40" color="#888"></u-icon>
						<view class="mian-title">上传图片</view>
					</view>
				</u-upload>
			</view>
			<!-- 视频 -->
			<view style="width: 100%;margin-top: 15px;display: flex;flex-direction: row;" v-if="addMsg.FileType==2">
				
				<view style="width: 150px; height: 200px;position: relative;margin-right: 20px;">
					<video id="myVideo" :src="addMsg.FileList[0]"
						:controls='controls'
						:show-center-play-btn='false'
						:show-fullscreen-btn='false' 
						@fullscreenchange='videoControl' ></video>
						
						<view style="width: 100%;height: 100%;position: absolute;left: 0;top: 0;display: flex;align-items: center;justify-content: center;" @click="enlarge(addMsg.FileList[0])">
							<u-icon name="play-circle-o" :size="70" color="#FFF"></u-icon>
						</view>
				</view>
				
			</view>
			
			<!-- 音频 -->
			<view class="audio" v-if='addMsg.FileType==3'>
				<view class="audio-o" @click="statraudio()" v-if="addMsg.FileList.length==0">
					<image src="https://viitto-1301420277.cos.ap-chengdu.myqcloud.com/Static/Sound.png" mode="widthFix" style="width: 20px;height: auto;"></image>
					<text style="margin-left: 10px;">语音录制</text>
					<text style="color: #BBBBBB;">（点击进入录制页面）</text>
				</view>
				<view v-if="addMsg.FileList.length>0" class="audio-o" style="justify-content: space-around;width: 100%;">
					<view class="audio-ot" @click="playVoice">
						<image v-if="playshow==false" src="https://viitto-1301420277.cos.ap-chengdu.myqcloud.com/Static/Sound.png" mode="widthFix" style="width: 20px;height: auto;"></image>
						<image v-if="playshow==true" src="https://viitto-1301420277.cos.ap-chengdu.myqcloud.com/Static/bofanggif.gif" mode="widthFix" style="width: 20px;height: auto;"></image>
						<text>{{reDate2!=reDate?(reDate2+'/'):''}}{{reDate}}</text>
					</view>
					<view style="font-size: 14px;color: #40766E;" @click="reset">
						重新录制
					</view>
					
				</view>
			</view>
			
			<view class="option-box" @click="getAddress()" style="margin-top: 10px;">
				<view class="ob-l">
					<image src="https://viitto-1301420277.cos.ap-chengdu.myqcloud.com/Static/Lockation.png" mode="widthFix" style="width: 15px;height: auto;"></image>
					<text style="margin-left: 5px;">所在位置</text>
				</view>
				<view class="ob-r">
					<view style="white-space: nowrap;text-overflow: ellipsis;overflow: hidden;width: 400rpx;text-align: right;">{{addMsg.Address}}</view>
					<u-icon name="arrow" :size="32" color="#B7B7B7"></u-icon>
				</view>
			</view>
			<view class="option-box" @click="whoshow=true">
				<view class="ob-l">
					<image src="https://viitto-1301420277.cos.ap-chengdu.myqcloud.com/Static/Users.png" mode="widthFix" style="width: 15px;height: auto;"></image>
					<text style="margin-left: 5px;">谁可以看</text>
				</view>
				<view class="ob-r">
					<text>{{addMsg.IsOpen==1?'全部可见':'关注可见'}}</text>
					<u-icon name="arrow" :size="32" color="#B7B7B7"></u-icon>
				</view>
			</view>
			<view class="releasebtn" @click="publish">
				发布
			</view>
		</view>
		<u-popup v-model="whoshow" mode="center" length="70%" border-radius="14">
			<view style="width: 100%;background: #FFF;border-radius: 6px;
			padding: 20px;">
				<u-radio-group v-model="addMsg.IsOpen" :active-color='mainColor' @change='whoshow=false'>
					<u-radio shape="circle" style='width: 100%;margin: 5px 0;' v-for="(item, index) in list" :key="index" :name="item.Id">
						{{item.name}}
					</u-radio>
				</u-radio-group>
			</view>
		</u-popup>
		<!-- 音频模块 -->
		<u-popup v-model="audioshow" mode="bottom"  >
			<view class="as-box">
				<view style="width: 40px;height: 40px;display: flex;align-items: center;justify-content: center;
				position: absolute;right: 0;top: 0;" @click="audioshow=false">
					<u-icon name="cross" :size="50" color="#333"></u-icon>
				</view>
				<view class="as-yuyin">
					<image v-if="gifshow==false" src="https://viitto-1301420277.cos.ap-chengdu.myqcloud.com/Static/mic.png" mode="widthFix" style="width: 37px;height: auto;"></image>
					<image v-if="gifshow==true" src="https://viitto-1301420277.cos.ap-chengdu.myqcloud.com/Static/luyin.gif" mode="widthFix" style="width: 37px;height: auto;"></image>
				</view>
				<text class="now-date">{{reDate2!=reDate && voicePath!=''?(reDate2+'/'):''}}{{ reDate }}</text>
				
				<view class="as-btn">
					<view class="as-btn-item" @click="luyintype!=2? playVoice():''">
						试听
					</view>	
					<view class="as-btn-item"  style="background: #40766E;color: #FFFFFF;" @click="onStartRecoder">
						{{luyintype==1?'开始':(luyintype==2?'结束':'重录制')}}
					</view>
					<view class="as-btn-item" @click="luyintype!=2?asupload():''">
						确定
					</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
  const recorderManager = uni.getRecorderManager();
  const innerAudioContext = uni.createInnerAudioContext();
	export default {
	
		data() {
			return {
				whoshow: false,
				audioshow:false,
				pageTitle: "发布",
				mainColor: "",
				secondary: '',
				pricecolor: '',
				addMsg: {
					Content: '',
					LatAndLong: '', //经纬度可为空
					Address: '', //地址
					IsOpen: 1, //1-是，2-关注可见
					FileList: [],
					FileType: 0,
				},
				fileList:[],
				list: [{
						'name': '全部可见',
						Id: 1
					},
					{
						'name': '关注可见',
						Id: 2
					},
				],
				action: this.host2 + "/api/File/UploadTencent",
				reDate: '00:00',
				reDate2: '00:00',
				timer: null,
				sec: 0,
				min: 0,
				voicePath:'',
				nowbofo:false,//播放状态
				videoContext:null,
				gifshow:false,
				playshow:false,
				controls:false,//显示默认控件
				luyintype:1,
			}
		},
		
		onLoad(options) {
			if (options && options.type) {
				this.addMsg.FileType = options.type
				if(options.file){
					this.addMsg.FileList=[]
					this.addMsg.FileList.push(options.file)
					
				}
			}
			
			this.mainColor = this.$uiConfig.mainColor;
			this.secondary = this.$uiConfig.secondary;
			this.pricecolor = this.$uiConfig.pricecolor;
			uni.setNavigationBarTitle({
				title: this.pageTitle,
			});
			let MallBaseId = uni.getStorageSync("mall_UserInfo").MallBaseId ? uni.getStorageSync("mall_UserInfo").MallBaseId : 1;
			this.action = this.host2 + '/api/File/UploadTencent?MallBaseId=' + MallBaseId
		},
		created () {
		  // 监听
		  this.onMonitorEvents()
		},
		onUnload(){
			innerAudioContext.stop();
		},
		methods: {
			publish() { //发布
				if (this.addMsg.FileType == 0 && this.addMsg.Content == '') {
					uni.showToast({
						title: '请输入此刻想法...',
						icon: 'none',
						duration: 2000
					});
					return
				}
				if( this.addMsg.FileList.length == 0 && (this.addMsg.FileType == 1 || this.addMsg.FileType == 2 || this.addMsg.FileType == 3)){
					let title = '请选择相应的图片或者视频'
					if(this.addMsg.FileType == 3 ){
						title='请录入音频'
					}
					uni.showToast({
						title: title,
						icon: 'none',
						duration: 2000
					});
					return
					
				}
				
				uni.showLoading({
					title: '发布中...'
				})
				console.log(this.addMsg)
				this.request2({
						url: '/api/AppletEducation/GetPublishDynamic',
						data: this.addMsg
					},
					res => {
						uni.hideLoading()
						if (res.resultCode == 1) {
							uni.showToast({
								title: res.message,
								position: 'bottom',
								icon: 'none',
								duration: 2000
							});
							let pages = getCurrentPages(); // 当前页面
							let beforePage = pages[pages.length - 2]; // 前一个页面
							setTimeout(() => {
								uni.navigateBack({
									success: function() {
										beforePage.$vm.getList(); // 执行前一个页面的created方法
									}
								});
							}, 500)
						}
					}
				);
			},
			//打开地图
			getAddress() {
				let that = this;
				uni.chooseLocation({
					success: function(res) {
						that.addMsg.Address = res.name;
						that.addMsg.LatAndLong = res.longitude + ',' + res.latitude;
					},
					fail: function(err) {

						that.fetchAgainLocation()
					}
				});
			},
			uploadSuccessHandler(data, index, lists) {
				let r = JSON.parse(data);
				console.log(r)
				this.addMsg.FileList.push(r.data);
			},
			onRemove1(index) {
				this.addMsg.FileList.splice(index, 1);
			},
			//提前对音频授权
			statraudio(){
				let that = this
				uni.getSetting({
				   success(res) {
					   console.log(res.authSetting)
					  if(!res.authSetting['scope.record']){//没有获取音频的时候
						  uni.authorize({
						      scope: 'scope.record',
						      success(r) {
								  console.log(r)
								  that.reDate = '00:00'
						          that.audioshow = true;
								  that.voicePath = ''
								  that.luyintype=1;
						      },fail(){
								  wx.showModal({
								  title: '录音管理器',
								  content: '尚未进行授权，部分功能将无法使用',
								  success(res) {
									if (res.confirm) {
									  wx.openSetting({
										success: (res) => {
										 if (data.authSetting["scope.record"] === true) {
										 	wx.showToast({
										 		title: '授权成功',
										 		icon: 'success',
										 		duration: 1000
										 	})
											that.reDate = '00:00'
										 	that.audioshow = true;
											that.voicePath = ''
											that.luyintype=1;
										 } else {
										 	wx.showToast({
										 		title: '授权失败',
										 		duration: 1000
										 	})
										 }
										},
										fail: function (err) {
										  console.log(err);
										}
									  })
									} else if (res.cancel) {
									  console.log('用户点击取消')
									}
								  },fail(err){
									  console.log(err)
								  }
								})
							  }
						  })
					  }else{
						  that.reDate = '00:00'
						  that.audioshow = true;
						  that.voicePath = ''
						  that.luyintype=1;
					  }
				   }
				})
			},
			//重新提示用户打开设置对地图授权
			fetchAgainLocation() {
				let that = this
				wx.getSetting({
					success: (res) => {
						var statu = res.authSetting;
						if (!statu['scope.userLocation']) {
							wx.showModal({
								title: '是否授权当前位置',
								content: '需要获取您的地理位置，请确认授权，否则地图功能将无法使用',
								success: (tip) => {

									if (tip.confirm) {
										console.log(tip)
										wx.openSetting({
											success: (data) => {
												console.log(data)
												if (data.authSetting["scope.userLocation"] === true) {
													wx.showToast({
														title: '授权成功',
														icon: 'success',
														duration: 1000
													})
													if (that.latitude != '' && that.longitude != '') {
														that.getAddress()
													} else {
														that.getAddress()
													}
												} else {
													wx.showToast({
														title: '授权失败',
														duration: 1000
													})
												}
											},
											fail: (err) => {
												console.log(err)
											},
											complete: () => {}
										});
									}
								}
							})
						}
					},
					fail: () => {},
					complete: () => {}
				})
			},
			reset(){//重新录制
				this.voicePath = ''
				this.min = 0
				this.sec = 0
				this.reDate = '00:00'
				this.addMsg.FileList=[];
				this.audioshow= true;
				this.luyintype=1;
				 clearInterval(this.timer)
				 innerAudioContext.stop();//视频播放完停止
				 
			},
			// 开始录制
			onStartRecoder () {
				if(this.luyintype==1){
					this.gifshow = true
					recorderManager.start({
						duration: 600000,
						format:'mp3'
					})
					this.luyintype=2
				}else if(this.luyintype==2){// 录制结束
					console.log('结束')
					this.gifshow = false
					recorderManager.stop()
					this.luyintype=3
				}else{
					this.reset()
				}
				
			},
			shiting(){//试听
				innerAudioContext.src = this.voicePath;
			},
			// 播放暂停录音
			playVoice() {
				let that = this
			  innerAudioContext.src = this.voicePath;
			 
			  if (this.nowbofo== false) {
			    
				this.playstartDate()
				this.nowbofo=true;
				this.playshow =true
			  } else {
				  console.log('暂停')
			    innerAudioContext.pause();
				 clearInterval(that.timer)
				 this.nowbofo=false;
				 this.playshow =false
			  }
			},
			playstartDate(){
				clearInterval(this.timer)
				if(this.reDate2 == this.reDate){//如果等于音频总时间就初始化，没有的话就继续
					this.sec = 0
					this.min = 0
				}
				innerAudioContext.play()
				this.playshow =true
				this.timer = setInterval(() => {
				  this.sec++
				  if (this.sec >= 60) {
				    this.min ++
				    this.sec = 0
				  }
				  this.playresetDate()
				}, 1000)
			},
			playresetDate(){
				let _s = this.sec < 10 ? '0' + parseInt(this.sec) : parseInt(this.sec)
				let _m = this.min < 10 ? '0' + this.min : this.min
				this.reDate2 = _m + ':' + _s
				if(this.reDate2==this.reDate){
					this.playshow =false
					innerAudioContext.stop();//视频播放完停止
					this.nowbofo=false;//控制播放的字段
					clearInterval(this.timer)
				}
			},
			// 监听
			onMonitorEvents(){
				 // 录制开始
				recorderManager.onStart(() => {
				  uni.showLoading({
				    title: '录制中...'
				  })
				  this.startDate()
				})
				// 录制结束
				recorderManager.onStop(({ tempFilePath }) => {
				  this.voicePath = tempFilePath
				  clearInterval(this.timer)
				  uni.hideLoading()
					console.log(tempFilePath)
				})
			},
			// 录音计时
			startDate () {
			  clearInterval(this.timer)
			  this.sec = 0
			  this.min = 0
			  this.timer = setInterval(() => {
			    this.sec++
			    if (this.sec >= 60) {
			      this.min ++
			      this.sec = 0
			    }
			    this.resetDate()
			  }, 1000)
			},
			resetDate () {
			  let _s = this.sec < 10 ? '0' + parseInt(this.sec) : parseInt(this.sec)
			  let _m = this.min < 10 ? '0' + this.min : this.min
				this.reDate = _m + ':' + _s
				this.reDate2 = _m + ':' + _s
			 
			},
			// 音频的上传
			asupload(){
				innerAudioContext.stop();//
				clearInterval(this.timer)
				let that = this
				that.reDate2 = '00:00'
				that.playshow=false
				that.nowbofo=false;//控制播放的字段
				that.sec = 0
				that.min = 0
				 uni.uploadFile({
					url: that.action, 
					filePath: that.voicePath,
					name: 'file',
					formData: {
						  user: 'tesdt'
					},
					success: (uploadFileRes) => {
						if(uploadFileRes.statusCode==200){
							console.log(JSON.parse(uploadFileRes.data));
							that.addMsg.FileList=[]
							that.addMsg.FileList.push(JSON.parse(uploadFileRes.data).data)
							that.audioshow = false;
						}
					
					},
					 fail: function(res) {
						console.log(res)
						wx.showToast({
							title: '上传失败!',
							icon:'none',
							duration: 1000
						})
			        }
				});
			},
		
			 enlarge(file) {
			 	// 全屏
			 	innerAudioContext.stop();
			 	this.videoContext = uni.createVideoContext('myVideo');
			 	this.videoContext.requestFullScreen({
			 		direction:0
			 	})
			 	
			 },
			 videoControl(e){
			 	if(e.detail.fullScreen==false){
			 		this.videoContext.stop()
			 		this.controls=false
			 	}else{
			 		this.videoContext.play()
			 		this.controls=true
			 	}
			 }
			
		}
	}
</script>
