<template>
	<view class="pages">				
		<form @submit="formSubmit" @reset="formReset">
			<view class="form-item-type nomal-top">				
				<view class="form-item">
					<view class="form-item-til">类目</view>
					<view class="form-item-con">
						<input type="text" disabled placeholder="商品类目" v-model="params.type" value="" />
					</view>
				</view>
			<!-- 	<view class="form-item arrow">
					<view class="form-item-til">地理位置</view>
					<view class="form-item-con" @click="chooseaddr">
						<input type="text" placeholder="请选择地理位置" v-model="params.myposition" value="" />
					</view>
				</view>	 -->			
			</view>
			<view class="form-item-type">
				<view class="form-item">
					<view class="form-item-til">标题</view>
					<view class="form-item-con">
						<input type="text" placeholder="请输入发布产品标题" v-model="params.title" value="" />
					</view>
				</view>
				<view class="form-item">
					<view class="form-item-til">品牌</view>
					<view class="form-item-con">
						<input type="text" placeholder="请输入品牌" v-model="params.brand" value="" />
					</view>
				</view>
				<view class="form-item">
					<view class="form-item-til">零售价</view>
					<view class="form-item-con">
						<input type="text" placeholder="请输入零售价" v-model="params.price" value="" />
					</view>
				</view>
				<view class="form-item">
					<view class="form-item-til">供应商</view>
					<view class="form-item-con">
						<input type="text" disabled placeholder="" v-model="params.supplier" value="" />
					</view>
				</view>
				<view class="form-item arrow" @click="openplaceoforigin">
					<view class="form-item-til">生产地</view>
					<view class="form-item-con">
						<input type="text" disabled="disabled" placeholder="" v-model="params.placeoforigin" value="" />
					</view>
				</view>
				<view class="form-item arrow" @click="openspecifications">
					<view class="form-item-til">规格</view>
					<view class="form-item-con">
						<text v-for="(item,index) in params.specifications">{{item}},</text>
						<!-- <input type="text" placeholder="" v-model="params.specifications" value="" /> -->
					</view>
				</view>
				<view class="form-item">
					<view class="form-item-til">保质期</view>
					<view class="form-item-con">
						<input type="text" placeholder="请输入保质期" v-model="params.shelflife" value="" />
					</view>
				</view>
				<view class="form-item">
					<view class="form-item-til">生产日期</view>
					<view class="form-item-con">
						<picker mode="date" :value="params.date" :start="startDate" :end="endDate" @change="bindDateChange">
							<view class="uni-input">{{params.date}}</view>
						</picker>
					<!-- <input type="text" placeholder="请输入生产日期" v-model="params.productiondate" value="" /> -->
					</view>
				</view>
				<view class="form-item">
					<view class="form-item-til">包装</view>
					<view class="form-item-con">
						<input type="text" placeholder="请输入包装" v-model="params.packaging" value="" />
					</view>
				</view>
				<view class="form-item">
					<view class="form-item-til">标签</view>
					<view class="form-item-con">
						<input type="text" placeholder="请输入标签，用逗号隔开" v-model="params.productlabel" value="" />
					</view>
				</view>
			</view>
			<view class="form-item upfile">
				<view class="form-item-til">图片视频</view>
				<view class="form-item-con">					
					<view class="form-item-chooseIMGs-wrap">
						<image v-for="(item,index) in params.media" :key="index" :src="item" class="choosedIMG" ></image>
					</view>
					<view class="chooseIMG-btn">
						<image class="chooseIMG-btn-img" @click="chooseimg" src="/static/img/icon-upload.png"></image>
					</view>					
				</view>				
			</view>
		</form>
		<view class="bottom-btn-wrap">
			<button class="bottom-btn" @click="publish" type="primary">发布</button>
		</view>
		<!-- 页面显示结束 下面是隐藏内容 -->
		<!-- 供应商开始 -->
		<!-- <view class="supplier-page fix-content translate" :class="{ 'open': supplieropen }" >
			<view class="search-wrap search-left-color">
				<view class="search">
					<view class="searchTxt">
						<uni-search-bar placeholder="搜索供应商关键词" @confirm="searchsupplier" @input="searchsupplier" ></uni-search-bar>
					</view>
				</view>	
			</view>
			<view class="simplepage-wrap">
				<mescroll-body ref="mescrollRef0" @init="mescrollInit" @down="downCallback" @up="upCallback" :down="downOption" :up="upOption">
					<view>
						<view v-for="(item,index) in supplierlist" :key="index" @click="supplierclick(item)" class="simplepage-item">{{item}}</view>					
					</view>	 					
				</mescroll-body>
			</view>
		</view> -->
		<!-- 供应商结束 -->
		<!-- 产地开始 -->
		<view class="placeoforigin-page fix-content translate" :class="{ 'open': placeoforiginopen }" >
			<view class="search-wrap search-left-color">
				<view class="search">
					<view class="searchTxt">
						<uni-search-bar placeholder="搜索产地关键词" @confirm="searchplace" @input="searchplace" ></uni-search-bar>
					</view>
				</view>	
			</view>
			<!-- 搜索 结束 -->
			<scroll-view class="simplepage-wrap" scroll-y="true">
				<view v-for="(item,index) in placeoforiginlist" :key="index" @click="placeoforiginclick(item.detailAddress)" class="simplepage-item">{{item.detailAddress}}</view>
			</scroll-view>
		</view>
		<!-- 产地结束 -->
		<!-- 规格开始 -->
		<view class="specifications-page fix-content translate" :class="{ 'open': specificationsopen }" >
			<view class="specifications-wrap wrap">
				 <checkbox-group @change="checkboxChange">
					<label  v-for="(item,index) in specificationslist" :key="index" class="checkbox-style" >
						<checkbox :value="item.value" :checked="item.checked"   />{{item.name}}
					</label>
				</checkbox-group>
				<view class="pecifications-btn-wrap">
					<button type="default" class="big-btn big-btn-hollow" @click="resetcheckbox">重置</button>
					<button type="default" class="big-btn primary" @click="specificationsclick">确定</button>
				</view>
			</view>
		</view>
		<!-- 规格结束 -->
	</view>
