<template>
	<view class="container">
		<!-- <invinbg-image-cropper :show-rotate-btn='false' :crop-fixed='true' crop-width='375' crop-height='375' -->
			<!-- :src="tempFilePath" @confirm="confirm"></invinbg-image-cropper> -->
		<view class="attention-h">
			<view class="nav-bar" :style="{'height': navHeight}">
				<view class="nav-bar-c">
					<text class="iconfont icon-icon_arrow_left right-t" @tap="goBacck(true)"></text>
					<text class="">{{nav_title}}</text>
				</view>
			</view>

		</view>
		<view class="" :style="{'height': hearHeight + 'px'}"></view>
		<view class="image_box pd20" style="margin-top: 20rpx;" v-if="opt.type == 'video'">
			
			<view :style="{'margin-right':(index+1)%3 == 0?'0':'34rpx'}" class="item bor-noe" v-for="(item,index) in pics"
				:key='index'>
				<view class="close" @tap="removeimg" :data-index="index" data-field="pics">
					<!-- <image :src="event_rul + '/static/img/static/img/ico-del.png'"></image> -->
					<view class="del-con">
					  <view class="del-wrap">
						<image
						  class="del-image"
						  style="width: 20rpx;height: 20rpx;"
						  src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACEAAAAhCAYAAABX5MJvAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAhdEVYdENyZWF0aW9uIFRpbWUAMjAyMDowNzoyNSAyMTo1NDoyOU4TkJAAAADcSURBVFhH7ZfRCoMwDEXLvkjwwVf/bH/emmAyN6glTW9WBjsgwm28OeCLpj81Sil7zvlJ90UiONS/yY5VogsO6XrBg3IEQ5a/s8vRSWUAKmLqp2w5jz5BiNQEGMo3GbloDLtFXJ1IkaEuhAiiY6gEIqB4yqACSk9piIBiKQ8VUFpLviKg3C2rESKgWERCBZSWiEfgIfffYvrrsAgoISJ3Apy3zuTxcSxLQkV6ykNEPKVQkZEyiAiiZKgDIaC4upACSlcn5fM/+WuDCAHF1E/Z/N9AhkMZnPNDPI+UDjPIXgAQIGjNAAAAAElFTkSuQmCC"
						></image>
					  </view>
					</view>
				</view>
				<image class="bor-rads" :src="item" @tap="previewImage" :data-url="item" mode="aspectFill"></image>
			</view>

			<view class="item"  @tap="uploadimg" data-field="pics" v-if="pics.length<( opt.type == 'video'?1:8)">
				<!-- <text style="font-size: 60rpx; color: #ccc;">+</text> -->
				<image
				  style="width: 54rpx;height: 54rpx;"
				  src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADYAAAA2CAYAAACMRWrdAAABIUlEQVRoQ+2a2w2DMAxFeQzWrsMUbadAsEw3S1CqVgppKwLX8BEOP4iHTXx8uUgWdVXoVhdaV0VhSmf7vr/H8V3XzY6V3P9iD+nYOI5P7/01LMI596AwoZV0TIBXIUWFXhKLFBWYSFGhhxQN6SFFQ5i4ogITKSr0cEVDekjRECauqMBEigq9U7piOk2yAti27SUe5ljlTfPEQ6KZecTvwl4P3ytvOv06R2HDMNzes7+6aRrvnHvtf50L13Lp50rx88zcvNlS3JpwKQ67XyK04nq2nFbk/LqVjin0TvmBNgQ2S4UUDcliHgpMpKjQwxUN6SFFQ5i4ogITKSr0cEVDekjRECauqMAsVoph+hVPtYr5+03p9tbYQ96xrYtT4ootbAJGVxxVTapVswAAAABJRU5ErkJggg=="
				></image>
				<text style="padding-top: 30rpx;">{{opt.type == 'video'?'添加封面':'添加照片'}}</text>
			</view>
			
			
			<view class="item bor-noe" style="margin-left: 20rpx;overflow: hidden;" v-if="opt.type == 'video' &&video" @tap="uploadvideo">
				<image class="bor-rads" :src="videoImg" mode=""></image>
				<text style="color: #fff; text-align: center;" class="videoImg">已上传视频</text>
			</view>
			<view class="item" style="margin-left: 20rpx;overflow: hidden;" v-if="opt.type == 'video' && !video" @tap="uploadvideo"
				data-field="pics">
				<!-- <text style="font-size: 60rpx; color: #ccc;">+</text> -->
				<image
				  style="width: 54rpx;height: 54rpx;"
				  src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADYAAAA2CAYAAACMRWrdAAABIUlEQVRoQ+2a2w2DMAxFeQzWrsMUbadAsEw3S1CqVgppKwLX8BEOP4iHTXx8uUgWdVXoVhdaV0VhSmf7vr/H8V3XzY6V3P9iD+nYOI5P7/01LMI596AwoZV0TIBXIUWFXhKLFBWYSFGhhxQN6SFFQ5i4ogITKSr0cEVDekjRECauqMBEigq9U7piOk2yAti27SUe5ljlTfPEQ6KZecTvwl4P3ytvOv06R2HDMNzes7+6aRrvnHvtf50L13Lp50rx88zcvNlS3JpwKQ67XyK04nq2nFbk/LqVjin0TvmBNgQ2S4UUDcliHgpMpKjQwxUN6SFFQ5i4ogITKSr0cEVDekjRECauqMAsVoph+hVPtYr5+03p9tbYQ96xrYtT4ootbAJGVxxVTapVswAAAABJRU5ErkJggg=="
				></image>
				<text style="padding-top: 30rpx;">{{video?'重新上传':'添加视频'}}</text>
				<text v-if="video">已上传视频</text>
			</view>
		</view>
		<shmily-drag-image v-else ref="dragImage" :imageWidth="220" :list.sync="list" @changeImg="changeImg" :number="9"></shmily-drag-image>
		<view class="title_info pd20"
			style="margin: 20rpx 0; display: flex; border-bottom:1px solid #ddd; padding: 10rpx 40rpx;">
			<input type="text" style="flex:1;" v-model="title"
				placeholder-style="color:#666; font-size:30rpx; font-weight:bold; font-style:italic; "
				placeholder="请填写标题" maxlength="25" />

			<text>{{25-title.length}}</text>
		</view>


		<view class="title_info pd20" v-if="opt.type == 'video'" style="margin-bottom: 20rpx;">
			<textarea type="text" v-model="content" placeholder="请填写正文" />
		</view>
		<view v-else class="title_box">
			<jin-edit ref='edit' :html='nodes' fileKeyName='file' placeholder="请输入内容" :formData='formData'
				@editOk="editOk" :uploadFileUrl="upUrl"></jin-edit>
		</view>

		<view class="flex_box">
			<view class="icon_row">
				<text @click="toShop('goods')" class="iconfont icon-shangpin"></text>
				<text @click="toShop('goods')" class="txt">{{'已选'+goodsArr.length+'商品'}}</text>
				<text @click="toShop('topic')" class="iconfont icon-jinghao"></text>
				<text @click="toShop('topic')" class="txt">{{'已选'+topicArr.length+'话题'}}</text>
			</view>
			<view class="bottom-btn">
				<view class="cao-g" @click="goBacck(false)">
					<text class="iconfont icon-caogaoxiang" style="font-size: 60rpx;"></text>
					<text class="" >存草稿</text>
				</view>
				<button type="default" :style="{'background-color': t('color1')}" @click="submit(0)">确认发布</button>
			</view>
		</view>
		<!-- 悬浮按钮 -->
		<drag-button></drag-button>
	</view>
