<template>
	<view class="content">
		<!-- 输入框 -->

		<view class="zhuige-post-box">
			<view class="box_title">
				<input class='box_text_input' maxlength="18" :placeholder="__('帖子标题3~18个字以内')" placeholder-style="color:#999;font-size: 30rpx;" v-model="story_title"></input>
			</view>
			<view class="zhuige-block">
				<view class="zhuige-post-input">
					<textarea v-model="story_content" :placeholder="__('想说你就多说点...')" maxlength="3000"></textarea>
				</view>
				<view class="zhuige-post-plug">
					<view class="zhuige-post-opt">
						<view @click="clickType('image')" :class="{active:type=='image'}">
							<uni-icons type="image-filled" color="#333333" size="20"></uni-icons>
							<text>{{__('图文')}}</text>
						</view>
						<view @click="clickType('video')" :class="{active:type=='video'}">
							<uni-icons type="videocam-filled" color="#333333" size="20"></uni-icons>
							<text>{{__('视频')}}</text>
						</view>
					</view>
					<view class="zhuige-post-count">{{story_content.length}}/3000</view>
				</view>
			</view>
		</view>

		<!-- 图片列表 -->
		<view v-if="type=='image'" class="zhuige-post-box">
			<view class="zhuige-upload-set">
				<view v-if="ImgList.length<9" @click="clickAddImage">
					<uni-icons type="plusempty" color="#777777" size="30"></uni-icons>
					<view>{{__('图片')}}</view>
				</view>
				<!-- 上传后，增加 class="loaded" view替换为image，icon type替换为clear -->
				<view class="loaded" v-for="(image, index) in ImgList" :key="index">
					<uni-icons class="img-clear" type="clear" color="#eee" size="24" @click="clickDelImage(index)"></uni-icons>
					<image mode="aspectFill" :src="image" :data-src="image" @click="previewImage"></image>
				</view>
			</view>
		</view>

		<!-- 视频 -->
		<view v-else-if="type=='video'" class="zhuige-post-video-box">
			<video class="loaded" v-if="story_video" :src="story_video" @click="clickAddVideo"></video>
			<view v-else @click="clickAddVideo" class="zhuige-upload-set">
				<view>
					<uni-icons type="plusempty" color="#777777" size="30"></uni-icons>
					<view>{{__('视频')}}</view>
				</view>
			</view>
			<view class="zhuige-upload-set">
				<view class="loaded" v-if="video_cover">
					<!-- <uni-icons class="img-clear"  type="clear" color="#eee" size="24" @click="clickDelVideoPoster"></uni-icons> -->
					<image mode="aspectFill" :src="video_cover" @click="clickAddVideoPoster"></image>
				</view>
				<view v-else @click="clickAddVideoPoster">
					<uni-icons type="plusempty" color="#777777" size="30"></uni-icons>
					<view>{{__('封面')}}</view>
				</view>
			</view>
		</view>

		<!-- 选择行 -->
		<view class="zhuige-post-box">
			<view class="zhuige-block">
				<view class="zhuige-post-line">
					<view>{{__('推荐商品：')}}</view>
					<view @tap='shopsearch'>
						<view>{{ProductName?ProductName: __('请选择商品')}}</view>
						<uni-icons type="forward" color="#BBBBBB" size="16"></uni-icons>
					</view>
				</view>
			</view>
		</view>

		<!-- 选择行 -->
		<view class="zhuige-post-box" v-if="false">
			<view class="zhuige-block">
				<view class="zhuige-post-line">
					<view>你的位置：</view>
					<view @click="clickAddress">
						<view>{{marker?marker:'请选择位置'}}</view>
						<uni-icons type="forward" color="#BBBBBB" size="16"></uni-icons>
					</view>
				</view>
			</view>
		</view>

		<!-- 选择行 -->
		<view class="zhuige-post-box">
			<view class="zhuige-block">
				<view class="zhuige-post-line">
					<view>{{__('动态板块：')}}</view>
					<view @click="clickSubject">
						<view>{{storyCategoryName?storyCategoryName:'请选择板块'}}</view>
						<uni-icons type="forward" color="#BBBBBB" size="16"></uni-icons>
					</view>
				</view>
			</view>
		</view>

		<!-- 选择行 @ 好友 -->
		<view v-if="at_switch==1" class="zhuige-post-box">
			<view class="zhuige-block">
				<view class="zhuige-post-line">
					<view>@ 好友：</view>
					<view @click="clickAtList">
						<view>已选{{atlist.length}}个好友</view>
						<uni-icons type="forward" color="#BBBBBB" size="16"></uni-icons>
					</view>
				</view>
			</view>
		</view>

		<!-- 选择行 积分数 -->
		<view v-if="score_switch==1" class="zhuige-post-box">
			<view class="zhuige-block">
				<view class="zhuige-post-line">
					<view>积分数：</view>
					<view>
						<input type="number" v-model="score" placeholder="如：88，填写即开启积分阅读全文" />
					</view>
				</view>
			</view>
		</view>

		<!-- 底部大按钮 -->
		<view class="zhuige-base-button">
			<view @click="AddMemberPosts">
				<view>{{__('发布')}}</view>
			</view>
			<view @click="SaveDraft">
				<view>{{__('保存草稿')}}</view>
			</view>
		</view>

	</view>
