<template>
	<gui-page>
		<view slot="gBody" v-if="goods">
			<view style="position: fixed;top:0;z-index: 99;height: 80rpx;overflow: hidden;width: 100%;">
				<image src="/static/3334.png" style="width: 100%;z-index: 8;margin-top: 0;">
				</image>
				<view
					style="position: fixed;top:0;z-index: 98;padding: 25rpx 20rpx;font-size: 32rpx;font-weight: bold;">
					<text class="gui-icons " style="color: #fff;" @click="fanhui">&#xe600; 编辑商品</text>
				</view>
			</view>
			<view style="position: relative;">
				<view style="width: 100%;height: 80rpx;background-color: #fff;">
				</view>
				<view style="padding: 15rpx;">
					<form @submit="submit">
						<view style="margin: 20rpx 0;">
							<text class="gui-h6  gui-bold">商品信息</text>
						</view>
						<view class="gui-padding" style="background-color: #fff;border-radius: 10rpx;">
							<view class="gui-form-item gui-border-b">
								<text class="gui-form-label"><text style="color: red;">*</text>商品名称</text>
								<view class="gui-form-body">
									<input type="text" class="gui-form-input" name="goods_name"
										v-model="goods.goods_name" style="text-align: right;" placeholder="请输入商品名称" />
								</view>
							</view>
							<view class="gui-form-item gui-border-b">
								<text class="gui-form-label"><text style="color: red;">*</text>商品分类</text>
								<view class="gui-form-body" style="text-align: right;">
									<picker mode="selector" range-key="name" :range="CategoryList"
										@change="pickerCategory">
										<text class="gui-text gui-secondary-text"
											v-if="CategoryIndex > -1">{{CategoryList[CategoryIndex].name}}</text>
										<text class="gui-text gui-secondary-text" v-else>请选择商品分类</text>
									</picker>
								</view>
								<text class="gui-form-icon gui-icons gui-text-center gui-color-gray">&#xe601;</text>
							</view>
							<view class="gui-form-item gui-border-b">
								<text class="gui-form-label"><text style="color: red;">*</text>商品价格</text>
								<view class="gui-form-body">
									<input type="number" class="gui-form-input" name="goods_price"
										v-model="goods.goods_price_min" style="text-align: right;"
										placeholder="请输入商品价格" />
								</view>
							</view>
							<view class="gui-form-item gui-border-b">
								<text class="gui-form-label" style="width: 200rpx;">商品划线价格</text>
								<view class="gui-form-body">
									<input type="number" class="gui-form-input" name="line_price"
										v-model="goods.line_price_min" style="text-align: right;"
										placeholder="请输入商品划线价格" />
								</view>
							</view>
							<view class="gui-form-item gui-border-b">
								<text class="gui-form-label"><text style="color: red;">*</text>库存数量</text>
								<view class="gui-form-body">
									<input type="number" class="gui-form-input" name="stock_num"
										v-model="goods.stock_total" style="text-align: right;" placeholder="请输入库存数量" />
								</view>
							</view>
							<view class="gui-form-item">
								<text class="gui-form-label"><text style="color: red;">*</text>商品主图</text>
							</view>
							<view class="image-list">
								<view class="image-preview" v-for="(image, imageIndex) in formData[0].imageList"
									:key="imageIndex">
									<text class="image-delete iconfont icon-shanchu"
										@click="deleteImage(0, imageIndex)"></text>
									<image class="image" mode="aspectFill" :src="image.path"></image>
								</view>
								<view v-if="!formData[0].imageList || formData[0].imageList.length < maxImageLength"
									class="image-picker" @click="chooseImage(0)">
									<text class="choose-icon iconfont icon-camera"></text>
									<text class="choose-text">上传图片</text>
								</view>
							</view>
							<view style="height: 20rpx;"></view>
							<view class="gui-form-item gui-border-b">
								<text class="gui-form-label" style="width: 200rpx;"><text
										style="color: red;">*</text>活动结束时间</text>
								<view class="gui-form-body" style="text-align: right;">
									<gui-datetime @confirm="confirm1" :value="demo1Val" @change="chang1"
										:isSecond="false" :isMinute="false" :isTime="false">
										{{demo1Val ? demo1Val:'请选择活动结束时间'}}
									</gui-datetime>
								</view>
							</view>
						</view>

						<view style="margin: 20rpx 0 "
							class="gui-flex gui-rows gui-nowrap gui-align-items-center gui-space-between">
							<text class="gui-h6  gui-bold"><text style="color: red;">*</text>购买须知</text>
							<text style="font-size: 24rpx;color: #9E1A91 ;" @click="bianjiqi('gmxz')">编辑购买须知</text>
						</view>
						<view class="gui-padding"
							style="background-color: #fff;border-radius: 10rpx;min-height: 200rpx;max-height: 400rpx;overflow: auto;">
							<mp-html :content="gmxz" />
						</view>
						<view style="margin: 20rpx 0 "
							class="gui-flex gui-rows gui-nowrap gui-align-items-center gui-space-between">
							<text class="gui-h6  gui-bold"><text style="color: red;">*</text>商品详情</text>
							<text style="font-size: 24rpx;color: #9E1A91 ;" @click="bianjiqi('spxq')">编辑商品详情</text>
						</view>
						<view class="gui-padding"
							style="background-color: #fff;border-radius: 10rpx;min-height: 200rpx;max-height: 400rpx;overflow: auto;">
							<mp-html :content="spxq" />
						</view>

						<view class="gui-margin-top" style="padding: 0 120rpx;">
							<gui-radio @change="radioChange" :checked="radiochecked">
								<text class="gui-text " style="color: #9e9e9e;">我已阅读并同意<text style="color: #b53190;"
										@click="onagreement">《商家入驻协议》</text></text>
							</gui-radio>
						</view>



						<view class=" gui-flex gui-rows gui-nowrap gui-justify-content-end">
							<button type="default" class="gui-button gui-bg-blue" style="width: 90%;text-align: center;padding: 0rpx 0;text-align: center;background: linear-gradient(to bottom, #90178b, #590b6e);margin: 80rpx auto 0;color: #fff;border-radius: 40rpx;"
								formType="submit">
								<text class="gui-icons gui-color-white gui-button-text">提交</text>
							</button>
							
						</view>
						<view style="height:80rpx;"></view>
					</form>
				</view>
				<gui-modal ref="guimodal" width="660rpx" :isCloseBtn="false" title="商家协议" :canCloseByShade='false'>
					<template v-slot:content>
						<scroll-view scroll-y :style="{height:contentHeight+'px'}"
							class="gui-bg-gray gui-dark-bg-level-2">
							<mp-html :content="ArticleDetail.content" />
						</scroll-view>
					</template>
					<template v-slot:btns>
						<view class="gui-flex gui-row gui-space-between">
							<view hover-class="gui-tap" class="modal-btns gui-flex1">
								<text class="modal-btns gui-primary-color" @tap="confirm">同意</text>
							</view>
						</view>
					</template>
				</gui-modal>
			</view>
		</view>
	</gui-page>
