<template>
	<view class='content'>
		<u--form :model="formData" :rules="rules" ref="formData" :labelStyle="{fontSize:'32rpx'}" labelWidth='auto'>
			<view class="card" style="height: 300rpx;"
				@click="navgo(`/pages/product/addGoodDetail/goodsSearch?mer_id=${mer_id}&&type=simple&&formData=${JSON.stringify(formData)}`)">
				<u-form-item label="想卖什么" prop="title">
					<text slot='right' style="font-size:28rpx ; color:#989898 ;">{{value1.length}}/{{maxLength}}</text>
				</u-form-item>
				<u-line></u-line>
				<u--textarea v-model="formData.cate_name" placeholder="请输入内容" :autoHeight='true'
					:maxlength='maxLength'></u--textarea>
			</view>

			<view class="card" style="min-height: 268rpx;">
				<u-form-item label="商品图片" prop="formData.imageList" ref="item1" labelWidth='auto'>
					<text style="font-size:24rpx ; color:#E18C34 ;">上传时应注重真实性、清晰度</text>
				</u-form-item>
				<view class="" style="display: flex;flex-wrap: wrap;">
					<view v-for="(item,index) in formData.imageList" style="margin-right: 20rpx;margin-bottom: 20rpx;">
						<view class="video_list" v-if='vidioTypeList.includes(getSuffix(item))'>
							<view class="video_list_item photo" style="position: relative;">
								<view class="jiao" @click="formData.imageList.splice(index,1)">
									<!-- video标签在app端层级过高 -->
									<!--#ifndef APP-PLUS-->
									<video :src="item"></video>
									<!--#endif-->
									<!--#ifdef APP-PLUS-->
									<img src="https://lihai001.oss-cn-chengdu.aliyuncs.com/public/kk/luzhou/static4/3/video_bg.png"
										style=" width:140rpx"></img>
									<!--#endif-->
									<image src="@/static/images/gban.png" mode="widthFix"></image>
								</view>
								<view style="position: absolute;top: 20rpx;z-index: 99;width: 140rpx;height: 100%;"
									@click="videoshow(index)">
									<view class="videoHover">
									</view>
								</view>
							</view>
						</view>
						<view class="" style="position: relative;" v-else>
							<view class="jiao" @click="formData.imageList.splice(index,1)">
								<image src="@/static/images/gban.png" mode="widthFix">
								</image>
							</view>
							<u--image @click="preViewImg(item,index)" :src="item" :fade="true" duration="450"
								width='140rpx' height='140rpx'></u--image>
						</view>
					</view>
					<view class='uploadimg' @click="show=true">
						<u-icon name="plus" color="#777777"></u-icon>
						<view class="" style="color: #777777;font-size: 20rpx;">
							上传图片/视频
						</view>
					</view>
				</view>
			</view>

			<view class="card">
				<u-form-item label="规格与价格" prop="userInfo.name" ref="item1" border-bottom>
				</u-form-item>
				<u-form-item label="计量单位" prop="userInfo.name" ref="item1" border-bottom>
					<view style="display: flex;" slot='right' @click='showPouple=true'>
						<view style="margin-right: 10rpx;line-height: 25rpx;color:#777777">
							{{formData.attrValue[0].unit_name ||'请选择'}}
						</view>
						<u-icon name="arrow-right" style="margin-right: 30rpx;"></u-icon>
					</view>
				</u-form-item>
				<u-form-item label="零售价格" prop="userInfo.name" ref="item1" border-bottom>
					<u--input inputAlign='right' placeholderStyle="color:#777777" style="width: 300rpx;"
						placeholder="请输入零售价" type='number' v-model="formData.attrValue[0].price"
						slot='right'></u--input>
				</u-form-item>
				<u-form-item v-if='isWholeSale' label="批发价格" prop="userInfo.name" ref="item1" border-bottom>
					<u--input inputAlign='right' placeholderStyle="color:#777777" style="width: 300rpx;"
						placeholder="请输入批发价格" type='number' v-model="formData.attrValue[0].wholesale_price"
						slot='right'></u--input>
				</u-form-item>
				<u-form-item label="商品库存" prop="userInfo.name" ref="item1">
					<u--input inputAlign='right' type='number' placeholderStyle="color:#777777" style="width: 300rpx;"
						placeholder="请输入库存" v-model="formData.attrValue[0].stock" slot='right'></u--input>
				</u-form-item>
			</view>
			<view class="footer">
				<view class="footer-top" @click='goDetail'>
					<text style="margin: 10rpx auto;">
						显示全部<u-icon style="display: inline-block;font-weight: bold;" color="$uni-newTheme-color"
							name="arrow-right"></u-icon>
					</text>
				</view>
				<view class="footer-bottom">
					发布内容越详尽，成单力越高哦~
				</view>
			</view>

			<view class="submit-btn" @click='submit'>
				<u-button text="立即发布获取订单" color="#33BB3C" class="custom-style"></u-button>
			</view>
		</u--form>

		<u-popup :show="showPouple" @close="showPouple=false" @open="showPouple=true" :round="10">
			<view class="RegularFont" style="padding: 42rpx 40rpx">
				<view class="pop-head">
					<text v-if='!showCustom' @click='showPouple=false'>取消</text>
					<text v-else @click='showCustom=false'>
						<u-icon name="arrow-left" size="20"></u-icon>
					</text>
					<text style="font-size:32rpx ;color:#333333 ;">计量单位</text>
					<text v-if='showCustom' @click='addAttr'>确定</text>
					<text v-else></text>
				</view>
				<view style="height: 500rpx;">
					<u-transition :show="!showCustom" mode="slide-right">
						<view class="goods-leval">
							<view class="goods-leval-li" v-for='(item,index) in attrList' :key='index'
								@click='choseAttr(item)'>
								{{item}}
							</view>
							<view class="goods-leval-li " style="display: flex;color:#38BE41 ;"
								@click="showCustom=true">
								<u-icon name="plus" color="#38BE41" style='margin-right: 8rpx;'></u-icon> 自定义
							</view>
						</view>
					</u-transition>
					<u-transition :show="showCustom" mode="slide-left">
						<view class="transition">
							<u--textarea v-model="selfAttr" placeholder="请输入计量单位"></u--textarea>
						</view>
					</u-transition>
				</view>
			</view>
		</u-popup>




		<u-picker :show="show" :columns="columns" confirmColor='#33BB3C' @close='show=false' @confirm='choseMedia'
			@cancel='show=false'></u-picker>

		<view v-if="showVideo" class="video-count">
			<video id="myVideo" class="videoLink" autoplay loop muted :src="formData.imageList[videoIndex]"></video>
		</view>
		<view class='mask' catchtouchmove="true" :hidden='showVideo==false' @tap="showVideo=false"></view>
	</view>


