<template>
	<view class="post" :class="AppStyle" style="background-color: #f6f6f6;">
		<view class="header" :style="[{height:CustomBar + 'px'}]" v-if="showContent">
			<view class="cu-bar bg-white" :style="{'height': CustomBar + 'px','padding-top':StatusBar + 'px'}">
				<view class="action" @tap="isback">
					<text class="cuIcon-back"></text>
				</view>
				<view class="content text-bold" :style="[{top:StatusBar + 'px'}]">
					<block v-if="type=='edit'">
						修改帖子
					</block>
					<block v-else>
						发布帖子
					</block>
				</view>
				<!--  #ifdef H5 || APP-PLUS -->
				<view class="action" @click="toDraft()" style="display: flex;color: #333;">
					<!-- <text class="cuIcon-upload"></text> -->
					<block v-if="type=='add'">
						<text style="margin-right: 5px;">草稿箱</text>
						<span class="tn-icon-edit-form" style="font-size: 40upx;"></span></span>
					</block>

				</view>
				<!--  #endif -->

			</view>
		</view>
		<view :style="[{padding:(NavBar+10) + 'px 10px 0px 10px'}]"></view>
		<form>
			<view class="cu-form-group margin-sm bg-white" style="border-radius: 20upx;">
				<input placeholder="输入帖子标题" name="input" v-model="title" :adjust-position="false"
					:focus="false"></input>
				<block v-if="type=='add'">
					<view class="picker" style="color: #333;" @tap="toCategory">
						<block v-if="sectionName=='未知圈子'">
							选择圈子
						</block>
						<block v-else>
							<text class="text-shojo">{{sectionName}}</text>
						</block>
					</view>
				</block>
			</view>
			<view class="bg-white margin-sm" style="border-radius: 20upx;">
				<view class="margin-sm">
					<cu-editor ref="editor" :mrPoster="videoPoster" :SPimg="SPimg" :musicpic='musicpic'
						editorId='editor' :NavBar="NavBar" @editorFocus="handleEditorFocus" :uploadTime="uploadTime"
						@editorBlur="handleEditorBlur" :url="this.$API.upload()" :formData="formData" :content="text"
						:MusicUpload='MusicUpload' :isPay="false" :isWz="false" @save="onSave"></cu-editor>
				</view>

			</view>
			<view  class="bg-white margin-sm"
				style="border-radius: 20upx; padding: 14px;" v-if="Fanstey_Topic ==true">
				<view class="flex flex-row justify-between items-center" style="align-items: center;">
					<text style="color: #333;">选择话题</text>
					 <view class="" @click="changeTopic()" style="min-width: 50px;height: 25px;border-radius: 15px;text-align: center;line-height: 25px;width: auto;">
					 	{{changeText}}
					 </view>
				
					<!-- <tn-switch :disabled="isPayShop" v-model="isPaid" /> -->
				</view>
					<tn-select v-model="show"  mode="single" :searchShow="true" :list="list" @confirm="confirm"></tn-select>
			
			</view>
			<view :style="showContent?'':'display:none'" class="bg-white margin-sm"
				style="border-radius: 20upx; padding: 14px;">
				<view class="flex flex-row justify-between items-center" style="align-items: center;">
					<text style="color: #333;">是否插入付费内容</text>
					<tn-switch :disabled="isPayShop" v-model="isPaid" />
				</view>
				<view v-if="isPaid" class="margin-top-sm">
					<tn-button backgroundColor="#f6f6f6" fontColor='#444' width='100%'
						@click="editPaidContent">编辑付费内容</tn-button>
				</view>
			</view>
			<view :style="showContent?'':'display:none'">
				<!--#ifdef APP-PLUS || H5 -->
				<view v-if="type=='add'" class="margin-sm" style="display: flex;justify-content: space-between;">
					<tn-button type="button" fontColor="#333" width="35%" class="form-btn"
						@click="submit(false)">保存草稿</tn-button>
					<tn-button type="button" backgroundColor="rgb(1, 190, 255)" fontColor="#fff" width="60%"
						class="form-btn" @click="submit(true)">发布帖子</tn-button>
				</view>
				<!--#endif -->
				<!--#ifdef MP-WEIXIN -->
				<view v-if="type=='add'" class="margin-sm">
					<tn-button type="button" fontColor="#333" width="100%" class="form-btn"
						@click="submit(false)">保存草稿</tn-button>
					<view class="margin-top-sm">
						<tn-button class="form-btn margin-top-sm" type="button" backgroundColor="rgb(1, 190, 255)"
							fontColor="#fff" width="100%" @click="submit(true)">发布帖子</tn-button>
					</view>
				</view>
				<!--#endif -->

				<view v-else class="margin-sm">
					<tn-button type="button" backgroundColor="rgb(1, 190, 255)" fontColor="#fff" width="100%"
						class="form-btn" @click="submit(true)">
						<block v-if="draft==0">
							修改帖子
						</block>
						<block v-if="draft==1">
							发布帖子
						</block>
					</tn-button>
				</view>
				<!--  #ifdef MP-WEIXIN -->
				<view class="margin-sm">
					<tn-button type="button" fontColor="#333" width="100%" class="form-btn" @click="toDraft()">
						<text style="margin-right: 5px;">草稿箱</text>
						<span class="tn-icon-edit-form" style="font-size: 30upx;"></span></span>
					</tn-button>
				</view>
				<!--  #endif -->
			</view>
		</form>

	</view>