</template>
<script>
	var graceJS = require('@/GraceUI5/js/grace.js');
	import * as ArticleApi from '@/api/article'
	import * as UploadApi from '@/api/upload'
	import * as GoodsApi from '@/api/goods/index.js'
	import * as CategoryApi from '@/api/category'
	const maxImageLength = 6
	export default {

		data() {
			return {
				contentHeight: 300,
				// 表单数据
				formData: [{
					imageList: [],
					uploaded: []
				}],
				// 最大图片数量
				maxImageLength,
				textareaVal: '', // 文本内容
				maxWords: 100, // 最多字符数
				textareatimer: null, // 延迟记录
				radiochecked: false,
				ArticleDetail: '',
				CategoryList: '',
				CategoryIndex: '-1',
				spxq: '',
				gmxz: '',
				demo1Val: '',
				disabled: false,
				goodsId: 0,
				goods: ''
			}
		},
		watch: {
			textareaVal: function(val) {
				if (this.textareatimer != null) {
					clearTimeout(this.textareatimer);
				}
				this.textareatimer = setTimeout(() => {
					if (val.length > this.maxWords) {
						this.textareaVal = this.textareaVal.substr(0, this.maxWords);
					}
				}, 200);
			}
		},
		mounted: function() {
			var systemInfo = graceJS.system();
			this.contentHeight = systemInfo.windowHeight * 0.65;
		},

		/**
		 * 生命周期函数--监听页面加载
		 */
		onLoad(options) {
			this.goodsId = options.goodsId
			this.getArticleDetail()
			this.getCategory()
			
		},


		methods: {
			getGoods() {
				let _this = this
				GoodsApi.shopdetail(_this.goodsId)
					.then(result => {
						_this.goods = result.data.detail
						_this.spxq = _this.goods.content
						_this.gmxz = _this.goods.contents
						_this.demo1Val = _this.goods.become_time


						_this.CategoryList.forEach(function(element, index) {
							if (element.category_id == _this.goods.category_id) {
								_this.CategoryIndex = index
							}
						});

						_this.goods.goods_images.forEach(function(element, index) {
							uni.downloadFile({
								url: element.preview_url, // 图片的网络地址
								success: (res) => {
									if (res.statusCode === 200) {
										_this.formData[0]['imageList'].push({
											path: res.tempFilePath
										})
									}
								},
							});
							// _this.formData[0]['imageList'].push({
							// 	path: element.preview_url
							// })
							// _this.formData[0]['uploaded'].push(element.file_id)
						});

					})
			},
			submit: function(e) {
				const app = this
				var fromData = e.detail.value;
				fromData.category_id = app.CategoryList[app.CategoryIndex].category_id
				fromData.become_time = app.demo1Val
				fromData.content = app.spxq
				fromData.contents = app.gmxz
				if (!fromData['goods_name']) {
					app.$toast('请填写商品名称')
					return false
				}
				if (app.CategoryIndex < 0) {
					app.$toast('请选择商品分类')
					return false
				}
				if (!fromData['goods_price']) {
					app.$toast('请填写商品价格')
					return false
				}
				if (!fromData['stock_num']) {
					app.$toast('请填写库存数量')
					return false
				}
				if (!app.demo1Val) {
					app.$toast('请选择活动结束时间')
					return false
				}
				if (!app.gmxz) {
					app.$toast('请编辑购买须知')
					return false
				}
				if (!app.spxq) {
					app.$toast('请编辑商品详情')
					return false
				}
				if (!app.radiochecked) {
					app.$toast('请阅读协议')
					return false
				}
				const imagesLength = app.getImagesLength()
				if (imagesLength == 0) {
					app.$toast('请上传商品图片')
					return false
				}
				// 判断是否重复提交
				if (app.disabled === true) return false
				// 按钮禁用
				app.disabled = true
				// 判断是否需要上传图片

				if (imagesLength > 0) {
					app.uploadFile()
						.then(() => {
							app.onSubmit(fromData)
						})
						.catch(err => {
							app.disabled = false
							if (err.statusCode !== 0) {
								app.$toast(err.errMsg)
							}
							console.log('err', err)
						})
				} else {
					app.onSubmit(fromData)
				}
			},
			getImagesLength() {
				const {
					formData
				} = this
				let imagesLength = 0
				formData.forEach(item => {
					imagesLength += item.imageList.length
				})
				return imagesLength
			},

			// 提交到后端
			onSubmit(fromData) {
				const app = this
				fromData.uploaded = this.formData[0].uploaded
				GoodsApi.edit(app.goodsId,fromData)
					.then(result => {
						app.$toast(result.message)
						setTimeout(() => {
							app.disabled = false
							uni.navigateBack()
						}, 1500)
					})
					.catch(err => app.disabled = false)
			},

			// 上传图片
			uploadFile() {
				const app = this
				const {
					formData
				} = app
				// 整理上传文件路径
				const files = []
				formData.forEach((item, index) => {
					if (item.imageList.length) {
						const images = item.imageList.map(image => image)
						files.push({
							formDataIndex: index,
							images
						})
					}
				})
				// 批量上传
				return new Promise((resolve, reject) => {
					Promise.all(files.map((file, index) => {
							return new Promise((resolve, reject) => {
								UploadApi.image(file.images)
									.then(fileIds => {
										app.formData[index].uploaded = fileIds
										resolve(fileIds)
									})
									.catch(reject)
							})
						}))
						.then(resolve, reject)
				})
			},

			chang1: function(e) {
				console.log(e);
			},
			confirm1: function(res) {
				this.demo1Val = res[0] + '-' + res[1] + '-' + res[2];
			},
			pickerCategory(e) {
				this.CategoryIndex = e.detail.value;
			},
			getCategory() {
				CategoryApi.shoplist()
					.then(result => {
						this.CategoryList = result.data.list
						this.getGoods()
					})
			},
			bianjiqi(type) {
				uni.navigateTo({
					url: './editor?type=' + type + '&goodsId=' + this.goods.goods_id
				})
			},
			confirm: function() {
				// 客户点击确认按钮后的逻辑请在此处实现
				this.$refs.guimodal.close();
				this.radiochecked = true
			},
			getArticleDetail() {
				const app = this
				ArticleApi.detail(3)
					.then(result => {
						app.ArticleDetail = result.data.detail
					})


			},
			radioChange(e) {
				this.radiochecked = !this.radiochecked
			},
			onagreement() {
				this.$refs.guimodal.open();
			},
			// 选择图片
			chooseImage(index) {
				const app = this
				const oldImageList = app.formData[0].imageList
				// 选择图片
				uni.chooseImage({
					count: maxImageLength - oldImageList.length,
					sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
					success({
						tempFiles
					}) {
						// tempFiles = [{path:'xxx', size:100}]
						console.log(tempFiles)
						app.formData[0].imageList = oldImageList.concat(tempFiles)
					}
				});
			},

			// 删除图片
			deleteImage(index, imageIndex) {
				this.formData[index].imageList.splice(imageIndex, 1)
			},

			fanhui() {
				uni.navigateBack()
			},

		},


	}
