<template>
	<div class="form-submit">
		<div class="i-layout-page-header">
			<PageHeader class="product_tabs" hidden-breadcrumb>
				<div slot="title">
					<router-link :to="{ path: `${roterPre}/erp/in_list` }">
						<!-- <Button icon="ios-arrow-back" size="small" class="mr20"
              >返回</Button
            > -->
						<div class="font-sm after-line">
							<span class="iconfont iconfanhui"></span>
							<span class="pl10">返回</span>
						</div>
					</router-link>
					<span v-text="
              $route.params.id !== '0' ? '添加入库单' : '添加入库单'
            " class="mr20 ml16"></span>
				</div>
			</PageHeader>
		</div>
		<Card :bordered="false" dis-hover class="ivu-mt">
			<Form class="formValidate mt20" ref="formValidate" :model="formValidate"
				:label-width="labelWidth" :label-position="labelPosition" @submit.native.prevent>
				<Row :gutter="24" type="flex">
					<Col span="24">
						<FormItem label="采购单号：" prop="orderNumber">
							<Input v-model="formValidate.orderNumber" placeholder="请输入采购单号" v-width="'400'" @submit.native.prevent />
							<a @click="getGoods" style="margin-left: 20px;">确认</a>
						</FormItem>
					</Col>
					<Col span="24">
						<FormItem label="运费：" prop="freight">
							<Input v-model="formValidate.freight" placeholder="请输入运费" v-width="'400'" type="number"/>
						</FormItem>
					</Col>
					<Col span="24" v-if="showWid">
						<FormItem label="仓库：" prop="wid">
							<el-cascader placeholder="请选择仓库" class="input-add" size="mini" v-model="formValidate.wid"
								:options="data1" :props="props" filterable v-width="'400'">
							</el-cascader>
						</FormItem>
					</Col>
					<Col span="24">
					<FormItem label="创建人：" prop="create_uid" v-if="formValidate.wid != 0">
						<el-cascader placeholder="请选择创建人" class="input-add" size="mini"
							v-model="formValidate.create_uid" :options="authList" :props="propsss"
							@change="userSearchsss" filterable clearable v-width="'400'" :disabled="formValidate.id != 0">
						</el-cascader>
					</FormItem>
					</Col>
					<Col span="24" v-if="goodsList.length > 0">
						<FormItem label="商品：">
							<Table :columns="columns" :data="goodsList" ref="table" :loading="loading"
								no-userFrom-text="暂无数据" no-filtered-userFrom-text="暂无筛选结果">
								<template slot-scope="{ row,index }" slot="product_name">{{row.product_name}}</template>
								<template slot-scope="{ row,index }" slot="unit_name">{{row.unit_name}}</template>
								<template slot-scope="{ row,index }" slot="price">{{row.price}}</template>
								<template slot-scope="{ row,index }" slot="pur_num">
									<Input v-model="goodsList[index].pur_num" placeholder="请输入数量" v-width="'150'" type="number"/>
								</template>
								<template slot-scope="{ row,index }" slot="tare_weight">
									<Input v-if="row.is_weigh == 1" v-model="goodsList[index].tare_weight" :placeholder="'请输入商品毛重('+row.p_unit_name+')'" v-width="'150'" type="number"/>
									<div v-else>/</div>
								</template>
								<template slot-scope="{ row,index }" slot="net_weight">
									<Input v-if="row.is_weigh == 1" v-model="goodsList[index].net_weight" :placeholder="'请输入商品净重('+row.p_unit_name+')'" v-width="'150'" type="number"/>
									<div v-else>/</div>
								</template>
								<template slot-scope="{ row,index }" slot="timeValue">
									<el-date-picker v-model="row.timeValue" type="date" size="mini" style="width: 150px;"
									placeholder="选择日期" @change="changeTime($event,row,index)" ></el-date-picker>
								</template>
								<template slot-scope="{ row,index }" slot="bin_number">
									<div v-if="row.bin_number">{{goodsList[index].bin_number}}</div>
									<div v-else>
										<!-- <Select v-model="goodsList[index].bin_number_value" style="width:150px"> -->
											<Select v-model="goodsList[index].bin_number" style="width:150px">
											<Option v-for="item in binList" :value="item.bin_number" :key="item.bin_number">
												{{ item.bin_number }}</Option>
										</Select>
										<a @click="addPosition">添加仓位</a>
									</div>
								</template>
							</Table>
						</FormItem>
					</Col>
				</Row>
			</Form>
		</Card>
		<Card :bordered="false" dis-hover class="fixed-card"
			:style="{ left: `${!menuCollapse ? '200px' : isMobile ? '0' : '80px'}` }">
			<Form>
				<FormItem>
					<Button type="primary" class="submission" @click="handleSubmit('formValidate')" >保存</Button>
				</FormItem>
			</Form>
		</Card>
		<Modal v-model="modalPosition" scrollable title="添加仓位" class="order_box" :closable="false"
			:mask-closable="false">
			<Form ref="remarks" :model="remarks" :rules="rulePosition" :label-width="100" @submit.native.prevent>
				<Col span="24">
				<FormItem label="仓位名称：" prop="title">
					<Input v-model="remarks.title" placeholder="请输入仓位名称/编号" v-width="'200'" />
				</FormItem>
				</Col>
				<Col span="24">
				<FormItem label="通道：" prop="passageway">
					<Input v-model="remarks.passageway" placeholder="请输入通道" type="number" v-width="'200'"
						:disabled="remarks.id != 0" /> (1~99)
				</FormItem>
				</Col>
				<Col span="24">
				<FormItem label="左右：" prop="control">
					<RadioGroup v-model="remarks.control">
						<Radio label="L" :disabled="remarks.id != 0">
							<Icon type="social-apple"></Icon>
							<span>左</span>
						</Radio>
						<Radio label="R" :disabled="remarks.id != 0">
							<Icon type="social-android"></Icon>
							<span>右</span>
						</Radio>
					</RadioGroup>
				</FormItem>
				</Col>
				<Col span="24">
				<FormItem label="层数：" prop="layer">
					<Input v-model="remarks.layer" placeholder="请输入层数" type="number" v-width="'200'"
						:disabled="remarks.id != 0" /> (1~9)
				</FormItem>
				</Col>
				<Col span="24">
				<FormItem label="仓位编号：" prop="number">
					<Input v-model="remarks.number" placeholder="请输入仓位编号" type="number" v-width="'200'"
						:disabled="remarks.id != 0" /> (1~999)
				</FormItem>
				</Col>
			</Form>
			<div slot="footer">
				<Button type="primary" @click="putRemark()">提交</Button>
				<Button @click="cancels()">取消</Button>
			</div>
		</Modal>
	</div>
