<template>
	<el-dialog
		title="分批"
		v-model="visible"
		width="1000px"
		:size="1000"
		destroy-on-close
		@closed="$emit('closed')"
	>
		<el-form
			ref="dialogForm"
			:model="form"
			:rules="rules"
			label-width="80px"
		>
			<el-row>
				<el-col>
					<el-form-item label="物料批次：" label-width="100px">
						<b>{{batchOrign.batch}}</b>
						<span style="width: 80px;margin-left:60px;">物料总数：</span>
						<b>{{batchOrign.count}} </b>
						<el-button type="primary" @click="batchAdd" style="margin-left: 40px;">分批</el-button>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row v-for="(listItem,$index) in form.handoverb" :key="listItem">
				<el-col :span="10">
					<el-form-item label="批次号">
						<el-input  v-model="listItem.batch" :disabled="true"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="14">
					<span style="margin: 0 0 0 20px;" v-if="route_code=='pengma'">选择物料:</span>
					<el-input  ref="codeInput" 
					 	v-if="route_code=='pengma'"
						placeholder="扫描交接物料"
						v-model="listItem.wm_in"  clearable 
						style="width: 120px;margin: 0 10px;"
						@change="formWminChange($index,listItem.wm_in)" 
					></el-input>
					<el-select 
					    v-if="route_code=='pengma'"
						v-model="listItem.wpr" 
						placeholder="选择交接物料" 
						@change="wm_inChange($index)" 
						style="width: 140px;">
							<el-option
								v-for="item in wprOptions"
								:disabled="item.disabled"
								:key="item.id"
								:label="item.number"
								:value="item.id"
							>
						</el-option>
					</el-select>
					<span style="margin: 0 20px;">数量：{{ listItem.count }}</span>
					<el-button  v-if="mode!=='show'" type="danger" icon="el-icon-delete" @click="delMaterial($index)"></el-button>
				</el-col>
				<el-col v-if="route_code=='pengma'" style="padding-left: 80px;margin-bottom: 20px;margin-top: -5px;">
					<div v-for="(item2,index2) in form.handoverb[$index].handoverbw" :key="item2.wpr" class="wprItem">
						<span>{{ item2.number }}</span>
						<el-icon class="circleCloseFilled" @click="deleteWpr($index,index2,item2.wpr)"><el-icon-circleClose-filled /></el-icon>
					</div>
					<div v-for="item3 in diff" :key="item3" class="wprItem disabledItem">
						<span>{{ item3 }}</span>
					</div>
				</el-col>
				<el-col v-else-if="route_code=='kaiaomian'" :span="24" style="padding-left: 80px;margin-bottom: 20px;margin-top: -5px;">
					<span v-for="(item2) in wprOptions" :key="item2.wpr" style="margin-right: 10px;">
						<el-checkbox v-model="item2.checked" :label="item2.number" @change="handleChange($index)"/>
					</span>
				</el-col>
			</el-row>
			<el-row>
				<el-col :md="12" :sm="24">
					<el-form-item label="交送日期" prop="send_date">
						<el-date-picker
							v-model="form.send_date"
							type="date"
							placeholder="选择时间"
							format="YYYY-MM-DD"
							value-format="YYYY-MM-DD"
							style="width: 100%"
						/>
					</el-form-item>
				</el-col>
				<el-col :md="12" :sm="24">
					<el-form-item label="处理备注">	
						<el-input v-model="form.note" placeholder="处理备注"></el-input>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<el-footer v-if="mode!=='show'">
			<el-button type="primary" v-loading="isSaveing" @click="submit">确定</el-button>
			<el-button @click="visible = false">取消</el-button>
		</el-footer>
	</el-dialog>
