<style lang="scss">
	.container{
		min-height: 100%;
		background:#f6f6f6;
		padding:30rpx 0;

		&>.type{
			margin:0 30rpx 30rpx;
			.title{
				color:#333;
				margin-bottom:22rpx;
				&:before{
					content:"*";
					color:#EE4949;
				}
			}
			.content{
				display:flex;
				flex-wrap: wrap;
				margin:0 -30rpx -20rpx 0;
				text{
					background:#EEEEEE;
					color:#999;
					height:54rpx;
					line-height: 54rpx;
					border-radius: 50rpx;
					margin:0 30rpx 20rpx 0;
					width:calc(100%/4 - 30rpx);
					text-align: center;
					transition: all 0.3s;
					&.active{
						color:#fff;
						background:#10C176;
					}
				}
			}
		}
		.card{
			margin-top:0;
			&>.item{
				border-bottom:2rpx solid rgba(216, 216, 216, 0.4);
				padding-bottom:10rpx;
				.tabulation{
					display:flex;
					align-items:center;
					height:70rpx;
					&.mast:before{
						content:"*";
						color:red;
						margin-right:5rpx;
					}
					.title{
						margin-right:auto;
					}
					.record{
						color:#FBA83C;
					}
				}
				.value{
					background:#F7F7F7;
					border-radius: 24rpx;
					color:#333;
					padding:20rpx 30rpx;
				}
			}
			.plant-dikuaimianji{
				display: flex;
				align-items: center;
				font-weight: bold;
				&:before{
					font-weight: normal;
					color:#10C176;
					font-size:40rpx;
					margin-right:16rpx;
					transform: translateY(5rpx);
				}
			}
			.plant-batch-add{
				margin-top:20rpx;
				display: flex;
				align-items: center;
				padding:0 30rpx;
				justify-content: space-between;
				flex-direction: row-reverse;
				background:#F7F7F7;
				border-radius: 24rpx;
				height:80rpx;
				&:before{
					color:#10C176;
				}
				&:after{
					content:"添加农资";
					color:#777;
				}
			}
			.info{
				display:flex;
				align-items: center;
				background:rgba(16, 193, 119, 0.1);
				border-radius: 24rpx;
				height:94rpx;
				margin-top:20rpx;
				padding:0 30rpx;
				text{
					&:first-child{
						flex-shrink: 0;
						color:#fff;
						background:#10C176;
						font-size: 20rpx;
						border-radius:4px 40px 4px 40px;
						width:80rpx;
						height:40rpx;
						text-align: center;
						line-height: 40rpx;
						margin-right:20rpx;
					}
					&:nth-child(2){
						flex-grow: 1;
					}
					&:nth-child(3){
						flex-shrink: 0;
						color:#10C176;
						font-weight: bold;
						margin-left:20rpx;
					}
				}
			}
			&>.u-swipe-action{
				margin-top:20rpx;
				.u-swipe-action-item__right__button{
					display:flex;
					align-items: center;
				}
				&/deep/ .u-swipe-action-item__content>view{
					display:flex;
					align-items: center;
					background:rgba(16, 193, 119, 0.1);
					border-radius: 24rpx;
					height:94rpx;
					padding:0 30rpx;
					text{
						&:first-child{
							flex-shrink: 0;
							color:#fff;
							background:#10C176;
							font-size: 20rpx;
							border-radius:4px 40px 4px 40px;
							width:80rpx;
							height:40rpx;
							text-align: center;
							line-height: 40rpx;
							margin-right:20rpx;
						}
						&:nth-child(2){
							flex-grow: 1;
						}
						&:nth-child(3){
							flex-shrink: 0;
							color:#10C176;
							font-weight: bold;
							margin-left:20rpx;
						}
					}
				}
			}
		}
		.u-popup{
			.u-popup__content>input{
				width:100%;
				margin:30rpx;
			}
		}
	}
