<template>
	<el-drawer
		:title="headTitle[mode]"
		v-model="visible"
		:size="'90%'"
		destroy-on-close
		@closed="$emit('closed')"
	>
		<el-container>
			<el-main id="mlogbwMain">
				<sc-form-table
				hideDelete
				id="mlogbwlist"
				:tableHeight="tableHeight"
				v-model="mlogbwlist"
				:addTemplate="addTemplate"
				placeholder="暂无数据"
			>
				<el-table-column prop="number" label="物料编号">
					<template #default="scope">
						<span v-if="!scope.row.isEdit">{{ scope.row.number }}</span>
						<el-input v-if="scope.row.isEdit&&mode == 'outs'" v-model="scope.row.number" placeholder="物料编号"></el-input>
						<el-select
							v-if="scope.row.isEdit&&mode == 'ins'"
							v-model="scope.row.wpr"
							placeholder="动态成品"
							clearable
							style="width: 100%"
							@change="optionChange(scope.row)"
						>
							<el-option
								v-for="item in options"
								:key="item.id"
								:label="item.number"
								:value="item.id"
							>
							</el-option>
						</el-select>
					</template>
				</el-table-column>
				<el-table-column prop="note" :label="item.testitem_name" v-for="item in qct_testitems" :key="item.id">
					<template #default="scope">
						<el-input-number
							v-if="item.testitem_field_type=='input-number'"
							v-model="scope.row[item.testitem_name]"
							:min="0"
							:disabled="!scope.row.isEdit"
							class="width-100"
							controls-position="right"
							@change="defectCountSun(scope.row)"
						>
						</el-input-number>
						<el-input-number
							v-if="item.testitem_field_type=='input-int'"
							v-model="scope.row[item.testitem_name]"
							:min="0"
							:disabled="!scope.row.isEdit"
							class="width-100"
							controls-position="right"
							@change="defectCountSun(scope.row)"
						>
						</el-input-number>
						<el-input
							v-if="item.testitem_field_type=='input-text'"
							v-model="scope.row[item.testitem_name]"
							class="width-100"
							:disabled="!scope.row.isEdit"
							@change="defectCountSun(scope.row)"
						>
						</el-input>
						<el-select
							v-if="item.testitem_field_type=='select-text'"
							v-model="scope.row[item.testitem_name]"
							clearable
							class="width-100"
							:disabled="!scope.row.isEdit"
							@change="defectCountSun(scope.row)"
						>
							<el-option
								v-for="item0 in item.testitem_choices"
								:key="item0"
								:label="item0"
								:value="item0"
							>
							</el-option>
						</el-select>
						<el-select
							v-if="item.testitem_field_type=='selects-text'"
							v-model="scope.row[item.testitem_name]"
							clearable
							multiple
							class="width-100"
							:disabled="!scope.row.isEdit"
							@change="defectCountSun(scope.row)"
						>
							<el-option
								v-for="item1 in item.testitem_choices"
								:key="item1"
								:label="item1"
								:value="item1"
							>
							</el-option>
						</el-select>
					</template>
				</el-table-column>
				<el-table-column prop="note" :label="item.defect_name" v-for="item in qct_defects" :key="item.id" width="70px">
					<template #default="scope">
						<el-switch 
							:disabled="!scope.row.isEdit"
							v-model="scope.row[item.defect_name]" 
							style="--el-switch-on-color: red"
							@change="switchChange(scope.row, item)"
						></el-switch>
					</template>
				</el-table-column>
				<el-table-column prop="note" label="备注" width="80px">
					<template #default="scope">
						<span v-if="!scope.row.isEdit">{{ scope.row.note }}</span>
						<el-input v-else v-model="scope.row.note" placeholder="备注"></el-input>
					</template>
				</el-table-column>
				<el-table-column prop="open" label="操作" width="60" align="center">
					<template #default="scope">
						<el-button
							v-if="scope.row.isEdit"
							text
							type="primary"
							size="small"
							@click="formTableSave(scope.row)"
							>保存</el-button
						>
						<el-button
							v-if="scope.row.isEdit"
							text
							type="primary"
							size="small"
							@click="formTableCancel(scope.row)"
							>取消</el-button
						>
						<el-button
							v-else
							text
							type="primary"
							size="small"
							@click="formTableEdit(scope.row)"
							>编辑</el-button
						>
						<el-button
							v-if="!scope.row.isEdit"
							text
							type="danger"
							size="small"
							@click="formTableDel(scope.row.id)"
							>删除</el-button
						>
					</template>
				</el-table-column>
			</sc-form-table>
			</el-main>
		</el-container>
		
	</el-drawer>
</template>
<script>