</template>

<script>
	import {
		productCreate,
		productUpdate,
		productDetail
	} from '@/api/product.js';
	import uploadImgVideo from "./components/uploadImgVideo.vue"
	import {
		TOKENNAME,
		HTTP_REQUEST_URL
	} from '@/config/app.js';
	import store from 'store';
	import {
		Toast,
		Modal
	} from "@/libs/uniApi.js";
	export default {
		components: {
			uploadImgVideo,
		},
		data() {
			return {
				videoIndex: 0,
				showVideo: false,
				upload_max: 100,
				uploadUrl: `${HTTP_REQUEST_URL}/api/upload/video`,
				columns: [
					['图片', '视频', ]
				],
				isWholeSale: false, //批发商
				show: false, //选择图片还是视屏
				showCustom: false, //计量单位自定义 
				mer_id: "",
				vidioTypeList: ['mp4', 'avi', 'mov', 'wmv', 'mkv', 'flv', 'mpeg', '3gp', 'webm'],
				attrList: ['斤',
					"公斤",
					"吨",
					"升",
					"个",
					"台",
					"瓶",
					"桶",
					"箱",
					"袋",
					"包",
					"盒",
					"件",
					"罐"
				],
				selfAttr: "",
				formData: {
					"store_name": "",
					"imageList": [

					],
					attr: [{
						detail: [],
						value: ""
					}, ],
					"attrValue": [{
						detail: {
							规格名: '',
						},
						"price": "",
						"unit_name": "",
						"wholesale_unit_name": "",
						"wholesale_price": '',
						"cost": "",
						"stock": "",
						sku: '',
						"ot_price": "",
						"procure_price": "",
						"bar_code": "",
						"weight": "",
						"extension_one": "",
						"extension_two": "",
						uuid: "",
						volume: "",
						"is_use": 0,
					}],
					"cate_name": "",
					"unit_name": "",
					"cate_id": '',
					"mer_cate_id": [

					],
					"mer_cate_name": "",
					"spec_type": "0",

					"specifica": "",
					"delivery_way": [

					],
					"delivery_free": "1",
					"temp_id": "",
					"tempName": "",
					"once_min_count": "",
					"image": "",
					"slider_image": [
						""
					],
					"is_good": 0,
					"is_gift_bag": 0,
					"sort": "",
					"once_count": "",
					"video_link": "",
					"content": {
						"title": "",
						"image": []
					},
					"stock": "",
					product_attribute: {
						address: "",
						leval: "",
						pack: "",
						attr: [{
							label: "",
							value: ''
						}]
					}
				},
				showPouple: false,
				fileList6: [],
				value1: "",
				value2: "",
				value3: "",
				value4: "",
				maxLength: 30,
				showSex: false,
				rules: {
					"formData.imageList": [{
						validator: (rule, value, callback) => {
							return this.formData.imageList.length >= 2
						},
						message: '请至少上传2张图片',
						trigger: ['change', 'blur'],
					}]

				},
			};
		},

		methods: {
			deleteImage(index) {
				// this.addGoodsSecoundData.video_link = '';
			},
			videoshow(index) {
				this.videoIndex = index
				console.log('show')
				this.showVideo = true
				this.videoContext = uni.createVideoContext('myVideo', this);
				this.$nextTick(() => {
					this.videoContext.play();
				})
			},
			getSuffix(url) {
				const str = url;
				const lastIndex = str.lastIndexOf(".");
				if (lastIndex !== -1) {
					const extension = str.substring(lastIndex + 1);
					return extension
				} else {
					console.log("字符串中没有找到点号。");
				}
			},
			choseMedia(e) {
				console.log(e.value)
				this.show = false
				if (e.value[0] == '图片') {
					this.handleChooseImage()

				} else {
					this.uploadVideo()

				}

			},
			// 选择图片
			handleChooseImage() {
				let that = this;
				that.$util.uploadImages({
					count: 6,
					url: 'upload/image'
				}, function(res) {
					that.formData.imageList.push(res.data.path);
				});
			},
			// 上传视频
			uploadVideo() {
				let that = this
				uni.chooseVideo({
					sourceType: ['camera', 'album'],
					limit: 6,
					success: res => {
						uni.showLoading({
							title: '正在上传中。。。'
						});
						if (Math.ceil(res.size / 1024) < this.upload_max * 1024) {
							uni.uploadFile({
								url: this.uploadUrl, //仅为示例，非真实的接口地址
								filePath: res.tempFilePath,
								name: 'file',
								header: {
									// #ifdef MP
									'Content-Type': 'multipart/form-data',
									// #endif
									[TOKENNAME]: 'Bearer ' + store.state.app.token
								},
								success: uploadFileRes => {
									uni.hideLoading();
									let data = JSON.parse(uploadFileRes.data);
									that.formData.imageList.push(data.data.src.replace(/\\/g, ""))
								},
								complete: a => {
									// console.log(a);
								}
							});
						} else {
							uni.showModal({
								title: '提示',
								content: `视频超出限制${this.upload_max}MB,已过滤`
							});
						}
					},
					fail: err => {
						// 取消上传也会出现弹框
						// uni.showModal({
						//   content: JSON.stringify(err)
						// });
						console.log(err)
					}
				});
			},

			test() {
				uni.chooseFile({
					count: 6, //默认100
					extension: ['.zip', '.doc'],
					success: function(res) {
						console.log(JSON.stringify(res.tempFilePaths));
					}
				});

			},

			choseAttr(name) {
				this.formData.attrValue[0].unit_name = name;
				this.formData.attrValue[0].wholesale_unit_name = name;
				this.showPouple = false
			},
			addAttr() {
				if (!this.selfAttr) return;
				this.attrList.push(this.selfAttr)
				this.formData.attrValue[0].unit_name = this.attrList[this.attrList.length - 1]
				this.formData.attrValue[0].wholesale_unit_name = this.attrList[this.attrList.length - 1]
				this.selfAttr = ''
				this.showCustom = false
				this.showPouple = false
			},

			goDetail() {
				uni.redirectTo({
					url: `/pages/product/addGoodDetail/addGoodDetail?mer_id=${this.mer_id}&&formData=${JSON.stringify(this.formData)}&&showSet=${false}`
				})
			},
			navgo(url) {
				uni.navigateTo({
					url
				})
			},
			preViewImg(url, index) {
				let that = this
				uni.previewImage({
					urls: [url],

				});

			},
			handAdd() {
				let data = uni.$u.deepClone(this.formData)
				data.image = data.imageList.find(item => {
					return !this.vidioTypeList.includes(this.getSuffix(item))
				})
				data.slider_image = this.formData.imageList.filter((item, index) => index != 0)
				data.store_name = data.cate_name
				productCreate(this.mer_id, data)
					.then(res => {
						Modal('提交成功', '点击确定，前往商品列表页面').then(() => {
							if (this.import == 1) {
								uni.$emit('importAttrValueOK', this.setFormData.import_id);
								uni.navigateBack();
							} else uni.redirectTo({
								url: `/pages/product/list/index?mer_id=${this.mer_id}&type=6`
							})
						}).catch(() => {
							uni.redirectTo({
								url: `/pages/product/list/index?mer_id=${this.mer_id}&type=2`
							})
						})
					})
					.catch(rej => {
						// Toast(rej);
					});
			},
			async submit() {
				this.$refs.formData.validate().then(res => {
					this.handAdd()
				}).catch(errors => {
					console.log(errors)
					uni.$u.toast(errors[0].message)
				})

			}
		},
		onLoad(option) {
			this.mer_id = option.mer_id
			this.isWholeSale = this.$store.state.app.userInfo?.mer_info?.wholesale == 2;

			if (option.formData) {
				this.formData = JSON.parse(option.formData)
			}
			if (option.data) {
				this.formData.cate_name = JSON.parse(option.data).label.includes('--') ? JSON.parse(option.data).label
					.split('--')[1] : JSON.parse(option.data).label;
				this.formData.cate_id = JSON.parse(option.data).value
			}
		},
	};