</style>
<template>
	<view class="container">
		<d-navbar style="--bg:#10C176;--c:#fff;" isBack text="添加农事">
			<button slot="right" class="cu-btn round" @click="submit">提交</button>
		</d-navbar>

		<view class="type">
			<view class="title">农事类型</view>
			<view class="content">
				<text :class="{active:formData.farmingType==v.value}" v-for="(v,k) in typeList" :key="k" @click="formData.farmingType=v.value">{{v.label}}</text>
				<text @click="isShow=true">自定义+</text>
			</view>
		</view>

		<view class="card">
			<view class="plant-dikuaimianji">{{massif.plotName}}</view>
			<view v-if="formData.inputList.length<=0" class="plant-batch-add" @click="toCollectList"/>
			<u-swipe-action v-for="(v,k) in formData.inputList" :key="k">
				<u-swipe-action-item>
					<view>
						<text>{{v.goodsType}}</text> <text>{{v.substanceName}}</text> <text>{{v.inputQuantity}}{{v.specs[1]}}</text>
					</view>
					<view slot="button" class="u-swipe-action-item__right__button">
						<button class="cu-btn bg-red" style="margin:auto;" @click="formData.inputList.splice(k,1)">删除</button>
					</view>
				</u-swipe-action-item>
			</u-swipe-action>
			<button class="cu-btn round bg-green shadow submit" v-if="formData.inputList.length>0" @click="toCollectList">+继续添加农资</button>
		</view>

		<view class="card">
			<!-- <view v-if="/^用药$|^施肥$/.test(formData.farmingType)" class="item" @click="toPestRecord">
				<view class="tabulation" :class="{mast:/^用药$/.test(formData.farmingType)}">
					<text class="title">操作</text> <text class="record">病虫害记录</text><text class="plant-youbian"/>
				</view>
				<view class="value" v-if="formData.farmPests">
					过程:{{formData.farmPests.growthProcess}}，病虫害部位:{{formData.farmPests.pestSite}}，症状：{{formData.farmPests.symptom}}({{formData.farmPests.pestName.map(v=>v.name).join(',')}})
				</view>
			</view> -->
			<u-form class="inline" errorType="toast" :model="formData" :rules="rules" ref="form" labelWidth="auto">
				<template v-if="/^用药$/.test(formData.farmingType)">
					<d-form label="防治类型" type="radio" v-model="formData.pestsType" @select="formData.pestsType=$event.slice(-1)[0].value" :columns="[{label:'病害',value:'病害'},{label:'虫害',value:'虫害'}]"/>
					<d-form label="防治对象" type="navigate" :value="formData.pests" :btnFun="pestsFun"/>
					<d-form label="农资作用面积" type="digit" v-model="formData.roleArea" suffix="亩"/>
				</template>
				<d-form
					v-for="(v,k) in fields"
					:key="k"
					v-bind="v"
					:field="k"
					:required="!!rules[k]"
					:value="/^select$/.test(v.type)?fields[k].value:formData[k]"
					@input="formData[k]=$event"
					@select="fields[k].value=$event.map(v=>v.value);formData[k]=fields[k].value[0]"
					@imgs="fields[k].value=$event"/>
			</u-form>
		</view>
		<u-popup :show="isShow" closeOnClickOverlay @close="isShow=false">
			<input placeholder="请输入" :focus="isShow" confirm-type="done" v-model="tempType" @confirm="addType"/>
		</u-popup>
	</view>