</template>

<script>
	import dateUtil from "../../helpers/util_date";
	import {
		mapMutations,
		mapState
	} from 'vuex'

	var Interval, picPath = [];
	export default {
		components: {

		},

		data() {
			this.requesting = false;

			return {
				type: 'image',

				ProductName: '',

				story_title: "",

				story_content: '',

				shopback: [],
				storyCategoryId: 0,
				storyCategoryName: '',

				//图片
				ImgList: [],
				objlist: [],
				sortList: [],
				item_ids: [],

				//视频
				story_video: undefined,
				video_cover: undefined,
				tiaozhuan: true,




				// 是否开启帖子积分功能
				score_switch: 0,
				// 积分值
				score: '',



				forum: undefined,

				// 选择的话题
				subjects: [],

				// 是否启用 @ 好友的功能
				at_switch: 0,
				// 选择的好友
				atlist: [],

				longitude: '',
				latitude: '',
				marker: '',
				address: '',
			}
		},
		computed: mapState(['Config', 'StateCode', 'notice', 'plantformInfo', 'shopInfo', 'userInfo', 'hasLogin']),
		onLoad(options) {
			var that = this;

			uni.setNavigationBarTitle({
				title: this.__('发帖')
			});
			this.setData({
				options: options
			});

			if (options.type) {
				this.type = options.type;
			}

			that.$.getStorage({
				key: "draft_key",
				success: function(t) {
					t.data ? that.getStorage(t) : picPath = []
				}
			});


			that.notice.addNotification("RefreshCoupon", that.RefreshCoupon, that);
			that.notice.addNotification("RefreshPlate", that.RefreshPlate, that);

		},
		onShow: function() {
			var that = this;
			Interval = setInterval(function() {
					that.zdSaveDraft()
				},
				3e4)
		},

		onUnload() {
			let that = this;
			this.notice.removeNotification("RefreshCoupon", that);
			this.notice.removeNotification("RefreshPlate", that);
		},

		onShareAppMessage() {
			return {
				title: '发布-' + getApp().globalData.appName,
				path: Util.addShareSource('pages/bbs/post/post?n=n')
			};
		},

		// #ifdef MP-WEIXIN
		onShareTimeline() {
			return {
				title: '发布-' + getApp().globalData.appName,
			};
		},
		// #endif

		methods: {
			...mapMutations(['logout', 'getPlantformInfo', 'forceUserInfo', 'getStoreInfo']),
			getStorage: function(t) {
				var that = this;
				//console.log(t.data);
				t = JSON.parse(t.data);
				//console.log(t);
				for (var s = [], o = 0; o < t.story_file.length; o++) {
					s.push({
						Url: t.story_file[o],
						order: o
					});
				}
				picPath = s;
				that.setData({
					type: t.type,
					story_title: t.story_title,
					ImgList: t.type == 'image' ? t.story_file : [],
					video_cover: t.type == 'video' ? t.story_file[0] : '',
					shopback: that.shopback.concat(t.proList),
					storyCategoryId: t.story_category_id,
					story_content: t.story_content,
					story_video: t.story_video,
					storyCategoryName: t.storyCategoryName,
					ProductName: t.ProductName,
				});

				picPath = [];

			},
			RefreshPlate: function(e) {
				console.log(e)
				this.setData({
					storyCategoryId: e.storyCategory.story_category_id,
					storyCategoryName: e.storyCategory.story_category_name,
				})
			},
			RefreshCoupon: function(t) {
				if (true) {
					this.setData({
						shopback: t.couponItemId
					});
				} else {
					var a = [];
					a = this.shopback;
					for (var s = 0; s < a.length; s++) {
						for (var o = 0; o < t.couponItemId.length; o++) {
							a[s].item_id == t.couponItemId[o].item_id && a.splice(s, 1);
						}
					}
					for (o = 0; o < t.couponItemId.length; o++) {
						a.push(t.couponItemId[o]);
					}

					this.setData({
						shopback: a
					})
				}
				var name = '';
				console.log(this.shopback)
				for (var i = 0; i < this.shopback.length; i++) {
					name += this.shopback[i].ProductName + ','
				}
				this.ProductName = name;

			},
			/**
			 * 点击打开链接
			 */
			openLink(link) {

			},

			/**
			 * 切换类型
			 */
			clickType(type) {
				this.type = type;
			},

			/**
			 * 添加图片
			 */
			clickAddImage() {
				var that = this,
					max_num = 9;
				if (that.$.isNull(that.ImgList) || (max_num = 9 - that.ImgList.length), 0 != max_num) {
				
					that.$.chooseImage({
						count: 1,
						sizeType: ['compressed'],
						success: function(n) {
							that.$.showLoading();
							var r = n.tempFilePaths;
							that.$.uploadFile({
								url: that.Config.URL.upload,
								method: 'POST',
								filePath: r[0],
								name: 'upfile',
								//header: { 'content-type': 'multipart/form-data' },
								success: function(n) {
									that.$.hideLoading();
									var up_res = that.$.parseJSON(n.data);
									console.log(up_res)
									var s = up_res.data.url;
									that.ImgList.push(s);
								},
								fail: function(e) {
									that.$.hideLoading();
								},
								complete: function(e) {
									that.$.hideLoading();
								}
							});
						},
						fail: function(e) {
							that.$.hideLoading();
						},
						complete: function(e) {
							that.$.hideLoading();
						}
					});

				} else {
					that.$.alert(that.__("最多上传9张图片！"))
				}
			},

			/**
			 * 删除图片
			 */
			clickDelImage(index) {
				var that = this;
				that.$.confirm("是否放弃上传本张图片?", function(t) {
						if (t.confirm) {
							if (index >= 0 && index < that.ImgList.length) {
								that.ImgList.splice(index, 1);
							}
						}
					},
					true)
			},

			/**
			 * 添加视频
			 */
			clickAddVideo() {
				let that = this;
				// 上传视频
				//console.log('上传视频')
				uni.chooseVideo({
					maxDuration: 10,
					count: 1,
					camera: 'back',
					sourceType: ['camera', 'album'],
					success: function(result) {
						uni.showToast({
							title: that.__('上传中'),
							icon: 'loading',
							duration: 10000,
							mask: true,
						})

						that.$.uploadFile({
							url: that.Config.URL.upload,
							method: "POST",
							filePath: result.tempFilePath,
							name: "upfile",
							formData: {
								video: true
							},
							//header: {"content-type": "multipart/form-data"},
							success: function(t) {
								//console.log(t), //console.log(t.data);
								var a = JSON.parse(t.data);
								//console.log(a);
								var s = that.$.parseJSON(t.data);

								if (s.status == 200) {
									that.setData({
										story_video: s.data.url,
										video_cover: s.data.thumb,
									})
								} else {
									s.$.confirm(up_res.msg || that.__('发生错误'));
								}

							},
							fail: function(t) {},
							complete: function(t) {
								uni.hideToast();
							}
						})
					},
					fail: function(t) {},
					complete: function(t) {}
				})
			},
			previewImage: function(e) {
				//预览图片
				var current = e.target.dataset.src

				var that = this;
				var n = this.ImgList;

				uni.previewImage({
					current: current,
					urls: n
				})
			},

			/**
			 * 添加视频封面
			 */
			clickAddVideoPoster() {
				var that = this;
				that.$.showLoading();
				that.$.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					success: function(n) {
						that.$.showLoading();
						var r = n.tempFilePaths;
						that.$.uploadFile({
							url: that.Config.URL.upload,
							method: 'POST',
							filePath: r[0],
							name: 'upfile',
							//header: { 'content-type': 'multipart/form-data' },
							success: function(n) {
								that.$.hideLoading();
								var up_res = that.$.parseJSON(n.data);
								that.video_cover = up_res.data.url;

							},
							fail: function(e) {
								that.$.hideLoading();
							},
							complete: function(e) {
								that.$.hideLoading();
							}
						});
					},
					fail: function(e) {
						that.$.hideLoading();
					},
					complete: function(e) {
						that.$.hideLoading();
					}
				});
			},

			/**
			 * 删除视频封面
			 */
			clickDelVideoPoster() {
				this.video_cover = '';
			},

			/**
			 * 选择话题结果
			 */
			onSubjectChange(data) {
				this.subjects = data;
			},

			/**
			 * 选择 @ 的用户
			 */
			onAtlistChange(data) {
				this.atlist = data;
			},




			/**
			 * 选择商品
			 */
			shopsearch: function() {
				var that = this
				var ids = [];
				for (var i = 0; i < this.shopback.length; i++) {
					ids.push(this.shopback[i].item_id)
				}
				that.$.navigateTo({
					url: "/community/community/searchsq?num=" + (4 - this.shopback.length) + "&item_ids=" +
						JSON.stringify(ids)
				})
			},

			/**
			 * 选择板块
			 */
			clickSubject() {
				var that = this

				that.$.navigateTo({
					url: "/community/community/plate?storyCategoryId=" + that.storyCategoryId
				})
			},



			/**
			 * 发帖
			 */
			AddMemberPosts: function() {
				var that = this;
				if (19 < that.story_title.length || that.story_title.length < 3) {
					that.$.alert(that.__("标题在3~18字内"));
				} else if (that.story_content.length > 3000) {
					that.$.alert(that.__("内容在0~3000字内"));
				} else if (0 != that.storyCategoryId) {
					var t = [];
					that.$.isNull(that.story_content) || t.push(0);
					var a = [];
					if (that.type == 'image') {
						a = that.ImgList;
					} else if (that.type == 'video') {
						a.push(that.video_cover)
					}

					that.setData({
						sortList: t
					});
					var e = [];
					console.log(this.shopback)
					for (var o = 0; o < this.shopback.length; o++) {
						e.push(this.shopback[o].item_id);
					}
					if (that.setData({
							objlist: e
						}), 1 == that.tiaozhuan) {
						that.setData({
							tiaozhuan: false
						});
						var params = {
							story_category_id: that.storyCategoryId,
							story_title: that.story_title,
							story_content: that.story_content,
							story_file: JSON.stringify(a || []),
							SortList: that.sortList,
							item_id_row: JSON.stringify(that.objlist || []),
							story_video: that.type == 'video' ? that.story_video : '',
						};
						console.log(params)

						that.$.request({
							url: this.Config.URL.sns.story_add,
							method: "POST",
							data: params,
							success: function(data, status, msg, code) {
								if (200 == status) {
									that.$.showToast({
										title: that.__("已发布，待审核"),
										icon: "success",
										duration: 3e3
									}), clearTimeout(a);
									var a = setTimeout(function() {
											that.setData({
												story_title: "",
												story_content: "",
												storyCategoryId: 0,
												CategoryList: [],
												ImgList: [],
												sortList: [],
												shopback: [],
												caogaolist: [],
												proLista: [],
												objlist: [],
												story_video: "",
												storyCategoryName: '',
												ProductName: '',
											});

											picPath = [];
											//that.$.gopage({url: "/community/community/detail?id=" + data.story_id})
											that.$.gopage({
												url: '/community/community/userspace'
											})
										},
										1500);
									that.$.removeStorage({
										key: "draft_key",
										success: function(t) {
											//console.log(t.data)
										}
									})
								} else {
									that.$.alert(msg);
									that.setData({
										tiaozhuan: true
									})
								}
							}
						});
					}
				} else {
					that.$.showToast({
						title: "请选择板块",
						icon: "success",
						duration: 2e3
					})
				}
			},

			/**
			 * 保存草稿
			 */
			SaveDraft: function() {
				var that = this,
					a = [];
				that.$.isNull(that.story_content) || a.push(0);
				var s = [];
				if (that.type == 'image') {
					s = that.ImgList;
				} else if (that.type == 'video') {
					s.push(that.video_cover)
				}
				that.setData({
					sortList: s
				});
				var e = [];
				for (var o = 0; o < this.shopback.length; o++) {
					e.push(this.shopback[o]);
				}
				that.setData({
					objlist: e
				});
				var i = {
						story_category_id: that.storyCategoryId || 0,
						story_title: that.story_title,
						story_content: that.story_content,
						story_file: s || [],
						SortList: that.sortList,
						proList: that.objlist || [],
						story_video: that.type == 'video' ? that.story_video : '',
						storyCategoryName: that.storyCategoryName,
						ProductName: that.ProductName,
						type: that.type
					},
					n = JSON.stringify(i);


				that.$.setStorage({
					key: "draft_key",
					data: n
				}), that.$.showToast({
					title: that.__("保存成功"),
					icon: "success",
					duration: 1500
				})
			},
			zdSaveDraft: function() {
				var that = this,
					a = [];
				return;
				that.$.isNull(that.story_content) || a.push(0);
				var s = [];
				if (!that.$.isNull(that.ImgList)) {
					for (var o = 0; o < that.ImgList.length; o++) {
						a.push(o + 1), s.push(that.ImgList[o].Url);
					}
				}
				that.setData({
					sortList: a
				});
				var e = [];
				for (var o = 0; o < this.shopback.length; o++) {
					e.push(this.shopback[o]);
				}
				that.setData({
					objlist: e
				});
				var i = {
						story_category_id: that.storyCategoryId,
						story_title: that.story_title,
						story_content: that.story_content,
						story_file: s || [],
						SortList: that.sortList,
						proList: that.objlist || [],
						story_video: that.story_video
					},
					n = JSON.stringify(i);
				that.$.setStorage({
					key: "draft_key",
					data: n
				})
			},


		}
	}