</template>

<script>
	// 引入mescroll-mixins.js
	import MescrollMixin from "@/components/mescroll-uni/mescroll-mixins.js";	
	// 引入mescroll-body组件 (如已在main.js注册全局组件,则省略此步骤)
	import MescrollBody from "@/components/mescroll-uni/mescroll-body.vue"; // 注意.vue后缀不能省
	
	import uniSearchBar from '@/components/uni-search-bar/uni-search-bar.vue';
	import { bus } from '../../utils/bus.js';
	export default {
		mixins: [MescrollMixin], // 使用mixin
		components: {
			MescrollBody,
			uniSearchBar,
			
		
		},
		data() {
			const currentDate = this.getDate({
				format: true
			})
			return {				
				mescroll: null, // mescroll实例对象 (此行可删,mixins已默认)
				// 下拉刷新的配置(可选, 绝大部分情况无需配置)
				downOption: { 
					// ...
				},
				// 上拉加载的配置(可选, 绝大部分情况无需配置)
				upOption: {
					page: {
						size: 10 // 每页数据的数量,默认10
					},
					noMoreSize: 5, // 配置列表的总数量要大于等于5条才显示'-- END --'的提示
					empty: {
						tip: '暂无相关数据'
					}
				},
				params: {
					token: '',
					type:'',
					myposition:'',					
					title:'',
					brand:'',
					price:'',
					supplier:'默认的供应商',//供应商
					placeoforigin:'',//产地
					specifications:[],//规格
					shelflife:'',//保质期					
					date: currentDate,//生产日期 // productiondate:'',//生产日期
					packaging:'',//包装
					productlabel:'',//标签
					media:[],//图片视频
				},
				//表单检查结果
				checkStatus:false,
				//供应商
				supplieropen:false,
				supplierlist:[],
				// 产地
				placeoforiginopen:false,
				placeoforiginlist:[],
				places:[],//临时暂存
				// 规格
				specificationsopen:false,
				specificationslist:[
					{value: '500g/提(250g/盒*2)',name: '500g/提(250g/盒*2)',checked: false},
					{value: '10g/罐',name: '10g/罐',checked: false},
					{value: '30g/盒',name: '30g/盒',checked: false},
					{value: '150g/盒',name: '150g/盒',checked: false},
					{value: '30g/盒(1.5g*20瓶)',name: '30g/盒(1.5g*20瓶)',checked: false},
				],
				backtyep:1,

			}
		},
		onShow() {
			uni.hideTabBar();
			let serf = this;
			//检查登录,获取token
			// let loginRes = this.checkLogin('/pages/publish/publish', '2');
			// if (!loginRes) {
			// 	return false;
			// }
			// serf.params.token = loginRes[0];
		},
		onHide() {
			uni.showTabBar()
		},
		onLoad(option) {
			let self = this;
			if(Object.keys(bus.data).length>0){
				console.log('bus.data',bus.data)
				this.params.type = bus.data.name;
				// console.log(this.params.type);
			};
			// console.log(option);
			// this.params.type = option.type;
			
			uni.getStorage({
				key:'token',
				success: function (res) {
					self.params.token = res.data;
				   // console.log(res.data);
				}
			});
			uni.getStorage({
				key:'tokenhead',
				success: function (res) {
					self.params.tokenhead = res.data;
				   // console.log(res.data);
				}
			});
			
			//供应商详情
			let thetoken = this.params.tokenhead+this.params.token;
			this.$api.http.get(this.config.apiBaseurl+'/company/cp/detail',{header: {Authorization:thetoken},params:{compId:72}}).then(res =>{
				console.log('res',JSON.parse(JSON.stringify(res)));
				this.placeoforiginlist = res.data.data.origines;
				this.places = res.data.data.origines;
				this.params.supplier= res.data.data.compName;
			}).catch( err => {
				console.log(err)				
			});
			
		},
		computed: {
			startDate() {
				return this.getDate('start');
			},
			endDate() {
				return this.getDate('end');
			}
		},
		methods: {
			getDate(type) {
				const date = new Date();
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let day = date.getDate();
	
				if (type === 'start') {
					year = year - 60;
				} else if (type === 'end') {
					year = year + 2;
				}
				month = month > 9 ? month : '0' + month;;
				day = day > 9 ? day : '0' + day;
				return `${year}-${month}-${day}`;
			},
			bindDateChange: function(e) {
				this.params.date = e.target.value
				// console.log(this.params.date);
			},
			/*mescroll组件初始化的回调,可获取到mescroll对象 (此处可删,mixins已默认)*/
			mescrollInit(mescroll) {
				this.mescroll = mescroll;
			},
			downCallback(){
				this.mescroll.resetUpScroll(); // 重置列表为第一页 (自动执行 page.num=1, 再触发upCallback方法 )
			},
			/*上拉加载的回调*/
			upCallback(page) {
				let pageNum = page.num; // 页码, 默认从1开始
				let pageSize = page.size; // 页长, 默认每页10条
				this.params = Object.assign(this.params,{page:pageNum,rows:pageSize});
				this.$api.http.post(this.config.apiBaseurl+'hotel/reserve/data',this.params,{
					header: {
						Accept:'application/json',
						Authorization: 'Bearer '+ this.params.token, //注意Bearer后面有一空格
					}
				}).then(data => {
					if(data.data.code=='1001'){
						// uni.redirectTo({
						// 	url:'/pages/login/login?backpage=/pages/index/index'+'&backtype='+2,
						// });							
					};
					console.log(data);
					// 接口返回的当前页数据列表 (数组)
					let curPageData = data.data.rows; 
					console.log('curPageData',curPageData);
					// 接口返回的当前页数据长度 (如列表有26个数据,当前页返回8个,则curPageLen=8)
					let curPageLen = curPageData.length; 
					// 接口返回的总页数 (如列表有26个数据,每页10条,共3页; 则totalPage=3)
					// let totalPage = data.xxx; 
					// 接口返回的总数据量(如列表有26个数据,每页10条,共3页; 则totalSize=26)
					let totalSize = data.data.total; 
					// 接口返回的是否有下一页 (true/false)
					// let hasNext = data.xxx; 
					
					//设置列表数据
					if(page.num == 1) this.dataList = []; //如果是第一页需手动置空列表
					this.dataList = this.dataList.concat(curPageData); //追加新数据
					
					//方法二(推荐): 后台接口有返回列表的总数据量 totalSize
					this.mescroll.endBySize(curPageLen, totalSize); 
			
					// setTimeout(()=>{
					// 	this.mescroll.endSuccess(curPageLen)
					// },20)
				
				}).catch(err => {
					this.mescroll.endErr()
					console.log(err)
				
				});								
			},

			//选择图片
			chooseimg() {
				let _self = this;
				uni.chooseImage({
					count: 3,
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], //从相册选择
					success: function(res) {
						const tempFilePaths = res.tempFilePaths;
						_self.image = tempFilePaths[0];
						console.log("tempFilePaths[0]", tempFilePaths[0]) //能够打印出选中的图片
						_self.iconcheck = 1; //点击后图片更改状态由0变成1
						console.log('111', JSON.stringify(res.tempFilePaths));
						_self.params.media = res.tempFilePaths;
						console.log(_self.params.media);
						
						// 预览图片
						// uni.previewImage({
						// 	urls: res.tempFilePaths,
						// 	longPressActions: {
						// 		// itemList: [],
						// 		success: function(data) {
						// 			console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
						// 		},
						// 		fail: function(err) {
						// 			console.log(err.errMsg);
						// 		}
						// 	}
						// });
								
					},
					error: function(e) {
						console.log(e);
					}
				});
			},
			//发布
			publish() {
				this.checkStatus = this.check_form();
				if(this.checkStatus){					
					let _self = this;
					//上传图片
					// uni.uploadFile({
					// 	url: _self.httpUrl + '', // 后端api接口
					// 	filePath: _self.image, // uni.chooseImage函数调用后获取的本地文件路劲
					// 	name: 'EmployeeImage', //后端通过'file'获取上传的文件对象(字段)
					// 	formData: {
					// 		// openid:_self.openid,  //剩下的字段
					// 	},
					// 	header: {
					// 		"Content-Type": "multipart/form-data"
					// 	},
					// 	success: (res) => {
					// 		console.log(res)
					// 		if (res.statusCode == 200) {
					// 			uni.showToast({
					// 				icon: 'success',
					// 				title: "添加成功...",
					// 			})
					// 		}
					// 		setTimeout(() => {
					// 			uni.navigateTo({
					// 				url: ''
					// 			})
					// 		}, 2000)

					// 	},
					// 	error(error) {
					// 		uni.showToast({
					// 			title: "添加失败...",
					// 		})
					// 	}
					// });
					uni.showLoading({
					    title: '请稍等'
					});					
					setTimeout(function () {
					    uni.hideLoading();
					}, 2000);
					// setTimeout(()=>{
					// 	uni.showToast({
					// 		icon:'success',
					// 		title:`发布成功,请等待审核!`,
					// 		duration: 2000
					// 	});						
					// },2000);
					
					setTimeout(() => {
						uni.redirectTo({
							url:'/pages/publish/publishsuccess/publishsuccess'
						})
					}, 2000);
				}

			},
			//表单验证
			check_form() {
				console.log('this.params',this.params);
				if(this.params.type.length <= 0) {					
					uni.showToast({icon:'none',title:`请填写类别!`,duration: 2000});					
					return false;
				}
				// if(this.params.myposition.length <= 0) {
				// 	console.log(this.params.myposition);
				// 	uni.showToast({icon:'none',title:`请填写地理位置!`,duration: 2000});					
				// 	return false;
				// }
				if(this.params.title.length <= 0) {
					uni.showToast({icon:'none',title:`请填写标题!`,duration: 2000});					
					return false;
				}
				if(this.params.brand.length <= 0) {
					uni.showToast({icon:'none',title:`请填写品牌!`,duration: 2000});					
					return false;
				}
				if(this.params.price.length <= 0) {
					uni.showToast({icon:'none',title:`请填写零售价!`,duration: 2000});					
					return false;
				}
				if(this.params.supplier.length <= 0) {
					uni.showToast({icon:'none',title:`请填写供应商!`,duration: 2000});					
					return false;
				}
				if(this.params.placeoforigin.length <= 0) {
					uni.showToast({icon:'none',title:`请填写生产地!`,duration: 2000});					
					return false;
				}
				if(this.params.specifications.length <= 0) {
					uni.showToast({icon:'none',title:`请填写规格!`,duration: 2000});					
					return false;
				}
				if(this.params.shelflife.length <= 0) {
					uni.showToast({icon:'none',title:`请填写保质期!`,duration: 2000});					
					return false;
				}
				if(this.params.date.length <= 0) {
					uni.showToast({icon:'none',title:`请填写生产日期!`,duration: 2000});					
					return false;
				}
				if(this.params.packaging.length <= 0) {
					uni.showToast({icon:'none',title:`请填写包装!`,duration: 2000});					
					return false;
				}
				if(this.params.productlabel.length <= 0) {
					uni.showToast({icon:'none',title:`请填写标签!`,duration: 2000});					
					return false;
				}
				if(this.params.media.length <= 0) {
					uni.showToast({icon:'none',title:`请上传图片!`,duration: 2000});					
					return false;
				}				
				return true;
			},
			//选择供应商
			// supplierclick(name){
			// 	this.params.supplier = name;
			// 	this.supplieropen = false;
			// 	this.showback();
			// },
			//打开供应商弹出框
			// opensupplier(){
			// 	this.supplieropen = true;
			// 	this.hideback();
			// },
			// 搜索供应商
			// searchsupplier(e){
			// 	console.log(e);
			// },
			//选择生产地
			placeoforiginclick(name){
				this.params.placeoforigin = name;
				this.placeoforiginopen = false;
				this.showback();
			},
			//打开生产地弹出框
			openplaceoforigin(){
				this.placeoforiginopen = true;
				this.hideback();
			},
			//选择规格
			specificationsclick(e){
				// this.params.specifications = name;
				this.specificationsopen = false;
				this.showback();
			},
			//打开规格弹出框
			openspecifications(){
				this.specificationsopen = true;
				this.hideback();
			},
			// 规格checkbox
			checkboxChange: function (e) {
				var items = this.specificationslist,
					values = e.detail.value;
				for (var i = 0, lenI = items.length; i < lenI; ++i) {
					const item = items[i]
					if(values.includes(item.value)){
						this.$set(item,'checked',true)
					}else{
						this.$set(item,'checked',false)
					}
				}
				this.params.specifications = e.detail.value;
				console.log(this.params.specifications);
			},
			resetcheckbox(){
				var items = this.specificationslist;
				for (var i = 0, lenI = items.length; i < lenI; ++i) {
					const item = items[i];
					this.$set(item,'checked',false)				
				}
				this.params.specifications = [];
				// console.log(this.params.specifications);
			},
			//隐藏返回按钮
			hideback(){
				// let backbtn = document.getElementsByClassName('uni-page-head-hd')[0];
				// backbtn.style.display = 'none';
				this.backtyep = 2;
				console.log(this.backtyep)
			},
			// 显示返回按钮
			showback(){
				// let backbtn = document.getElementsByClassName('uni-page-head-hd')[0];
				// backbtn.style.display = 'block';
				this.backtyep = 1;
				console.log(this.backtyep)
			},
			// 导航返回按钮
			onBackPress(e){
				console.log(this.backtyep)
				if(this.backtyep == 2){
					this.placeoforiginopen = false;
					this.backtyep = 1;
					return true;
				};				
			},
			// 选择位置
			chooseaddr(){
				let self = this;
				uni.chooseLocation({
					success: function (res) {
						self.params.myposition = res.address;
						console.log('位置名称：' + res.name);
						console.log('详细地址：' + res.address);
						console.log('纬度：' + res.latitude);
						console.log('经度：' + res.longitude);
					}
				});
			},
			// 搜索产地
			searchplace(e){							
				if(e.value){
				let place = this.placeoforiginlist.filter(function (value) {
						console.log(value.detailAddress);	
					  return value.detailAddress.includes(e.value);
				});
				console.log('place',place);
				this.placeoforiginlist = place;
				}else{
					this.placeoforiginlist = this.places;
				}
			}
			
			

		}
	}
</script>

<style >
	@import url("./publish.css");
</style>