</template>

<script>
	import { mapState,mapMutations } from "vuex";
	import Setting from "@/setting";
	import { getPurchaseId,batch_save,getPositionList,createRuku ,getGodownList,createPosition,getUserList} from "@/api/erp";
	import { in_status } from "@/api/erpAdmin";
	import { formatDate } from "@/utils/validate";
	const jy = (min, max) => {
		return {
			validator(rule, value) {
				if (!value || value > max || value < min) {
					return [{
						message: `范围为${min}~${max}`
					}];
				} else {
					return [];
				}
			}
		}
	}
	export default {
		name: "addInList",
		data() {
			return {
				authList:[],
				propsss: {
					emitPath: false,
					multiple: false,
					checkStrictly: true,
					value: "id",
					label: "staff_name"
				},
				modalPosition: false,
				rulePosition: {
					title: [{
						required: true,
						message: "请输入仓位名称",
						trigger: "blur"
					}, ],
					wid: [{
						required: true,
						message: "请选择仓库",
						trigger: "blur"
					}, ],
					passageway: [{
						required: true,
						message: "请输入通道",
						trigger: "blur"
					}, jy(1, 99)],
					control: [{
						required: true,
						message: "请选择左右",
						trigger: "blur"
					}, ],
					layer: [{
						required: true,
						message: '请输入层数',
						trigger: 'blur',
					}, jy(1, 9)],
					number: [{
						required: true,
						message: '请输入仓位编号',
						trigger: 'blur',
					}, jy(1, 999)],
				},
				remarks: {
					id: 0,
					title: "",
					wid: '0',
					passageway: '',
					control: "L",
					layer: '',
					number: ''
				},
				props: {
					emitPath: false,
					multiple: false,
					checkStrictly: true,
					value: "id",
					label: "title"
				},
				loading: false,
				showWid: false,
				roterPre: Setting.roterPre,
				columns: [{
						title: '商品名称',
						key: 'product_name',
						minWidth: 180
					},
					{
						title: '单位',
						slot: 'unit_name',
						minWidth: 90
					},
					{
						title: '单价',
						slot: 'price',
						minWidth: 90
					},
					{
						title: '数量',
						slot: 'pur_num',
						minWidth: 150
					},
					
					{
						title: '毛重',
						slot: 'tare_weight',
						minWidth: 150
					},
					{
						title: '净重',
						slot: 'net_weight',
						minWidth: 150
					},
					{
						title: '批次',
						slot: 'timeValue',
						minWidth: 150
					},
					{
						title: '仓位',
						slot: 'bin_number',
						minWidth: 150
					},
				],
				formValidate: {
					create_admin_id:0,
					create_uid: 0,
					id: 0,
					orderNumber:'',
					freight:'',
					goods: [],
					wid: 0
				},
				info:'',//采购单信息
				goodsList:[],//采购单商品
				binList:[],//仓位列表
				data1: [],
			};
		},
		computed: {
			...mapState("admin/layout", ["isMobile", "menuCollapse"]),
			labelWidth() {
				return this.isMobile ? undefined : 120;
			},
			labelPosition() {
				return this.isMobile ? "top" : "right";
			},
		},
		created() {
			this.getGodownList()
		},
		mounted() {
			if (this.$route.query.id != 0) {
				// this.getWantInfo(this.$route.query.id)
			}
		},
		methods: {
			userSearchsss(e) {
				if (e) {
					let obj = this.authList.find(item => item.id == e)
					this.formValidate.create_admin_id = obj.admin_id
				}
			},
			getUserList() {
				getUserList({
					wid: this.formValidate.wid
				}).then(res => {
					this.authList = res.data.data
				})
			},
			addPosition() {
				this.modalPosition = true
				this.remarks.wid = this.inInfo.wid
			},
			cancels() {
				this.modalPosition = false
				this.remarks = {
					id: 0,
					title: "",
					wid: '0',
					passageway: '',
					control: "L",
					layer: '',
					number: ''
				}
			},
			putRemark() {
				this.$refs.remarks.validate((valid) => {
					if (valid) {
						// this.remarks.id = this.$route.query.id;
						createPosition({
							id: this.remarks.id,
							title: this.remarks.title,
							wid: this.info.wid,
							passageway: this.remarks.passageway,
							control: this.remarks.control,
							layer: this.remarks.layer,
							number: this.remarks.number
						}).then(res => {
							this.$Message.success(res.msg);
							this.getBin(this.info.wid)
			
							this.cancels()
							// this.$router.push({
							// 	path: this.roterPre + "/erp/position_list"
							// });
						}).catch(err => {
							this.$Message.error(err.msg);
						})
					} else {
						// this.$Message.error("请输入参数模板名称");
					}
				});
			},
			getGodownList() {
				getGodownList().then(res => {
					console.log(res);
					this.data1 = res.data.data
				})
			},
			//提交数据
			handleSubmit(name) {
				if(!this.formValidate.wid) {
					this.$Message.error("请选择仓库");
					return
				}
				if(this.formValidate.id == 0) {
					if(!this.formValidate.freight){
						this.$Message.error("请输入运费");
						return;
					}
					for (var i = 0; i < this.goodsList.length; i ++) {
						if(this.goodsList[i].is_weigh == 1){
							if(this.goodsList[i].tare_weight == '' || this.goodsList[i].tare_weight == null){
								this.$Message.error("请输入商品毛重");
								return;
							}
							if(this.goodsList[i].net_weight == ''|| this.goodsList[i].net_weight == null){
								this.$Message.error("请输入商品净重");
								return;
							}
						}
					}
				}else {
					
				}
				let list = []
				let total_num = 0
				let total_price = 0
				this.goodsList.forEach(item => {
					total_num += Number(item.net_weight)
					total_price += Number(item.total_price)
					list.push({
						batch_code:item.batch_code,
						bin_number:item.bin_number,
						bar_code:item.bar_code,
						net_weight:item.net_weight,
						product_code:item.product_code,
						product_id:item.product_id,
						product_name:item.product_name,
						product_num:item.pur_num,
						tare_weight:item.tare_weight,
						unit_name:item.unit_name,
						unit_type:item.unit_type,
						wid:item.wid || this.formValidate.wid,
						price:item.price,
						total_price:item.total_price,
						is_weigh:item.is_weigh,
						rate:item.unit_type == 1?item.p_unit_rate_1:item.unit_type == 2?item.p_unit_rate_2:1,
						shelf_life:item.shelf_life,
					})
				})
				createRuku({
					create_uid: this.formValidate.create_uid,
					create_admin_id: this.formValidate.create_admin_id,
					info:list,
					total_num:total_num,
					total_price:total_price,
					freight:this.formValidate.freight,
					purchase_order_id:this.formValidate.orderNumber,
					wid:this.formValidate.wid
				},0).then(res => {
					if(res.status == 200){
						this.$Message.success(res.msg);
						this.$router.push({
							path: this.roterPre + "/erp/in_list"
						});
					}
				}).catch(err => {
					this.$Message.error(err.msg);
				})
			},
			//根据采购单号获取商品
			getGoods() {
				in_status(this.formValidate.orderNumber).then(res => {
					console.log(res,'根据采购单号获取商品')
					if(res.data.status == true){
					   getPurchaseId(this.formValidate.orderNumber).then(res => {
					   	if(res.status == 200){
					   		this.info = res.data
							if(!this.info.wid) {
								this.showWid = true
							}else {
								this.formValidate.wid = this.info.wid
							}
							this.getUserList()
					   		this.info.info.forEach(item => {
					   			item.batch_code = ''
					   			item.tare_weight = ''
					   			item.net_weight = ''
					   			item.timeValue = ''
					   			// item.bin_number_value = ''
								item.bin_number = ''
					   		})
					   		this.goodsList = this.info.info
					   		this.getBin()
					   		console.log(this.goodsList,'this.goodsList')
					   	}else{
					   		this.$Message.error('订单号异常');
					   	}
					   }).catch(err => {
					   	this.$Message.error(err.msg);
					   })
					}else{
						this.goodsList = []
						this.$Message.error('采购单号状态异常');
					}
				}).catch(err => {
					this.$Message.error(err.msg);
				})
			},
			//选择批次的时间
			changeTime(value,row,index){
				console.log(value,row,index,'value,row,index')
				let time = formatDate(value, "yyyy-MM-dd")
				this.goodsList[index].timeValue = time
				console.log(this.goodsList[index].timeValue,'this.goodsList[index].timeValue')
				batch_save({
					product_id:row.product_id,
					bar_code:row.bar_code,
					production_date:time
				}).then(res => {
					if(res.status == 200){
						this.goodsList[index].batch_code = res.data.batch_code
					}else{
						this.$Message.error(res.msg);
					}
				}).catch(err => {
					this.$Message.error(err.msg);
				})
			},
			//获取仓位列表
			getBin(){
				getPositionList({
					page:1,
					limit:10000,
					wid:this.info.wid,
					not_used:1
				}).then(res => {
					if(res.status == 200){
						this.binList = res.data.data
					}else{
						this.$Message.error(res.msg);
					}
				}).catch(err => {
					this.$Message.error(err.msg);
				})
			},
		},
	};
