<template>
	<el-dialog
		:title="titleMap[mode]"
		v-model="visible"
		style="width: 80%;"
		destroy-on-close
		@closed="$emit('closed')"
	>
		<el-container v-loading="loading">
			<el-main style="padding: 0 0 20px 0">
				<el-form
					ref="dialogForm"
					:model="form"
					:rules="rules"
					label-position="right"
					label-width="100px"
				>
					<el-row>
						<el-col>
							<el-form-item label="批次号" prop="wm_in">
								<xtSelect
									:apiObj="apiObjM"
									v-model="form.wm_in"
									v-model:obj="selectObj"
									:labelField="'batch'"
									style="width: 100%;"
									:params = "paramsM"
									@change="materialBatchChange"
								>
									<!-- :params = "{type__in: '10,20',is_hidden: false}" -->
									<el-table-column label="物料" prop="full_name">
										<template #default="scope">
											<span v-if="scope.row.state==20" style="color: red;border: 1px solid red;border-radius: 3px;">不合格</span>
											<span v-if="scope.row.state==30" style="color: orange;border: 1px solid orange;border-radius: 3px;">返工</span>
											<span>{{ scope.row.batch }}({{ scope.row.material_name }})</span>
											<span v-if="scope.row.defect_name !== null" style="color: orangered">{{ scope.row.defect_name }}</span>
										</template>
									</el-table-column>
									<el-table-column label="数量" prop="count" width="110px"></el-table-column>
								</xtSelect>
							</el-form-item>
							<!-- <el-form-item label="批次号" prop="wm_in">
								<el-select
									v-model="form.wm_in"
									placeholder="物料"
									clearable
									filterable
									class="width-100"
									@change="materialBatchChange"
								>
									<el-option
										v-for="item in materialOptions"
										:key="item.id"
										:label="item.batch"
										:value="item.id"
									>
										<div style="display: flex;justify-content: space-between;">
											<div>
												<span v-if="item.state==20" style="color: red;border: 1px solid red;border-radius: 3px;">不合格</span>
												<span v-if="item.state==30" style="color: orange;border: 1px solid orange;border-radius: 3px;">返工</span>
												<span>{{ item.batch }}({{ item.material_name }})</span>
												<span v-if="item.defect_name !== null" style="color: orangered">{{ item.defect_name }}</span>
											</div>
											<span>{{ item.count }}</span>
										</div>
									</el-option>
								</el-select>
							</el-form-item> -->
						</el-col>
						<el-col :md="12" :sm="24">
							<el-form-item label="关联任务">
								<el-select
									v-model="form.mtask"
									placeholder="关联任务"
									clearable
									style="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="24" v-if="mgroupName=='黑化'||mgroupName=='退火'">
							<el-form-item label="进炉数">
								<el-input-number
									v-model="batch_count"
									class="width-100"
									:disabled="true"
									controls-position="right"
								/>
							</el-form-item>
						</el-col>
						<el-col :md="12" :sm="24">
							<el-form-item :label="mgroupMtype==10?'领用数量':'批次总数'">
								<el-input-number
									v-model="selectObj.count_cando"
									:min="0"
									class="width-100"
									controls-position="right"
								/>
							</el-form-item>
						</el-col>
						<el-col :md="12" :sm="24" v-if="mgroupMtype==10">
							<el-form-item label="加工前不良" prop="count_pn_jgqbl">
								<el-input-number
									v-model="form.count_pn_jgqbl"
									:min="0"
									:disabled="true"
									style="width: 100%"
									controls-position="right"
								/>
							</el-form-item>
						</el-col>
						<el-col :md="12" :sm="24">
							<el-form-item label="备注">
								<el-input v-model="form.note"/>
							</el-form-item>
						</el-col>
					</el-row>
					<el-divider v-if="(mgroupName=='黑化'||mgroupName=='退火')&&cellsList.length>0"></el-divider>
					<el-button 
						v-if="mgroupName=='黑化'||mgroupName=='退火'" 
						icon="el-icon-plus"
						type="primary"
						@click="cellsAdd"
					></el-button>
					<template v-if="mgroupName=='黑化'||mgroupName=='退火'">
						<el-row v-for="(item,$index) in cellsList" :key="item">
							<el-col style="display: flex;">
								<el-form-item label="第" label-width="50">
									<el-input-number
										v-model="item.start"
										:min="1"
										placeholder="层数"
										controls-position="right"
									/>
								</el-form-item>
								<el-form-item label="层到第" label-width="65">
									<el-input-number
										v-model="item.end"
										:min="1"
										placeholder="层数"
										controls-position="right"
									/>
								</el-form-item>
								<el-form-item label="层，总数:" label-width="80">
									<el-input-number
									v-model="item.count_t"
									:min="0"
									placeholder="总数量"
									controls-position="right"
									@change="countTotalChange"
									/>
								</el-form-item>
								<el-button
									type="danger" 
									style="margin: 0 20px;" 
									@click="cellsDel($index)">删除</el-button>
							</el-col>
						</el-row>
					</template>
					<el-divider v-if="qct_defects.length>0"></el-divider>
					<el-row>
						<el-col :md="12" :sm="24" v-for="item in qct_defects" :key="item.id">
							<el-form-item :label="item.defect_name">
								<el-input-number
									v-model="defectform[item.defect_name]"
									:min="0"
									style="width: 100%"
									controls-position="right"
									@change="countChange"
								/>
							</el-form-item>
						</el-col>
					</el-row>
				</el-form>
			</el-main>
			<el-footer>
				<el-button type="primary" :loading="isSaveing" @click="submit">保存</el-button>
				<el-button @click="visible = false">取消</el-button>
			</el-footer>
		</el-container>
	</el-dialog>
