<template>
	<el-drawer
		title="关联产品"
		v-model="visible"
		:size="'70%'"
		destroy-on-close
	>
		<template #header>
			<h4>关联产品</h4>
			<el-button v-if="mode=='out'" type="primary" @click="wprNumberChange">发货编号</el-button>
			<el-button v-if="mode=='out'" type="warning" @click="wprNumberClear">清空编号</el-button>
			<el-button
				type="warning"
				:disabled="selectedRows.length === 0"
				:loading="batchCoderLoading"
				@click="batchSendToCoder"
			>批量喷码</el-button>
			<el-input
				style="margin-right: 5px;width: 200px;"
				v-model="search"
				placeholder="编号"
				clearable
				@keyup.enter="handleWprQuery"
			></el-input>
			<el-button
				type="primary"
				icon="el-icon-search"
				@click="handleWprQuery"
			></el-button>
		</template>
		<template #default>
			<el-table ref="wprTable" id="wprTable" :data="wprList" :height="wprTableHeight" border highlight-current-row @selection-change="handleSelectionChange">
				<el-table-column type="selection" width="50"></el-table-column>
				<el-table-column label="序号" type="index" width="50"></el-table-column>
				<el-table-column label="产品编号" prop="number" min-width="100px" ></el-table-column>
				<el-table-column label="对外编号" prop="number_out" min-width="100px"
					v-if="mgroupName=='成品内外初检'||mgroupName=='成品内质复检'||mgroupName=='成品性能检测'||mgroupName=='成品尺寸检测'||mgroupName=='成品外观复检一'||mgroupName=='成品外观复检二'"
				></el-table-column>
				<el-table-column label="记录数据" prop="oinfo">
					<template #default="scope">
						<div v-for="(item,index) in scope.row.oinfo" :key="item.id">
							{{ item.name }}:{{ item.val}}
							<span v-if="index<(scope.row.oinfo.length-1)">,</span>
						</div>
					</template>
				</el-table-column>
				<el-table-column label="缺陷项"  min-width="200px">
					<template #default="scope">
						<span v-for="item in scope.row.wprdefect" :key="item.id">
							<el-tag
								type="warning"
							>{{ item.defect_name }}</el-tag>
						</span>
					</template>
				</el-table-column>
				<el-table-column
					label="操作"
					fixed="right"
					align="center"
					width="200"
				>
					<template #default="scope">
						<el-button v-if="mode=='ins'&&mgroupName=='毛坯检测后打码'"  @click="QRCode(scope.row)" type="success">二维码</el-button>
						<el-button  @click="printMaterial(scope.row)" type="primary">打签</el-button>
						<el-button  @click="sendToCoder(scope.row)" type="warning" :loading="!!coderLoadingIds[scope.row.id]" :disabled="!!coderLoadingIds[scope.row.id]">喷码</el-button>
					</template>
				</el-table-column>
			</el-table>
		</template>
	</el-drawer>
	<el-dialog title="二维码" v-model="showQrCode" width="500px">
		<el-container>
			<el-main style="text-align: center;padding: 50px 0;">
				<scQrCode :text="scQr_code"></scQrCode>
			</el-main>
		</el-container>
	</el-dialog>
	<el-dialog title="设置发货编号" v-model="showBatch">
		<el-form :model="wprParams" label-width="80px">
			<el-form-item label="编号前缀">
				<el-input v-model="prefix"></el-input>
			</el-form-item>
		</el-form>
		<template #footer>
			<el-button @click="getWprNum">确定</el-button>
			<el-button @click="showBatch=false">取消</el-button>
		</template>
	</el-dialog>
	<el-dialog title="设置发货流水位数" v-model="showDigit">
		<h4>没有找到该前缀的发货编号，请完善发货流水号位数（填整数）</h4>
		<el-form :model="wprParams" label-width="80px">
			<el-form-item label="流水位数">
				<el-input-number controls-position="right" precision="0" v-model="digitNum"></el-input-number>
			</el-form-item>
		</el-form>
		<template #footer>
			<el-button @click="digitSure">确定</el-button>
		</template>
	</el-dialog>