</template>

<script>
	var app = getApp();

	export default {
		onLoad(opt) {
			this.opt = opt
			if (this.opt.type != 'video') {
				this.nav_title = '知味'
			}
			if(this.opt.recordlist) {
				this.records = JSON.parse(this.opt.recordlist)
			}
			if(this.opt.detail) {
				let dataDetail = null
				dataDetail = JSON.parse(this.opt.detail)
				if( this.opt.type == 'note') {
					this.title = dataDetail.title
					this.content = dataDetail.content
					this.nodes = dataDetail.content
					this.list = dataDetail.pics
					this.video = dataDetail.video
					this.topicArr = dataDetail.topic_ids.length >= 1 ? dataDetail.topic_ids.indexOf(',') ? dataDetail.topic_ids.split(',') : dataDetail.topic_ids.split('') : []
					this.goodsArr = dataDetail.goods_ids.length >= 1 ? dataDetail.goods_ids.indexOf(',') ? dataDetail.goods_ids.split(',') : dataDetail.goods_ids.split('') : []

				}
				else {
					this.title = dataDetail.name
					this.content = dataDetail.description
					this.pics.push(dataDetail.coverimg)
					this.video = dataDetail.url
					this.duration = dataDetail.video_duration
					this.videoImg = dataDetail.url +'?x-oss-process=video/snapshot,t_0,f_jpg'
					this.topicArr = dataDetail.topic_ids.length >= 1 ? dataDetail.topic_ids.indexOf(',') ? dataDetail.topic_ids.split(",") : dataDetail.topic_ids.split(" ") : []
					this.goodsArr = dataDetail.productids.length >= 1 ? dataDetail.productids.indexOf(',') ? dataDetail.productids.split(",") : dataDetail.productids.split(" ") : []
				}
			}
			
			let elemetn
			// #ifdef MP-WEIXIN
			let menuButtonInfo = uni.getMenuButtonBoundingClientRect()
			uni.getSystemInfo({
				success: res => {
					elemetn = res.statusBarHeight
				}
			})
			 // #endif
			// #ifdef MP-WEIXIN
			this.navHeight = ((menuButtonInfo.bottom + menuButtonInfo.top) - elemetn) + 'px'
			// #endif
			 // #ifndef MP 
			this.navHeight = 45 + 'px'
			 // #endif 
		},
		onUnload() {
			uni.removeStorageSync('is_more_record_goods')
			uni.removeStorageSync('is_more_record_topic')
		},
		onReady() {
			let query = uni.createSelectorQuery().in(this)
			query.select('.attention-h').boundingClientRect()
			query.exec(res => {
				this.hearHeight = res[0].height
			})
		},
		onShow() {
			if (uni.getStorageSync('is_more_show_goods')) {
				this.goodsArr = uni.getStorageSync('goods_type_id') || []
				uni.removeStorageSync('goods_type_id')
				uni.removeStorageSync('is_more_show_goods')
			}


			if (uni.getStorageSync('is_more_show_topic')) {
				this.topicArr = uni.getStorageSync('topic_type_id') || []
				uni.removeStorageSync('is_more_show_topic')
				uni.removeStorageSync('topic_type_id')
			}

		},
		data() {
			return {
				navHeight: 0,
				hearHeight: 0,
				nav_title: '知味',
				list: [],
				formData: {},
				goodsArr: [],
				topicArr: [],
				opt: {
					type: 'diary', //笔记  video 视频
				},
				upUrl: app.globalData.baseurl + 'ApiImageupload/uploadImg/aid/' + app
					.globalData.aid + '/platform/' + app.globalData.platform +
					'/session_id/' + app.globalData.session_id,
				loading: false,
				isload: false,
				menuindex: -1,
				tempFilePath: '',
				pre_url: app.globalData.pre_url,
				datalist: [],
				content_pic: [],
				videoImg:'',
				content: '',
				title: '',
				pagenum: 1,
				cateArr: [],
				duration:0,
				cindex: -1,
				pics: [],
				video: '',
				nodes: '',
				
				records: [],
				
				event_rul: app.globalData.event_url,
			};
		},
		watch: {
			list: {
				handler(val, oldVal){ 
					if(this.opt.type !='video') {
						this.pics = val
						// console.log(this.pics, val, '改变后的图片数组-----')
					}
				},
				// deep: true,
				// immediate: true
			}
		},
		methods: {
			goBacck(isg) {
				let txt = ''
				if(isg) {
					if(this.opt.type == 'video') {
						txt = '视频未发布，是否保存草稿箱?'
					}else {
						txt = '笔记未发布，是否保存草稿箱?'
					}
				}else {
					if(this.opt.type == 'video') {
						txt = '确认保存视频至草稿箱吗?'
					}else {
						txt = '确认保存笔记至草稿箱吗?'
					}
				}
				uni.showModal({
					title: '提示',
					content: txt,
					confirmColor: this.t('color1'),
					cancelColor: '#ccc',
					success:  (res) => {
						if (res.confirm) {
							this.submit(1)
						} else if (res.cancel) {
							if (isg) {
								uni.navigateBack()
							}
							
						}
					}
				});
			},
			changeImg(e) {
				// console.log(e,'=====', this.list, 'fanhuuid返回的是啥------')
			},
			confirm(e) {
				
				
				// console.log(e)
				this.tempFilePath = ''
				// cropFilePath = e.detail.tempFilePath
				const tempFilePaths = e.detail.tempFilePath;
				uni.showLoading({
					title: '上传中'
				});
				uni.uploadFile({
					url: this.upUrl, //仅为示例，非真实的接口地址
					filePath: tempFilePaths,
					name: 'file',
					fileType: 'image',

					formData: {
						// access_token:info.this_.$store.state.loginInfo.token,
					},
					success: (uploadFileRes) => {
						console.log(JSON.parse(uploadFileRes.data))
						// info.headImg = JSON.parse(uploadFileRes.data).url;
						this.pics.push(JSON.parse(uploadFileRes.data).url);
					},
					complete: () => {
						// uni.showLoading({
						// 	title: '加载中'
						// });
						uni.hideLoading()
					},
				})
			},
			editOk(e) {
				console.log('zhessha', e.html)
				this.content = e.html
				
				if(this.content.length){
					  	let regex = new RegExp('<img','gi');
					  		this.content =this.content.replace(regex,'<img style="max-width:100%;"')
				}
			},
			toShop(e) {
				uni.navigateTo({
					url: '/newOtherPages/moreSearch/moreSearch?type=' + e + (e == 'goods' ? '&goodsArr=' +  JSON.stringify(this.goodsArr)  +'&topicArr='+ JSON.stringify(this.topicArr): '&goodsArr=' +  JSON.stringify(this.goodsArr.map(Number))  +'&topicArr='+ JSON.stringify(this.topicArr.map(Number)))  + '&records=' + JSON.stringify(this.records)	
				})
			},
			showT(e) {
				uni.showToast({
					title: e,
					icon: 'none'
				})
			},
			editSubmit(num){
				if (this.opt.type == 'video') {
				
					if (!this.video) {
						this.showT('请先上传视频')
						return
					} else if (!this.pics.length) {
						this.showT('请先上传图片')
						return
					} else if (!this.title) {
						this.showT('请先填写标题')
						return
					}
					//视频
					app.post('ApiShortvideo/drafts', {
						id: this.opt.editId,
						isdraft: num,
						topic_ids: String(this.topicArr),
						goods_ids: String(this.goodsArr),
						pics: String(this.pics),
						title: this.title,
						content: this.content,
						video_duration:this.duration,
						video: this.video
					}, function(res) {
						app.showLoading(false);
						if (res.status == 1) {
							app.success(res.msg);
							setTimeout(function() {
								app.goback(true);
							}, 1000);
						} else {
							app.error(res.msg);
						}
					});
				} else {
					this.$refs.edit.release(true)
					if (!this.pics.length) {
						this.showT('请先上传图片')
						return
					} else if (!this.title) {
						this.showT('请先填写标题')
						return
					}
					//笔记
				
				 
					setTimeout(() => {
						app.post('ApiLuntan/drafts', {
							id: this.opt.editId,
							isdraft: num,
							topic_ids: String(this.topicArr),
							goods_ids: String(this.goodsArr),
							pics: String(this.pics),
							title: this.title,
							content: this.content,
							video: this.video,
							is_edit: 1
						}, function(res) {
							app.showLoading(false);
							if (res.status == 1) {
								app.success(res.msg);
								setTimeout(function() {
									app.goback(true);
								}, 1000);
							} else {
								app.error(res.msg);
							}
						});
					}, 11)
				
				}
				
			},
			submit(num) {
				if(this.opt.detail) {
					this.editSubmit(num)
					return
				}

				if (this.opt.type == 'video') {

					if (!this.video) {
						this.showT('请先上传视频')
						return
					} else if (!this.pics.length) {
						this.showT('请先上传图片')
						return
					} else if (!this.title) {
						this.showT('请先填写标题')
						return
					}
					//视频
					app.post('ApiShortvideo/uploadvideo', {
						isdraft: num,
						topic_ids: String(this.topicArr),
						goods_ids: String(this.goodsArr),
						pics: String(this.pics),
						title: this.title,
						content: this.content,
						video_duration:this.duration,
						video: this.video
					}, function(res) {
						app.showLoading(false);
						if (res.status == 1) {
							app.success(res.msg);
							setTimeout(function() {
								app.goback(true);
							}, 1000);
						} else {
							app.error(res.msg);
						}
					});
				} else {
					this.$refs.edit.release(true)
					if (!this.pics.length) {
						this.showT('请先上传图片')
						return
					} else if (!this.title) {
						this.showT('请先填写标题')
						return
					}
					//笔记

 
					setTimeout(() => {
						app.post('ApiLuntan/fatie', {
							isdraft: num,
							topic_ids: String(this.topicArr),
							goods_ids: String(this.goodsArr),
							pics: String(this.pics),
							title: this.title,
							content: this.content,
							video: this.video,
							is_edit: 0
						}, function(res) {
							app.showLoading(false);
							if (res.status == 1) {
								app.success(res.msg);
								setTimeout(function() {
									app.goback(true);
								}, 1000);
							} else {
								app.error(res.msg);
							}
						});
					}, 11)

				}

			},
			getdata: function() {
				var that = this;
				that.loading = true;
				app.get('ApiLuntan/fatie', {}, function(res) {
					that.loading = false;
					if (res.status == 0) {
						app.alert(res.msg);
						return;
					}
					that.clist = res.clist;
					var clist = res.clist;
					if (clist.length > 0) {
						var cateArr = [];
						for (var i in clist) {
							if (that.opt && that.opt.cid == clist[i].id) {
								that.cindex = i;
							}
							cateArr.push(clist[i].name);
						}
					} else {
						cateArr = false;
					}
					that.cateArr = cateArr
					that.loaded();
				});
			},
			cateChange: function(e) {
				this.cindex = e.detail.value;
			},
			formsubmit: function(e) {
				var that = this;
				console.log(e);
				var clist = that.clist;
				if (clist.length > 0) {
					if (that.cindex == -1) {
						app.error('请选择分类');
						return false;
					}
					var cid = clist[that.cindex].id;
				} else {
					var cid = 0;
				}
				var formdata = e.detail.value;
				var content = formdata.content;
				var pics = formdata.pics;
				var video = formdata.video;
				if (content == '' && pics == '') {
					app.error('请输入内容');
					return false;
				}
				app.post('ApiLuntan/fatie', {
					cid: cid,
					pics: pics,
					content: content,
					video: video
				}, function(res) {
					app.showLoading(false);
					if (res.status == 1) {
						app.success(res.msg);
						setTimeout(function() {
							app.goback(true);
						}, 1000);
					} else {
						app.error(res.msg);
					}
				});
			},
			uploadimg: function(e) {

				// uni.chooseImage({
				// 	count: 1, //默认9
				// 	sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
				// 	success: (res) => {
				// 		this.tempFilePath = res.tempFilePaths.shift()
				// 		// console.log(tempFilePath,'cao',res.tempFilePaths.shift())
				// 	}
				// });
				// return
				var that = this;
				var field = e.currentTarget.dataset.field
				var pics = that[field]
				if (!pics) pics = [];
				app.chooseImage(function(urls) {
					for (var i = 0; i < urls.length; i++) {
						pics.push(urls[i]);
					}
					if (field == 'pic') that.pic = pics;
					if (field == 'pics') that.pics = pics;
					if (field == 'zhengming') that.zhengming = pics;
				},this.opt.type =='video'?1: (9-this.pics.length))
			},
			uploadvideo: function() {
				var that = this;
				uni.chooseVideo({
					// maxDuration: 60,
					success: function(res) {
						// console.log(res, '上传视频-------')
						that.duration = res.duration
						var tempFilePath = res.tempFilePath;
						// that.videoImg = res.thumbTempFilePath;
						app.showLoading('上传中');
						uni.uploadFile({
							url: app.globalData.baseurl + 'ApiImageupload/uploadImg/aid/' + app
								.globalData.aid + '/platform/' + app.globalData.platform +
								'/session_id/' + app.globalData.session_id,
							filePath: tempFilePath,
							name: 'file',
							formData: {
								video_duration: that.duration,
							},
							success: function(res) {
								app.showLoading(false);
								var data = JSON.parse(res.data);

								if (data.status == 1) {
									that.video = data.url;
									that.videoImg = data.url +'?x-oss-process=video/snapshot,t_0,f_jpg'
								} else {
									app.alert(data.msg);
								}
							},
							fail: function(res) {
								app.showLoading(false);
								app.alert(res.errMsg);
							}
						});
					},
					fail: function(res) {
						console.log(res); //alert(res.errMsg);
					}
				});
			},
			removeimg: function(e) {
				var that = this;
				var index = e.currentTarget.dataset.index
				var field = e.currentTarget.dataset.field
				var pics = that[field]
				pics.splice(index, 1)
			},
		}
	}
