<template>
	<view class="post" :class="$store.state.AppStyle" style="background-color: #f6f6f6;">
		<view class="header" :style="[{height:CustomBar + 'px'},{top:jpHeight + '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>

			</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" @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="true" placeholder="请输入商品介绍" :isWz="false"
						@save="onSave"></cu-editor>
				</view>

			</view>
			<view :style="showContent?'':'display:none'" class="bg-white margin-sm"
				style="border-radius: 20upx; padding: 14px;">
				<view class="margin-top-sm">
					<tn-button backgroundColor="#f6f6f6" fontColor='#444' width='100%'
						@click="editPaidContent">编辑付费内容</tn-button>
				</view>
			</view>
			<view :style="showContent?'':'display:none'">
				<view class="bg-white margin-sm" style="font-size: 30upx;padding: 20upx;border-radius: 20upx;">

					<view class="margin-sm">
						<view style="display: flex; justify-content: space-between; align-items: center;">
							<text>库存数量</text>
							<view style="flex: 1; display: flex; justify-content: flex-end;">
								<input v-model="num" type="number" placeholder="请输入库存数量"
									style="width: 130px; text-align: right;margin-right: 5px;" /><span>件</span>
							</view>
						</view>
					</view>
					<hr style="width: 100%;margin: auto;height: 1px;background: #e5e5e5d9;border: none;" />
					<view class="margin-sm" @click="sortShow=true">
						<view style="display: flex;justify-content: space-between;align-items: center;">
							<view>商品大类</view>
							<view>
								<blcok v-if="sortText==''">
									未选择
								</blcok>
								<blcok v-else>
									{{sortText}}
								</blcok>
							</view>
						</view>
					</view>
					<hr style="width: 100%;margin: auto;height: 1px;background: #e5e5e5d9;border: none;" />
					<view class="margin-sm" @click="setSubtypeShow()">
						<view style="display: flex;justify-content: space-between;align-items: center;">
							<view>商品小类</view>
							<view>
								<blcok v-if="subtypeText==''">
									未选择
								</blcok>
								<blcok v-else>
									{{subtypeText}}
								</blcok>
							</view>
						</view>
					</view>
					<hr style="width: 100%;margin: auto;height: 1px;background: #e5e5e5d9;border: none;" />
					<view class="margin-sm">
						<view style="display: flex; justify-content: space-between; align-items: center;">
							<view>商品封面</view>
							<tn-button backgroundColor="#f6f6f6" @click="imgUpload()" fontColor='#444'>上传</tn-button>
						</view>
						<view v-if="imgurl" class="margin-top-sm">
							<tn-lazy-load borderRadius="20upx" :image="imgurl" mode="widthFix" width="100%"
								height="348px" @tap="previewImage(imgurl,imgurl)"></tn-lazy-load>
						</view>
					</view>

				</view>
				<view v-if="type=='add'" class="margin-sm">
					<tn-button type="button" backgroundColor="rgb(1, 190, 255)" fontColor="#fff" width="100%"
						class="form-btn" @click="submit()">
						发布商品
					</tn-button>
				</view>
				<view v-else class="margin-sm">
					<tn-button type="button" backgroundColor="rgb(1, 190, 255)" fontColor="#fff" width="100%"
						class="form-btn" @click="submit()">
						<block v-if="draft==0">
							修改商品
						</block>
						<block v-if="draft==1">
							发布商品
						</block>
					</tn-button>
				</view>
			</view>
		</form>
		<tn-select v-model="sortShow" title="选择商品大类" :list="sortSelect" @confirm="sortConfirm"></tn-select>
		<tn-select v-model="subtypeShow" title="选择商品小类" :list="subtypeSelect" @confirm="subtypeConfirm"></tn-select>
	</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: "",
				sortShow: false,
				subtypeShow: false,
				showContent: true,
				havePay: false,
				uid: 0,
				token: "",
				poster: this.$API.SPmusicpic(),
				isShow: false,
				show: false,
				isPayShop: false,
				name: "",
				sortSelect: [],
				subtypeSelect: [],
				sortList: [],
				sortText: "",
				subtypeText: "",
				subtypeList: [],
				title: "",
				category: "",
				metaList: "",
				imgurl: "",
				num: "",
				sort: 0,
				subtype: 0,
				curHeight: 0,
				shopPrice: "",
				subtypeText: "",
				jpHeight: 0,
				screenHeight: 0,
				postheight: 0,
				poststyle: "",
				readstyle: "",
				isText: 0,
				shopCategoryList: [],

				uploadTime: this.$API.getuploadTime(),
				draft: 0,
				MusicUpload: this.$API.SPstarMusicUpload(),
				musicpic: this.$API.SPmusicpic(),
				videoPoster: this.$API.getVideoPoster(),
				SPimg: this.$API.SPimgs(),
				formData: {},
				//文章表单部分
				title: "",
				category: 1,
				tag: "",
				categoryText: "",
				text: '',
				textRead: "",
				isLoading: false,
				isSpace: false,
				//页面状态
				type: "add",
				id: 0,
				lenght: 0,
				payId: 0,
				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');
			}
			uni.$emit('tOnLazyLoadReachBottom');

		},
		onLoad(res) {
			var that = this;
			localStorage.setItem('isSaveSp', "false");
			that.editInterval = setInterval(function() {
				if (localStorage.getItem('goBack')) {
					localStorage.removeItem('goBack');
					that.back();
				}
			}, 500);
			// #ifdef APP-PLUS || MP
			that.NavBar = this.CustomBar;
			// #endif
			if (res.draft) {
				that.draft = res.draft;
			}
			if (res.type=='edit') {
				that.type = 'edit';
			}else{
				that.type = 'add';
			}
			
			that.setloading();
			var timer = setTimeout(function() {
				that.getShopTypelist();
			}, 500)
		
			if (that.type == 'edit') {
				if (!res.id) {
					uni.showToast({
						title: "参数不能为空",
						icon: 'none'
					});
					that.back();
					return false;
				} else {
					that.id = res.id;
					that.setloading();
					var timer = setTimeout(function() {
						that.getInfo(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: {
			subtypeConfirm(e) {
				var that = this;
				that.subtype = e[0].value;
				that.subtypeText = e[0].label;
			},
			sortConfirm(e) {
				var that = this;
				that.sort = e[0].value;
				that.sortText = e[0].label;
				for (var s in that.sortList) {
					if (that.sortList[s].id == that.sort) {
						that.setSort(that.sortList[s], true);
					}
				}

			},
			imgUpload() {
				let that = this
				uni.chooseImage({
					count: 1,
					sourceType: ['album', 'camera'],
					success: function(res) {
						uni.showLoading({
							title: "加载中"
						});
						const tempFilePaths = res.tempFilePaths;
						const uploadTask = uni.uploadFile({
							url: that.$API.upload(),
							filePath: tempFilePaths[0],
							name: 'file',
							formData: {
								'token': that.token
							},
							success: function(uploadFileRes) {
								setTimeout(function() {
									uni.hideLoading();
								}, 1000);
								var data = JSON.parse(uploadFileRes.data);
								uni.showToast({
									title: data.msg,
									icon: 'none'
								})
								if (data.code == 1) {
									that.imgurl = data.data.url;

								}
							},
							fail: function() {
								setTimeout(function() {
									uni.hideLoading();
								}, 1000);
							}


						});

						uploadTask.onProgressUpdate(function(res) {

						});
					}
				})
			},
			setSubtypeShow() {
				var that = this;
				if (that.sortText != '') {
					that.subtypeShow = true;
				} else {
					uni.showToast({
						title: '请先选择大类',
						icon: 'none',
					});
				}
			},
			previewImage(imageList, image) {
				//预览图片
				uni.previewImage({
					urls: imageList,
					current: image
				});
			},
			getShopTypelist() {
				var that = this;
				var data = {
					"limit": 100,
					"token": that.token,
				};
				that.$Net.request({
					url: that.$API.shopTypeList(),
					data: data,
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					method: "get",
					dataType: 'json',
					success: function(res) {
						if (res.data.code == 1) {
							that.shopTypelist = res.data.data;
							var list = res.data.data;
							var sortList = [];
							for (var i in list) {
								if (list[i].parent == 0) {
									sortList.push(list[i]);
								}
							}
							that.sortList = sortList;

							// Create sortSelect array
							that.sortSelect = sortList.map(item => {
								return {
									value: item.id,
									label: item.name
								};
							});

							if (that.sort > 0) {
								for (var s in sortList) {
									if (sortList[s].id == that.sort) {
										that.setSort(sortList[s], true);
									}
								}
							}
							that.isLoading = true;
							that.setloading();
						}
					},
					fail: function(res) {
						console.log(error);
					}
				});
			},
			setSort(data, noSub) {
				var that = this;
				that.sortShow = false;
				that.sort = data.id;
				that.sortText = data.name;

				if (that.sort != 0) {
					var list = that.shopTypelist;
					var subtypeList = [];
					for (var i in list) {
						if (list[i].parent == that.sort) {
							subtypeList.push(list[i]);
						}
					}
					that.subtypeList = subtypeList;

					// Create subtypeSelect array
					that.subtypeSelect = subtypeList.map(item => {
						return {
							value: item.id,
							label: item.name
						};
					});

					if (!noSub) {
						if (subtypeList.length > 0) {
							that.subtype = subtypeList[0].id;
							that.subtypeText = subtypeList[0].name;
						} else {
							that.subtype = 0;
						}
					} else {
						if (subtypeList.length > 0) {
							for (var s in subtypeList) {
								if (subtypeList[s].id == that.subtype) {
									that.subtypeText = subtypeList[s].name;
								}
							}
						} else {
							that.subtype = 0;
						}
					}
				}
			},
			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.id
				});
			},
			getInfo(id) {
				var that = this;
				var token = "";
				var data = {
					"key": id,
					"token": that.token,
				}

				that.$Net.request({
					url: that.$API.shopInfo(),
					data: data,
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					method: "get",
					dataType: 'json',
					success: function(res) {
						if (res.data.id) {
							that.title = res.data.title;
							that.category = res.data.type;
							that.imgurl = res.data.imgurl;
							that.num = res.data.num;
							that.sort = res.data.sort;
							that.subtype = res.data.subtype;
							that.text = res.data.text;
							that.havePay = true;
							var a = res.data.value;
							var b = res.data.price;
							var c = res.data.vipDiscount;
							var payData = {
								text: a,
								shopPice: b,
								shopDiscount: c
							};

							localStorage.setItem("payId" + res.data.id, JSON.stringify(payData));
							console.log(localStorage.getItem("payId" + res.data.id));
							that.isLoading = true;
							that.setloading();
							if (that.sort > 0) {
								for (var s in that.sortList) {
									that.setSort(that.sortList[s], true);
									if (that.subtype) {
										let subtype = that.shopTypelist.find(item => item.id == that.subtype);
										if (subtype) {
											that.subtypeText = subtype.name;
										}
									}
								}
							}
						}
					},
					fail: function(res) {
						console.log(error);
						uni.showToast({
							title: '网络开小差了哦',
							icon: 'none'
						});
					}

				});
			},

			back() {
				localStorage.removeItem('isSaveSp')
				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() {
				var that = this;
				var type = that.type;
				if (type == "edit") {
					that.$refs.editor.save();
					setTimeout(function() {
						that.updateShop();
					}, 200)
				} else {
					that.$refs.editor.save()
					setTimeout(function() {
						that.addShop();
					}, 200)
				}

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

			},
			onSave(e) {
				var that = this
				that.content = e.html;
			},
			addShop() {
				var that = this;
				if (that.title == "") {
					uni.showToast({
						title: '请输入商品标题',
						icon: 'none'
					});
					return false
				}
				if (that.content == '<p><br></p>' || that.content == '') {
					uni.showToast({
						title: "内容不可为空",
						icon: 'none'
					});
					return false
				}
				if (that.sort == 0 && that.subtype == 0) {
					uni.showToast({
						title: "请选择分类",
						icon: 'none'
					});
					return false
				}
				var text = that.content;
				var isSpace = 0;
				var params = {
					'title': that.title,
					'type': 1,
					'imgurl': that.imgurl,
					'num': that.num,
					'integral': "0",
					'sort': that.sort,
					'subtype': that.subtype,
				}
				if (that.havePay && that.id != '0') {
					var payData = JSON.parse(localStorage.getItem("payId" + that.id));
					if (payData) {
						params.value = payData.text;
						params.price = payData.shopPice;
						params.vipDiscount = payData.shopDiscount;
					}
				} else {
					var payData = JSON.parse(localStorage.getItem("payIdmy"));
					if (payData) {
						params.value = payData.text;
						params.price = payData.shopPice;
						params.vipDiscount = payData.shopDiscount;
					}
				}
				var data = {
					"params": JSON.stringify(that.removeObjectEmptyKey(params)),
					"token": that.token,
					'text': text,
					"isSpace": isSpace,
					"isMd": 0
				}
				that.$Net.request({

					url: that.$API.addShop(),
					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) {
							uni.showToast({
								title: res.data.msg,
								icon: 'none'
							});
							localStorage.removeItem('payIdmy');
							setTimeout(function() {
								that.back();
							}, 1000)
						} else {
							uni.showToast({
								title: res.data.msg,
								icon: 'none'
							});
						}
					},
					fail: function(res) {
						setTimeout(function() {
							uni.hideLoading();
						}, 1000);
						uni.showToast({
							title: "网络开小差了哦",
							icon: 'none'
						})
					},
				})
			},
			removeObjectEmptyKey(json) {
				var value;
				for (var key in json) {
					if (json.hasOwnProperty(key)) {
						value = json[key];
						if (value === undefined || value === '' || value === null) {
							delete json[key]
						}
					}
				}
				return json;
			},
			updateShop() {
				var that = this;
				if (that.title == "") {
					uni.showToast({
						title: '请输入商品标题',
						icon: 'none'
					});
					return false
				}
				if (that.content == '<p><br></p>' || that.content == '') {
					uni.showToast({
						title: "内容不可为空",
						icon: 'none'
					});
					return false
				}
				if (that.sort == 0) {
					uni.showToast({
						title: "请选择大类",
						icon: 'none'
					});
					return false
				}
				var text = that.content;
				var isSpace = 0;
				var params = {
					'id': that.id,
					'title': that.title,
					'type': 1,
					'imgurl': that.imgurl,
					'num': that.num,
					'integral': "0",
					'sort': that.sort,
					'subtype': that.subtype,
				}
				if (that.havePay && that.id != '0') {
					var payData = JSON.parse(localStorage.getItem("payId" + that.id));
					if (payData) {
						params.value = payData.text;
						params.price = payData.shopPice;
						params.vipDiscount = payData.shopDiscount;
					}
				} else {
					var payData = JSON.parse(localStorage.getItem("payIdmy"));
					if (payData) {
						params.value = payData.text;
						params.price = payData.shopPice;
						params.vipDiscount = payData.shopDiscount;
					}
				}
				var data = {
					"params": JSON.stringify(that.removeObjectEmptyKey(params)),
					"token": that.token,
					'text': text,
					"isMd": 0
				}
				that.$Net.request({

					url: that.$API.editShop(),
					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) {
							uni.showToast({
								title: res.data.msg,
								icon: 'none'
							});
							localStorage.setItem('isShopEdit', 'true');
							setTimeout(function() {
								that.back();
							}, 1000)
						} else {
							uni.showToast({
								title: res.data.msg,
								icon: 'none'
							});
						}
					},
					fail: function(res) {
						setTimeout(function() {
							uni.hideLoading();
						}, 1000);
						uni.showToast({
							title: "网络开小差了哦",
							icon: 'none'
						})
					},
				})
			},
			isback() {
				var that = this;

				var isSave = localStorage.getItem('isSaveSp');
				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>