<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/losses` }">
						<!-- <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.query.id !== '0' ? '编辑报损单' : '添加报损单'
            " class="mr20 ml16"></span>
				</div>
			</PageHeader>
		</div>
		<Card :bordered="false" dis-hover class="ivu-mt">
			<Form class="formValidate mt20" ref="formValidate" :rules="ruleValidate" :model="formValidate"
				:label-width="labelWidth" :label-position="labelPosition" @submit.native.prevent>
				<Row :gutter="24" type="flex">
					<!-- <Col span="24">
					<FormItem label="仓位名称：" prop="title">
						<Input v-model="formValidate.title" placeholder="请输入仓位名称/编号" v-width="'400'" />
					</FormItem>
					</Col>
					<Col span="24"> -->
					<!-- <Col span="24">
					<FormItem label="报损单位：" prop="outType">
						<RadioGroup v-model="formValidate.outType" @on-change="changeOutType">
							<Radio :label="0" :disabled="formValidate.id != 0">
								<Icon type="social-apple"></Icon>
								<span>仓库</span>
							</Radio>
							<Radio :label="1" :disabled="formValidate.id != 0">
								<Icon type="social-android"></Icon>
								<span>门店</span>
							</Radio>
						</RadioGroup>
					</FormItem>
					</Col> -->
					<FormItem label="仓库：" prop="wid" v-if="formValidate.outType == 0">
						<el-cascader placeholder="请选择所属仓库" class="input-add" size="mini" v-model="formValidate.wid"
							:options="data1" :props="props" @change="userSearchs" filterable clearable v-width="'400'">
						</el-cascader>
					</FormItem>
					</Col>
					
					<Col span="24">
					<FormItem label="门店：" prop="store_id" v-if="formValidate.outType == 1">
						<el-cascader placeholder="请选择门店" class="input-add" size="mini"
							v-model="formValidate.store_id" :options="staffData" :props="propss"
							@change="userSearchse" filterable clearable v-width="'400'">
						</el-cascader>
					</FormItem>
					</Col>
					<Col span="24">
					<FormItem label="创建人：" prop="create_uid" v-if="formValidate.store_id != 0 || 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'">
						</el-cascader>
					</FormItem>
					</Col>
					<!-- <Col span="24">
					<FormItem label="报损原因：" prop="type" >
						<el-cascader placeholder="请选择报损原因" class="input-add" size="mini"
							v-model="formValidate.type" :options="yList" :props="propses" 
							filterable clearable v-width="'400'">
						</el-cascader>
					</FormItem>
					</Col> -->
					<Col span="24">
					<FormItem label="商品：" prop="goods">
						<Card>
							<div class="user-info" v-for="(goods,gindex) in chooseGoods">
								<Button type="primary" @click="delGood(gindex)" class="del-btn">删除</Button>
								<div class="section-hd">{{goods.product_name}}</span> 								</div>
								<div  class="section" v-for="(item,index) in goods.batchs">
									<div class="section-bd">
										<div class="item">
											<div>批次编号：</div>
											<div class="value">{{ item.batch_code || '/'}}</div>
										</div>
										<div class="item">
											<div>库存（{{item.unit_name}}）：</div>
											<div class="value">{{ item.product_num}}</div>
										</div>
										<div class="item">
											<div>单位：</div>
											<div class="value">{{ item.unit_name}}</div>
										</div>
										<div class="item">
											<div>报损数量({{item.unit_name}})：</div>
											<div class="value"><Input
													v-model="chooseGoods[gindex].batchs[index].pur_number"
													placeholder="请输入数量" v-width="'150'" type="number"/>
											</div>
										</div>
										<div class="item">
											<div>报损原因：</div>
											<div class="value">
												<!-- <Select v-model="chooseGoods[gindex].batchs[index].type" style="width:200px">
													<Option v-for="items in yList" :value="items.type" :key="items.type" label="name">
														{{ item.label }}
													</Option>
												</Select> -->
												<el-cascader placeholder="请选择报损原因" class="input-add" size="mini"
													v-model="chooseGoods[gindex].batchs[index].type" :options="yList" :props="propses" 
													filterable clearable >
												</el-cascader>
											</div>
										</div>
										<!-- <div class="item" >
											<div>皮重（kg）：</div>
											<div class="value"><Input v-model="chooseGoods[gindex].tare_weight"
													placeholder="请输入重量" v-width="'150'" type="number" /></div>
										</div>
										<div class="item " >
											<div>净重（kg）：</div>
											<div class="value"><Input v-model="chooseGoods[gindex].net_weight"
													placeholder="请输入重量" v-width="'150'" type="number" /></div>
										</div> -->
										<a v-if="goods.batchs.length > 1" @click="delBatch(gindex,index)" class=" del-btn-1">删除</a>
									</div>
								</div>
							</div>
						</Card>
						<Button type="primary" class="submission" style="margin-top:20px;" @click="getGoods()"
							>添加商品</Button>
					</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>
		<good-detail ref="goodDetail" @setGoods="setGoods"></good-detail>
	</div>
</template>

<script>
	import {
		staffListInfo
	} from "@/api/store";
	import {
		mapState,
		mapMutations
	} from "vuex";
	import {
		getGodownList,
		createGodown,
		getGodownInfo,
		createPosition,
		getPosition,
		getUserList,
		createLoss,
		getYlist,
		getProductBatch
	} from "@/api/erp";
	import {
		keyApi,
		storeGetInfoApi,
		cityApi,
		storeUpdateApi,
		cascaderList
	} from '@/api/store';
	import {
		productSpecs,
		productSpecsInfo
	} from "@/api/product";
	import Setting from "@/setting";
	import goodDetail from './goodDetail.vue'
	const jy = (min,max)=>{
		return {
	        validator(rule, value){
	            if (!value || value > max || value < min) {
	                return [{message:`范围为${min}~${max}`}];
	            } else {
	                return [];
	            }
	        }
	    }
	}
	

	export default {
		name: "lossesAdd",
		components: {
			goodDetail
		},
		data() {
			return {
				yList: [],
				chooseGoods:[],
				authList:[],
				addresData: [],
				props: {
					emitPath: false,
					multiple: false,
					checkStrictly: true,
					value: "id",
					label: "title"
				},
				propses: {
					emitPath: false,
					multiple: false,
					checkStrictly: true,
					value: "type",
					label: "name"
				},
				roterPre: Setting.roterPre,
				data1: [],
				grid: {
					xl: 7,
					lg: 7,
					md: 12,
					sm: 24,
					xs: 24,
				},
				formValidate: {
					create_uid: 0,
					create_admin_id: 0,
					store_id: 0,
					outType: 0,
					id: 0,
					title: "",
					wid:0,
					passageway:'',
					control: "L",
					layer: '',
					number:''
				},
				propss: {
					emitPath: false,
					multiple: false,
					checkStrictly: true,
					value: "id",
					label: "name"
				},
				propsss: {
					emitPath: false,
					multiple: false,
					checkStrictly: true,
					value: "id",
					label: "staff_name"
				},
				staffData:[],
				ruleValidate: {
					wid: [{
						required: true,
						message: "请选择仓库"
					}, ],
					store_id: [{
						type: 'number',
						required: true,
						message: "请选择门店",
						trigger: "blur"
					}, ],
					create_uid: [{
						type: 'number',
						required: true,
						message: "请选择创建人",
						trigger: "blur"
					}, ],
					type: [{
						required: true,
						message: "请选择报损原因",
						trigger: "blur"
					}, ],
				},
			};
		},
		computed: {
			...mapState("admin/layout", ["isMobile", "menuCollapse"]),
			labelWidth() {
				return this.isMobile ? undefined : 120;
			},
			labelPosition() {
				return this.isMobile ? "top" : "right";
			},
		},
		created() {
			this.getGodownList()
			this.staffList()
			this.getYlist()
		},
		mounted() {
			// this.setCopyrightShow({
			// 	value: false
			// });
			if(this.$route.query.id != 0) {
				// this.getPosition(this.$route.query.id)
			}else {
				this.formValidate.id = 0
			}
		},
		destroyed() {
			// this.setCopyrightShow({
			// 	value: true
			// });
		},
		methods: {
			...mapMutations("admin/layout", ["setCopyrightShow"]),
			getYlist() {
				getYlist().then(res => {
					this.yList = res.data.list
				})
			},
			jyNum(a = 0, b = 0, item) {
				if (a * 1 < b * 1) {
					item.pur_number = 0
					return this.$Message.error('输入值大于可商品的库存')
				}
			},
			setGoods(e) {
				// 校验商品是否重复
				if (this.chooseGoods.find(item => e.product_id == item.product_id)) {
					console.log('55');
					this.$refs.goodDetail.clearAll()
					return this.$Message.error('该商品已选择');
				} else {
					this.$refs.goodDetail.modals = false
					let qdata;
					if (this.formValidate.outType == 1) {
							qdata = {
								store_id: this.formValidate.store_id,
								product_id: e.product_id
							}
				
					} else {
						qdata = {
							wid: this.formValidate.wid,
							product_id: e.product_id
						}
					}
					getProductBatch(qdata).then(res => {
						if (res.data.length > 0) {
							console.log(res.data,'pici');
							try{
								this.chooseGoods = this.chooseGoods.concat({
									bar_code: e.bar_code,
									batchs: res.data.map(item => {
										let obj = {
											bar_code: item.bar_code,
											batch_code: item.batch_code,
											is_weigh: item.is_weigh,
											product_id: item.product_id,
											product_name: item.product_name,
											product_num: item.product_num,
											pur_number: 0,
											rate: item.rate,
											type: '',
											unit_name: item.unit_name,
											unit_type: item.unit_type,
											wid: item.wid
										}
										return obj
									}),
									product: e.info,
									product_id: e.product_id,
									product_name: e.product_name,
									product_num: e.product_num,
									unit_name: e.unit_name,
									think_count: e.think_count,
									wid: e.wid
								})
							}catch(e){
								console.log(e,'err');
								//TODO handle the exception
							}
							
						}
					})
					// this.chooseGoods = this.chooseGoods.concat(e)
				
				}
			},
			getGoods() {
				if (this.formValidate.wid == 0 && this.formValidate.store_id == 0) {
					return this.$Message.error('请选择报损单位');
				}
				try {
					this.$refs.goodDetail.formValidate.outType = this.formValidate.outType
					this.$refs.goodDetail.formValidate.wid = this.formValidate.wid
					this.$refs.goodDetail.formValidate.store_id = this.formValidate.store_id
					this.$refs.goodDetail.modals = true
					this.$refs.goodDetail.getList()
			
				} catch (e) {
					//TODO handle the exception
					console.log('err', e);
				}
			
			},
			delGood(index) {
				this.chooseGoods.splice(index, 1)
			},
			userSearchse(e) {
				this.formValidate.create_uid = "";
				this.authList = []
				this.getUserList()
			},
			getUserList() {
				let qdata = {}
				if(this.formValidate.outType == 1) {
					qdata.store_id = this.formValidate.store_id
				}else {
					qdata.wid = this.formValidate.wid
				}
				getUserList(qdata).then(res => {
					// console.log(res);
					this.authList = res.data.data
					// .map(item => {
					// 		item.id += ''
					// 		return item
					// 	});
				})
			},
			staffList() {
				console.log('kais');
				try{
					staffListInfo()
						.then((res) => {
							this.staffData = res.data
						})
						.catch((err) => {
							this.$Message.error(err.msg);
						});
				}catch(e){
					console.log(e,'eee');
					//TODO handle the exception
				}
				
			},
			changeOutType() {
				this.chooseGoods = []
				this.formValidate.store_id = 0
				this.formValidate.wid = 0
				this.formValidate.create_uid = 0
				this.formValidate.create_admin_id = 0
			},
			
			addchack(e, selectedData) {
				console.log(selectedData,'selectedData');
				e.forEach((i, index) => {
					if (index == 0) {
						this.formValidate.province = i
					} else if (index == 1) {
						this.formValidate.city = i
					} else if (index == 2) {
						this.formValidate.area = i
					} else {
						this.formValidate.street = i
					}
				})
				this.formValidate.address = (selectedData.map(o => o.label)).join('/')
				// console.log('this.formValidate.addressSelect',this.formValidate.addressSelect);
				
			},
			cityInfo(data) {
				cityApi(data).then(res => {
					this.addresData = res.data
				})
			},
			loadData(item, callback) {
				item.loading = true;
					cityApi({
						pid: item.value
					}).then(res => {
						item.children = res.data;
						item.loading = false;
						callback();
					});
				

			},
			getGodownList() {
				getGodownList({
					page: 1,
					limit: 10000
				}).then(res => {
					console.log(res);
					this.data1 = res.data.data.map(item => {
						item.id = item.id + ''
						return item
					})
					console.log(this.data1,'this.data1');
				})
			},
			del(index) {
				this.data.splice(index, 1);
			},
			userSearchsss(e) {
				if(e) {
					let obj = this.authList.find(item => item.id == e)
					this.formValidate.create_admin_id = obj.admin_id
				}
				
			},
			userSearchs(e) {
				this.getUserList()
			},
			handleSubmit(name) {
				let arr = []
				let goods = JSON.parse(JSON.stringify(this.chooseGoods))
					//过滤
					goods.forEach(item => {
						item.batchs = item.batchs.filter(items => {
							return items.pur_number && items.type
						})
						if(item.batchs.length > 0) {
							arr.push(item)
						}
					})
				
				
				console.log(arr,'this.chooseGoods');
				if(arr.length == 0) {
					return this.$Message.error('请至少填写一项报损数量和报损原因')
				}
				console.log(goods,'goods');
				this.$refs[name].validate((valid) => {
					if (valid) {
						this.formValidate.id = this.$route.query.id;
						let pdata = {}
						
						pdata = {
							create_uid: this.formValidate.create_uid,
							create_admin_id: this.formValidate.create_admin_id,
							// type: this.formValidate.type,
							info: arr
						}
						if(this.formValidate.outType == 1) {
							pdata.store_id = this.formValidate.store_id
						}else {
							pdata.wid = this.formValidate.wid
						}
						createLoss(pdata).then(res => {
							this.$Message.success(res.msg);
									this.$router.push({
										path: this.roterPre + "/erp/losses"
									});
						}).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;
	}
	.user-info {
		position: relative;
		padding: 20px;
	
		.section {
			padding: 25px 25px;
			border-bottom: 1px dashed #EEEEEE;
			position: relative;
	
			&-hd {
				padding-left: 10px;
				border-left: 3px solid #1890FF;
				font-weight: 500;
				font-size: 14px;
				line-height: 16px;
				color: #303133;
			}
	
			&-bd {
				display: flex;
				flex-wrap: wrap;
			}
	
			.item {
				// flex: 0 0 calc(~"(100% - 60px) / 3");
				width: 25%;
				min-width: 250px;
				display: flex;
				margin: 16px 30px 0 0;
				font-size: 13px;
				color: #606266;
	
				&:nth-child(3n+3) {
					margin: 16px 0 0;
				}
			}
	
			.value {
				flex: 1;
			}
	
			.avatar {
				width: 60px;
				height: 60px;
				overflow: hidden;
	
				img {
					width: 100%;
					height: 100%;
				}
			}
		}
	}
	.del-btn {
		position: absolute;
		right: 20px;
		top: 10px;
	}
	.del-btn-1 {
		position: absolute;
		right: 80px;
		bottom: 20px;
	}
</style>