<template>
	<view class="content">
		<view class="content-form">
			<!-- <view class="content-detail">
				<view class="detail-text">
					<u-image src="/static/pop_icon_warning.png" width="32" height="32"></u-image>
					<text>请按照回收要求合理预约服务</text>
				</view>
				<view class="detail-xqtext">查看详情</view>
			</view> -->
			<view class="form-data">
				<u-form :model="form" ref="uForm" :label-width="140" :error-type="['toast']">
						<u-form-item prop="time" label="预约时间:" required>
							<u-select v-model="show"  mode="mutil-column-auto" :list="list" @confirm="confirm"></u-select>
							<u-input placeholder="请选择预约时间" v-model="time" @click="selectTime" :disabled="true"/>
							<u-icon name="arrow-right" slot="right"  @click="selectTime"></u-icon>
						</u-form-item>
						<u-form-item prop="info" label="用户信息:" required>
							<u-input placeholder="请选择用户信息" v-model="form.info" @click="selectUserInfo" :disabled="true"/>
							<u-icon name="arrow-right" slot="right" @click="selectUserInfo"></u-icon>
						</u-form-item>
				</u-form>
			</view>
			<view class="form-data rubbishType">
				<view class="rubbishType-title u-required:before">回收分类</view>
				<view class="rubbishType-tags">
					<view :class="['item-tags', item.check ? 'active' : '']" v-for="item in rubbishTypeListData" :key="item.code" @click="itemRubbishChange(item)">{{item.dispName}}</view>
				</view>
			</view>
			<view class="form-data rubbishType">
				<view class="rubbishType-title u-required:before">预估重量</view>
				<view class="rubbishType-tags">
					<view :class="['item-weightTags', checkWeightType == item.code ? 'active' : '']" v-for="item in rubbishweightList" :key="item.code" @click="itemRubbishWeightChange(item)">{{item.dispName}}</view>
				</view>
			</view>
			<view class="form-data qyImg">
				<view> 上传图片 <text style="color: #a6a6a6;">(最多3张，单张10MB以内)</text></view> 
				<view class="info-main">
					<view v-if="photograph.length<3 && !isView" class="camera-btn">
						<view @click="goPhotograph" class="photograph-camera">
							<u-icon name="camera" color="#bfbfbf" size="60" ></u-icon>
						</view>
					</view>
					<view v-show="photograph.length" v-for="(item,index) in photograph" :key="index" class="photograph-con">
						<u-icon v-show="!isView" name="close-circle-fill" color="#fa3534" size="50" class="close-circle-icon" @click="cancelPhotograph(index)"></u-icon>
						<u-image width="100%" height="100%" :src="item" @click="previewPictures(item)"></u-image>
					</view>
				</view>
			</view>
		</view>
		<view style="color:#FF2C5C;text-align: center;margin-bottom: 10upx;" v-if="!hasRider">当前地址/时段无可上门骑手，暂不能下单</view>
		<view class="btns">
			<u-button @click="submit" :loading="loading" :custom-style="submitBtn" :disabled="!hasRider">提交</u-button>
			<!-- <u-button @click="submit" :loading="loading" :custom-style="submitBtn">提交</u-button> -->
		</view>
	</view>
</template>