</template>

<script>
const defaultForm = {
	mlog: "",
	mtask: "",
	batch: "",
	count_pn_jgqbl:0,
	count_use: 0,
};

export default {
	props: {
		mlog: {
			type: String,
			default: "",
		},
		mgroup: {
			type: String,
			default: "",
		},
		mgroupName:{
			type: String,
			default: "",
		},
		materialIn: {
			type: String,
			default: "",
		},
		codeText: {
			type: String,
			default: "",
		},
		is_fix: {
			type: Boolean,
			default: false,
		},
		mgroupMtype:{
			type: String,
			default: "",
		},
		mlogbdefect:{
			type:Array,
			default:()=>[]
		},
	},
	emits: ["success", "closed"],
	data() {
		return {
			loading: false,
			mode: "add",
			titleMap: {
				add: "新增",
				edit: "编辑",
			},
			//表单数据
			form: defaultForm,
			//验证规则
			rules: {
				wm_in: [
					{
						required: true,
						message: "请填写批次号",
						trigger: "blur",
					},
				],
				count_use: [
					{
						required: true,
						message: "请填写领用数量",
						trigger: "blur",
					},
				],
			},
			selectObj:{count:0},
			batch_count:null,
			codeBatch:"",
			materialFix:"",
			options: [],
			cellsList:[],
			qct_defects:[],
			materialOptions: [],
			defectform:{},
			visible: false,
			isSaveing: false,
			setFiltersVisible: false,
			apiObjM:this.$API.wpm.wmaterial.list,
			paramsM:{},
		};
	},
	mounted() {
		let that = this;
		that.paramsM.mtaskx =that.form.mtask;
		that.paramsM.mgroup = that.mgroup;
		// that.paramsM.query = "{id,batch,count,material,material_name,defect_name}";
		that.paramsM.page =0;
		if(that.is_fix){//来料未完成的返修品&&出料已完成的返修品和不合格品
			that.paramsM.tag = 'canfix';
		}else{
			that.paramsM.material =that.materialIn;
			that.paramsM.state =10;
			that.paramsM.tag = 'todo';
		}
		if(that.codeText!==''){
			let id = that.codeText.split('#')[1];
			this.$API.cm.labelmat.item.req(id).then((res) => {
				that.codeBatch = res.batch;
				that.paramsM.search = that.codeBatch;
				that.apiObjM = that.$API.wpm.wmaterial.list;
				// this.getMaterial();
			}).catch((err) => {
				that.apiObjM = that.$API.wpm.wmaterial.list;
			    // that.getMaterial();
			})
		}else{
			that.apiObjM = that.$API.wpm.wmaterial.list;
			// that.getMaterial();
		}
		if(that.is_fix){}else{
			this.getdefects();
		}
	},
	methods: {
		open(mode="add",data) {
			this.visible = true;
			this.form.mtask = "";
			this.form.wm_in = "";
			this.form.count_use = 0;
			this.form.parent = "";
			if(data){
				this.form = data;
				this.cellsList = data.count_json_from;
			}
		},
		getMtask() {
			let that = this;
			this.$API.pm.mtask.list.req({ page: 0, mgroup: that.mgroup, state: 20 }).then((res) => {
				that.options = res;
			});
		},
		//获取车间物料
		getMaterial() {
			let that = this;
			let obj = {};
			obj.mtaskx =that.form.mtask;
			obj.mgroup = that.mgroup;
			obj.search = that.codeBatch;
			// obj.query = "{id,batch,count,material,material_name,defect_name}";
			obj.page =0;
			if(that.is_fix){//来料未完成的返修品&&出料已完成的返修品和不合格品
				obj.tag = 'canfix';
				// obj.state = 20;
				// obj.state =30;
			}else{
				obj.material =that.materialIn;
				obj.state =10;
				obj.tag = 'todo';
			}
			this.$nextTick(()=>{
				this.$API.wpm.wmaterial.list.req(obj).then((res) => {
					that.materialOptions = res;
					res.forEach(item => {
						if(item.batch==that.codeBatch){
							that.form.wm_in = item.id;
							that.form.count_use = item.count;
							that.batch_count = item.count;
						}
						if(that.form.wm_in == item.id){
							that.codeBatch=item.batch;
							that.batch_count = item.count;
						}
					});
				});
			})
		},
		getdefects(){
			let that = this;
			let material = that.is_fix?that.materialFix:that.materialIn;
			that.$API.qm.qct.getQct.req({material: material,tag:'process'}).then((res) => {
				res.qct_defects.forEach((item) => {
					that.defectform[item.defect_name] = 0;
				})
				that.qct_defects=res.qct_defects;
				let count_pn_jgqbl = 0;
				if(data.mlogbdefect.length>0){
					that.qct_defects.forEach(item => {
						data.mlogbdefect.forEach(item2=>{
							if(item.defect==item2.defect){
								count_pn_jgqbl+=item2.count;
								that.defectform[item.defect_name] = item2.count;
							}
						})
					})
				}
			})
		},
		materialBatchChange(){
			let that = this;
			that.form.batch = that.selectObj.batch;
			that.form.count_use = that.selectObj.count;
			that.batch_count = that.selectObj.count;
			that.materialFix = that.selectObj.material;
			that.getdefects();
			// that.materialOptions.forEach(item => {
			// 	if(item.id==that.form.wm_in){
			// 		that.form.batch = item.batch;
			// 		that.form.count_use = item.count;
			// 		that.batch_count = item.count;
			// 		that.materialFix = item.material;
			// 		that.getdefects();
			// 	}
			// });
		},
		//添加层组
		cellsAdd(){
			let that = this;
			let obj = {start:null, end:null,count_t:null};
			that.cellsList.push(obj)
		},
		//删除层组
		cellsDel(index){
			this.cellsList.splice(index,1)
		},
		countTotalChange(){
			let that = this;
			let sum = 0,sumTotal=0;
			that.cellsList.forEach(item=>{
				sum+=item.count_t;
				if(sum>that.batch_count){
					item.count_t=0;
					that.$message.error('合计数量超过该批次总数量，请重新分配第'+item.start+'层到第'+item.end+'层的数量');
				}else{
					sumTotal+=item.count_t;
				}
			})
			that.form.count_use = sumTotal;
			
		},
		cellStartChanges(){
			let that = this;
			let remaind = (that.form.count_use-that.form.count_pn_jgqbl)%that.count_cell;
			that.cellsList = [];
			for(let i=0;i<that.cells;i++){
				let obj = {};
				obj.floor=that.cell_start+i;
				if((that.cells-i)==1&&remaind>0){
					obj.count_use = remaind;
				}else{
					obj.count_use = that.count_cell;
				}
				that.cellsList.push(obj)
			}
		},
		countCellChanges(){
			this.cells =Math.ceil((this.form.count_use-this.form.count_pn_jgqbl)/this.count_cell);
			this.cellStartChanges();
		},
		countChange() {
			let that = this;
			that.form.count_pn_jgqbl = 0;
			that.qct_defects.forEach(item => {
				if(item.defect_okcate==30){
			    	that.form.count_pn_jgqbl += that.defectform[item.defect_name];
				}
			})
			that.countCellChanges();
		},
		//表单提交方法
		submit() {
			let that = this;
			that.$refs.dialogForm.validate(async (valid) => {
				if (valid) {
					that.isSaveing = true;
					that.form.mlog = that.mlog;
					that.form.batch = that.selectObj.batch;
					that.form.count_use = that.selectObj.count_cando;
					if(that.mgroupMtype==10&&that.cellsList.length>0){
						that.form.count_json_from = that.cellsList;
					}
					let count_pn_jgqbl = 0,mlogbdefect=[];
					that.qct_defects.forEach(item => {
						if(that.defectform[item.defect_name]>0){
							count_pn_jgqbl += that.defectform[item.defect_name] ;
							let obj = {};
							obj.defect = item.defect;
							obj.count = that.defectform[item.defect_name];
							mlogbdefect.push(obj);
						}
					})
					that.form.mlogbdefect = mlogbdefect;
					that.form.count_pn_jgqbl = count_pn_jgqbl;
					console.log(that.form);
					console.log(that.selectObj);
					that.$API.wpm.mlogb.in.req(that.form).then((res) => {
						that.isSaveing = false;
						that.$emit("success");
						that.visible = false;
						that.$message.success("操作成功");
					}).catch((err) => {
						that.isSaveing = false;
					});
				}
			});
		},
		//设置过滤项
		setFilters(filters) {
			this.selectionFilters = filters;
			this.setFiltersVisible = true;
		},
	},
};
</script>

<style></style>