</template>

<script>
	import mpHtml from '@/components/mp-html/mp-html'
	import {
		localStorage
	} from '../../js_sdk/mp-storage/mp-storage/index.js'
	var wv;
	export default {
		data() {
			return {
				StatusBar: this.StatusBar,
				CustomBar: this.CustomBar,
				NavBar: this.StatusBar + this.CustomBar,
				AppStyle: this.$store.state.AppStyle,
				isPaid: false,
				modalName: "",
				showContent: true,
				havePay: false,
				uid: 0,
				uploadTime: this.$API.getuploadTime(),
				token: "",
				poster: this.$API.SPmusicpic(),
				isShow: false,
				isPayShop: false,
				name: "",
				curHeight: 0,
				jpHeight: 0,
				screenHeight: 0,
				postheight: 0,
				poststyle: "",
				readstyle: "",
				isText: 0,
				draft: 0,
				MusicUpload: this.$API.SPstarMusicUpload(),
				musicpic: this.$API.SPmusicpic(),
				videoPoster: this.$API.getVideoPoster(),
				SPimg: this.$API.SPimgs(),
				formData: {},
				//文章表单部分
				title: "",
				category: "",
		list: [
		{
										 value:"123",
										 label:"这个是默认的，不要选",
		}
		
									
									],
				tag: "",
				categoryText: "",
				text: '',
				textRead: "",
				isLoading: false,
				isSpace: false,
				//页面状态
				type: "add",
				id: 0,
				lenght: 0,
				payId: 0,
				Fanstey_Topic:false,
				shopList: [],
				editInterval: null,
				shopID: -1,
				sectionName: "未知圈子",
				sectionid: 0,
				content: "",
			}
		},
		onPullDownRefresh() {
			var that = this;

		},
		onShow() {
			var that = this;

		},
		onHide() {
			var that = this;
			clearInterval(that.editInterval);
			that.editInterval = null;
		},
		onShow() {
			var that = this;
			if (localStorage.getItem('userinfo')) {
				var userInfo = JSON.parse(localStorage.getItem('userinfo'));
				that.token = userInfo.token;
				if (userInfo.screenName) {
					that.name = userInfo.screenName;
				} else {
					that.name = userInfo.name;
				}
				that.formData = {
					'token': userInfo.token,
					'username': that.name
				}
			}
			if (localStorage.getItem('curSection')) {
				var curSection = JSON.parse(localStorage.getItem('curSection'));
				that.sectionid = curSection.id;
				that.sectionName = curSection.name;
				console.log(curSection);
				localStorage.removeItem('curSection');
			}

		},
		onLoad(res) {
			var that = this;
			localStorage.setItem('isSaveTz', "false");
			that.editInterval = setInterval(function() {
				if (localStorage.getItem('goBack')) {
					localStorage.removeItem('goBack');
					that.back();
				}
			}, 500);
			var cachedPlugins = localStorage.getItem('getPlugins');
			if (cachedPlugins) {
				const pluginList = JSON.parse(cachedPlugins);
				// 检查插件是否存在于插件列表中 
				
				   that.Fanstey_Topic = pluginList.includes('Fanstey_Topic');
				   
			}
			
			// #ifdef APP-PLUS || MP
			that.NavBar = this.CustomBar;
			// #endif
			if (res.type) {
				that.type = res.type;
			}
			if (res.draft) {
				that.draft = res.draft;
			}
			if (that.type != 'add') {
				if (!res.id) {
					uni.showToast({
						title: "参数不能为空",
						icon: 'none',
						duration: 1000,
						position: 'bottom',
					});
					that.back();
					return false;
				} else {
					that.id = res.id;
				}
			}
			if (res.type) {
				that.type = res.type;
				if (res.id) {
					that.id = res.id;
					that.setloading();
					var timer = setTimeout(function() {
						that.postInfoForum(that.id);
					}, 500)
				}
			}
			if (res.section) {
				that.sectionName = res.section;
			}
			if (res.sectionid) {
				that.sectionid = res.sectionid;
			}
			var verifyLevel = 0;
			if (localStorage.getItem('AppInfo')) {
				try {
					var AppInfo = JSON.parse(localStorage.getItem('AppInfo'));
					verifyLevel = AppInfo.verifyLevel;
				} catch (e) {
					console.log(e);
				}

			}
			if (localStorage.getItem('userinfo')) {
				var userInfo = JSON.parse(localStorage.getItem('userinfo'));
				that.token = userInfo.token;
				that.uid = userInfo.uid;
				that.uid = userInfo.uid;
				if (userInfo.screenName) {
					that.name = userInfo.screenName;
				} else {
					that.name = userInfo.name;
				}
			}
		},
			
		methods: {
		getForumId(){
					var that = this;
					that.$Net.request({
						url:that.$API.PluginLoad('Fanstey_Topic'),//括号中填插件名
						data: {
							"action":"getForum",
							
							"Fan_id":that.uid,
							"Fan_title":that.title
						},
						method: "get",
						dataType: 'json',
						success: function(res) {
						console.log(res);
					that.sid = res.data.data[0].id
					// that.AvatarItem = res.data.data[0].AvatarFrame;
					// console.log("666"+that.AvatarItem);
						// console.log(that.allMedalList);
						setTimeout(() => {
						        that.addTopicByid();
						      }, 1000);
						},
						fail: function(res) {
										   
						
						
						}
					})
				},
				changeTopic(){
					const that = this;
					// that.show = true;
					that.show = true;
					that.getTopic();
					
					
				},
				addTopicByid(){
							var that = this;
							that.$Net.request({
							url:that.$API.PluginLoad('Fanstey_Topic'),//括号中填插件名
								data: {
									"action":"addinfoid",
									
									"Fan_id":that.sid,
									"Fan_topic":that.value
								},
								method: "get",
								dataType: 'json',
								success: function(res) {
								console.log(res);
						    
							// that.AvatarItem = res.data.data[0].AvatarFrame;
							// console.log("666"+that.AvatarItem);
								// console.log(that.allMedalList);
								},
								fail: function(res) {
						   
								
								
								}
							})
				
					
				},
				getTopic(){
							var that = this;
							that.list = [{
										 value:"123",
										 label:"这个是默认的，不要选",
		}];
							that.$Net.request({
								url:that.$API.PluginLoad('Fanstey_Topic'),//括号中填插件名
								data: {
									"action":"getTopic",
									
									// "fa_uid":that.userinfo.uid
								},
								method: "get",
								dataType: 'json',
								success: function(res) {
								console.log(res);
								
								for(var i = 0;i<res.data.data.length;i++){
									var o = {
										value:res.data.data[i].id,
										label:res.data.data[i].name,
										
									}
									
									that.list.push(o);
									console.log(that.list);
								}
							
							// that.AvatarItem = res.data.data[0].AvatarFrame;
							// console.log("666"+that.AvatarItem);
								// console.log(that.allMedalList);
								},
								fail: function(res) {
						   
								
								
								}
							})
				
					
				},
				confirm(e) {
					const that = this;
					console.log(e);
				that.changeText = e[0].label;
				// console.log(e.label,that.changeText);
				that.value = e[0].value;
								
							},
			setloading() {
				var that = this;
				if (!that.isLoading) {
					uni.showLoading({
						title: '获取数据中',
					});
				} else {
					uni.hideLoading();
				}

			},
			editPaidContent() {
				uni.navigateTo({
					url: '/pages/edit/payText?havePay=' + this.havePay + '&sid=' + this.payId
				});
			},
			postInfoForum(id) {
				var that = this;
				var token = "";
				if (localStorage.getItem('userinfo')) {

					var userInfo = JSON.parse(localStorage.getItem('userinfo'));
					token = userInfo.token;

				}
				var data = {
					"id": id,
					"token": token,
				}

				that.$Net.request({
					url: that.$API.postInfoForum(),
					data: data,
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					method: "get",
					dataType: 'json',
					success: function(res) {
						if (res.data.code == 1) {
							that.title = res.data.data.title;
							var textOld = res.data.data.text;
							var textNew = textOld.replace(
								/<video[^>]*?src="([^"]+)"[^>]*?(poster="([^"]+)")?[^>]*?>\s*<\/video>/g,
								(match, src, posterAttr, poster) => {
									const finalPoster = poster ? poster : that.videoPoster;
									return `<img src="${finalPoster}" alt="src=${src}|poster=${finalPoster}|type=video" />`;
								}
							);
							that.text = textNew;

							var sid = res.data.data.sid;
							if (sid > 0) {
								that.getPaid(sid)
							}
							that.isLoading = true;
							that.setloading();
						}
					},
					fail: function(res) {}
				})
			},
			getShopList() {
				var that = this;
				var uid = 0;
				if (localStorage.getItem('userinfo')) {

					var userInfo = JSON.parse(localStorage.getItem('userinfo'));
					uid = userInfo.uid;

				} else {
					uni.showToast({
						title: "请先登录",
						icon: 'none',
						duration: 1000,
					});
					var timer = setTimeout(function() {
						uni.navigateTo({
							url: '/pages/user/login'
						});
						clearTimeout('timer')
					}, 1000)
					return false
				}
				var data = {
					"uid": uid,
					"status": 1,
				}

			},
			getPaid(sid) {
				var that = this;
				var searchParams = {
					"id": sid,
					"status": 1,
					"type": 4,
				}
				that.$Net.request({
					url: that.$API.shopList(),
					data: {
						"searchParams": JSON.stringify(that.$API.removeObjectEmptyKey(searchParams)),
						"token": that.token
					},
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					method: "get",
					dataType: 'json',
					success: function(res) {

						if (res.data.code == 1) {
							var list = res.data.data;
							if (list.length > 0) {
								that.isPaid = true;

								var paidInfo = list[0];
								that.shopID = paidInfo.id;
								console.log(res);
								if (paidInfo.value) {
									var text = paidInfo.value;
									that.havePay = true
								}
								that.isPayShop = true;
								var shopPice = paidInfo.price;
								var shopDiscount = paidInfo.vipDiscount;
								var payData = {
									text: paidInfo.value || "",
									shopPice: paidInfo.price,
									shopDiscount: paidInfo.vipDiscount
								};
								localStorage.setItem("payId" + sid, JSON.stringify(payData));
								that.payId = sid
							}

						}
					},
					fail: function(res) {
						uni.showToast({
							title: "网络不太好哦",
							icon: 'none'
						})

					}
				})

			},
			back() {
				localStorage.removeItem('isSaveTz')
				uni.navigateBack({
					delta: 1
				});
			},
			toDraft() {
				uni.navigateTo({
					url: '/pages/forum/draftList'
				});
			},
			okBtn() {
				const nowDate = +new Date();
				uni.setStorageSync('modelView', nowDate);
				this.cancleBtn();
			},
			handleEditorFocus() {
				this.showContent = false;
				this.NavBar = this.StatusBar;
			},
			handleEditorBlur() {
				this.showContent = true;
				this.NavBar = this.CustomBar;
			},
			cancleBtn() {
				this.modelVisible = false;
			},
			toSpace(e) {
				this.isSpace = e.detail.value
			},
			submit(isPost) {
				var that = this;
				var type = that.type;
				if (isPost) {
					if (type == "add") {
						that.$refs.editor.save()
						setTimeout(function() {
							that.postForum(false);
						}, 200)


					} else {
						that.$refs.editor.save();
						setTimeout(function() {
							that.editForum();
						}, 200)

					}
				} else {
					if (type == "add") {
						that.$refs.editor.save()
						setTimeout(function() {
							that.postForum(true);
						}, 200)
					}
				}

				// if(that.shopID!=-1){
				// 	that.mountShop();
				// }

			},
			onSave(e) {
				var that = this
				that.content = e.html;
				console.log('html:'+e.html)
			},
			postForum(Draft) {
				var that = this;
				if (that.title == "") {
					uni.showToast({
						title: "标题不可为空",
						icon: 'none',
						duration: 1000,
						position: 'bottom',
					});
					return false
				}
				if (that.content == '<p><br></p>' || that.content == '') {
					uni.showToast({
						title: "内容不可为空",
						icon: 'none',
						duration: 1000,
						position: 'bottom',
					});
					return false
				}
				if (that.sectionid == 0) {
					uni.showToast({
						title: "请选择圈子",
						icon: 'none',
						duration: 1000,
						position: 'bottom',
					});
					return false
				}
				var text = that.content;
				text = text.replace(/\r\n/g, "||rn||");
				text = text.replace(/\n/g, "||rn||");
				var isDraft = 0;
				if (Draft) {
					isDraft = 1
				}
				var data = {
					'title': that.title,
					'text': text,
					'isMd': 0,
					"isDraft": isDraft,
					"section": that.sectionid,
					"token": that.token,
				}
				var isPay = 0;
				if (that.isPaid) {
					isPay = 1;
					data.isPaid = isPay;
					if (that.havePay && that.payId != '0') {
						var payData = JSON.parse(localStorage.getItem("payId" + that.payId));
						if (payData) {
							data.shopText = payData.text;
							data.shopPice = payData.shopPice;
							data.shopDiscount = payData.shopDiscount;
						}
					} else {
						var payData = JSON.parse(localStorage.getItem("payIdmy"));
						if (payData) {
							data.shopText = payData.text;
							data.shopPice = payData.shopPice;
							data.shopDiscount = payData.shopDiscount;
						}
					}
				}
				uni.showLoading({
					title: "加载中"
				});
				that.$Net.request({

					url: that.$API.postForum(),
					data: data,
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					method: "post",
					dataType: 'json',
					success: function(res) {
						setTimeout(function() {
							uni.hideLoading();
						}, 1000);
						if (res.data.code == 1) {
							if(that.Fanstey_Topic){//如果开启了Fanstey_Topic插件
								that.getForumId();
							}
							if (!Draft) {
								uni.showToast({
									title: res.data.msg,
									icon: 'none',
								})
								localStorage.removeItem('payIdmy');
								var timer = setTimeout(function() {
									that.back();
								}, 1000)
							} else {
								localStorage.setItem('isSaveTz', "true");
								uni.showToast({
									title: '已保存到草稿箱',
									icon: 'none',
								})
							}

						} else {
							uni.showToast({
								title: res.data.msg,
								mask: false,
								icon: 'icon-error',
								duration: 3000
							})
						}

					},
					fail: function(res) {
						setTimeout(function() {
							uni.hideLoading();
						}, 1000);
						uni.showToast({
							title: "网络开小差了哦",
							icon: 'none'
						})
						uni.stopPullDownRefresh()
					}
				})
			},
			editForum() {
				var that = this;
				if (that.title == "") {
					uni.showToast({
						title: "标题不可为空",
						icon: 'none',
						duration: 1000,
						position: 'bottom',
					});
					return false
				}
				if (that.content == '<p><br></p>' || that.content == '') {
					uni.showToast({
						title: "内容不可为空",
						icon: 'none',
						duration: 1000,
						position: 'bottom',
					});
					return false
				}
				if (that.sectionid == 0) {
					uni.showToast({
						title: "请选择圈子",
						icon: 'none',
						duration: 1000,
						position: 'bottom',
					});
					return false
				}
				var text = that.content;

				text = text.replace(/\r\n/g, "||rn||");
				text = text.replace(/\n/g, "||rn||");
				var data = {
					'id': that.id,
					'title': that.title,
					'text': text,
					"token": that.token,
					'isMd': 0
				}
				var isPay = 0;
				if (that.isPaid) {
					isPay = 1;
					data.isPaid = isPay;
					if (that.havePay && that.payId != '0') {
						var payData = JSON.parse(localStorage.getItem("payId" + that.payId));
						if (payData) {
							data.shopText = payData.text;
							data.shopPice = payData.shopPice;
							data.shopDiscount = payData.shopDiscount;

						}
					} else {
						var payData = JSON.parse(localStorage.getItem("payIdmy"));
						if (payData) {
							data.shopText = payData.text;
							data.shopPice = payData.shopPice;
							data.shopDiscount = payData.shopDiscount;

						}
					}
				} else {
					data.isPaid = isPay;
				}
				uni.showLoading({
					title: "加载中"
				});
				that.$Net.request({

					url: that.$API.editForum(),
					data: data,
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					method: "post",
					dataType: 'json',
					success: function(res) {
						setTimeout(function() {
							uni.hideLoading();
						}, 1000);
						uni.showToast({
							title: res.data.msg,
							icon: 'none',
						})
						if (res.data.code == 1) {
							localStorage.setItem('isEdit', true);
							var timer = setTimeout(function() {
								that.back();
							}, 1000)

						}
					},
					fail: function(res) {
						setTimeout(function() {
							uni.hideLoading();
						}, 1000);
						uni.showToast({
							title: res.data.msg,
							mask: false,
							icon: 'icon-error',
							duration: 3000
						})
						uni.stopPullDownRefresh()
					}
				})
			},
			toCategory() {
				var that = this;
				uni.navigateTo({
					url: '/pages/forum/section?type=1'
				});
			},
			addTag() {
				var that = this;
				uni.navigateTo({
					url: '/pages/contents/alltag?type=edit'
				});
			},
			toPostlinktype(i) {
				var that = this;
				that.postlinktype = i;
			},
			toAddShop() {
				var that = this;
				uni.navigateTo({
					url: '/pages/edit/addshop'
				});
			},
			goImgData() {
				var that = this;
				uni.navigateTo({
					url: '/pages/contents/imagetoday?type=post'
				});
			},
			isback() {
				var that = this;

				var isSave = localStorage.getItem('isSaveTz');
				if (isSave == 'true') {
					that.back()
				} else {
					uni.showModal({
						title: '提示',
						content: '编辑的内容还没保存，确定要退出吗？',
						cancelText: '退出',
						confirmText: '留下',
						success: function(res) {
							if (res.confirm) {

							} else if (res.cancel) {
								that.back()
							}
						}
					});
				}
			}


		}
	}
</script>

<style>
	.post {
		display: flex;
		flex: 1;
		flex-direction: column;
		justify-content: space-between;
	}
</style>