<script>
	import {searchRider} from '@/api/index.js'
	import {saveImgToAliOss} from '@/libs/tools.js'
	import { getLookUpDatas,userDetail,yuyueInfoSave } from '@/api/data'
	export default {
		data() {
			return {
				title:'',
				loading:false, // 提交按钮加载圈
				check:'', // 是否选中
				checkWeightType:'',
				photograph: [], //  图片路径
				RubbishType:[], // 回收分类
				rubbishweightList:[], // 重量分类
				latitude:'', // 当前位置经度
				longitude:'' ,// 当前位置维度
				day:'', // 今天、明天，后天
				timeType:'', // 上午、下午
				reserveDateBegin:'', // 预约开始时间
				reserveDateEnd:'', // 预约结束时间
				time: '', // 其它垃圾
				rubbishTypeListData:[],
				userDetailInfo:{}, // 用户信息
				nowDate:'',
				form: {
					info: '', // 厨余垃圾
				},
				rubbishTypeList:[], // 垃圾类型
				reserveWeight:'',
				isView: false ,// 是否是查看详情
				hasRider:true, // 是否有骑手
				itemId:'',
				submitBtn:{
					backgroundColor: '#4F88F7',
					color: '#fff',
					borderRadius: '12px'
				},
				show: false,
				val:'',
				list: [
					{
						value: 1,
						label: '今天',
						children: [
							{
								value: 2,
								label: '上午（08-13点）',
							},
							{
								value: 3,
								label: '下午（13-18点）',
							}
						]
					},
					{
						value: 4,
						label: '明天',
						children: [
							{
								value: 5,
								label: '上午（08-13点）',
							},
							{
								value: 6,
								label: '下午（13-18点）',
							}
						]
					},
					{
						value: 7,
						label: '后天',
						children: [
							{
								value: 8,
								label: '上午（08-13点）',
							},
							{
								value: 9,
								label: '下午（13-18点）',
							}
						]
					},
				],
			};
		},
		onLoad(option) {
			console.log(option,option.pageType,'ppppppppp')
			// this.pageInfo()
			// if(!option.pageType){
			// 	this.pageInfo()
			// }
			uni.$on('pageType', this.pageType)
			
			// 查看
			// if(option && option.id){
			// 	this.isView = true
			// 	this.itemId=option.id
			// }else {
			// 	console.log('--------新增')
			// 	this.photograph = []
			// 	this.$refs.uForm.resetFields()
			// }
			wx.getLocation({
			 type: 'wgs84',
			 success:(res=> {
			   if(res.latitude && res.longitude){
			     this.latitude = res.latitude
			     this.longitude = res.longitude
			   }
			   console.log(res,'位置信息',this.latitude,this.longitude)
			 })
			})
			setTimeout(()=>{
				this.getRiderStatus()
			},300)
		},
		onShow() {
			this.pageInfo()
		},
		onUnload() {
		},
		watch:{
		},
		methods: {
			// 初始化页面
			pageInfo(){
				this.time=''
				this.userDetailInfo={}
				this.photograph=[]
				this.rubbishTypeList=[]
				this.rubbishTypeListData=[]
				this.latitude=''  // 当前位置经度
				this.longitude='' // 当前位置维度
				this.rubbishType()
				this.getDetailData()
				this.rubbishWeightType()
			},
			pageType(e){
				this.val += e.data
				if(this.val!='userInfo'){
					this.pageInfo()
				}
				console.log(this.val,'----------',e)
			},
			// 获取垃圾分类
			rubbishType () {
			  let _this = this
			  getLookUpDatas({
			    type: 'RESERVE_RUBBISH_TYPE'
			  }).then(result => {
			    if (result && result.status + '' === '200') {
					result.data.forEach(item=>{
						item.check=false
					})
					this.$nextTick(()=>{
						_this.rubbishTypeListData= result.data || []
					})
			    }
			  })
			},
			rubbishWeightType () {
			  let _this = this
			  getLookUpDatas({
			    type: 'RUBBISH_WEIGHT_TEMPLATE'
			  }).then(result => {
			    if (result && result.status + '' === '200') {
					_this.rubbishweightList= result.data || []
			      
			    }
			  })
			},
			// 查询附近有无骑手可接单
			getRiderStatus(){
				searchRider({lng:this.longitude,lat:this.latitude}).then(res=>{
					if(res.status==200){
						this.hasRider=res.data
					}
				})
			},
			// 选择时间
			selectTime(){
				wx.hideKeyboard()
				this.show=true
			},
			confirm(e) {
				const date=new Date
				const year=date.getFullYear()
				const month = date.getMonth() + 1
				const day = date.getDate()
				if(e){
					this.time=e[0].label + e[1].label
					this.day=e[0].label
					this.timeType=e[1].label.substr(0, e[1].label.indexOf("（")) // 上午、下午
					if(e[0].label=='今天'){
						if(this.timeType=='上午'){
							this.reserveDateBegin=this.nowDate = year + "-" +( month<10? '0'+month:month ) + "-" + (day<10? '0'+day:day)+' 08:00:00';
							this.reserveDateEnd=this.nowDate = year + "-" +( month<10? '0'+month:month ) + "-" + (day<10? '0'+day:day)+' 12:59:59';
						}else{
							this.reserveDateBegin=this.nowDate = year + "-" +( month<10? '0'+month:month ) + "-" + (day<10? '0'+day:day)+' 13:00:00';
							this.reserveDateEnd=this.nowDate = year + "-" +( month<10? '0'+month:month ) + "-" + (day<10? '0'+day:day)+' 18:00:00';
						}
						
					}
					if(e[0].label=='明天'){
						if(this.timeType=='上午'){
							this.reserveDateBegin=this.nowDate = year + "-" +( month<10? '0'+month:month ) + "-" + (day<10? '0'+(day+1):day+1)+' 08:00:00';
							this.reserveDateEnd=this.nowDate = year + "-" +( month<10? '0'+month:month ) + "-" + (day<10? '0'+(day+1):day+1)+' 12:59:59';
						}else{
							this.reserveDateBegin=this.nowDate = year + "-" +( month<10? '0'+month:month ) + "-" + (day<10? '0'+(day+1):day+1)+' 13:00:00';
							this.reserveDateEnd=this.nowDate = year + "-" +( month<10? '0'+month:month ) + "-" + (day<10? '0'+(day+1):day+1)+' 18:00:00';
						}
					}
					if(e[0].label=='后天'){
						if(this.timeType=='上午'){
							this.reserveDateBegin=this.nowDate = year + "-" +( month<10? '0'+month:month ) + "-" + (day<10? '0'+(day+2):day+2)+' 08:00:00';
							this.reserveDateEnd=this.nowDate = year + "-" +( month<10? '0'+month:month ) + "-" + (day<10? '0'+(day+2):day+2)+' 12:59:59';
						}else{
							this.reserveDateBegin=this.nowDate = year + "-" +( month<10? '0'+month:month ) + "-" + (day<10? '0'+(day+2):day+2)+' 13:00:00';
							this.reserveDateEnd=this.nowDate = year + "-" +( month<10? '0'+month:month ) + "-" + (day<10? '0'+(day+2):day+2)+' 18:00:00';
						}
					}
				}
			},
			// 选择用户信息
			selectUserInfo(){
				uni.navigateTo({
				    url: '/pages/index/userInfo'
				})
			},
			// 选择垃圾分类
			itemRubbishChange(item){
				item.check=!item.check
				console.log(item,item.code,'--------------',this.check)
			},
			itemRubbishWeightChange(item){
				this.checkWeightType=item.code
				console.log(item,item.code,'--------------',this.check,this.checkWeightType)
			},
			// 获取详情数据
			getDetailData(){
				userDetail().then(res=>{
					if(res.status==200){
						this.form.info=res.data.contactName
						this.userId=res.data.id
						delete res.data.id
						this.userDetailInfo=res.data
						console.log(res)
					}
				})
			},
			// 拍照或从相册选图片
			goPhotograph() {
				uni.chooseImage({
				    count: 1, //默认9
				    sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
				    sourceType: ['album','camera'], //从相册选择
				    success:  (res) =>{
						console.log(res,'rrrrrrrrrrr')
				        console.log(JSON.stringify(res.tempFilePaths));
						console.log(this.photograph.length,'this.photograph')
						if(res.tempFiles[0].size>10485760){
							uni.showToast({
								title: '图片过大无法上传！',
								icon: 'none'
							})
							return
						}
						uni.showLoading({
							title:'正在保存图片...',
							mask: true
						})
						saveImgToAliOss(res.tempFilePaths[0],(ret)=>{
							this.photograph.push(ret.data)
							uni.hideLoading()
						})
				    }
				});
			},
			//  预览图片
			previewPictures(item) {
				const photograph = [item];
				uni.previewImage({
					urls: photograph,
				});
			},
			//  删除图片
			cancelPhotograph(index) {
				setTimeout(() => {
					this.photograph.splice(index,1)
				}, 500);
			},
			// 提交
			submit(){
				this.rubbishTypeList=[]
				console.log('-------------提交')
				this.$refs.uForm.validate(valid => {
					const params= Object.assign(this.userDetailInfo, this.form,{userId:this.userId})
					console.log('-------------校验')
					if (valid) {
						if(this.time ==''){
							uni.showToast({
								title: '请选择预约时间',
								icon: 'none'
							})
							return false
						}
						console.log('-------------时间校验')
						if(this.form.info ==''){
							uni.showToast({
								title: '请选择用户信息',
								icon: 'none'
							})
							return false
						}
						console.log('-------------用户校验')
						if(this.checkWeightType ==''){
							uni.showToast({
								title: '请选择预估重量',
								icon: 'none'
							})
							return false
						}
						console.log('-------------重量校验')
						if(this.rubbishTypeListData){
							this.rubbishTypeListData.map(item=>{
								if(item.check==true){
									this.rubbishTypeList.push(item.code)
								}
							})
							console.log(this.rubbishTypeListData,this.rubbishTypeList,'--------选中垃圾分类')
							params.rubbishTypeList=this.rubbishTypeList
						}
						console.log(params,'----------params垃圾类型')
						if(this.rubbishTypeList ==[]){
							uni.showToast({
								title: '请选择回收分类',
								icon: 'none'
							})
							return false
						}
						console.log(params,'----------params垃圾类型')
						if(this.time){
							params.reserveDateBegin=this.reserveDateBegin
							params.reserveDateEnd=this.reserveDateEnd
						}
						if(this.checkWeightType){
							params.reserveWeight=this.checkWeightType
						} 
						if(this.photograph){
							params.imageList=this.photograph
						}
						console.log(params,'------------参数')
						yuyueInfoSave(params).then(res=>{
							if(res.status==200){
								uni.showToast({
									title: res.message,
									icon: 'none'
								})
								setTimeout(()=>{
									uni.navigateTo({
									    url: '/pages/index/yuyueResult'
									})
								},500)
							}
						})
					} else {
						console.log('验证失败');
					}
				});
			},
			
		},
		// 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		}
	}