</template>
<script>
import { wmState } from "@/utils/enum.js";
export default {
	name: "inm_record",
	props: {
		wm: { type: String, default: "" },
		mgroupId: { type: String, default: "" },
		process: { type: String, default: "" },
		ofromName: { type: String, default: "" },
		ofromBatch: { type: String, default: "" },
		mgroupName: {type: String,default: "",},
	},
	emits: ["success", "closed"],
	data() {
		return {
			wmState,
			visible: false,
			showBatch:false,
			showDigit:false,
			showQrCode:false,
			params:{
				page:0,
				wm:'',
			},
			mode:'',
			prefix:'',
			search:"",
			wmId:'',
			wmtype:'',
			scQr_code:'',
			wprList:[],
			selectedRows:[],
			batchCoderLoading: false,
			digitNum:3,
			wprTableHeight:500,
			printer_name:localStorage.getItem("printer_name"),
			apiObjPrint:this.$API.cm.labelmat.fromWm,
			coderLoadingIds:{},
		};
	},
	mounted() {
		let that = this;
		let paths = that.$route.path;
		let arr = paths.split("/");
		that.route_code = arr[2];
	},
	methods: {
		open(mode) {
			let that = this;
			that.wprList = [];
			this.mode = mode;
			this.params.wm = this.wm;
			this.visible = true;
			this.getRowWpr();
			that.$nextTick(() => {
			    let heights = document.getElementsByClassName("el-drawer__body")[0].clientHeight;
				that.wprTableHeight = heights-20;
			})
			return this;
		},
		getRowWpr(){
			let that = this;
			that.$API.wpm.wpr.list.req(that.params).then((res) => {
			    that.wprList = res;
			})
		},
		QRCode(row){
			this.showQrCode = true;
			this.$nextTick(() => {
				this.scQr_code=row.number;
			});
		},
		wprNumberChange(){
			let that = this;
			that.showBatch = true;
		},
		wprNumberClear(){
			let that = this;
			let items = [];
			for(let i=0;i< that.wprList.length;i++){
				let obj = {};
				obj.id =  that.wprList[i].id;
				obj.number_out = null;
				items.push(obj)
			}
			let params = {};
			params.items = items;
			that.$API.wpm.wpr.assginNumberOut.req(params).then((res) => {
				that.getRowWpr();
			})
		},
		getWprNum(){
			let that = this;
			let params0 = {};
			params0.prefix = that.prefix;
			that.$API.wpm.wpr.numberOutLast.req(params0).then((res) => {
				let number_out_last = '';
				if(res.number_out_last==null){//没有该前缀的发货编号
					number_out_last = null;
					that.showBatch=false;
					that.showDigit = true;
				}else{//有该前缀的发货编号
					let items = [];
					number_out_last = res.number_out_last;
					let str = number_out_last.replace(/[^a-zA-Z]/g, ''); // 提取字母
    				let num = number_out_last.replace(/[^0-9]/g, '');  // 提取数字
					let length = num.length;//流水号的长度
					for(let i=0;i< that.wprList.length;i++){
						let numb = Number(num)+i+1;
						let numbs = numb+'';
						let len = numbs.length;
						let zoreStr = '';
						for(let j=0;j<length-len;j++){
							zoreStr+='0';
						}
						let obj = {};
						obj.id =  that.wprList[i].id;
						obj.number_out = str + zoreStr + numb;
						items.push(obj)
					}
					let params = {};
					params.items = items;
					that.$API.wpm.wpr.assginNumberOut.req(params).then((res) => {
						that.showBatch=false;
						that.getRowWpr();
					})
				}
			})
		},
		//没有找到前缀的发货编号，从1开始编号时
		digitSure(){
			let that = this;
			//根据前缀和流水位数获取编号
			let items = [];
			for(let i=0;i< that.wprList.length;i++){
				let numb = i+1,zoreStr = '';
				numb+= '';
				let len = numb.length;
				for(let j=0;j<that.digitNum-len;j++){
					zoreStr+='0';
				}
				let obj = {};
				obj.id =  that.wprList[i].id;
				obj.number_out = that.prefix + zoreStr + numb;
				items.push(obj)
			}
			let params = {};
				params.items = items;
				that.$API.wpm.wpr.assginNumberOut.req(params).then((res) => {
					that.showDigit = false;
					that.getRowWpr();
				})
		},
		handleWprQuery(){
			let that = this;
			let foundIndex = that.wprList.findIndex(item => item.number.indexOf(that.search) > -1);
			if(foundIndex > -1){
				let found = that.wprList.splice(foundIndex, 1)[0];
				that.wprList.unshift(found);
				that.$nextTick(() => {
					that.$refs.wprTable.setCurrentRow(that.wprList[0]);
					that.$refs.wprTable.toggleRowSelection(that.wprList[0], true);
					that.$refs.wprTable.scrollTo({ top: 0 });
				});
			}
		},
		//打签
		printMaterial(row){
			let that = this;
			if(that.printer_name!==''&&that.printer_name!==null&&that.printer_name!==undefined){
				let params = {};
				let name = row.material_name.split('|')[0];
				if(that.route_code=='paiyicibang'||that.route_code=='kunbang'){
					console.log('that.route_code',that.route_code);
					console.log('that.ofromName',that.ofromName);
					that.$API.mtm.route.list.req({material_out:row.material,page:0}).then((res) => {
						let data = res[0].params_json;
						data.number = row.number;
						data.name=name;
						data.ofrom_name=that.ofromName;
						params.data = data;
						if(that.route_code=='paiyicibang'){
							params.label_template_name = '排一次棒单件打印模板';
						}else{
							params.label_template_name = '捆棒单件打印模板';
						}
						that.$API.cm.labeltemplate.commands.req(params).then((res) => {
							let obj = {};
							obj.printer_commands = res.commands;
							obj.printer_name = that.printer_name;
							let printer_ip=localStorage.getItem("printer_ip")||'127.0.0.1';
that.$API.wpm.prints.req(printer_ip, obj).then((response) => {
								that.$message.success("打印成功");
							});
						});
					})
				}else{
					if(that.route_code=='paiban'||that.route_code=='zhuangmo'||that.route_code=='zlybcl'||that.route_code=='tuomoceliang'||
						that.route_code=='reyatuihuo'||that.route_code=='banduangunyuan'||that.route_code=='banduangunyuanhoudama'||that.route_code=='banduangunyuantuihuo'
					){
						let oinfo = [];
						for(let key in row.oinfo){
							oinfo.push(row.oinfo[key])
						}
						let data = {sigao:'',duibian:'',moban:'',hengya:'',istest:'否',number:row.number,name:name,ofrom_name:that.ofromName,ofrom_batch:that.ofromBatch};
						if(that.route_code=='zhuangmo'||that.route_code=='tuomoceliang'||that.route_code=='reyatuihuo'||that.route_code=='banduangunyuan'){
							params.label_template_name = '脱膜测量单件标签模板';
						}else if(that.route_code=='zlybcl'){
							data.luhao = row.data.装炉压板出炉_设备编号?row.data.装炉压板出炉_设备编号:'';
							params.label_template_name = '装炉压板出炉单件标签模板';
						}else{
							params.label_template_name = '排扳单件打印模板';
						}
						if(oinfo.length>0){
							oinfo.forEach((item)=>{
								if(item.name=="丝高"){
									data.sigao = item.val;
								}else if(item.name=="横压"){
									data.hengya = item.val;
								}else if(item.name=="对边"){
									data.duibian = item.val;
								}else if(item.name=="模具号"){
									data.moban = item.val;
								}else if(item.name=="实验板段"){
									data.istest = item.val?'是':'否';
								}
							})
						}
						params.data = data;
					}else{
						params.label_template_name = '单件打印模板';
						params.data = {number:row.number,name:name};
					}
					that.$API.cm.labeltemplate.commands.req(params).then((res) => {
						let obj = {};
						obj.printer_commands = res.commands;
						obj.printer_name = that.printer_name;
						let printer_ip=localStorage.getItem("printer_ip")||'127.0.0.1';
that.$API.wpm.prints.req(printer_ip, obj).then((response) => {
							that.$message.success("打印成功");
						});
					});
				}
			}else{
				that.$message.warning("请先设置打印机");
			}
		},
		//把 wpr 行转成模板渲染数据
		rowToTdata(row){
			return {
				number: row.number,
				name: (row.material_name||'').split('|')[0],
				ofrom_name: this.ofromName,
				ofrom_batch: this.ofromBatch,
			};
		},
		//下发喷码: 单行入队 1 条
		sendToCoder(row){
			let that = this;
			if (that.coderLoadingIds[row.id]) return;
			let release = () => {
				let map = { ...that.coderLoadingIds };
				delete map[row.id];
				that.coderLoadingIds = map;
			};
			that.coderLoadingIds = { ...that.coderLoadingIds, [row.id]: true };
			that._postCoder([that.rowToTdata(row)])
				.then(() => that.$message.success("喷码下发成功"))
				.finally(release);
		},
		handleSelectionChange(rows){
			this.selectedRows = rows;
		},
		//批量喷码: 一次请求入队 N 条
		batchSendToCoder(){
			let that = this;
			if (!that.selectedRows.length || that.batchCoderLoading) return;
			let tdataList = that.selectedRows.map(r => that.rowToTdata(r));
			that.batchCoderLoading = true;
			that._postCoder(tdataList)
				.then(() => that.$message.success(`已入队 ${tdataList.length} 条`))
				.finally(() => { that.batchCoderLoading = false; });
		},
		//公共: 查模板 + 拼 body + 调接口
		_postCoder(tdataList){
			let that = this;
			let coder_ip = localStorage.getItem('coder_ip') || '';
			let coder_port = localStorage.getItem('coder_port') || '';
			let coder_field = localStorage.getItem('coder_field') || '';
			if (!coder_ip) {
				that.$message.error('请先在右上角"喷码设置"配置喷码IP');
				return Promise.reject(new Error('no coder_ip'));
			}
			let templateName = '喷码模板';
			return that.$API.cm.labeltemplate.list.req({name: templateName, page: 0}).then((res) => {
				let list = Array.isArray(res) ? res : (res && res.results) || [];
				let template = list.find(t => t.name === templateName);
				if (!template) {
					that.$message.error(`未找到标签模板: ${templateName}`);
					return Promise.reject(new Error('no template'));
				}
				let body = {tdata_list: tdataList, coder_ip};
				if (coder_port) body.coder_port = Number(coder_port);
				if (coder_field) body.coder_field = coder_field;
				return that.$API.cm.labeltemplate.sendToCoder.req(template.id, body);
			});
		},
		//本地更新数据
		handleSaveSuccess() {
			this.$refs.tables.refresh();
		},
	},
};
</script>
