<template>
	<view class="content flex flex_column">
		<view class="form-body">
			<u-form :model="form" label-width="180rpx" :error-type="['toast']" ref="uForm">
				<u-form-item label="货位号">
					<view class="flex align_center flex_1 justify_between">
						<view style="width: 80%;">{{shelfPlaceCode}}</view>
						<view v-if="!productEntity" style="width: 20%;text-align: center;" @click="editShelf"><u-icon name='edit-pen'></u-icon>修改</view>
					</view>
				</u-form-item>
				<view v-if="productEntity">
					<u-form-item label="" prop="productSn">
						<view class="flex flex_1 align_center">
							<view class="pimgs">
								<u-image :src="productEntity.productMsg?productEntity.productMsg:`../../static/${$config('themePath')}/def_img@2x.png`" width="128" height="128" border-radius="10"></u-image>
							</view>
							<view class="pinfo flex_1">
								<view class="ptxt flex align_center justify_between">
									<text>{{productEntity.code}}</text>
									<text class="pcode" @click="toBindProduct">
										<u-icon name='reload'></u-icon>
										更换产品
									</text>
								</view>
								<view class="pname">
									{{productEntity.name}}
								</view>
								<view>
									当前库存：{{productEntity.currQty||0}} {{productEntity.unit}}
								</view>
							</view>
						</view>
					</u-form-item>
					<u-form-item label="销售价(元)" required prop="price">
						<u-input clearable type="number" :min="0" @input="numberToFixed('price',2,999999)" v-model="form.price" placeholder="请输入销售价，最多两位小数"/>
					</u-form-item>
					<u-form-item label="结算价(元)" required prop="cost">
						<u-input clearable type="number" :min="0" @input="numberToFixed('cost',2,999999)" v-model="form.cost" placeholder="请输入结算价，最多两位小数"/>
					</u-form-item>
					<u-form-item label="最大库容(件)" required prop="maxQty">
						<u-number-box :min="0" :max="999999" positive-integer v-model="form.maxQty" color="#000" bg-color="#fff" size="30" :input-height="70" :input-width="150"></u-number-box>
					</u-form-item>
				</view>
				<view class="noproduct" v-else  @click="toBindProduct">
					<view>
						<u-empty :src="`/static/${$config('themePath')}/def_no_data@3x.png`" icon-size="150" text="此货位还未绑定产品" mode="list"></u-empty>
					</view>
					<view>点击去 <text>绑定产品</text></view>
				</view>
			</u-form>
		</view>
		<view class="flex footer-btn">
			<u-button v-if="type=='bind'" class="delbtn" :loading='loading' @click="handleDel" type='primary' shape="circle" size="medium">删除货位</u-button>
			<u-button :style="{width:type=='bind'?'45%':'100%'}" class="newbtn" :loading='loading' @click="formSubmit" type='primary' shape="circle" size="medium">保存</u-button>
		</view>
	</view>
</template>