</template>
<script>
import scanDialog from "./../template/scan.vue";
export default {
	emits: ["success", "closed"],
	props: {
		type: {
			type: Number,
			default: 10,
		},
		mgroupId: {
			type: String,
			default: "",
		},
		process:{
			type:String,
			default:""

		}
	},
	components: {
		scanDialog
	},
	data() {
		return {
			mode: "add",
			wm_in:"",
			mtype:20,
			lastBatchNum:1,
			addBactchNum:1,
			form: {
				send_date: null,
				send_user: null,
				send_mgroup: null,
				recive_user: null,
				recive_mgroup: null,
				handoverb:[],
			},
			rules: {
				batch: [
					{
						required: true,
						message: "请输入批次号",
						trigger: "blur",
					},
				],
				wm: {
					required: true,
					message: "请选择物料",
					trigger: "blur",
				},
			},
			route_code:"",
			batchOrign:{},
			wprOptions: [],
			materialOptions: [],
			loading: false,
			visible: false,
			isSaveing: false,
			setFiltersVisible: false,
		};
	},
	mounted() {
		let that  = this;
		let paths = that.$route.path;
		let arr = paths.split("/");
		that.route_code = arr[2];
		that.form.type = that.type;
		that.form.handle_date = that.form.send_date = that.$TOOL.dateFormat2(new Date());
		that.form.send_mgroup = that.form.recive_mgroup = that.mgroupId;
		let userInfo = that.$TOOL.data.get("USER_INFO");
		that.form.send_user = that.form.recive_user= userInfo.id;
	},
	methods: {
		getWpr(id){
			let that = this;
			that.$API.wpm.wpr.list.req({page:0,wm:id}).then((res) => {
				res.forEach(item=>{
					item.checked = false;
				})
				that.wprOptions = res;
			});
		},
		getNum(batch){
			let that = this;
			that.$API.wpm.batchlog.batchesTo.req({batch:batch}).then((res) => {
				if(res.last_batch_num!==null){
					that.lastBatchNum = res.last_batch_num;
					that.addBactchNum = res.last_batch_num+1;
				}else{
				    that.lastBatchNum = 0;
					that.addBactchNum = 1;
				}
				let obj = { };
				obj.wm = that.batchOrign.id;
				obj.batch = that.batchOrign.batch+"-"+that.addBactchNum;
				that.addBactchNum++;
				obj.count = 0;
				obj.wm_in = "";
				obj.handoverbw=[];
				that.form.handoverb.push(obj);
			})
		},
		//显示
		open(mode = "add",data,mtype) {
			this.mode = mode;
			this.form.mtype = mtype;
			this.batchOrign = data;
			this.getWpr(data.id);
			this.getNum(data.batch);
			this.visible = true;
			return this;
		},
		wm_inChange(index){
			let that = this;
			//放入对应的行中的handoverb中，并且在列表中disabled
			that.wprOptions.forEach(item=>{
			    if(item.id == that.form.handoverb[index].wpr){
					let obj = {};
					obj.number = item.number;
					obj.wpr = item.id;
					item.disabled = true;
					that.form.handoverb[index].handoverbw.push(obj);
					that.form.handoverb[index].wpr = '';
				}
			})
			that.form.handoverb[index].count = that.form.handoverb[index].handoverbw.length;
		},
		formWminChange(index,number){
			let that = this;
			let arrs = number.split(" ");
			let barchArrs = [];
			that.form.handoverb[index].wm_in = "";
			if(arrs.length>1){
				that.form.handoverb[index].wpr = '';
				arrs.forEach(arr=>{
				    that.wprOptions.forEach(item=>{
						if(item.number.indexOf(arr) > -1&&!item.disabled){
							item.disabled = true;
							let obj = {};
							obj.number = item.number;
							obj.wpr = item.id;
							barchArrs.push(arr);
							that.form.handoverb[index].handoverbw.push(obj);
							that.form.handoverb[index].count = that.form.handoverb[index].handoverbw.length;
						}
					})
				})
				//如果arrs里有不是这个批次的wpr,提示错误
				let diff = arrs.filter(item => !barchArrs.includes(item));
				that.diff = diff;
				console.log('diff',diff)
				if(diff.length>0){
					that.$message.warning("物料"+diff.join(",")+"不在该批次中");
					// that.$confirm("物料"+diff.join(",")+"不在该批次中", "提示", {type: "warning",}).then(() => {});
				}
			}else{
				//放入对应的行中的handoverb中，并且在列表中disabled
				that.wprOptions.forEach(item=>{
					if(item.number.indexOf(arr) > -1){
						if(item.disabled){
							that.$message.error("该物料已被分配");
							that.form.handoverb[index].wpr = '';
						}else{
							item.disabled = true;
							let obj = {};
							obj.number = item.number;
							obj.wpr = item.id;
							that.form.handoverb[index].handoverbw.push(obj);
							that.form.handoverb[index].count = that.form.handoverb[index].handoverbw.length;
							that.form.handoverb[index].wpr = '';
						}
					}
				})
			}
			console.log('this.$refs.codeInput',this.$refs.codeInput)
			this.$refs.codeInput[index].focus();
		},
		deleteWpr(index1,index2,wpr){
			let that = this;
			that.wprOptions.forEach(item=>{
			    if(item.id == wpr){
					item.disabled = false;
				}
			})
			that.form.handoverb[index1].handoverbw.splice(index2,1);
			that.form.handoverb[index1].count = that.form.handoverb[index1].handoverbw.length;
		},
		batchAdd(){
			let that = this;
			let obj = { };
			obj.wm_in = "";
			obj.wm = that.batchOrign.id;
			obj.batch = that.batchOrign.batch+"-"+that.addBactchNum;
			that.addBactchNum++;
			obj.count =0;
			obj.handoverbw=[];
			that.form.handoverb.push(obj)
		},
		delMaterial(index){
			let that = this;
			//解除该记录的wpr的disabled
			if(that.form.handoverb[index].handoverbw.length>0){
				that.form.handoverb[index].handoverbw.forEach(item=>{
					that.wprOptions.forEach(item2=>{
						if(item2.id == item.wpr){
							item2.disabled = false;
						}
					})
				})
			}
			that.form.handoverb.splice(index,1);
		},
		handleChange(index){
			let that = this;
			that.form.handoverb[index].handoverbw = [];
			let trueCount = this.wprOptions.filter(item => item.checked === true).length;
			that.form.handoverb[index].count =trueCount;
			this.wprOptions.forEach(item=>{
				if(item.checked){
					let obj = {};
					obj.number = item.number;
					obj.wpr = item.id;
					item.disabled = true;
					that.form.handoverb[index].handoverbw.push(obj);
				}
			})
		},
		//提交
		submit() {
			let that = this;
			that.$refs.dialogForm.validate(async (valid) => {
				if (valid) {
					let total = 0;
					if(this.form.handoverb.length>0){
						this.form.handoverb.forEach(item=>{
							total += item.count;
						})
					}
					if(total>that.totalCount){
						that.$message.error("分配数量不能大于总数量");
					}else{
						that.form.wm = that.batchOrign.id;
						if (that.mode == "add") {
							that.$API.wpm.handover.create.req(that.form).then((res) => {
								that.$API.wpm.handover.submit.req(res.id).then((res1) => {
									that.isSaveing = false;
									that.$emit("success");
									that.visible = false;
									that.$message.success("操作成功");
								});
							}).catch((err) => {
								//可以处理校验错误
								that.isSaveing = false;
								return err;
							});
						} 
					}
				}
			});
		},
		//表单注入数据
		setData(data) {
			Object.assign(this.form, data);
			console.log('this.form',this.form);
		},
		//设置过滤项
		setFilters(filters) {
			this.selectionFilters = filters;
			this.setFiltersVisible = true;
		},
	},
};
</script>
<style scoped>
.formTitle {
	margin-bottom: 10px;
	font-weight: 600;
}
.total-count{
	width: 100%;
    text-align: right;
    height: 50px;
    line-height: 50px;
}
.wprItem{
	background: #eeeeee;
	padding: 0 10px;
	border-radius: 5px;
	display: inline-block;
	position: relative;
	height: 30px;
	line-height: 30px;
	margin-right: 20px;
	margin-top: 5px;
}
.disabledItem{
	color: #fff;
	background: #f56c6c;
}
.circleCloseFilled{
	position: absolute;
    top: -7px;
    right: -10px;
    color: red;
    font-size: 20px;
}
</style>