</script>

<style lang="scss">
	.videoImg{
		position: absolute;
		left: 0;
		right: 0;
		background-color: rgba($color: #000000, $alpha: 0.4);
		color: #fff;
		z-index: 2;
		bottom: 0;
	}
	.pd20 {
		padding: 0 40rpx;
	}
	.del-con {
	  position: absolute;
	  top: -10rpx;
	  right: -10rpx;
	  padding: 0 0 20rpx 20rpx;
	  .del-wrap {
		width: 36rpx;
		height: 36rpx;
		background-color: #ccc;
		border-radius: 50%;
		// background-color: rgba(0, 0, 0, 0.4);
		// border-radius: 0 0 0 10rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		.del-image {
		  width: 20rpx;
		  height: 20rpx;
		}
	  }
	}
	.flex_box {
		position: fixed;
		right: 0rpx;
		bottom: 0rpx;
		left: 0rpx;
		padding: 20rpx;
		padding-bottom: 60rpx;
		background-color: #f6f6f6;

		.icon_row {
			color: #666;

			.iconfont {
				font-size: 40rpx;
			}

			.txt {
				margin-right: 20rpx;
			}
		}

		button {
			height: 80rpx;
			line-height: 80rpx;
			flex: 1;
			margin-top: 0;
			// background-color: #d6a662;
			font-weight: bold;
			padding: 5rpx 0;
			color: #fff;
			// margin-right: 20rpx;
			border-radius: 40rpx;
		}
		
		.bottom-btn {
			margin-top: 30rpx;
			display: flex;
			align-items: center;
			
			.cao-g {
				display: flex;
				flex-direction: column;
				align-items: center;
				padding: 0 30rpx;
				color: #666;
			}
		}
	}
	.attention-h {
		width: 100%;
		position: fixed;
		top: 0;
		left: 0;
		z-index: 2;
	}
	.nav-bar {
		display: flex;
		align-items: flex-end;
		justify-self: center;
	}
	.nav-bar-c {
		width: 100%;
		height: 60rpx;
		position: relative;
		margin-bottom: 8rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		
		.right-t {
			position: absolute;
			left: 20rpx;
			font-size: 50rpx;
		}
		text {font-size: 30rpx;}
	}
	
	.container {
		// padding: 20rpx;
		padding-bottom: 100rpx;

		.image_box {
			display: flex;
			flex-wrap: wrap;

			.item {
				margin-bottom: 20rpx;
				position: relative;
				// margin-right: 20rpx;
				width: 200rpx;
				height: 200rpx;
				border-radius: 12rpx;
				border: 1px solid #ccc;
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;

				image {
					width: 100%;
					height: 100%;
				}

				text {
					font-size: 24rpx;
					color: #999;
				}

				.close {
					width: 30rpx;
					height: 30rpx;
					position: absolute;
					right: 0;
					top: 0;

				}
				
				.bor-rads {
					border-radius: 12rpx;
				}
				
			}
			.bor-noe {
				border: none;
			}
		}
	}
</style>