</script>

<style lang="scss" scoped>
	.content {
		position: fixed;
		height: 100%;
		width: 100%;
		overflow-y: scroll;
	}

	.box_title {
		margin: 20rpx 0;
		background-color: #fff;
		padding: 20rpx;
		border-radius: 12rpx;
	}

	.active {
		color: #010101;
	}

	.zhuige-block {
		padding: 20rpx;
		border-radius: 12rpx;
		background: #FFFFFF;
		margin-bottom: 24rpx;
	}

	.uniui-right:before {
		content: "\e6b5";
	}

	.zhuige-post-box {
		padding: 0 20rpx;
	}



	.zhuige-post-video-box {
		padding: 0 20rpx;
		display: flex;
		flex-wrap: wrap;
	}

	.zhuige-post-video-box video {
		width: 164rpx;
		height: 164rpx;
		border-radius: 12rpx;
		margin-bottom: 20rpx;
	}

	.content .zhuige-post-box:nth-last-child(2) {
		margin-bottom: 180rpx;
	}

	.zhuige-post-line {
		display: flex;
		align-items: center;
		justify-content: space-between;
		line-height: 2.2em;
		height: 2.2em;
	}

	.zhuige-post-line>view:nth-child(1) {
		font-size: 30rpx;
		font-weight: 400;
		width: 156rpx;
	}

	.zhuige-post-line>view:nth-child(2) {
		display: flex;
		align-items: center;
		max-width: 510rpx;
	}

	.zhuige-post-line view:nth-child(2) view {
		margin-right: 12rpx;
		font-size: 28rpx;
		font-weight: 400;
		height: 1.6rem;
		line-height: 1.6rem;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.zhuige-post-line view:nth-child(2) input {
		width: 450rpx;
		text-align: right;
	}

	.zhuige-upload-set {
		display: flex;
		align-items: center;
		flex-wrap: wrap;
		margin-left: 20rpx;
	}

	.zhuige-upload-set>view {
		height: 154rpx;
		width: 154rpx;
		border-radius: 12rpx;
		position: relative;
		text-align: center;
		margin: 0 20rpx 20rpx 0;
		text-align: center;
		background: #FFFFFF;
	}

	.zhuige-upload-set>view view {
		font-size: 28rpx;
		font-weight: 400;
		color: #777777;
		height: 1em;
		line-height: 1em;
		margin-top: -28rpx;
	}

	.zhuige-upload-set view.loaded image {
		height: 100%;
		width: 100%;
		border-radius: 12rpx;
	}

	.zhuige-upload-set>view.loaded uni-icons {
		position: absolute;
		z-index: 3;
		right: -20rpx;
		top: -46rpx;
	}

	.zhuige-post-input textarea {
		height: 240rpx;
		padding: 20rpx 0;
		font-size: 30rpx;
		line-height: normal;
	}

	.zhuige-post-plug {
		display: flex;
		flex-wrap: nowrap;
		justify-content: space-between;
		align-items: center;
	}

	.zhuige-post-opt {
		display: flex;
		flex-wrap: nowrap;
	}

	.zhuige-post-opt view {
		display: flex;
		flex-wrap: nowrap;
		align-items: center;
		opacity: 0.5;
		margin-right: 8rpx;
		line-height: 1.8em;
	}

	.zhuige-post-plug view.active {
		opacity: 1;
	}

	.zhuige-post-plug view image {
		height: 28rpx;
		width: 28rpx;
		margin-right: 8rpx;
	}

	.zhuige-post-plug view text {
		font-size: 28rpx;
		font-weight: 300;
		margin-left: 8rpx;
		white-space: nowrap;
	}

	.zhuige-post-count {
		color: #999;
	}



	.zhuige-base-button {


		display: flex;
		align-items: center;
		justify-content: space-between;
		position: fixed;
		bottom: 0;
		width: 100%;
		padding: 40rpx 0;
		z-index: 3;
	}

	.zhuige-base-button view {
		width: 360rpx;
		text-align: center;
		height: 96rpx;
		line-height: 96rpx;
		border-radius: 96rpx;
		font-size: 32rpx;
		font-weight: 400;
		color: #FFFFFF;
		background: #db384c;
	}

	.loaded {
		position: relative;

		.img-clear {
			position: absolute;
			right: 0;
			top: -34rpx;
			z-index: 9;
		}
	}
</style>