</template>
<script>
import request from '@/common/request'
export default {
	data(){
		return{
			typeList:[],
			fields:{
				principal:{label:"操作人",styleType:"parallel", disabled:true},
				farmingTime:{label:"操作日期",styleType:"parallel",type:"calendar"},
				farmingPlanId:{label:"种植计划",type:"select",columns:[],value:[]},
				userNum:{label:"人工投入(个)",type:"number"},
				workTime:{label:"工时(天)",type:"number"},
				images:{label:"农事图片",type:"upImg",num:3},
				farmingRemarks:{label:"备注",type:"textarea"},
				
			},
			formData:{
				farmingType:"",
				principal: this.$store.getters['userInfo'].realname,
				principalId: this.$store.getters['userInfo'].id,
				farmingPlanId:"",
				farmingTime:"",
				images:[],
				farmingRemarks:"",
				userNum:0,
				workTime:0,
				inputList:[],
				farmPests:null,//病虫害
				pestsType:"",
				pests:"",
				plotId:"",
				plantBaseInfoId: this.$store.state.baseInfo.id,
			},
			rules:{
				userNum:{required:true,type:'number',message:"人工投入必填！",trigger:'blur'},
				farmingTime:{required:true,message:"操作日期必填！",trigger:'blur'},
				workTime:{required:true,type:'number',message:"工时必填！",trigger:'blur'},
				farmingPlanId:{required:true,message:"种植计划必选！",trigger:'blur'},
			},
			massif:{},
			tempType:"",
			isShow:false,
			eventChannel:null,
		}
	},
	watch:{
		'formData.pestsType'(n,o){
			if(n){
				this.formData.pests=''
			}
		}
	},
	onLoad(options){
		this.eventChannel=this.getOpenerEventChannel()
		this.eventChannel.on("detail", e=>{
			this.formData={
				...e,
				images:e?.images?.split?.(',')?.filter(v=>v)||[],
				inputList: e?.inputList?.map?.(v=>({...v, unit:(v.specDescribe.match(/\d+(\w+)\/./)||[])[1]}))||[]
			}
			this.fields.images.value=e.images
			this.fields.farmingPlanId.value=[e.farmingPlanId]
			this.saveInput=e?.inputList?.map?.(v=>({...v}))
		})
		this.formData.plotId=options.plotId
		this.init()
		this.getMassifDetail()
		//添加监听
		this.$provise.on("forming_agr",e=>e(this.formData.inputList))
	},
	methods:{
		async init(){
			//农事类型
			var res=await request("/api/plantFarming/queryFarmTypeByBaseId",{
				params:{baseId:this.$store.state.baseInfo.id}
			})
			if(res.statu){
				this.typeList=res.data
			}else{
				uni.showModal({
					title:"提示",
					content:res.msg||"获取农事类型失败！",
					showCancel:false,
				})
			}
			//种植计划下拉选择
			var res=await request("/api/plantFarming/getPlantPlan",{
				params:{plotId: this.formData.plotId}
			})
			if(res.statu){
				this.fields.farmingPlanId.columns=[res.data]
			}else{
				uni.showModal({
					title:"提示",
					content:res.msg||"获取种植计划选项失败！",
					showCancel:false,
				})
			}
		},
		async getMassifDetail(){
			var res=await request("/api/plantPlot/queryById",{
				params:{id:this.formData.plotId}
			})
			if(res.statu){
				this.massif=res.data
			}else{
				uni.showModal({
					title:"提示",
					content:res.msg||"获取地块信息失败！",
					showCancel:false,
				})
			}
		},
		toCollectList(){
			uni.navigateTo({
				url:"/pages/massif/collectList",
				events:{ addSpecs: e=>{
					if(!this.formData.inputList.some(v=>{
						if(v.inventoryId==e.inventoryId){
							v.inputQuantity=Math.round((v.inputQuantity+e.inputQuantity)*100)/100
							return true
						}else{
							return false
						}
					})){
						this.formData.inputList.push(e)
					}
				} }
			})
		},
		check(){
			if(!this.formData.farmingType){
				uni.showToast({title:"农资类型必选！",icon:"none"})
				return false
			//农事类型 为播种、施肥、用药 必选添加农资
			}else if(/^施肥$|^用药$/.test(this.formData.farmingType) && this.formData.inputList.length<=0){
				uni.showToast({title:"请添加农资！",icon:"none"})
				return false
			// }else if(/^用药$/.test(this.formData.farmingType) && !this.formData.farmPests){
			// 	uni.showToast({title:"请添加病虫害记录！",icon:"none"})
			// 	return false
			}
			return true
		},
		submit(){
			if(this.check()){
				this.$refs.form.validate().then(async valid=>{
					if(valid){
						var res=await request("/api/plantFarming/addOrUpdate",{
							method:"post",
							body:{
								...this.formData,
								images: this.fields.images.value,
								farmPests: Object.assign(this.formData.farmPests||{},{pestName:this.formData.farmPests?.pestName?.map?.(v=>v.name).join(",")||''})
							}
						})
						if(res.statu){
							uni.navigateBack()
							this.eventChannel.emit("update")
						}else{
							uni.showModal({
								title:"提示",
								content:res.msg||"保存农事失败！",
								showCancel:false,
							})
						}
					}
				})
			}
		},
		async addType(){
			if(this.tempType){
				// var res=await request("/common/api/dict/addDictItem",{
				// 	params:{
				// 		text: this.tempType,
				// 		dictCode:"farming_type",
				// 	}
				// })
				// if(res.statu){
					this.isShow=false
					this.typeList.push({label: this.tempType, value: this.tempType})
					this.formData.farmingType=this.tempType
					this.tempType=''
					// this.typeList.push({label: res.data.itemText, value: res.data.itemValue})
				// }else{
				// 	uni.showModal({
				// 		title:"提示",
				// 		content:res.msg||"添加农资类型失败！",
				// 		showCancel:false,
				// 	})
				// }
			}else{
				uni.showToast({title:"请输入内容！",icon:"none"})
			}
		},
		//选择病虫害名称
		pestsFun(){
			if(this.formData.pestsType){
				uni.navigateTo({
					url:`/pages/massif/pestType?type=${this.formData.pestsType}&plantType=${this.massif.plantType}`,
					events:{type:e=>{
						this.formData.pests=e.map(v=>v).join(',')
					}},
					success:res=>{
						res.eventChannel.emit('ids',this.formData?.pests?.split?.(',')?.filter(v=>v)||[])
					}
				})
			}else{
				uni.showToast({title:"请选择病虫害类型！"})
			}
		},
		//添加病虫害记录
		toPestRecord(){
			uni.navigateTo({
				url:"/pages/massif/pestRecord",
				events:{addPest: e=>this.formData.farmPests=e},
				success:(res)=>{
					res.eventChannel.emit("detail",{...(this.formData.farmPests||{})})
				}
			})
		},
	},
	onUnload(){
		this.$provise.off('forming_agr')
	},
}
</script>