</script>

<style lang="scss">
	.content{
		width: 100%;
		height: 100vh;
		padding: 0;
		background: #F5F5F5;
		display: flex;
		flex-direction: column;
		.content-form{
			flex: 1;
			overflow-y: scroll;
			.content-detail{
				padding:20upx 30upx;
				background: rgba(255, 209, 0, 0.4);
				opacity: 1;
				display: flex;
				justify-content: space-between;
				.detail-text{
					display: flex;
					align-items: center;
					text{
						display: inline-block;
						margin-left: 15upx;
					}
				}
				.detail-xqtext{
					font-size: 30upx;
					font-family: PingFang SC;
					font-weight: 500;
					color: #FF9528;
				}
			}
		}
		.receiveAddress{
			width: 100%;
			line-height: 1.5em;
			box-sizing: border-box;
			font-style: normal;
		}
		.form-data{
			padding:0 30upx 0 50upx;
			margin-bottom: 20upx;
			background-color: #fff;
		}
		.rubbishType{
			padding:30upx 30upx 30upx 50upx;
			.rubbishType-title{
				margin-bottom: 20upx;
			}
			.rubbishType-tags{
				display: flex;
				justify-content: space-between;
				.item-tags.active{
					padding: 10upx;
					background-color:rgba(79, 136, 247, 0.2);
					border-radius: 100px;
				}
				.item-weightTags.active{
					padding: 10upx;
					background-color:rgba(79, 136, 247, 0.2);
					border-radius: 100px;
				}
				.check{
					background: #F5F5F5;
				}
			}
		}
		.qyImg{
			padding: 40upx ;
		}
		.info-main {
			margin-top: 14upx;
			border-radius: 12upx;
			background-color: #fff;
			display: flex;
			.location-icon {
				padding-left: 10upx;
				vertical-align: sub;
			}
			.photograph-camera {
				border: 2upx dashed #bfbfbf;
				border-radius: 12upx;
				width: 140upx;
				height: 140upx;
				display: flex;
				align-items: center;
				justify-content: center;
			}
			.camera-btn{
				display: flex;
				flex-direction: column;
				align-items: center;
				color: #999999;
				font-size: 24upx;
			}
			.photograph-con {
				margin: 0 20upx;
				width: 140upx;
				height: 140upx;
				text-align: center;
				position: relative;
				.photograph-icon {
					display: inline-block;
					padding-top: 48upx;
				}
				.close-circle-icon {
					background-color: #fff;
					border-radius: 50%;
					position: absolute;
					right: -23upx;
					top: -23upx;
					z-index: 9;
				}
			}
		}
		.btns{
			padding: 30upx 30upx 50upx;
			background-color: #fff;
		}
	}
</style>
