<!-- 新增mlogbIn -->
<template>
	<el-dialog
		title="添加日志详情"
		v-model="visible"
		:size="1000"
		destroy-on-close
		@closed="$emit('closed')"
	>
		<el-container v-loading="loading">
			<el-main style="padding: 0">
				<el-form
					ref="dialogForm"
					:model="form"
					:rules="rules"
					label-position="right"
					label-width="80px"
					style="padding: 0"
				>
					<el-row>
						<el-col :md="12" :sm="12" :xs="24" v-if="!isfix&&!hasRoute">
							<el-form-item label="工艺步骤" prop="route">
								<el-select
									v-model="form.route"
									placeholder="工艺步骤"
									clearable
									filterable
									style="width: 100%"
									:disabled="mode == 'edit'"
									@change="routeChange"
								>
									<el-option
										v-for="item in routeOptions"
										:key="item.id"
										:label="item.name"
										:value="item.id"
									>
									<span>[{{ item.routepack_name }}]{{ item.name }}</span>
									</el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :md="12" :sm="12" :xs="24" v-if="!isfix">
							<el-form-item label="关联任务">
								<el-select
									v-model="form.mtask"
									placeholder="关联任务"
									clearable
									class="width-100"
									@change="getMaterial"
								>
									<el-option
										v-for="item in options"
										:key="item.id"
										:label="item.number"
										:value="item.id"
									>
									</el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :md="12" :sm="12" :xs="24">
							<el-form-item label="批次选择">
								<el-select
									v-model="batchs"
									placeholder="批次选择"
									clearable
									class="width-100"
									@change="changeMaterial"
								>
									<el-option
										v-for="item in materialOptions"
										:key="item.id"
										:label="item.batch"
										:value="item.id"
									>
									<span>{{ item.batch }}</span>
									<span v-if="item.defect_name&&item.defect_name!==null">({{ item.defect_name }})</span>
									<span style="float: right;">{{ item.count_cando }}</span>
									</el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :md="12" :sm="12" :xs="24">
							<el-form-item label="物料扫码" style="display: flex;">
								<el-input ref="codeInput" v-model="wm_in" clearable @change="formWminChange(wm_in)" style="width: 200px;margin-left: 4px;"></el-input>
							</el-form-item>
						</el-col>
						<el-col :md="12" :sm="12" :xs="24">
							<el-form-item label="使用数量" prop="count_use">
								<el-input-number  ref="codeInput" v-model="form.count_use" :min="0" clearable class="width-100"></el-input-number>
							</el-form-item>
						</el-col>
						<el-col :md="12" :sm="12" :xs="24">
							<el-form-item label="主要批次" v-if="!isfix">
								<el-select
									v-model="form.parent"
									placeholder="主要批次"
									clearable
									class="width-100"
								>
									<el-option
										v-for="item in mlogbInOptions"
										:key="item.id"
										:label="item.batch"
										:value="item.id"
									>
									</el-option>
								</el-select>
							</el-form-item>
						</el-col>
					</el-row>
				</el-form>
				<el-footer>
					<el-button type="primary" :loading="isSaveing" @click="submit">提交</el-button>
					<el-button @click="visible = false">取消</el-button>
				</el-footer>
			</el-main>
		</el-container>
	</el-dialog>
</template>