</script>

<style scoped lang="stylus">
	.table {
		/deep/.ivu-table-header table {
			border: 0 !important;
		}

		/deep/.ivu-table-header thead tr th:nth-of-type(1) {
			padding-left: 16px;
		}

		/deep/.ivu-table td:nth-of-type(1) {
			padding-left: 16px;
		}

		/deep/.ivu-table-cell {
			padding: 0 !important;
		}

		/deep/.ivu-table-border th,
		/deep/.ivu-table-border td {
			border-right: unset;
		}

		/deep/.ivu-table td {
			height: 59px;
		}
	}

	.form-submit {
		/deep/.ivu-card {
			border-radius: 0;
		}

		margin-bottom: 79px;

		.fixed-card {
			position: fixed;
			right: 0;
			bottom: 0;
			left: 200px;
			z-index: 99;
			box-shadow: 0 -1px 2px rgb(240, 240, 240);

			/deep/ .ivu-card-body {
				padding: 15px 16px 14px;
			}

			.ivu-form-item {
				margin-bottom: 0;
			}

			/deep/ .ivu-form-item-content {
				margin-right: 124px;
				text-align: center;
			}

			.ivu-btn {
				height: 36px;
				padding: 0 20px;
			}
		}
	}

	.after-line {
		display: inline-block;
		position: relative;
		margin-right: 16px;
	}

	.ml16 {
		margin-left: 16px;
	}
</style>