</script>
<style lang='scss'>
	.content {
		width: 100vw;
		min-height: 100vh;
		background-color: #F1F1F1;
		box-sizing: border-box;
		padding: 20rpx;
		padding-bottom: 200rpx;
		font-family: PingFangRegular;


	}

	.card {
		background-color: white;
		padding: 28rpx 30rpx;
		border-radius: 12rpx;
		margin-bottom: 30rpx;
	}

	.uploadimg {
		width: 140rpx;
		height: 140rpx;
		border-radius: 16rpx;
		border: 2rpx solid #F1F1F1;
		display: flex;
		flex-direction: column;
		justify-content: space-around;
		align-items: center;
		box-sizing: border-box;
		/* padding: 20rpx 0; */
		/* margin-left: 20rpx; */

	}


	.footer {
		margin-top: 130rpx;
		text-align: center;


		.footer-top {
			color: $uni-newTheme-color;
			display: flex;
			font-weight: bold;
			align-items: center;
		}

		.footer-bottom {
			font-size: 28rpx;
			color: #989898;

		}

	}

	.pop-head {
		display: flex;
		justify-content: space-between;
		color: #20B128;
		margin-bottom: 42rpx;
	}

	.goods-leval {
		display: flex;
		flex-wrap: wrap;
		overflow-y: auto;

		.goods-leval-li {
			margin-right: 20rpx;
			padding: 10rpx 40rpx;
			height: 60rpx;
			margin-bottom: 20rpx;
			border-radius: 36rpx 36rpx 36rpx 36rpx;
			background-color: #F1F1F1;
		}

		.act {
			color: #20B128;
			background-color: #E8F7E9;
			border: 1px solid #20B128;


		}
	}

	.submit-btn {
		position: fixed;
		bottom: 50rpx;
		left: 50%;
		transform: translate(-50%, 0);
		width: 670rpx;
		border-radius: 40rpx;
		overflow: hidden;
	}

	.jiao {
		image {
			position: absolute;
			top: -14rpx;
			right: -14rpx;
			width: 50rpx;
			height: 50rpx;
			border-radius: 50%;
			padding: 8rpx;
			z-index: 2;
		}

		video {
			width: 140rpx;
			height: 140rpx;
		}
	}

	.preview_video {
		position: absolute;
		background-color: red;

	}

	.content_list_video {
		min-height: 154rpx;
		padding: 23rpx 10rpx;
		display: flex;
		justify-content: space-between;

		.content_list_video_title {
			padding-top: 10rpx;
		}

		.video_list {
			flex: 1;
			display: flex;
			justify-content: flex-end;
			flex-wrap: wrap;

		}
	}

	.video-count {
		position: fixed;
		width: 600rpx;
		height: 500rpx;
		top: 50%;
		left: 50%;
		margin-left: -300rpx;
		margin-top: -250rpx;
		z-index: 100;
		display: flex;
		align-items: center;
		justify-content: center;

		.videoLink {
			width: 600rpx;
			height: 500rpx;
		}
	}

	.video-text {
		color: red;
		font-size: 24rpx;
		text-align: center;
		/* position: absolute; */

	}
</style>