export default {
	props: {
		mlogb: {
			type: String,
			default: "",
		},
		wm: {
			type: String,
			default: "",
		},
		qct: {
			type: String,
			default: "",
		},
		handle_user:{
			type: String,
			default: "",
		},
		handle_date:{
			type: String,
			default: "",
		},
	},
	emits: ["success", "closed"],
	data() {
		return {
			loading: false,
			headTitle:{
				ins:'输入物料详情',
				outs:'输出物料详情',
			},
			mode:'ins',
			//表单数据
			form: {},
			mgroup: "",
			params: {mlogb:'',page:0},
			visible: false,
			options:[],
			qct_defects:[],
			qct_testitems:[],
			mlogbwlist:[],
			addTemplate:{
                mlogb: "",
                number: "",
                note: "",
                isEdit: true,
            },
			tableHeight:500,
			apiObjPrint:this.$API.cm.labelmat.fromWm,
			printer_name:localStorage.getItem("printer_name")
		};
	},
	mounted() {
		let that = this;
		that.params.mlogb = that.addTemplate.mlogb = that.mlogb;
		that.getOptions();
		that.getdefects();
	},
	methods: {
		open(mode = "ins") {
			this.mode = mode;
			console.log(this.mode);
			this.visible = true;
			setTimeout(() => {
				this.tableHeight = document.getElementById('mlogbwMain').clientHeight-20;
			},500)
			
		},
		getdefects(){
			let that = this;
			if(that.qct!==null&&that.qct!==''){
				that.$API.qm.qct.item.req(that.qct).then((res) => {
					that.qct_defects = [];
					res.qct_defects.forEach((item) => {
						that.addTemplate[item.defect_name] = false;
					})
					that.qct_defects = res.qct_defects;
					that.qct_testitems = [];
					res.qct_testitems.forEach((item2) => {
						let obj2 = Object.assign({}, item2);
						obj2.value = '';
						obj2.addto_wpr = item2.addto_wpr;
						if(item2.testitem_field_type=='input-number'||item2.testitem_field_type=='input-int'){
							obj2.value = 0;
							that.addTemplate[item2.testitem_name] = 0;
						}
						if(item2.testitem_field_type=='select-text'||item2.testitem_field_type=='selects-text'){
							let str = obj2.testitem_choices.replace(/'/g, '"');
							let arr = JSON.parse(str);
							obj2.testitem_choices = arr;
							that.addTemplate[item2.testitem_name] = '';
						}
						that.qct_testitems.push(obj2);
					})
					that.getList();
				})
			}else{
				that.getList();
			}
		},
		getOptions(){
			let that = this;
			that.$API.wpm.wpr.list.req({wm:that.wm,page:0}).then((res) => {
				that.options = res;
			})
		},
		optionChange(row){
			let that = this;
			that.options.forEach((item) => {
				if(item.id == row.wpr){
					console.log('item',item);
					let index = that.mlogbwlist.indexOf(row);
					that.mlogbwlist[index].number = item.number;
					// that.mlogbwlist[index].wpr = item.id;
				}
			})
		},
		getList(){
			let that = this;
			that.$API.wpm.mlogbw.list.req(that.params).then((res) => {
				if(res.length>0){
					that.mlogbwlist = [];
					res.forEach((item) => {
						let obj = {};
					    obj = Object.assign({},item);
                    	obj.isEdit = false;
						if(that.qct!=null&&that.qct!=''&&item.ftest!=null){
							if(item.ftest.ftestdefects!==undefined&&item.ftest.ftestdefects!==''&&item.ftest.ftestdefects!==null&&item.ftest.ftestdefects.length>0){
								item.ftest.ftestdefects.forEach((item1) => {
									obj[item1.defect_name] = item1.has;
								})
							}
							if(item.ftest.ftestitems!==undefined&&item.ftest.ftestitems!==''&&item.ftest.ftestitems!==null&&item.ftest.ftestitems.length>0){
								item.ftest.ftestitems.forEach((item2) => {
									obj[item2.testitem_name] = item2.test_val_json;
								})
							}
						}else{
							that.qct_defects.forEach((item1) => {
								obj[item1.defect_name] = false;
							})
							that.qct_testitems.forEach((item2) => {
								if(item2.testitem_field_type=='input-number'||item.testitem_field_type=='input-int'){
									obj[item2.testitem_name] = 0;
								}else{
									obj[item2.testitem_name] = "";
								}
							})
						}
						that.mlogbwlist.push(obj);
					})
					console.log('mlogbwlistmlogbwlist',that.mlogbwlist);
				}
			})
		},
        //添加
		formTableSave(row) {
			let that = this;
			let obj = {};
			obj.number = row.number;
			obj.mlogb = row.mlogb;
			obj.wpr = row.wpr;
			obj.note = row.note;
			//qct不为空，有检验表
			if(that.qct!==null&&that.qct!==''){
				//检验表已经填过
				if(row.ftest!==null&&row.ftest!==undefined&&row.ftest!==''){
					console.log('已填过');
					obj.ftest =row.ftest;
					obj.ftest.ftestdefects.forEach((item) => {
						item.has = row[item.defect_name];
					})
					row.ftest.ftestitems.forEach((item1) => {
						item1.test_val_json = row[item1.testitem_name];
					})
					console.log('obj',obj);
				}else{//检验表未填过
					console.log('未填过');
					obj.ftest = {};
					obj.ftest.ftestitems = [];
					obj.ftest.ftestdefects = [];
					obj.ftest.qct = that.qct;
					obj.ftest.test_date = that.handle_date;
					obj.ftest.test_user = that.handle_user;
					that.qct_defects.forEach((item) => {
						let itemObj = {};
						itemObj.defect = item.defect;
						itemObj.test_user = that.handle_user;
						itemObj.has = row[item.defect_name]?row[item.defect_name]:false;
						obj.ftest.ftestdefects.push(itemObj);
					})
					that.qct_testitems.forEach((item1) => {
						let itemObj1 = {};
						itemObj1.testitem = item1.testitem;
						itemObj1.test_user = that.handle_user;
						itemObj1.addto_wpr = item1.addto_wpr;
						itemObj1.test_val_json = row[item1.testitem_name];
						obj.ftest.ftestitems.push(itemObj1);
					})
				}	
			}
            if(row.id!==''&&row.id!==undefined&&row.id!==null){
				obj.id = row.id;
				that.$API.wpm.mlogbw.update.req(row.id,obj).then((res) => {
					that.$message.success("保存成功");
					that.getList();
					return res;
				}).catch((err) => {
					return err;
				});
			}else{
				that.$API.wpm.mlogbw.create.req(obj).then((res) => {
					that.$message.success("添加成功");
					that.getList();
					return res;
				}).catch((err) => {
					return err;
				});
			}
		},
		formTableCancel(row){
			this.mlogbwlist.forEach((item, index) => {
				if (item.id == row.id) {
					this.mlogbwlist[index].isEdit = false;
				}
			});
		},
        formTableEdit(row) {
            this.mlogbwlist.forEach((item, index) => {
				if (item.id == row.id) {
					this.mlogbwlist[index].isEdit = true;
				}
			});
        },
		//删除
		formTableDel(id) {
            let that = this;
			that.$confirm(`确定删除吗？`, "提示", {
				type: "warning",
			}).then(() => {
                that.$API.wpm.mlogbw.delete.req(id).then((res) => {
                    that.$message.success("删除成功");
                    that.getList();
                    return res;
                }).catch((err) => {
                    return err;
                });
            }).catch(() => {});
		},
		switchChange(row,item){
			let that = this;
			let obj = {};
			obj = Object.assign({},item);
			// that.$API.wpm.mlogbw.update.req(row.id,obj).then((res) => {
			    
			// })
		},
		//表单提交方法
		mlogbwSubmit() {
			let that = this;
		},
		//表单提交方法
		mlogbSubmit() {
			let that = this;
			that.$API.wpm.mlogb.submit.req(that.mlogb).then((res) => {
				that.isSaveing = false;
				that.visible = false;
				that.$message.success("操作成功");
			});
		},
		defectCountSun(row){
			let that = this;
			let index = that.mlogbwlist.indexOf(row);
			that.qct_defects.forEach(item => {
				console.log('item.rule_expression',item.rule_expression);
				if(item.rule_expression!==''&&item.rule_expression!==undefined&&item.rule_expression!==null){
					let str = item.rule_expression.replace(/`/g, '');
					str = str.replace(/\${(.*?)}/g, 'row.\$1')
					let judge = eval(str);
					that.mlogbwlist[index][item.defect_name] = judge;
				}else{
					that.mlogbwlist[index][item.defect_name] = false;
				}
			});
		},
		//设置过滤项
		setFilters(filters) {
			this.selectionFilters = filters;
			this.setFiltersVisible = true;
		},
		handlePrint(){
			let that = this;
			that.printVisible = true;
		},
		//打印物料标签
		printMaterial(row){
			let that = this;
			that.apiObj.req({tid:row.id}).then((res) => {
				let code = res.code_label;
				let str = [
					"SIZE 40 mm,70 mm",
					"GAP 7 mm,7 mm",
					"CLS",
					"REFERENCE 0,0",
					'QRCODE 30,400,H,5,A,0,"' +code +'"',
					"WINTEXT 200,550,28,90,0,0,Simhei," + res.material_name,
					"WINTEXT 240,550,28,90,0,0,Simhei," + res.batch,
					"PRINT 1",
				]; 
				let obj = {};
				obj.printer_commands = str;
				obj.printer_name = that.printer_name;
                that.$API.wpm.prints.req(obj).then((response) => {
                    that.$message.success("打印成功");
				});
			})
		},
	},
};
</script>

<style scoped>
.width-100{
	width: 100%;
}
</style>