<script>
const defaultForm = {
	mlog: "",
	mtask: "",
	batch: "",
	wm_in: "",
	count_use: 0,
	note:'',
	parent: "",
};
export default {
	props: {
		mlog: {
			type: String,
			default: "",
		},
		mgroup: {
			type: String,
			default: "",
		},
		tracking:{
			type: Number,
			default: null,
		},
		routeId:{
			type: String,
			default: "",
		},
		material_in: {
			type: String,
			default: "",
		},
		hasRoute:{
			type: Boolean,
			default: false,
		},
		isfix:{
			type: Boolean,
			default: false,
		},
		process:{
		    type: String,
			default: "",
		},
	},
	emits: ["success", "closed"],
	data() {
		return {
			batchs:"",
			loading: false,
			mode: "add",
			titleMap: {
				add: "新增",
				edit: "编辑",
			},
			//表单数据
			form: defaultForm,
			//验证规则
			rules: {
				wm_in: [
					{
						required: true,
						message: "请填写批次号",
						trigger: "blur",
					},
				]
			},
			wm_in:'',
			mlogbId:'',
			route_code:"",
			mlogbIns:[],
			options: [],
			optionsEq: [],
			routeOptions: [],
			mlogbInOptions:[],
			materialOptions: [],
			mgroup_code:'',
			mlogbInId:'',
			mlogbInCount:0,
			hasMlogbIn:false,
			visible: false,
			isSaveing: false,
			setFiltersVisible: false,
			params: {
				page: 0,
				mlog: "",
				material_in__isnull: 0,
			},
			bwItemForms:[],
			bwItemForm:{
				wpr:"",
				mlogb:"",
				number:"",
			},
		};
	},
	mounted() {
		this.materialIn = this.material_in;
		this.route_code = this.$route.path.split("/")[2];
		this.form.mlog = this.mlog;
		this.params.mlog = this.mlog;
		let arr = this.$route.path.split("/");
		this.mgroup_code = arr[2];
		this.$nextTick(()=>{
		   this.getMlogbIn();
			this.getMtask();
			this.getMaterial();
			this.getParentList();
			this.getEquipment();
			if(!this.hasRoute&&!this.isfix){
				this.getRoute();
			}
		})
	},
	methods: {
		open() {
			this.visible = true;
			this.form.mtask = "";
			this.wm_in = "";
			this.form.count_use = 0;
			this.form.parent = "";
		},
		getMlogbIn(){
			let that = this;
			let params = {};
			params.page= 0;
			params.mlog= that.mlog;
			params.material_in__isnull=0;
			this.$API.wpm.mlogb.list.req(params).then((res) => {
			    that.mlogbIns = res;
			})
		},
		getEquipment() {
			let that = this;
			this.$API.em.equipment.list.req({ page: 0, type: 10,mgroup:that.mgroup}).then((res) => {
				res.forEach((item) => {
					let obj = {};
					Object.assign(obj, item);
					obj.label = item.name+'-'+item.number;
					that.optionsEq.push(obj);
				});
			});
		},
		getRoute() {
			let that = this;
			that.$API.mtm.route.list
				.req({ process: that.process, page: 0, routepack__state: 30 })
				.then((res) => {
					that.routeOptions = res;
					if(res.length==1){
						that.form.route = res[0].id;
					}
				});
		},
		getParentList(){
			let that = this;
			that.$API.wpm.mlogb.list.req(that.params).then((res) => {
				if(res.length>0){
					that.mlogbInOptions = res.filter((item)=>{
						return item.parent==null;
					})
					// that.form.parent = that.mlogbInOptions[0].id;
				}else{
					that.form.parent = '';
				}
			})
		},
		//获取任务列表
		getMtask() {
			console.log(this.materialIn);
			let that = this;
			let obj = {};
			obj.page = 0;
			obj.state = 20;
			obj.mgroup = that.mgroup;
			obj.route__material_in = that.materialIn;
			this.$API.pm.mtask.list.req(obj).then((res) => {
				that.options = res;
			});
		},
		//获取车间物料
		getMaterial() {
			let that = this;
			let obj = {};
			console.log('that.mgroup',that.mgroup);
			obj.mtaskx =that.form.mtask;
			obj.mgroupx =that.mgroup;
			if(that.routeId!==null&&that.routeId!==''){
				obj.route =that.routeId;
			}
			obj.page =0;
			if(that.isfix ){//来料未完成的返修品&&出料已完成的返修品和不合格品
				obj.tag = 'canfix';
			}else{
				if(that.materialIn!==null&&that.materialIn!==''){
					obj.material =that.materialIn;
				}
				obj.state =10;
				obj.tag = 'todo';
			}
			this.$API.wpm.wmaterial.list.req(obj).then((res) => {
				let arr = [];
				if(res.length>0){
					arr = res.filter((item)=>{
						return Number(item.count_cando)>0;
					})
				}
				that.materialOptions = arr;
			});
		},
		routeChange(){
			let that = this;
			that.routeOptions.forEach(item=>{
			    if(item.id == that.form.route){
					that.materialIn = item.material_in;
					that.getMaterial();
				}
			})
		},
		changeMaterial(){
			let that = this;
			that.materialOptions.forEach(item=>{
			    if(item.id == that.batchs){
					that.form.batch = item.batch;
					that.form.wm_in = item.id;
					that.form.count_use = item.count_cando;
				}
			})
		},
		//扫描后处理方法
		formWminChange(code){
			console.log('code',code);
			let that = this,codeId='',arr=[];
			code = code.replace(/(^\s*)|(\s*$)/g, "");
			if(code.indexOf("#")>-1){
				let arrs = code.split("#");
				codeId = arrs[1];
				that.scanKyes = arrs[0];
				this.$API.cm.labelmat.item.req(codeId).then((res) => {
					if(res){
						arr = that.materialOptions.filter((item) => {
							return item.batch == res.batch&&item.state==res.state;
						})
						if (arr.length > 0) {
							that.form.batch = arr[0].batch;
							that.form.wm_in = arr[0].id;
							that.form.count_use = arr[0].count;
							that.wm_in = arr[0].batch;
						}else{
							that.wm_in = '';
							that.$message.error("批次号不存在");
						}
					}else{
						that.wm_in = '';
					}
				}).catch((err) => {
					that.wm_in = '';
					that.$message.error("批次号不存在");
				});
			}else{
				that.scanKyes = "";
				that.$API.wpm.wpr.list.req({number:code,page:0}).then((res) => {
					if(res.length>0){
						let index = res.length-1;//最后一条记录
						let bwitem = {};
						bwitem.mlogb="";
						bwitem.number=res[index].number;
						bwitem.wpr=res[index].id;
						let arr = that.materialOptions.filter((item) => {
							return item.id == res[index].wm;
						})
						if(arr.length>0){ //车间存在该批次
							let batch = arr[0].batch;
							that.wm_in = arr[0].batch;
							that.mlogbInCount = arr[0].count;//该批次数量
							//判断日志中是否存在该批次
							let arr0= that.mlogbIns.filter((item)=>{
								return item.batch == batch;
							})
							let arr1 = that.bwItemForms.filter((item)=>{
								return item.number == bwitem.number;
							})
							if (arr0.length > 0) {
								that.hasMlogbIn = true;
								that.form.count_use = 1;
								that.mlogbId = arr0[0].id;
								bwitem.mlogb = arr0[0].id;
							}else{
								if(arr1.length>0){
									that.wm_in = '';
									that.$message.error("已存在");
								}else{
									that.form.batch = arr[0].batch;
									that.form.wm_in = arr[0].id;
									that.form.count_use += 1;
									that.wm_in = '';
									that.batchs = arr[0].id;
								}
							}
							that.bwItemForms.push(bwitem);
							// that.bwItemForm = bwitem;
						}else{
							that.wm_in = '';
							that.$message.error("批次号不存在");
						}
					}
				})
				// if(that.tracking==10||that.tracking==null){//批次
				// 	arr = that.materialOptions.filter((item) => {
				// 		return item.batch == code;
				// 	})
				// 	if (arr.length > 0) {
				// 		that.form.batch = arr[0].batch;
				// 		that.form.wm_in = arr[0].id;
				// 		that.form.count_use = arr[0].count;
				// 		that.wm_in = arr[0].batch;
				// 	}else{
				// 		that.wm_in = '';
				// 		that.$message.error("批次号不存在");
				// 	}
				// }else{//单件
				// 	console.log('code',code);
					
				// }
			}
		},
		//表单提交方法
		submit() {
			let that = this;
			if(that.hasMlogbIn){
				that.$API.wpm.mlogbw.create.req(that.bwItemForms).then((res1) => {
					that.wm_in = '';
					that.form.mtask = '';
					that.form.batch = '';
					that.form.parent = '';
					that.form.count_use = 0;
					that.$emit("closed");
					that.visible = false;
				})
			}else{
				that.form.mlog = that.mlog;
				that.$API.wpm.mlogb.in.req(that.form).then((res) => {
					that.$message.success("添加成功");
					that.wm_in = '';
					that.form.mtask = '';
					that.form.batch = '';
					that.form.parent = '';
					that.form.count_use = 0;
					if(that.scanKyes!=='mat'&&that.bwItemForms.length>0){
						//2
						// async function callApis() {
						// for (const item of that.bwItemForms) {
						// 	item.mlogb = res.id;
						// 	try {
						// 		await that.$API.wpm.mlogbw.create.req(item).then((res) => {});
						// 	} catch (error) {
						// 		console.error('Error calling API:', error);
						// 	}
						// }
						// }
						// callApis();
						//1
						// const promises = that.bwItemForms.map(item => {
						// 	item.mlogb = res.id;
						// 	return that.$API.wpm.mlogbw.create.req(item).then((res) => {});
						// });
						// console.log('promises.length',promises.length);
						// Promise.all(promises).then(results => {
						// 	console.log('results',results);
						// 	that.$emit("closed");
						// }).catch(error => {
						// 	console.error(error);
						// });
						//0
						that.bwItemForms.forEach(item=>{
						    item.mlogb = res.id;
						})
						that.$API.wpm.mlogbw.create.req(that.bwItemForms).then((res1) => {
							that.$emit("closed");
						})
					}else{
						that.$emit("closed");
					}
					that.visible = false;
				}).catch((err) => {});
			}
		},
		//设置过滤项
		setFilters(filters) {
			this.selectionFilters = filters;
			this.setFiltersVisible = true;
		},
	},
};
</script>

<style></style>