</script>

<style>
	page {
		background-color: #f4f4f4;
	}
</style>
<style scoped>
	.gui-step-item {
		width: 130rpx;
	}

	.form-add-footer-btns {
		padding: 0 38rpx;
		font-size: 30rpx;
		line-height: 100rpx;
	}

	.modal-btns {
		line-height: 100rpx;
		height: 100rpx;
		font-size: 35rpx;
		text-align: center;
		width: 320rpx;
	}
</style>
<style lang="scss" scoped>
	.image-list {
		margin-top: 20rpx;
		margin-bottom: -20rpx;

		&:after {
			clear: both;
			content: " ";
			display: table;
		}

		.image {
			display: block;
			width: 100%;
			height: 100%;
		}

		.image-picker,
		.image-preview {
			width: 184rpx;
			height: 184rpx;
			margin-right: 30rpx;
			margin-bottom: 30rpx;
			float: left;

			&:nth-child(3n+0) {
				margin-right: 0;
			}
		}

		.image-picker {
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			border: 1rpx dashed #ccc;
			color: #ccc;

			.choose-icon {
				font-size: 48rpx;
				margin-bottom: 6rpx;
			}

			.choose-text {
				font-size: 24rpx;
			}
		}

		.image-preview {
			position: relative;

			.image-delete {
				position: absolute;
				top: -15rpx;
				right: -15rpx;
				height: 42rpx;
				width: 42rpx;
				background: rgba(0, 0, 0, 0.64);
				border-radius: 50%;
				color: #fff;
				font-weight: bolder;
				font-size: 22rpx;
				z-index: 10;
				display: flex;
				justify-content: center;
				align-items: center;
			}
		}
	}
</style>