<script>
	import { clzConfirm, numberToFixed } from '@/libs/tools';
	import { shelfProductSave, shelfProductDetail, delShelfPlaceSn } from '@/api/shelf'
	export default {
		data() {
			return {
				shelfPlaceCode: '',
				form: {
					productSn: undefined,
					productCode: undefined,
					shelfProductSn: undefined,
					price: '', //  销售价
					cost: '', //结算价
					maxQty: 1, //  最大库容
				},
				rules: {
					productSn: [{ required: true, message: '请选择绑定产品', trigger: 'change' }],
					price: [{ required: true,type:'number', message: '请输入销售价', trigger: 'change' }],
					cost: [{ required: true,type:'number', message: '请输入结算价', trigger: 'change' }],
					maxQty: [{ required: true,type:'number', message: '请输入最大库容', trigger: 'change' }],
				},
				productEntity: null,
				customerSn: null,
				shelfPlaceSn: null,
				loading: false,
				type:"",
				bakProductSn: null
			}
		},
		// 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},
		onLoad(opts) {
			const _this = this
			this.nowData = this.$store.state.vuex_tempData;
			this.customerSn = this.nowData.customerSn
			this.shelfSn = this.nowData.shelfSn
			this.type = opts.type
			this.shelfPlaceCode = this.nowData.shelfPlaceCode||''
			console.log(this.nowData)
			// 选在产品
			uni.$on('addProductToHw',function(data){
				console.log(data)
				_this.productEntity = data
				_this.form.price = Number(data.price)
				_this.form.cost = Number(data.cost)
				_this.form.productCode = data.code
				_this.form.productSn = data.productSn
				// 更换产品
				if(_this.bakProductSn != data.productSn){
					_this.form.updateProductFlag = 1
				}
			})
			
			// 修改货位号成功
			uni.$on('updateHwNo',(data)=>{
				this.shelfPlaceCode = data
			})
			
			if(this.type != 'bind'){
				// 获取产品信息
				this.getProductInfo()
			}
		},
		onUnload(){
			console.log('-----')
			uni.$off("addProductToHw")
			uni.$off("updateHwNo")
			this.$store.state.vuex_tempData = null
		},
		methods: {
			// 小数点后两位
			numberToFixed: function (key, num, max) {
				let val = this.form[key]
				let ret = numberToFixed(val, num, max)
				this.$nextTick(() => {
					this.form[key] = ret < 0 ? 0 : ret
				})
			},
			// 更换产品
			toBindProduct(){
				if(this.productEntity && this.productEntity.currQty){
					uni.showToast({
						icon:'none',
						title: '只有当前库存为0时才能更换产品',
						duration: 4000
					})
					return
				} 
				uni.navigateTo({
					url: "/pages/shelfSetting/bindProduct?customerSn="+this.customerSn+"&shelfSn="+this.shelfSn
				})
			},
			// 编辑货位号
			editShelf(){
				const type ='edit'
				const params={
					customerSn: this.nowData.customerSn,
					shelfSn: this.nowData.shelfSn,
					id: this.nowData.id,
				}
				uni.navigateTo({
					url: "/pages/shelfSetting/addShelfHw?detailData="+encodeURIComponent(JSON.stringify(params))+"&type="+type+"&shelfPlaceCode="+this.shelfPlaceCode
				})
			},
			// 获取产品信息
			getProductInfo () {
			  shelfProductDetail({ shelfPlaceSn: this.nowData && this.nowData.shelfPlaceSn }).then(res => {
			    if (res.status == 200 && res.data) {
				  console.log(res.data)
			      this.productEntity = {
					  code: res.data.productCode,
					  name: res.data.productName,
					  productMsg: res.data.productImageUrl,
					  currQty: res.data.qty,
					  unit: res.data.productEntity.unit
				  }
			      this.form.productSn = res.data.productSn
				  this.bakProductSn = res.data.productSn
			      this.form.productCode = res.data.productCode
			      this.form.price = res.data.price
			      this.form.cost = res.data.cost
			      this.form.maxQty = res.data.maxQty
			    } else {
			      this.productEntity = null
			    }
			  })
			},
			// 删除货位
			handleDel (row) {
			  const _this = this
			  clzConfirm({
			    title: '提示',
			    content: '删除后无法恢复，确认删除？',
			    success (ret) {
					if (ret.confirm || ret.index == 0) {
						_this.loading = true
						delShelfPlaceSn({ shelfPlaceSn: _this.nowData.shelfPlaceSn }).then(res => {
						  if (res.status == 200) {
							  uni.showToast({
							  	icon: "none",
							  	title: res.message
							  })
							  uni.navigateBack()
						  }
						  _this.loading = false
						})
					}
			    }
			  })
			},
			//  表单提交
			formSubmit(){
				const _this = this
				if(!this.productEntity){
					uni.showToast({
						icon: "none",
						title: '请先绑定产品'
					})
					return
				}
				this.$refs.uForm.validate(valid => {
					if (valid) {
						 const form = JSON.parse(JSON.stringify(_this.form))
						 form.shelfPlaceSn = _this.nowData && _this.nowData.shelfPlaceSn
						 if(this.type != 'bind'){ // 不是绑定产品
						 	form.shelfProductSn = _this.nowData && _this.nowData.shelfProductApiEntity && _this.nowData.shelfProductApiEntity.shelfProductSn || _this.nowData.shelfProductSn
						 }
						 
						 // 开始提交数据
						 _this.loading = true
						 shelfProductSave(form).then(res => {
						   if (res.status == 200) {
							 uni.showToast({
							 	icon: "none",
							 	title: res.message
							 })
						     uni.navigateBack()
						   }
						    _this.loading = false
						 })
					} else {
						console.log('验证失败');
					}
				});
			},
		}
	}
</script>

<style lang="less">
.content{
	height: 100vh;
	width: 100%;
	.form-body{
		flex-grow: 1;
		> view{
			background-color: #fff;
			padding: 0 1.5rem;
		}
		.pimgs{
			padding:0.1rem;
			background:#f8f8f8;
			border-radius:0.3rem;
		}
		.pinfo{
			line-height:normal;
			padding-left: 20rpx;
			color: #666;
			.ptxt{
				padding-bottom:20rpx;
			}
			.pcode{
				color:rgb(0, 170, 255);
			}
			.pname{
				font-weight: bold;
			}
		}
		.noproduct{
			padding: 40rpx 20rpx;
			text-align: center;
			color: #999;
			>view{
				padding: 10rpx 0;
			}
			text{
				color: #00aaff;
				margin-left: 10rpx;
			}
		}
	}
	.footer-btn{
		padding: 0.5rem 2rem;
		justify-content: space-between;
		button{
			min-width: 45%;
		}
		.newbtn{
			background-color: rgb(51, 95, 182);
			color: #fff;
		}
		.delbtn{
			background-color: #fff;
			color: red;
		}
	}
}
</style>
