/***文档注释***********************************************
 * 作者            ：
 * 创建日期     ：2018-09-17
 * 描述            ：平整机生产主实绩
 * 注意事项     ：
 * 遗留BUG   ：
 * 修改日期     ：
 * 修改人员     ：
 * 修改内容     ：
***********************************************************/
package market.Mes.Tpm.impl;
import java.io.File;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.UnderlineStyle;
import jxl.format.VerticalAlignment;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import market.Api.Lms.impl.LmsApiServiceImpl;
import market.Api.Mes.impl.MesApiDesignInfoImpl;
import market.Api.Mes.impl.MesApiServiceImpl;
import market.Api.Mes.impl.MesApiSkinrollingPlanImpl;
import market.Api.Mes.impl.MesApiTpmPdiPdoImpl;
import market.Api.Mes.impl.ProcessPoint;
import market.Api.Mes.impl.Utils;
import market.Api.Qms.impl.QmsApiServiceImpl;
import market.Api.Qms.vo.JudgeResult;
import market.Com.impl.PbModelDbServiceImpl;
import market.Com.mapper.ComBaseInfoMapper;
import market.Com.mapper.ComBaseMachineMapper;
import market.Com.mapper.ComBasePlineMapper;
import market.Com.mapper.ComBaseSteelMapper;
import market.Com.pb.DoubleUtil;
import market.Com.vo.ComBaseCbYdd;
import market.Com.vo.ComBaseInfo;
import market.Com.vo.ComBaseMachine;
import market.Com.vo.ComBasePline;
import market.Com.vo.ComBaseSteel;
import market.Com.vo.CommonPage;
import market.Com.vo.ResultModel;
import market.Lms.Warehouse.impl.YdmProductDetailServiceImpl;
import market.Lms.Warehouse.mapper.YdmProductDetailMapper;
import market.Lms.Warehouse.service.YdmProductInlistService;
import market.Lms.Warehouse.vo.YdmProductDetail;
import market.Mes.Lengthwise.Performance.vo.MesPrdDetailReport;
import market.Mes.Lengthwise.Performance.vo.MesSteelCodeTemp;
import market.Mes.Lengthwise.Plan.mapper.PlnMaterielDetailMapper;
import market.Mes.Lengthwise.Plan.mapper.PlnProcessPlanMapper;
import market.Mes.Lengthwise.Plan.vo.PlnMaterielDetail;
import market.Mes.Lengthwise.Plan.vo.PlnProcessPlan;
import market.Mes.MaterielTrack.vo.PrcMaterielRelation;
import market.Mes.Opr.mapper.MesOprLogMapper;
import market.Mes.Opr.vo.MesOprLog;
import market.Mes.OrderManager.Plan.impl.PlnProdorderStatisticServiceImpl;
import market.Mes.OrderManager.Plan.mapper.PlnProdorderMapper;
import market.Mes.OrderManager.Plan.vo.PlnProdorder;
import market.Mes.Packing.Result.mapper.MesOprInfoMapper;
import market.Mes.Packing.Result.vo.MesOprInfo;
import market.Mes.Shift.mapper.MesShiftMMapper;
import market.Mes.Shift.vo.MesShiftM;
import market.Mes.Tpm.mapper.IfTpm01LogMapper;
import market.Mes.Tpm.mapper.MesTpmDMapper;
import market.Mes.Tpm.mapper.MesTpmMMapper;
import market.Mes.Tpm.mapper.MesTpmWgtMapper;
import market.Mes.Tpm.mapper.PlnSkinrollingPlanDetailMapper;
import market.Mes.Tpm.mapper.PlnSkinrollingPlanMapper;
import market.Mes.Tpm.service.MesTpmMService;
import market.Mes.Tpm.vo.MesTpmD;
import market.Mes.Tpm.vo.MesTpmM;
import market.Mes.Tpm.vo.MesTpmTrc;
import market.Mes.Tpm.vo.MesTpmWgt;
import market.Mes.Tpm.vo.PlnSkinPlanDetailAndMesTpmD;
import market.Mes.Tpm.vo.PlnSkinRollingView;
import market.Mes.Tpm.vo.PlnSkinrollingPlan;
import market.Mes.Tpm.vo.PlnSkinrollingPlanDetail;
import market.Mes.anneal.mapper.MesCrAnnealMMapper;
import market.Mes.util.DateUtil;
import market.Qms.qcm.service.impl.QcmJhySampleConsignDItemServiceImpl;
import market.Qms.qcm.vo.QcmJhySampleFromPlan;
import market.Slm.FundManagement.impl.SlmFundFirstDetailServiceImpl;
import market.Slm.FundManagement.service.SlmFundFirstDetailService;

import org.apache.commons.lang.StringUtils;
import org.springframework.transaction.annotation.Transactional;

import com.hnshituo.basic.service.impl.BaseServiceImpl;
import com.hnshituo.basic.spring.remoting.annotation.RemoteService;
import com.hnshituo.core.auth.service.HomeService;

@RemoteService(path="MesTpmMService")
public class MesTpmMServiceImpl extends BaseServiceImpl<MesTpmM,Object> implements MesTpmMService {

	/**
	 * 生产监视页面接口
	 * @param oci
	 * memo1:传机台代码
	 * @return
	 */
	public ResultModel doQueryTrcWeb(CommonPage<MesTpmTrc> oci){
		ResultModel rm=new ResultModel();
		if(oci.getMemo1()==null || "".equals(oci.getMemo1())){
			rm.setState("500");
			rm.setMsgInfo("请输入机台代码");
			return rm;
		}
		try{
			rm.setData(this.getMapper(MesTpmMMapper.class).doQueryWebTrc(oci.getMemo1(),oci.getMemo2()));
			rm.setState("200");
		}catch(Exception ex){
			ex.printStackTrace();
			rm.setState("500");
			rm.setMsgInfo("查询失败!"+ex.getMessage());
		}
		return rm;
	}
		
	/**
	 * 平整机组生产明细报表
	 * memo1:机台代码
	 * startTime:计划下发时间开始
	 * endTime:计划下发时间结束
	 * startTime2:交工时间开始
	 * endTime2:交工时间结束
	 * memo2:生产时间开始
	 * meme3:生产时间结束
	 * memo4:交货时间开始
	 * memo5:交货时间结束
	 * */
	public ResultModel doPrdDetailWeb_tpm(CommonPage<MesPrdDetailReport> oci){
		ResultModel rm=new ResultModel();
		try{
			rm.setData(this.getMapper(MesTpmMMapper.class).doPrdDetailWeb_tpm(oci.getObject(),oci.getMemo1(),oci.getStartTime(),oci.getEndTime(),
					oci.getStartTime2(),oci.getEndTime2(),oci.getMemo2(),oci.getMemo3(),oci.getMemo4(),oci.getMemo5()));
			rm.setState("200");
		}catch(Exception ex){
			ex.printStackTrace();
			rm.setState("500");
			rm.setMsgInfo("查询失败!"+ex.getMessage());
		}
		return rm;
	}
		
	/**
	 * 平整机产量报表
	 * 根据班次统计报表
	 * */
	public ResultModel doProductionWrkReportWeb(CommonPage<MesTpmM> oci){
		ResultModel rm=new ResultModel();
		try{
			rm.setData(this.getMapper(MesTpmMMapper.class).doProductionWrkReport(oci.getObject()));
			rm.setState("200");
		}catch(Exception ex){
			ex.printStackTrace();
			rm.setState("500");
			rm.setMsgInfo("查询失败!"+ex.getMessage());
		}
		return rm;
	}
	
	/**
	 * 平整产量报表   导出Excel
	 * 根据班次统计报表
	 * */
	public ResultModel doProductionWrkReportWeb_Excel(CommonPage<MesTpmM> oci){
		ResultModel rm=new ResultModel();
		try{
			if(oci==null || "".equals(oci.getObject().getWrk_date())){
				rm.setState("500");
				rm.setMsgInfo("请输入参数!");
				return rm;
			}
			@SuppressWarnings("rawtypes")
			List<HashMap> lhap = this.getMapper(MesTpmMMapper.class).doProductionWrkReport(oci.getObject());
			// 2,设置用户下载路径
			String path = this.getRequest().getServletContext().getRealPath("/")+ "excel" + File.separator;  //临时保存路径
			File dir = new File(path);
			if(!dir.exists()) {
				new File(path).mkdir();
			}
			generateExcelProduWrk3(rm, lhap, path,oci.getObject().getWrk_date(),oci.getObject().getMachine_code());
			rm.setState("200");
		}catch(Exception ex){
			ex.printStackTrace();
			rm.setState("500");
			rm.setMsgInfo("导出失败!"+ex.getMessage());
		}
		return rm;
	}
	
	/**
	 * 平整产量报表   导出Excel
	 * @param rm
	 * @param lhap
	 * @param path
	 * @param wrk_date 
	 * @throws Exception 
	 */
	@SuppressWarnings("rawtypes")
	private void generateExcelProduWrk3(ResultModel rm, List<HashMap> lhap,
			String path, String wrk_date,String machine_code) throws Exception {
		String machine_name="";
		String curDate = DateUtil.formatDate(new Date(), "yyMMdd");
		String str=wrk_date.substring(0, 4)+"年"+wrk_date.substring(5, 7)+"月";
		String filename = str +machine_name+ "平整产量报表_"+curDate;
    	WritableWorkbook workbook;
    	String file=filename+".xls";  //文件名
    	//3. 操作EXCEL文件
    	workbook = Workbook.createWorkbook(new File(path+file));
    	WritableSheet sheet = workbook.createSheet(str +machine_name+"平整产量报表", 1);
    	//行高
    	sheet.getSettings().setDefaultRowHeight(300);
		//字体  参数可自行配置
		WritableFont font1 = new WritableFont(WritableFont.ARIAL,11,WritableFont.BOLD,false,UnderlineStyle.NO_UNDERLINE);  
		WritableCellFormat cellFormat1 = new WritableCellFormat(font1); 
		cellFormat1.setAlignment(Alignment.CENTRE);
		cellFormat1.setVerticalAlignment(VerticalAlignment.CENTRE);
		//表头
		/*
		 * //sheet.mergeCells(int m,int n,int p,int q);
           //作用是从(m,n)到(p,q)的单元格全部合并[我的理解：m列、n行和p列、q行合并]
          sheet.addCell(new Label(i, 0, tittles[i],wcf));//i列，1行，title内容，wcf样式
		 */
		sheet.mergeCells(0, 0, 0, 2);//设置第一列、第一行和 第一列、第三行合并
		sheet.addCell(new Label(0,0,"日期",cellFormat1));
		
		sheet.mergeCells(1, 0, 6, 0);
		sheet.addCell(new Label(1,0,"常白班",cellFormat1));
		sheet.mergeCells(1,1,3,1);
		sheet.addCell(new Label(1,1,"当日",cellFormat1));
		sheet.mergeCells(4,1,6,1);
		sheet.addCell(new Label(4,1,"月累",cellFormat1));
		
		sheet.addCell(new Label(1,2,"投入",cellFormat1));
		sheet.addCell(new Label(2,2,"产出",cellFormat1));
		sheet.addCell(new Label(3,2,"成材率(%)",cellFormat1));
		sheet.addCell(new Label(4,2,"投入",cellFormat1));
		sheet.addCell(new Label(5,2,"产出",cellFormat1));
		sheet.addCell(new Label(6,2,"成材率(%)",cellFormat1));
		
		sheet.mergeCells(7, 0, 12, 0);
		sheet.addCell(new Label(7,0,"甲班",cellFormat1));
		sheet.mergeCells(7,1,9,1);
		sheet.addCell(new Label(7,1,"当日",cellFormat1));
		sheet.mergeCells(10,1,12,1);
		sheet.addCell(new Label(10,1,"月累",cellFormat1));
		
		sheet.addCell(new Label(7,2,"投入",cellFormat1));
		sheet.addCell(new Label(8,2,"产出",cellFormat1));
		sheet.addCell(new Label(9,2,"成材率(%)",cellFormat1));
		sheet.addCell(new Label(10,2,"投入",cellFormat1));
		sheet.addCell(new Label(11,2,"产出",cellFormat1));
		sheet.addCell(new Label(12,2,"成材率(%)",cellFormat1));
			
		sheet.mergeCells(13, 0, 18, 0);
		sheet.addCell(new Label(13,0,"乙班",cellFormat1));
		sheet.mergeCells(13,1,15,1);
		sheet.addCell(new Label(13,1,"当日",cellFormat1));
		sheet.mergeCells(16,1,18,1);
		sheet.addCell(new Label(16,1,"月累",cellFormat1));
		
		sheet.addCell(new Label(13,2,"投入",cellFormat1));
		sheet.addCell(new Label(14,2,"产出",cellFormat1));
		sheet.addCell(new Label(15,2,"成材率(%)",cellFormat1));
		sheet.addCell(new Label(16,2,"投入",cellFormat1));
		sheet.addCell(new Label(17,2,"产出",cellFormat1));
		sheet.addCell(new Label(18,2,"成材率(%)",cellFormat1));
		
		sheet.mergeCells(19, 0, 24, 0);
		sheet.addCell(new Label(19,0,"丙班",cellFormat1));
		sheet.mergeCells(19,1,21,1);
		sheet.addCell(new Label(19,1,"当日",cellFormat1));
		sheet.mergeCells(22,1,24,1);
		sheet.addCell(new Label(22,1,"月累",cellFormat1));
		
		sheet.addCell(new Label(19,2,"投入",cellFormat1));
		sheet.addCell(new Label(20,2,"产出",cellFormat1));
		sheet.addCell(new Label(21,2,"成材率(%)",cellFormat1));
		sheet.addCell(new Label(22,2,"投入",cellFormat1));
		sheet.addCell(new Label(23,2,"产出",cellFormat1));
		sheet.addCell(new Label(24,2,"成材率(%)",cellFormat1));
		
		sheet.mergeCells(25, 0, 30, 0);
		sheet.addCell(new Label(25,0,"丁班",cellFormat1));
		sheet.mergeCells(25,1,27,1);
		sheet.addCell(new Label(25,1,"当日",cellFormat1));
		sheet.mergeCells(28,1,30,1);
		sheet.addCell(new Label(28,1,"月累",cellFormat1));
		
		sheet.addCell(new Label(25,2,"投入",cellFormat1));
		sheet.addCell(new Label(26,2,"产出",cellFormat1));
		sheet.addCell(new Label(27,2,"成材率(%)",cellFormat1));
		sheet.addCell(new Label(28,2,"投入",cellFormat1));
		sheet.addCell(new Label(29,2,"产出",cellFormat1));
		sheet.addCell(new Label(30,2,"成材率(%)",cellFormat1));
						
		sheet.mergeCells(31, 0, 39, 0);
		sheet.addCell(new Label(31,0,"合计",cellFormat1));
		sheet.mergeCells(31,1,33,1);
		sheet.addCell(new Label(31,1,"当日",cellFormat1));
		sheet.mergeCells(34,1,36,1);
		sheet.addCell(new Label(34,1,"月累",cellFormat1));
		sheet.mergeCells(37,1,39,1);
		sheet.addCell(new Label(37,1,"年累",cellFormat1));		
		
		sheet.addCell(new Label(31,2,"投入",cellFormat1));
		sheet.addCell(new Label(32,2,"产出",cellFormat1));
		sheet.addCell(new Label(33,2,"成材率(%)",cellFormat1));
		sheet.addCell(new Label(34,2,"投入",cellFormat1));
		sheet.addCell(new Label(35,2,"产出",cellFormat1));
		sheet.addCell(new Label(36,2,"成材率(%)",cellFormat1));
		sheet.addCell(new Label(37,2,"投入",cellFormat1));
		sheet.addCell(new Label(38,2,"产出",cellFormat1));
		sheet.addCell(new Label(39,2,"成材率(%)",cellFormat1));		
		
		WritableFont font = new WritableFont(WritableFont.ARIAL,11,WritableFont.NO_BOLD,false,UnderlineStyle.NO_UNDERLINE);  
		WritableCellFormat cellFormat = new WritableCellFormat(font); 
		cellFormat.setAlignment(Alignment.CENTRE);
		cellFormat.setVerticalAlignment(VerticalAlignment.CENTRE);
		int i=1;
		for(HashMap hm:lhap){
			//日期
			if(hm.get("WRK_DATE_2")!=null){
				sheet.addCell(new Label(0,i+2,""+hm.get("WRK_DATE_2"),cellFormat));
			}
			//常白班 -当日-投入
			if(hm.get("DAILY_0_IN")!=null){
				sheet.addCell(new Label(1,i+2,""+hm.get("DAILY_0_IN"),cellFormat));
			}
			//常白班 -当日-产出
			if(hm.get("DAILY_0")!=null){
				sheet.addCell(new Label(2,i+2,""+hm.get("DAILY_0"),cellFormat));
			}
			if(hm.get("RATE_DAILY_0")!=null){
				sheet.addCell(new Label(3,i+2,""+hm.get("RATE_DAILY_0"),cellFormat));
			}
			//常白班 -月累-投入
			if(hm.get("MONTH_0_IN")!=null){
				sheet.addCell(new Label(4,i+2,""+hm.get("MONTH_0_IN"),cellFormat));
			}
			//常白班 -月累-产出
			if(hm.get("MONTH_0")!=null){
				sheet.addCell(new Label(5,i+2,""+hm.get("MONTH_0"),cellFormat));
			}
			if(hm.get("RATE_MONTH_0")!=null){
				sheet.addCell(new Label(6,i+2,""+hm.get("RATE_MONTH_0"),cellFormat));
			}
			//甲班 -当日-投入
			if(hm.get("DAILY_1_IN")!=null){
				sheet.addCell(new Label(7,i+2,""+hm.get("DAILY_1_IN"),cellFormat));
			}
			//甲班 -当日-产出
			if(hm.get("DAILY_1")!=null){
				sheet.addCell(new Label(8,i+2,""+hm.get("DAILY_1"),cellFormat));
			}
			if(hm.get("RATE_DAILY_1")!=null){
				sheet.addCell(new Label(9,i+2,""+hm.get("RATE_DAILY_1"),cellFormat));
			}
			//甲班 -月累-投入
			if(hm.get("MONTH_1_IN")!=null){
				sheet.addCell(new Label(10,i+2,""+hm.get("MONTH_1_IN"),cellFormat));
			}
			//甲班 -月累-产出
			if(hm.get("MONTH_1")!=null){
				sheet.addCell(new Label(11,i+2,""+hm.get("MONTH_1"),cellFormat));
			}
			if(hm.get("RATE_MONTH_1")!=null){
				sheet.addCell(new Label(12,i+2,""+hm.get("RATE_MONTH_1"),cellFormat));
			}			
			
			//乙班 -当日-投入
			if(hm.get("DAILY_2_IN")!=null){
				sheet.addCell(new Label(13,i+2,""+hm.get("DAILY_2_IN"),cellFormat));
			}
			//乙班 -当日-产出
			if(hm.get("DAILY_2")!=null){
				sheet.addCell(new Label(14,i+2,""+hm.get("DAILY_2"),cellFormat));
			}
			if(hm.get("RATE_DAILY_2")!=null){
				sheet.addCell(new Label(15,i+2,""+hm.get("RATE_DAILY_2"),cellFormat));
			}
			//乙班 -月累-投入
			if(hm.get("MONTH_2_IN")!=null){
				sheet.addCell(new Label(16,i+2,""+hm.get("MONTH_2_IN"),cellFormat));
			}
			//乙班 -月累-产出
			if(hm.get("MONTH_2")!=null){
				sheet.addCell(new Label(17,i+2,""+hm.get("MONTH_2"),cellFormat));
			}
			if(hm.get("RATE_MONTH_2")!=null){
				sheet.addCell(new Label(18,i+2,""+hm.get("RATE_MONTH_2"),cellFormat));
			}
			
			//丙班 -当日-投入
			if(hm.get("DAILY_3_IN")!=null){
				sheet.addCell(new Label(19,i+2,""+hm.get("DAILY_3_IN"),cellFormat));
			}
			//丙班 -当日-产出
			if(hm.get("DAILY_3")!=null){
				sheet.addCell(new Label(20,i+2,""+hm.get("DAILY_3"),cellFormat));
			}
			if(hm.get("RATE_DAILY_3")!=null){
				sheet.addCell(new Label(21,i+2,""+hm.get("RATE_DAILY_3"),cellFormat));
			}
			
			//丙班-月累-投入
			if(hm.get("MONTH_3_IN")!=null){
				sheet.addCell(new Label(22,i+2,""+hm.get("MONTH_3_IN"),cellFormat));
			}
			//丙班-月累-产出
			if(hm.get("MONTH_3")!=null){
				sheet.addCell(new Label(23,i+2,""+hm.get("MONTH_3"),cellFormat));
			}
			if(hm.get("RATE_MONTH_3")!=null){
				sheet.addCell(new Label(24,i+2,""+hm.get("RATE_MONTH_3"),cellFormat));
			}
			
			//丁班 -当日-投入
			if(hm.get("DAILY_4_IN")!=null){
				sheet.addCell(new Label(25,i+2,""+hm.get("DAILY_4_IN"),cellFormat));
			}
			//丁班 -当日-产出
			if(hm.get("DAILY_4")!=null){
				sheet.addCell(new Label(26,i+2,""+hm.get("DAILY_4"),cellFormat));
			}
			if(hm.get("RATE_DAILY_4")!=null){
				sheet.addCell(new Label(27,i+2,""+hm.get("RATE_DAILY_4"),cellFormat));
			}		
			
			//丁班 -月累-投入
			if(hm.get("MONTH_4_IN")!=null){
				sheet.addCell(new Label(28,i+2,""+hm.get("MONTH_4_IN"),cellFormat));
			}
			//丁班 -月累-产出
			if(hm.get("MONTH_4")!=null){
				sheet.addCell(new Label(29,i+2,""+hm.get("MONTH_4"),cellFormat));
			}
			if(hm.get("RATE_MONTH_4")!=null){
				sheet.addCell(new Label(30,i+2,""+hm.get("RATE_MONTH_4"),cellFormat));
			}
			
			//合计-当日-投入
			if(hm.get("DAILY_ALL_IN")!=null){
				sheet.addCell(new Label(31,i+2,""+hm.get("DAILY_ALL_IN"),cellFormat));
			}
			//合计-当日-产出
			if(hm.get("DAILY_ALL")!=null){
				sheet.addCell(new Label(32,i+2,""+hm.get("DAILY_ALL"),cellFormat));
			}
			if(hm.get("RATE_DAILY_ALL")!=null){
				sheet.addCell(new Label(33,i+2,""+hm.get("RATE_DAILY_ALL"),cellFormat));
			}
			
			//合计-月累-投入
			if(hm.get("MONTH_ALL_IN")!=null){
				sheet.addCell(new Label(34,i+2,""+hm.get("MONTH_ALL_IN"),cellFormat));
			}
			//合计-月累-产出
			if(hm.get("MONTH_ALL")!=null){
				sheet.addCell(new Label(35,i+2,""+hm.get("MONTH_ALL"),cellFormat));
			}
			if(hm.get("RATE_MONTH_ALL")!=null){
				sheet.addCell(new Label(36,i+2,""+hm.get("RATE_MONTH_ALL"),cellFormat));
			}
			
			//合计-年累-投入
			if(hm.get("YEAR_ALL_IN")!=null){
				sheet.addCell(new Label(37,i+2,""+hm.get("YEAR_ALL_IN"),cellFormat));
			}
			//合计-年累-产出
			if(hm.get("YEAR_ALL")!=null){
				sheet.addCell(new Label(38,i+2,""+hm.get("YEAR_ALL"),cellFormat));
			}
			if(hm.get("RATE_YEAR_ALL")!=null){
				sheet.addCell(new Label(39,i+2,""+hm.get("RATE_YEAR_ALL"),cellFormat));
			}
			i++;
		}
		sheet.getSettings().setVerticalFreeze(1);  		//首行冻结
		sheet.getSettings().setVerticalFreeze(2);
		sheet.getSettings().setVerticalFreeze(3);
		//关闭
		workbook.write();
		workbook.close();
		rm.setData("/download?filename="+file);
	}
	
	/**
	 * 各牌号平整产量报表
	 * */
	public ResultModel doProductionSteelReportWeb(CommonPage<MesTpmM> oci){
		ResultModel rm=new ResultModel();
		try{
			rm.setData(this.getMapper(MesTpmMMapper.class).doProductionSteelReport(oci.getObject()));
			rm.setState("200");
		}catch(Exception ex){
			ex.printStackTrace();
			rm.setState("500");
			rm.setMsgInfo("查询失败!"+ex.getMessage());
		}
		return rm;
	}
	
	/**
	 * 各牌号平整产量报表    导出Excel
	 * */
	public ResultModel doProductionSteelReportWeb_Excel(CommonPage<MesTpmM> oci){
		ResultModel rm=new ResultModel();
		try{
			if(oci==null || "".equals(oci.getObject().getWrk_date())){
				rm.setState("500");
				rm.setMsgInfo("请输入参数!");
				return rm;
			}
			@SuppressWarnings("rawtypes")
			List<HashMap> lhap = this.getMapper(MesTpmMMapper.class).doProductionSteelReport(oci.getObject());
			// 2,设置用户下载路径
			String path = this.getRequest().getServletContext().getRealPath("/")+ "excel" + File.separator;  //临时保存路径
			File dir = new File(path);
			if(!dir.exists()) {
				new File(path).mkdir();
			}
			generateExcelProduSteel3(rm, lhap, path,oci.getObject().getWrk_date(),oci.getObject().getMachine_code());
			rm.setState("200");
		}catch(Exception ex){
			ex.printStackTrace();
			rm.setState("500");
			rm.setMsgInfo("导出失败!"+ex.getMessage());
		}
		return rm;
	}
	
	@SuppressWarnings("rawtypes")
	private void generateExcelProduSteel3(ResultModel rm, List<HashMap> lhap,
			String path, String wrk_date,String machine_code) throws Exception {
		//数据处理===============================
		//存储各牌号
		List<String> lstr=new ArrayList<>();
		//获取日期，各牌号日，月，年累集合
		Map<String,List<MesSteelCodeTemp>> maptp=new HashMap<String,List<MesSteelCodeTemp>>();
		List<MesSteelCodeTemp> lmsct=new ArrayList<>();
		for(HashMap hm:lhap){
			MesSteelCodeTemp msct=new MesSteelCodeTemp();
			if(!lstr.contains((""+hm.get("STEEL_CODE")))){
				lstr.add(""+hm.get("STEEL_CODE"));
			}
			msct.setSteel_code(""+hm.get("STEEL_CODE"));
			msct.setWrk_date(""+hm.get("WRK_DATE"));
			msct.setStl_daily(""+hm.get("STL_DAILY"));
			msct.setStl_month(""+hm.get("STL_MONTH"));
			msct.setStl_year(""+hm.get("STL_YEAR"));
			msct.setStl_daily_in(""+hm.get("STL_DAILY_IN"));
			msct.setStl_month_in(""+hm.get("STL_MONTH_IN"));
			msct.setStl_year_in(""+hm.get("STL_YEAR_IN"));
			msct.setRate_daily(""+hm.get("RATE_DAILY"));
			msct.setRate_month(""+hm.get("RATE_MONTH"));
			msct.setRate_year(""+hm.get("RATE_YEAR"));
			lmsct.add(msct);
		}
		if(lstr.size()<=0){
			rm.setMsgInfo("无对应的牌号");
			return ;
		}
		//对List集合中对象元素中的wrk_date分组  重要
		for(MesSteelCodeTemp tmExcpNew : lmsct){
			if(maptp.containsKey(tmExcpNew.getWrk_date())){//map中异常批次已存在，将该数据存放到同一个key（key存放的是异常批次）的map中
				maptp.get(tmExcpNew.getWrk_date()).add(tmExcpNew);
			}else{//map中不存在，新建key，用来存放数据
				List<MesSteelCodeTemp> tmpList = new ArrayList<MesSteelCodeTemp>();
				tmpList.add(tmExcpNew);
				maptp.put(tmExcpNew.getWrk_date(), tmpList);
			}
		}
		//====================================
		String machine_name="";
		String curDate = DateUtil.formatDate(new Date(), "yyMMdd");
		String str=wrk_date.substring(0, 4)+"年"+wrk_date.substring(5, 7)+"月";
		String filename = str + machine_name+"各牌号平整产量报表_"+curDate;
    	WritableWorkbook workbook;
    	String file=filename+".xls";  //文件名
    	//3. 操作EXCEL文件
    	workbook = Workbook.createWorkbook(new File(path+file));
    	WritableSheet sheet = workbook.createSheet(machine_name+"各牌号平整产量报表", 1);
    	//行高
    	sheet.getSettings().setDefaultRowHeight(300);
		//字体  参数可自行配置
		WritableFont font1 = new WritableFont(WritableFont.ARIAL,11,WritableFont.BOLD,false,UnderlineStyle.NO_UNDERLINE);  
		WritableCellFormat cellFormat1 = new WritableCellFormat(font1); 
		cellFormat1.setAlignment(Alignment.CENTRE);
		cellFormat1.setVerticalAlignment(VerticalAlignment.CENTRE);
		
		//表头
		/*
		 * //sheet.mergeCells(int m,int n,int p,int q);
           //作用是从(m,n)到(p,q)的单元格全部合并[我的理解：m列、n行和p列、q行合并]
          sheet.addCell(new Label(i, 0, tittles[i],wcf));//i列，1行，title内容，wcf样式
		 */
		sheet.mergeCells(0, 0, 0, 2);//设置第一列、第一行和 第一列、第三行合并
		sheet.addCell(new Label(0,0,"日期",cellFormat1));
		//各牌号对应的月累，年累。
		Map<String,MesSteelCodeTemp> mapSteelC=new HashMap<>();
		int i=1;
		for(String steel_code:lstr){
			MesSteelCodeTemp ms=new MesSteelCodeTemp();
			sheet.mergeCells(i, 0, i+8, 0);
			sheet.addCell(new Label(i,0,steel_code,cellFormat1));
			sheet.mergeCells(i, 1, i+2, 0);
			sheet.addCell(new Label(i,1,"当日",cellFormat1));
			sheet.mergeCells(i+3, 1, i+5, 0);
			sheet.addCell(new Label(i+3,1,"月累",cellFormat1));
			sheet.mergeCells(i+6, 1, i+8, 0);
			sheet.addCell(new Label(i+6,1,"年累",cellFormat1));
			sheet.addCell(new Label(i,2,"投入",cellFormat1));
			sheet.addCell(new Label(i+1,2,"产出",cellFormat1));
			sheet.addCell(new Label(i+2,2,"成材率(%)",cellFormat1));
			sheet.addCell(new Label(i+3,2,"投入",cellFormat1));
			sheet.addCell(new Label(i+4,2,"产出",cellFormat1));
			sheet.addCell(new Label(i+5,2,"成材率(%)",cellFormat1));
			sheet.addCell(new Label(i+6,2,"投入",cellFormat1));
			sheet.addCell(new Label(i+7,2,"产出",cellFormat1));
			sheet.addCell(new Label(i+8,2,"成材率(%)",cellFormat1));
			i=i+9;
			mapSteelC.put(steel_code, ms);
		}
		
		sheet.mergeCells(i, 0, i+8, 0);
		sheet.addCell(new Label(i,0,"合计",cellFormat1));
		sheet.mergeCells(i, 1, i+2, 0);
		sheet.addCell(new Label(i,1,"当日",cellFormat1));
		sheet.mergeCells(i+3, 1, i+5, 0);
		sheet.addCell(new Label(i+3,1,"月累",cellFormat1));
		sheet.mergeCells(i+6, 1, i+8, 0);
		sheet.addCell(new Label(i+6,1,"年累",cellFormat1));
		sheet.addCell(new Label(i,2,"投入",cellFormat1));
		sheet.addCell(new Label(i+1,2,"产出",cellFormat1));
		sheet.addCell(new Label(i+2,2,"成材率(%)",cellFormat1));
		sheet.addCell(new Label(i+3,2,"投入",cellFormat1));
		sheet.addCell(new Label(i+4,2,"产出",cellFormat1));
		sheet.addCell(new Label(i+5,2,"成材率(%)",cellFormat1));
		sheet.addCell(new Label(i+6,2,"投入",cellFormat1));
		sheet.addCell(new Label(i+7,2,"产出",cellFormat1));
		sheet.addCell(new Label(i+8,2,"成材率(%)",cellFormat1));		
		
		WritableFont font = new WritableFont(WritableFont.ARIAL,11,WritableFont.NO_BOLD,false,UnderlineStyle.NO_UNDERLINE);  
		WritableCellFormat cellFormat = new WritableCellFormat(font); 
		cellFormat.setAlignment(Alignment.CENTRE);
		cellFormat.setVerticalAlignment(VerticalAlignment.CENTRE);
		
		//合计对应的月累，年累。
		Map<String,MesSteelCodeTemp> mapSteelC_Total=new HashMap<>();
		MesSteelCodeTemp mt2=new MesSteelCodeTemp();
		mapSteelC_Total.put("total_mes", mt2);
		double all_day=0;
		double all_month=0;
		double all_year=0;
		double all_day_in=0;
		double all_month_in=0;
		double all_year_in=0;
		//wrk_date的天数
		int monthLastDay = DateUtil.getMonthLastDay(Integer.parseInt(wrk_date.substring(0, 4)), Integer.parseInt(wrk_date.substring(5, 7)));
		//2018-06-形式
		String wrkdate_temp=wrk_date+"-";
		int j=1;
		for(int day=1;day<=monthLastDay;day++){
			all_day=0;
			all_month=0;
			all_year=0;
			all_day_in=0;
			all_month_in=0;
			all_year_in=0;
			//日期
			sheet.addCell(new Label(0,j+2,String.format("%02d", day)+"日",cellFormat));
			i=1;
			
			if(maptp.containsKey(wrkdate_temp+String.format("%02d", day))){
				List<MesSteelCodeTemp> list = maptp.get(wrkdate_temp+String.format("%02d", day));
				
				for(String steel_code:lstr){
					MesSteelCodeTemp mt=new MesSteelCodeTemp();
					mt.setSteel_code(steel_code);
					if(list.contains(mt)){
						mt = list.get(list.indexOf(mt));
						sheet.addCell(new Label(i,j+2,"0.0".equals(mt.getStl_daily_in())?"0":mt.getStl_daily_in(),cellFormat));
						sheet.addCell(new Label(i+1,j+2,"0.0".equals(mt.getStl_daily())?"0":mt.getStl_daily(),cellFormat));
						sheet.addCell(new Label(i+2,j+2,"0.0".equals(mt.getRate_daily())?"0":mt.getRate_daily(),cellFormat));
						sheet.addCell(new Label(i+3,j+2,"0.0".equals(mt.getStl_month_in())?"0":mt.getStl_month_in(),cellFormat));
						sheet.addCell(new Label(i+4,j+2,"0.0".equals(mt.getStl_month())?"0":mt.getStl_month(),cellFormat));
						sheet.addCell(new Label(i+5,j+2,"0.0".equals(mt.getRate_month())?"0":mt.getRate_month(),cellFormat));
						sheet.addCell(new Label(i+6,j+2,"0.0".equals(mt.getStl_year_in())?"0":mt.getStl_year_in(),cellFormat));
						sheet.addCell(new Label(i+7,j+2,"0.0".equals(mt.getStl_year())?"0":mt.getStl_year(),cellFormat));
						sheet.addCell(new Label(i+8,j+2,"0.0".equals(mt.getRate_year())?"0":mt.getRate_year(),cellFormat));
						
						all_day=DoubleUtil.add(all_day, Double.parseDouble(mt.getStl_daily()));
						all_day_in=DoubleUtil.add(all_day_in, Double.parseDouble(mt.getStl_daily_in()));
						mapSteelC.get(steel_code).setStl_month(mt.getStl_month());
						mapSteelC.get(steel_code).setStl_month_in(mt.getStl_month_in());
						mapSteelC.get(steel_code).setStl_year(mt.getStl_year());
						mapSteelC.get(steel_code).setStl_year_in(mt.getStl_year_in());
					}else{
						sheet.addCell(new Label(i,j+2,"0",cellFormat));
						sheet.addCell(new Label(i+1,j+2,"0",cellFormat));
						sheet.addCell(new Label(i+2,j+2,"0",cellFormat));
						if(mapSteelC.get(steel_code).getStl_month()==null || "".equals(mapSteelC.get(steel_code).getStl_month())){
							sheet.addCell(new Label(i+4,j+2,"0",cellFormat));
						}else{
							sheet.addCell(new Label(i+4,j+2,mapSteelC.get(steel_code).getStl_month(),cellFormat));
						}
						if(mapSteelC.get(steel_code).getStl_year()==null || "".equals(mapSteelC.get(steel_code).getStl_year())){
							sheet.addCell(new Label(i+7,j+2,"0",cellFormat));
						}else{
							sheet.addCell(new Label(i+7,j+2,mapSteelC.get(steel_code).getStl_year(),cellFormat));
						}
						
						if(mapSteelC.get(steel_code).getStl_month_in()==null || "".equals(mapSteelC.get(steel_code).getStl_month_in())){
							sheet.addCell(new Label(i+3,j+2,"0",cellFormat));
							sheet.addCell(new Label(i+5,j+2,"0",cellFormat));
						}else{
							sheet.addCell(new Label(i+3,j+2,mapSteelC.get(steel_code).getStl_month_in(),cellFormat));
							Double stl_month_in=Double.parseDouble(mapSteelC.get(steel_code).getStl_month_in()+"");
							Double stl_month=Double.parseDouble(mapSteelC.get(steel_code).getStl_month()+"");
							if(stl_month_in==0){
								sheet.addCell(new Label(i+5,j+2,"0",cellFormat));
							}else{
								if("0.0".equals((""+DoubleUtil.round((stl_month/stl_month_in)*100, 2)))){
									sheet.addCell(new Label(i+5,j+2,"0",cellFormat));
								}else{
									sheet.addCell(new Label(i+5,j+2,""+DoubleUtil.round((stl_month/stl_month_in)*100, 2),cellFormat));
								}
							}							
						}
						if(mapSteelC.get(steel_code).getStl_year_in()==null || "".equals(mapSteelC.get(steel_code).getStl_year_in())){
							sheet.addCell(new Label(i+6,j+2,"0",cellFormat));
							sheet.addCell(new Label(i+8,j+2,"0",cellFormat));
						}else{
							sheet.addCell(new Label(i+6,j+2,mapSteelC.get(steel_code).getStl_year_in(),cellFormat));
							Double stl_year_in=Double.parseDouble(mapSteelC.get(steel_code).getStl_year_in()+"");
							Double stl_year=Double.parseDouble(mapSteelC.get(steel_code).getStl_year()+"");
							if(stl_year_in==0){
								sheet.addCell(new Label(i+8,j+2,"0",cellFormat));
							}else{
								if("0.0".equals((""+DoubleUtil.round((stl_year/stl_year_in)*100, 2)))){
									sheet.addCell(new Label(i+8,j+2,"0",cellFormat));
								}else{
									sheet.addCell(new Label(i+8,j+2,""+DoubleUtil.round((stl_year/stl_year_in)*100, 2),cellFormat));
								}
							}							
						}						
					}
					i=i+9;
					if(mapSteelC.get(steel_code).getStl_month()!=null && !"".equals(mapSteelC.get(steel_code).getStl_month())){
						all_month=DoubleUtil.add(all_month, Double.parseDouble(mapSteelC.get(steel_code).getStl_month()));
					}
					if(mapSteelC.get(steel_code).getStl_year()!=null && !"".equals(mapSteelC.get(steel_code).getStl_year())){
						all_year=DoubleUtil.add(all_year, Double.parseDouble(mapSteelC.get(steel_code).getStl_year()));
					}
					if(mapSteelC.get(steel_code).getStl_month_in()!=null && !"".equals(mapSteelC.get(steel_code).getStl_month_in())){
						all_month_in=DoubleUtil.add(all_month_in, Double.parseDouble(mapSteelC.get(steel_code).getStl_month_in()));
					}
					if(mapSteelC.get(steel_code).getStl_year_in()!=null && !"".equals(mapSteelC.get(steel_code).getStl_year_in())){
						all_year_in=DoubleUtil.add(all_year_in, Double.parseDouble(mapSteelC.get(steel_code).getStl_year_in()));
					}
					
					
					mapSteelC_Total.get("total_mes").setStl_month(""+all_month);
					mapSteelC_Total.get("total_mes").setStl_year(""+all_year);
					
					mapSteelC_Total.get("total_mes").setStl_month_in(""+all_month_in);
					mapSteelC_Total.get("total_mes").setStl_year_in(""+all_year_in);
				}
			}else{
				for(String steel_code:lstr){
					sheet.addCell(new Label(i,j+2,"0",cellFormat));
					sheet.addCell(new Label(i+1,j+2,"0",cellFormat));
					sheet.addCell(new Label(i+2,j+2,"0",cellFormat));
					if(mapSteelC.get(steel_code).getStl_month()==null || "".equals(mapSteelC.get(steel_code).getStl_month())){
						sheet.addCell(new Label(i+4,j+2,"0",cellFormat));
					}else{
						sheet.addCell(new Label(i+4,j+2,mapSteelC.get(steel_code).getStl_month(),cellFormat));
					}
					if(mapSteelC.get(steel_code).getStl_year()==null || "".equals(mapSteelC.get(steel_code).getStl_year())){
						sheet.addCell(new Label(i+7,j+2,"0",cellFormat));
					}else{
						sheet.addCell(new Label(i+7,j+2,mapSteelC.get(steel_code).getStl_year(),cellFormat));
					}
					
					if(mapSteelC.get(steel_code).getStl_month_in()==null || "".equals(mapSteelC.get(steel_code).getStl_month_in())){
						sheet.addCell(new Label(i+3,j+2,"0",cellFormat));
						sheet.addCell(new Label(i+5,j+2,"0",cellFormat));
					}else{
						sheet.addCell(new Label(i+3,j+2,mapSteelC.get(steel_code).getStl_month_in(),cellFormat));
						Double stl_month_in=Double.parseDouble(mapSteelC.get(steel_code).getStl_month_in()+"");
						Double stl_month=Double.parseDouble(mapSteelC.get(steel_code).getStl_month()+"");
						if(stl_month_in==0){
							sheet.addCell(new Label(i+5,j+2,"0",cellFormat));
						}else{
							if("0.0".equals((""+DoubleUtil.round((stl_month/stl_month_in)*100, 2)))){
								sheet.addCell(new Label(i+5,j+2,"0",cellFormat));
							}else{
								sheet.addCell(new Label(i+5,j+2,""+DoubleUtil.round((stl_month/stl_month_in)*100, 2),cellFormat));
							}
						}
					}
					if(mapSteelC.get(steel_code).getStl_year_in()==null || "".equals(mapSteelC.get(steel_code).getStl_year_in())){
						sheet.addCell(new Label(i+6,j+2,"0",cellFormat));
						sheet.addCell(new Label(i+8,j+2,"0",cellFormat));
					}else{
						sheet.addCell(new Label(i+6,j+2,mapSteelC.get(steel_code).getStl_year_in(),cellFormat));
						Double stl_year_in=Double.parseDouble(mapSteelC.get(steel_code).getStl_year_in()+"");
						Double stl_year=Double.parseDouble(mapSteelC.get(steel_code).getStl_year()+"");
						if(stl_year_in==0){
							sheet.addCell(new Label(i+8,j+2,"0",cellFormat));
						}else{
							if("0.0".equals((""+DoubleUtil.round((stl_year/stl_year_in)*100, 2)))){
								sheet.addCell(new Label(i+8,j+2,"0",cellFormat));
							}else{
								sheet.addCell(new Label(i+8,j+2,""+DoubleUtil.round((stl_year/stl_year_in)*100, 2),cellFormat));
							}
						}
					}					
					i=i+9;
				}
			}
			//all_day==0?"0":all_day这种形式是为了防止在excel中显示0.0的情况
			
			sheet.addCell(new Label(i,j+2,""+(all_day_in==0?"0":all_day_in),cellFormat));
			sheet.addCell(new Label(i+1,j+2,""+(all_day==0?"0":all_day),cellFormat));
			//日成材率
			if(all_day_in==0){
				sheet.addCell(new Label(i+2,j+2,0+"",cellFormat));
			}else{
				//sheet.addCell(new Label(i+2,j+2,""+DoubleUtil.round((all_day/all_day_in)*100, 2),cellFormat));
				if("0.0".equals((""+DoubleUtil.round((all_day/all_day_in)*100, 2)))){
					sheet.addCell(new Label(i+2,j+2,0+"",cellFormat));
				}else{
					sheet.addCell(new Label(i+2,j+2,""+DoubleUtil.round((all_day/all_day_in)*100, 2),cellFormat));
				}
			}
			sheet.addCell(new Label(i+3,j+2,("0.0".equals(mapSteelC_Total.get("total_mes").getStl_month_in())?"0":mapSteelC_Total.get("total_mes").getStl_month_in()),cellFormat));
			sheet.addCell(new Label(i+4,j+2,("0.0".equals(mapSteelC_Total.get("total_mes").getStl_month())?"0":mapSteelC_Total.get("total_mes").getStl_month()),cellFormat));
			if(mapSteelC_Total.get("total_mes").getStl_month_in()==null){
				mapSteelC_Total.get("total_mes").setStl_month_in("0");
			}
			if(mapSteelC_Total.get("total_mes").getStl_month()==null){
				mapSteelC_Total.get("total_mes").setStl_month("0");
			}
			Double stl_month_in=Double.parseDouble(mapSteelC_Total.get("total_mes").getStl_month_in()+"");
			Double stl_month=Double.parseDouble(mapSteelC_Total.get("total_mes").getStl_month()+"");
			if(stl_month_in==0){
				sheet.addCell(new Label(i+5,j+2,0+"",cellFormat));
			}else{
				//sheet.addCell(new Label(i+5,j+2,""+DoubleUtil.round((stl_month/stl_month_in)*100, 2),cellFormat));
				if("0.0".equals((""+DoubleUtil.round((stl_month/stl_month_in)*100, 2)))){
					sheet.addCell(new Label(i+5,j+2,0+"",cellFormat));
				}else{
					sheet.addCell(new Label(i+5,j+2,""+DoubleUtil.round((stl_month/stl_month_in)*100, 2),cellFormat));
				}
			}			
						
			sheet.addCell(new Label(i+6,j+2,("0.0".equals(mapSteelC_Total.get("total_mes").getStl_year_in())?"0":mapSteelC_Total.get("total_mes").getStl_year_in()),cellFormat));
			sheet.addCell(new Label(i+7,j+2,("0.0".equals(mapSteelC_Total.get("total_mes").getStl_year())?"0":mapSteelC_Total.get("total_mes").getStl_year()),cellFormat));
			if(mapSteelC_Total.get("total_mes").getStl_year_in()==null){
				mapSteelC_Total.get("total_mes").setStl_year_in("0");
			}
			if(mapSteelC_Total.get("total_mes").getStl_year_in()==null){
				mapSteelC_Total.get("total_mes").setStl_year("0");
			}
			Double stl_year_in=Double.parseDouble(mapSteelC_Total.get("total_mes").getStl_year_in()+"");
			Double stl_year=Double.parseDouble(mapSteelC_Total.get("total_mes").getStl_year()+"");
			if(stl_year_in==0){
				sheet.addCell(new Label(i+8,j+2,"0",cellFormat));
			}else{
				if("0.0".equals((""+DoubleUtil.round((stl_year/stl_year_in)*100, 2)))){
					sheet.addCell(new Label(i+8,j+2,"0",cellFormat));
				}else{
					sheet.addCell(new Label(i+8,j+2,""+DoubleUtil.round((stl_year/stl_year_in)*100, 2),cellFormat));
				}
			}
			j++;
		}		
		sheet.getSettings().setVerticalFreeze(1);  		//首行冻结
		sheet.getSettings().setVerticalFreeze(2);
		sheet.getSettings().setVerticalFreeze(3);
		//关闭
		workbook.write();
		workbook.close();
		rm.setData("/download?filename="+file);
	}
	
	
	
	
	/**
	 * memo1:机台代码  V_MCH_CODE
	 * 动作处理_自动定位按钮
	 * 展示到“平整作业计划”表格
	 * */
	public ResultModel doQueryWeb(CommonPage<MesTpmM> oci){
		ResultModel rm=new ResultModel();
		if(oci.getMemo1()==null || "".equals(oci.getMemo1())){
			rm.setState("500");
			rm.setMsgInfo("请输入机台代码");
			return rm;
		}
		try{
			List<PlnSkinRollingView> lpav = this.getMapper(MesTpmMMapper.class).doQueryWeb(oci.getMemo1());
			rm.setData(lpav);
			rm.setState("200");
		}catch(Exception ex){
			ex.printStackTrace();
			rm.setState("500");
			rm.setMsgInfo("查询失败!"+ex.getMessage());
		}
		return rm;
	}
	
	/**
	 * 展示到“当班汇总信息”区域
	 * V_MCH_CODE（机台代码）、V_WRK_DATE（登录日期）、V_WRK_ORD（登录班次）、V_WRK_GRP（登录班组）
	 * memo1-4
	 * @param oci
	 * @return
	 */
	public ResultModel doQueryWrkWeb(CommonPage<MesTpmM> oci){
		ResultModel rm=new ResultModel();
		if(oci.getMemo1()==null || "".equals(oci.getMemo1())){
			rm.setState("500");
			rm.setMsgInfo("请输入机台代码");
			return rm;
		}
		try{
			rm.setData(this.getMapper(MesTpmMMapper.class).doQueryWrkWeb(oci.getMemo1(),oci.getMemo2(),oci.getMemo3(),oci.getMemo4()));
			rm.setState("200");
		}catch(Exception ex){
			ex.printStackTrace();
			rm.setState("500");
			rm.setMsgInfo("查询失败!"+ex.getMessage());
		}
		return rm;
	}
	
	/**
	    动作处理_查询按钮
	 memo1:机台代码
	 memo2：作业计划号
	 memo3:原料卷号
	 startTime：开始时间
	 endTime：结束时间
	* @param oci
	* @return
	*/
	public ResultModel doQueryWeb2(CommonPage<MesTpmM> cp){
		ResultModel rm=new ResultModel();
		try{
			List<PlnSkinRollingView> lpav = this.getMapper(MesTpmMMapper.class).doQueryWeb2(cp.getMemo1(),cp.getStartTime(),cp.getEndTime(),cp.getMemo2(),cp.getMemo3());
			rm.setData(lpav);
			rm.setState("200");
		}catch(Exception ex){
			ex.printStackTrace();
			rm.setState("500");
			rm.setMsgInfo("查询失败!"+ex.getMessage());
		}
		return rm;
	}

	/**动作处理_作业计划选中行变化
	 * “平整生产实绩”（编辑区域）处理：
	 * memo1:机台代码
	 * memo2：作业计划号
	 * memo3:虚拟卷号
	 * @param cp
	 * @return
	 */
	public ResultModel doQueryWeb3(CommonPage<MesTpmM> cp){
		ResultModel rm=new ResultModel();
		try{
			rm.setData(this.getMapper(MesTpmMMapper.class).doQueryWeb3(cp.getMemo1(),cp.getMemo2(),cp.getMemo3()));
			rm.setState("200");
		}catch(Exception ex){
			ex.printStackTrace();
			rm.setState("500");
			rm.setMsgInfo("查询失败!"+ex.getMessage());
		}
		return rm;
	}
	
	/***
	 * 动作处理-上料按钮     
	 * object中：
	 * sr_plan_no 作业计划号
	 * object_no_vt 虚拟卷号
	 * material_no 原料卷号
	 * memo1：机台代码，
	 * memo2：登录班组，
	 * memo3:登录用户名
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doTpmInsWeb(CommonPage<PlnSkinrollingPlan> sum) throws Exception {
		ResultModel r=new ResultModel();
		Date now = new Date();
		String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(now); //操作时间
		String userId = (String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		String username = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		
		Integer v_cnt;				
		//  --(1)、验证前端传入参数的基本有效性
		if(sum.getMemo1()==null || sum.getMemo1().length()<=0){
			r.setMsgInfo("参数错误：机台代码不能为空！");
			r.setState("500");
			return r;
		}
		// --优特钢目前3班2运转，必须按此限制，   增加丁班：20230427 刘侣
		if (sum.getMemo2() == null
				|| ((!sum.getMemo2().equals("1")) && (!sum.getMemo2().equals("2")) && (!sum.getMemo2()
						.equals("3")) && (!sum.getMemo2().equals("4")))) {
			r.setMsgInfo("班组代码：" + sum.getMemo2() + "无效，\n只能是 1（甲班）或2（乙班）或3（丙班）或4（丁班）！请选择正确的班组，重新登录系统!");
			r.setState("500");
			return r;
		}
		// end
		PlnSkinrollingPlan plp = sum.getObject();
		if(plp.getSr_plan_no()==null || "".equals(plp.getSr_plan_no())){
			r.setMsgInfo("作业计划号为空");
			r.setState("500");
			return r;
		}
		if(plp.getObject_no_vt()==null || "".equals(plp.getObject_no_vt())){
			r.setMsgInfo("虚拟卷号为空");
			r.setState("500");
			return r;
		}
		if(plp.getMaterial_no()==null || "".equals(plp.getMaterial_no())){
			r.setMsgInfo("原料卷号为空");
			r.setState("500");
			return r;
		}
		//  --(2)、验证机台基础信息存在
		ComBaseMachine machine = new ComBaseMachine();
		machine.setMachine_code(sum.getMemo1());
		v_cnt = this.getMapper(ComBaseMachineMapper.class).count(machine);
		if (v_cnt <= 0) {
			r.setMsgInfo("机台代码：" + sum.getMemo1() + "，\n机台基础信息不存在！");
			r.setState("500");
			return r;
		}
		//  --（2.1)、获取机台基础信息表中，配置的机台设备代号（设备编号，如1,2,3）
		ComBaseMachine machine2 = new ComBaseMachine();
		machine2.setMachine_code(sum.getMemo1());
		List<ComBaseMachine> lcbm = this.getMapper(ComBaseMachineMapper.class)
				.find(machine2, 0, 0);
		String v_mch_mark=lcbm.get(0).getMachine_mark();
		if (v_mch_mark == null) {
			r.setMsgInfo("机台代码：" + sum.getMemo1() + "\n设备编号未配置，无法处理！");
			r.setState("500");
			return r;
		}
		// （3）、根据当前时刻，计算日期班次
		ResultModel rmDb=this.getBean(PbModelDbServiceImpl.class).findDbTime();
		String dbTime=rmDb.getData().toString().substring(11);
		String wrk_date=null,wrk_ord=null,wrk_grp=null;
		if("200".equals(rmDb.getState())){
			dbTime=rmDb.getData().toString().substring(11);
			wrk_date=rmDb.getData().toString().substring(0,10);			
			if(dbTime.compareTo(DateUtil.NBeginTime)>-1&&dbTime.compareTo(DateUtil.BeginTime)<0){
				wrk_ord="1";
			}else if(dbTime.compareTo(DateUtil.BeginTime)>-1&&dbTime.compareTo(DateUtil.EndTime)<0){
				wrk_ord="2";
			}else if(dbTime.compareTo(DateUtil.EndTime)>-1&&dbTime.compareTo(DateUtil.NEndTime)<0){
				wrk_ord="1";
				SimpleDateFormat formatYmd = new SimpleDateFormat("yyyy-MM-dd");
				Date date;
				try {
					date = formatYmd.parse(wrk_date);
				} catch (Exception e) {
					throw new Exception("获取数据库时间失败，请稍后重试");
				}
				Calendar c = Calendar.getInstance();  
    	        c.setTime(date);  
    	        c.add(Calendar.DAY_OF_MONTH, 1);//日期+1 
				wrk_date=formatYmd.format(c.getTime());
			}
		}else{
			throw new Exception("获取数据库时间失败！请稍后重试");
		}
		//  --（3.4）、根据计算的日期班次，获取交接班记录的班组
		MesShiftM msm=new MesShiftM();
		msm.setMachine_code(sum.getMemo1());
		msm.setWrk_date(wrk_date);
		msm.setWrk_ord(wrk_ord);
		v_cnt=this.getMapper(MesShiftMMapper.class).count(msm);
		if(v_cnt<=0){
			wrk_grp=sum.getMemo2();//   --暂无交接班记录，则使用前端传入的班组代码
		}else{
			//    --否则获取交接班记录中的班组
			List<MesShiftM> lmsm = this.getMapper(MesShiftMMapper.class).find(msm, 0, 0);
			wrk_grp=lmsm.get(0).getWrk_grp();
		}
		// --(4)、上料业务处理： 
		
		//  --(4.1)、验证平整作业计划主记录存在
		PlnSkinrollingPlan psp=new PlnSkinrollingPlan();
		psp.setMachine_code(sum.getMemo1());
		psp.setSr_plan_no(plp.getSr_plan_no());
		int count = this.getMapper(PlnSkinrollingPlanMapper.class).count(psp);
		if (count<=0) {
			throw new Exception("机台代码："+sum.getMemo1()+"\n作业计划号："+plp.getSr_plan_no()+"\n作业计划主记录不存在！");
		}
		//    --(4.2)、验证平整作业计划明细记录存在
		PlnSkinrollingPlanDetail pcpd=new PlnSkinrollingPlanDetail();
		pcpd.setMachine_code(sum.getMemo1());
		pcpd.setSr_plan_no(plp.getSr_plan_no());
		pcpd.setObject_no_vt(plp.getObject_no_vt());
		pcpd.setObject_no(plp.getMaterial_no());
		int count2 = this.getMapper(PlnSkinrollingPlanDetailMapper.class).count(pcpd);
		if (count2<=0) {
			throw new Exception("机台代码："+sum.getMemo1()+"\n作业计划号："+plp.getSr_plan_no()+"\n虚拟卷号："+plp.getObject_no_vt()+""
					+ "\n原料卷号："+plp.getMaterial_no()+"\n作业计划明细记录不存在！");
		}
		PlnSkinrollingPlanDetail cuttdel = new PlnSkinrollingPlanDetail();
		cuttdel.setMachine_code(sum.getMemo1());
		cuttdel.setSr_plan_no(plp.getSr_plan_no());
		cuttdel.setObject_no_vt(plp.getObject_no_vt());
		cuttdel.setObject_no(plp.getMaterial_no());
		List<PlnSkinrollingPlanDetail> v_rec_pln_d = this.getMapper(
				PlnSkinrollingPlanDetailMapper.class).findWithCondition(cuttdel, null, null, 0, 0);
		//2018-11-29 只有是已下发状态的钢卷才能下发
		if(v_rec_pln_d!=null && v_rec_pln_d.size()>0){
			if(!"5BSR02".equals(v_rec_pln_d.get(0).getStatus())){
				throw new Exception("当前状态{"+v_rec_pln_d.get(0).getStatus()+"}不为已下发");
			}
		}
		//    --(4.3)、验证虚拟物料表中，原料卷计划信息存在
		PlnMaterielDetail pmd=new PlnMaterielDetail();
		pmd.setObject_no_vt(plp.getObject_no_vt());
		int count3 = this.getMapper(PlnMaterielDetailMapper.class).count(pmd);
		if (count3<=0) {
			throw new Exception("虚拟卷号："+plp.getObject_no_vt()+"\n原料卷虚拟物料信息不存在！");
		}		
		
		//	    --(4.7)、验证指定的计划，还未创建平整作业主实绩
		MesTpmM mCross = new MesTpmM();
		mCross.setMachine_code(sum.getMemo1());
		mCross.setSchedule_no(plp.getSr_plan_no());
		mCross.setMaterial_no_vt(plp.getObject_no_vt());
		mCross.setMaterial_no(plp.getMaterial_no());
		v_cnt = this.getBean(MesTpmMMapper.class).count(mCross);
		if (v_cnt > 0) {
			throw new Exception("原料卷号：" + plp.getMaterial_no() + "，当前已存在平整作业实绩！");
		}
		
		// (4.4)、验证原料卷号库存明细记录存在
		YdmProductDetail tYdm2 = new YdmProductDetail();
		tYdm2.setCoilno(plp.getMaterial_no());
		v_cnt = this.getMapper(YdmProductDetailMapper.class).count(tYdm2);
		if (v_cnt <= 0) {
			throw new Exception("原料卷号：" + plp.getMaterial_no() + "库存明细记录不存在！");
		}
			
		// (4.5)、验证原料卷号库存明细记录为“在库”状态   【在库状态(-1待入库、0在库、1移送在途、2发运锁定、4包装出库、5出库)】
		YdmProductDetail tYdm3 = new YdmProductDetail();
		tYdm3.setCoilno(plp.getMaterial_no());
		List<YdmProductDetail>  v_rec_ydm_d = this.getMapper(
				YdmProductDetailMapper.class).findWithCondition(tYdm3,
						null, null, 0, 0);
		if (v_rec_ydm_d.get(0).getState()==null
				|| (!v_rec_ydm_d.get(0).getState().equals("0"))) {
			throw new Exception("原料卷号：" + plp.getMaterial_no() + "，当前不是“在库”状态！当前状态为【"+v_rec_ydm_d.get(0).getState()+"】(-1待入库、0在库、1移送在途、2发运锁定、4包装出库、5出库)");
		}
		//    --(4.6)、验证虚拟物料表中，出口卷虚拟物料信息存在
		PlnMaterielDetail pmd2=new PlnMaterielDetail();
		pmd2.setMat_object_no_vt(plp.getObject_no_vt());
		v_cnt = this.getMapper(PlnMaterielDetailMapper.class).count(pmd2);
		if (v_cnt<=0) {
			throw new Exception("虚拟卷号："+plp.getObject_no_vt()+"\n出口卷虚拟物料信息不存在！");
		}
		
		/*
	      --(4.9)、创建平整主实绩记录（未列出字段，表设置的缺省值）																																							
		  --(4.9.1)、原料卷计划规格、牌号等信息来源于 pln_materiel_detail 表																																							
		  --(4.9.2)、原料卷实际规格、牌号等信息来源于 ydm_product_detail 表																																							
		  --(4.9.3)、出口卷计划规格、牌号等信息来源于 pln_materiel_detail 表																																							
		  --(4.9.4)、出口卷实际规格、牌号等信息来源于 ydm_product_detail 表																																							
		 */
		PlnMaterielDetail tYdm = new PlnMaterielDetail();
		tYdm.setObject_no_vt(plp.getObject_no_vt());
		List<PlnMaterielDetail> v_rec_mtr_in = this.getBean(
				PlnMaterielDetailMapper.class).findWithCondition(tYdm, null, null, 0, 0);
		MesTpmM mcam=new MesTpmM();
		mcam.setMachine_code(sum.getMemo1());
		mcam.setSchedule_no(plp.getSr_plan_no());
		mcam.setInner_seq(v_rec_pln_d.get(0).getSr_seq());
		mcam.setMaterial_no_vt(plp.getObject_no_vt());
		mcam.setPln_steel_code(v_rec_mtr_in.get(0).getSteel_code());
		mcam.setPln_mtr_thk(v_rec_mtr_in.get(0).getThick());
		mcam.setPln_mtr_wdt(v_rec_mtr_in.get(0).getWidth());
		mcam.setPln_mtr_len(v_rec_mtr_in.get(0).getLength());
		mcam.setPln_mtr_inn_dia(v_rec_mtr_in.get(0).getDiameter_inn());
		mcam.setPln_mtr_out_dia(v_rec_mtr_in.get(0).getDiameter_out());
		mcam.setPln_mtr_thr_wgt(v_rec_mtr_in.get(0).getSingle_weight());
		mcam.setMaterial_no(plp.getMaterial_no());
		mcam.setMaterial_no_src(v_rec_ydm_d.get(0).getMaterailcoilno());
		mcam.setSteel_code(v_rec_ydm_d.get(0).getSteelcode());
		mcam.setMtr_thk(v_rec_ydm_d.get(0).getThick());
		mcam.setMtr_wdt(v_rec_ydm_d.get(0).getWidth());
		mcam.setMtr_len(v_rec_ydm_d.get(0).getLength());
		mcam.setMtr_inn_dia(v_rec_ydm_d.get(0).getDiameter_inn());
		mcam.setMtr_out_dia(v_rec_ydm_d.get(0).getDiameter_out());
		if(v_rec_ydm_d.get(0).getTheoryweight()!=null){
			mcam.setMtr_thr_wgt(v_rec_ydm_d.get(0).getTheoryweight());
		}else{
			mcam.setMtr_thr_wgt(v_rec_ydm_d.get(0).getFactweight());
		}		
		mcam.setMtr_act_wgt(v_rec_ydm_d.get(0).getFactweight());
		mcam.setWrk_date(wrk_date);
		mcam.setWrk_ord(wrk_ord);
		mcam.setWrk_grp(wrk_grp);
		mcam.setFeeding_time(now);
		mcam.setPartial_rejected("0");		
		mcam.setHand_over_status("0");
		mcam.setCreate_opr(username);
		mcam.setCreate_time(now);
		
		this.getMapper(MesTpmMMapper.class).insert(mcam);
		
		// --(4.10)、调用生产管理接口，执行业计划状态、物料进程状态相关操作（接口由生产管理模块提供）； ？？？
		MesTpmM  mcsm=new MesTpmM();
		mcsm.setMachine_code(sum.getMemo1());//机台号
		mcsm.setSchedule_no(plp.getSr_plan_no());//作业计划号
		mcsm.setMaterial_no(plp.getMaterial_no());//投料卷号
		mcsm.setMaterial_no_vt(plp.getObject_no_vt());//虚拟卷号 
		List<MesTpmM> lmcsm=new ArrayList<MesTpmM>();
		
		//时间
	    String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS").format(now);// now为获取当前系统时间，也可使用当前时间戳
	    mcsm.setMemo(date);
	    lmcsm.add(mcsm);
	    this.getBean(MesApiSkinrollingPlanImpl.class).MesTpmMAdd(lmcsm); 
		
		//调用物流模块（仓库管理）接口，对原料卷进行生产投料出库操作（接口由物流模块提供）；																																							
		YdmProductDetail ypd=new YdmProductDetail();
		ypd.setCoilno(mcam.getMaterial_no());		
		ypd.setMemo(date);// 传入操作时间字符串带毫秒
		CommonPage<YdmProductDetail> cp=new CommonPage<YdmProductDetail>();
		cp.setObject(ypd);
		this.getBean(LmsApiServiceImpl.class).doOutStorage(cp);
		
		try{
			this.getBean(PlnProdorderStatisticServiceImpl.class).updateProdSta(mcam.getMaterial_no(),true);
		}catch(Exception e){
			e.printStackTrace();
		}
		
		
		String isOpen = this.getMapper(ComBaseInfoMapper.class).findById("9512").getMemo();
		if ("1".equals(isOpen)) {
		
			// 记录成本异动点：20230811刘侣
			ComBaseCbYdd cd = new ComBaseCbYdd();
			cd.setCoilStus("0"); // 综判前算半成品0，综判入库后算成品1
			cd.setInstDisp("01");
			cd.setDataTypeIdx("O");
			// 当前产线：
			String currentMachine = v_rec_ydm_d.get(0).getCoilno().contains("S") ? "YTSX" : v_rec_ydm_d.get(0).getCoilno().contains("L") ? "YTZZ" : v_rec_ydm_d.get(0).getCoilno().contains("P") ? "YTPZ" : v_rec_ydm_d.get(0).getCoilno().contains("T") ? "YTTH" : v_rec_ydm_d.get(0).getCoilno().contains("K") ? "YTHJ" : v_rec_ydm_d.get(0).getCoilno().contains("F") ? "YTZJ" : "YT1";
			cd.setLocNo(currentMachine); // 填当前产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
			cd.setInvQtyUnit("块");
			cd.setInvWidth(v_rec_ydm_d.get(0).getWidth() != null ? String.valueOf(v_rec_ydm_d.get(0).getWidth()) : "0");
			cd.setCreateId(userId);
			cd.setActivityId("41A");
			cd.setInvLength(v_rec_ydm_d.get(0).getLength() != null ? String.valueOf(v_rec_ydm_d.get(0).getLength()) : "0");
			cd.setManageip(currentMachine); // 填当前产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
			cd.setProdName(v_rec_ydm_d.get(0).getProd_name());
			cd.setInvThick(v_rec_ydm_d.get(0).getThick() != null ? String.valueOf(v_rec_ydm_d.get(0).getThick()) : "0");
			
			
			String prevcoil = v_rec_ydm_d.get(0).getCoilno();
			// 上道产线：
			String prevMachine = prevcoil.contains("S") ? "YTSX" : prevcoil.contains("L") ? "YTZZ" : prevcoil.contains("P") ? "YTPZ" : prevcoil.contains("T") ? "YTTH" : prevcoil.contains("K") ? "YTHJ" : prevcoil.contains("F") ? "YTZJ" : "YT1";
			cd.setRefnoA("YT1".equals(prevMachine) ? v_rec_ydm_d.get(0).getMaterailcoilno() : prevcoil); // 投料卷号
			cd.setSysId("IA");
			cd.setOrderItem(v_rec_ydm_d.get(0).getOrderno());
			cd.setCrntMill(currentMachine); // 填当前产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
			cd.setBeTransUnit("t");
			cd.setExecJobFunc("N");
			ComBaseSteel cbs = this.getMapper(ComBaseSteelMapper.class).findById(v_rec_ydm_d.get(0).getSteelcode());
			if (cbs != null) {
				cd.setAlloyNo(cbs.getSteel_name()); // 牌号
			}
			
			cd.setAcctDate(new SimpleDateFormat("yyyyMMdd").format(now));
			cd.setLastMill(prevMachine); // 填上道工序产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
			cd.setBeTransWgt(v_rec_ydm_d.get(0).getFactweight() != null ? v_rec_ydm_d.get(0).getFactweight() / 1000 : v_rec_ydm_d.get(0).getFactweight());
			cd.setProdTypeNo("CTR");
			cd.setAppId("优特钢平整上料");
			cd.setInvId("YT1".equals(currentMachine) ? v_rec_ydm_d.get(0).getMaterailcoilno() : v_rec_ydm_d.get(0).getCoilno());
			cd.setInvQty("1");

			// setSrcFac根据卷的物料属性去判断：20231031刘侣
			cd.setSrcFac("507101".equals(v_rec_ydm_d.get(0).getObject_attr()) ? "1" : "3");
			
			cd.setGrade("40740801".equals(v_rec_ydm_d.get(0).getJudgeresult()) ? "1" : "1"); // 正品　1　协议　3　次品　5
			cd.setProdClassNo("H");
			
			// 存入表：1、上料一抛：原料转库（47）（原料上料准备生产时抛送）
			cd.setActivityId("55A");
			cd.setExecJobFunc("N");
			cd.setDataTypeIdx("O");
			cd.setProdTypeNo("YT1".equals(prevMachine) && cd.getInvId().startsWith("L") ? "CCR" : "YT1".equals(prevMachine) ? "HCR" : "CTR");
			cd.setCoilStus("0"); // 综判前算半成品0，综判入库后算成品1
			cd.setCrntMill(prevMachine); // 填上道产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
			cd.setManageip(prevMachine); // 填上道产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
			cd.setLocNo(prevMachine); // 填上道产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
//			String currentMName = v_rec_ydm_d.get(0).getCoilno().contains("S") ? "酸洗" : v_rec_ydm_d.get(0).getCoilno().contains("L") ? "冷轧" : v_rec_ydm_d.get(0).getCoilno().contains("P") ? "平整" : v_rec_ydm_d.get(0).getCoilno().contains("T") ? "退火" : v_rec_ydm_d.get(0).getCoilno().contains("K") ? "横剪" : v_rec_ydm_d.get(0).getCoilno().contains("F") ? "分条" : "原料";
			String prevMName = prevcoil.contains("S") ? "酸洗" : prevcoil.contains("L") ? "冷轧" : prevcoil.contains("P") ? "平整" : prevcoil.contains("T") ? "退火" : prevcoil.contains("K") ? "开平" : prevcoil.contains("F") ? "分条" : "原料";
			cd.setAppId("优特" + prevMName + "转库");
			
			// 一次结算后第一次生产点上料的时候，不抛 转库和接收原料  改抛 12AB
			// 该卷是否刚刚一次结算完：可以根据提单里是否有这卷的一次结算数据进行判断：
//			int isYcJs = this.getMapper(YdmProductDetailMapper.class).isHasYcJs(v_rec_ydm_d.get(0).getCoilno());
//			if (isYcJs <= 0) {
				this.getBean(SlmFundFirstDetailService.class).doCbDataIns(cd, cd.getActivityId(), v_rec_ydm_d.get(0).getMaterailcoilno());
//			}
			
			// 二抛：酸洗接收原料（17）(此时原料还未上酸洗产线) 
			// 对已有数据进行修改：
			cd.setDataTypeIdx("N");
//			cd.setProdTypeNo("CTR");
			cd.setManageip("YTPZ");
			cd.setLocNo("YTPZ");
			cd.setAppId("平整接收原料");
			
			// 20231130刘侣 废掉 xuli 20231229 来刘侣
//			if (isYcJs > 0) {
//				cd.setActivityId("12AB");
//				cd.setAppId("来料加工");
//			}
			// end
			this.getBean(SlmFundFirstDetailService.class).doCbDataIns(cd, cd.getActivityId(), v_rec_ydm_d.get(0).getMaterailcoilno());
			// 三抛：酸洗上料（41，开始生产
			cd.setActivityId("41A");
			cd.setDataTypeIdx("O");
			cd.setAppId("平整上料");
			cd.setLastMill("YTPZ");
			this.getBean(SlmFundFirstDetailService.class).doCbDataIns(cd, cd.getActivityId(), v_rec_ydm_d.get(0).getMaterailcoilno());
			// end
		}
		
		
		//日志
		MesOprLog mol = new MesOprLog("车间MES", "平整机作业管理", "上料", username, opr_time, mcam.getMaterial_no(), null, null, null, null);
		this.getMapper(MesOprLogMapper.class).insert(mol);
		// --(5)、提交事务
		r.setState("200");
		r.setMsgInfo("上料成功!");
		return r;
	}
		
	/**
	 * 动作处理 -恢复计划 
	 * object中：
	 * sr_plan_no 作业计划号
	 * object_no_vt 虚拟卷号
	 * material_no 原料卷号
	 * memo1：机台代码，
	 * memo2:登录用户名，
	 * memo3:登录班组
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doUpdateWeb(CommonPage<PlnSkinrollingPlan> sum) throws Exception {
		ResultModel r=new ResultModel();
		Date now = new Date();
		String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(now); //操作时间
		String userId = (String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		String username = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);

		Integer v_cnt;		
		//  --(1)、验证前端传入参数的基本有效性
		if(sum.getMemo1()==null || sum.getMemo1().length()<=0){
			r.setMsgInfo("参数错误：机台代码不能为空！");
			r.setState("500");
			return r;
		}
		PlnSkinrollingPlan plp = sum.getObject();
		if(plp.getSr_plan_no()==null || "".equals(plp.getSr_plan_no())){
			r.setMsgInfo("作业计划号为空");
			r.setState("500");
			return r;
		}
		if(plp.getObject_no_vt()==null || "".equals(plp.getObject_no_vt())){
			r.setMsgInfo("虚拟卷号为空");
			r.setState("500");
			return r;
		}
		if(plp.getMaterial_no()==null || "".equals(plp.getMaterial_no())){
			r.setMsgInfo("原料卷号为空");
			r.setState("500");
			return r;
		}
		
		// (2.1)、验证平整作业计划主记录存在
		PlnSkinrollingPlan pcp=new PlnSkinrollingPlan();
		pcp.setMachine_code(sum.getMemo1());
		pcp.setSr_plan_no(plp.getSr_plan_no());
		int count = this.getMapper(PlnSkinrollingPlanMapper.class).count(pcp);
		if (count<=0) {
			throw new Exception("机台代码："+sum.getMemo1()+"\n作业计划号："+plp.getSr_plan_no()+"\n作业计划主记录不存在！");
		}
		// (2.2)、验证平整作业计划明细记录存在
		PlnSkinrollingPlanDetail pcpd=new PlnSkinrollingPlanDetail();
		pcpd.setMachine_code(sum.getMemo1());
		pcpd.setSr_plan_no(plp.getSr_plan_no());
		pcpd.setObject_no_vt(plp.getObject_no_vt());
		pcpd.setObject_no(plp.getMaterial_no());
		int count2 = this.getMapper(PlnSkinrollingPlanDetailMapper.class).count(pcpd);
		if (count2<=0) {
			throw new Exception("机台代码："+sum.getMemo1()+"\n作业计划号："+plp.getSr_plan_no()+"\n虚拟卷号："+plp.getObject_no_vt()+""
					+ "\n原料卷号："+plp.getMaterial_no()+"\n作业计划明细记录不存在！");
		}
		// (2.3)、验证虚拟物料表中，原料卷计划信息存在
		PlnMaterielDetail pmd=new PlnMaterielDetail();
		pmd.setObject_no_vt(plp.getObject_no_vt());
		int count3 = this.getMapper(PlnMaterielDetailMapper.class).count(pmd);
		if (count3<=0) {
			throw new Exception("虚拟卷号："+plp.getObject_no_vt()+"\n原料卷虚拟物料信息不存在！");
		}
		// (2.5)、验证平整作业主实绩存在，且为“未交工”状态
		MesTpmM mCross = new MesTpmM();
		mCross.setMachine_code(sum.getMemo1());
		mCross.setSchedule_no(plp.getSr_plan_no());
		mCross.setMaterial_no_vt(plp.getObject_no_vt());
		mCross.setMaterial_no(plp.getMaterial_no());
		v_cnt = this.getBean(MesTpmMMapper.class).count(mCross);
		if (v_cnt<=0) {
			throw new Exception("原料卷号：" + plp.getMaterial_no() + "，当前不存在平整作业实绩！");
		}
	    List<MesTpmM> lmcam = this.getMapper(MesTpmMMapper.class).find(mCross, 0, 0);
	    MesTpmM v_rec_tpm =lmcam.get(0);
	    if(v_rec_tpm.getHand_over_status()!=null && !v_rec_tpm.getHand_over_status().equals("0")){
			throw new Exception("原料卷号："+plp.getMaterial_no()+"当前已生产交工，不能恢复计划！\n可取消交工，再进行此操作！");
	    }
	    // 5.验证原料卷，当前未生成出口卷实绩
	    MesTpmD crcrD = new MesTpmD();
 		crcrD.setMaterial_no(plp.getMaterial_no());
 		crcrD.setSchedule_no(plp.getSr_plan_no());
 		v_cnt = this.getBean(MesTpmDMapper.class).count(crcrD);
 		if (v_cnt > 0) {
 			r.setMsgInfo("原料卷号：" + plp.getMaterial_no() + "已生成出口卷信息，不能恢复计划"+"\n"
 					+"可删除所有出口卷记录后，再进行此操作！");
 			r.setState("500");
 			return r;
 		}
	    
	    //--(2.6)、调用生产管理接口，验证是否能执行相关操作，如果不满足条件，返回错误信息到前端，结束操作（接口由生产管理模块提供）；	 ??																																						
	    this.getBean(MesApiSkinrollingPlanImpl.class).MesTpmMCancelValid(lmcam);
	    //--(2.7)、调用物流模块接口，验证原料卷可撤销生产出库操作，如果不满足条件，返回错误信息到前端，结束操作（接口由物流模块提供）；		
		YdmProductDetail ypd=new YdmProductDetail();
		ypd.setCoilno(plp.getMaterial_no());
		CommonPage<YdmProductDetail> cp=new CommonPage<YdmProductDetail>();	
		cp.setObject(ypd);
		r = this.getBean(LmsApiServiceImpl.class).doDepend(cp);
		if("500".equals(r.getState())){
			throw new Exception(r.getMsgInfo());
		}
		//--(2.8)、删除平整作业实绩
		this.getMapper(MesTpmMMapper.class).doDelete(sum.getMemo1(),plp.getSr_plan_no(),plp.getObject_no_vt(),plp.getMaterial_no());
		
		// --(2.9)、调用生产管理接口，执行业计划状态、物料进程状态相关操作（接口由生产管理模块提供）；？？																																							
		this.getBean(MesApiSkinrollingPlanImpl.class).MesTpmMCancel(lmcam);
		//  --(2.10)、调用物流模块接口，执行原料卷出库撤销相关操作（接口由物流模块提供）；																																							
		this.getBean(LmsApiServiceImpl.class).doCancelOut(cp);
		
		try{
			this.getBean(PlnProdorderStatisticServiceImpl.class).updateProdSta(plp.getMaterial_no(),false);
		}catch(Exception e){
			e.printStackTrace();
		}
		
		
		String isOpen = this.getMapper(ComBaseInfoMapper.class).findById("9512").getMemo();
		if ("1".equals(isOpen)) {
		
			// 记录成本异动点：20230811刘侣
			YdmProductDetail ypdM = this.getMapper(YdmProductDetailMapper.class).findById(plp.getMaterial_no());
			ComBaseCbYdd cd = new ComBaseCbYdd();
			cd.setCoilStus("0"); // 综判前算半成品0，综判入库后算成品1
			cd.setInstDisp("01");
			cd.setDataTypeIdx("O");
			// 当前产线：
			String currentMachine = ypdM.getCoilno().contains("S") ? "YTSX" : ypdM.getCoilno().contains("L") ? "YTZZ" : ypdM.getCoilno().contains("P") ? "YTPZ" : ypdM.getCoilno().contains("T") ? "YTTH" : ypdM.getCoilno().contains("K") ? "YTHJ" : ypdM.getCoilno().contains("F") ? "YTZJ" : "YT1";
			cd.setLocNo(currentMachine); // 填当前产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
			cd.setInvQtyUnit("块");
			cd.setInvWidth(ypdM.getWidth() != null ? String.valueOf(ypdM.getWidth()) : "0");
			cd.setCreateId(userId);
			cd.setActivityId("41A");
			cd.setInvLength(ypdM.getLength() != null ? String.valueOf(ypdM.getLength()) : "0");
			cd.setManageip(currentMachine); // 填当前产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
			cd.setProdName(ypdM.getProd_name());
			cd.setInvThick(ypdM.getThick() != null ? String.valueOf(ypdM.getThick()) : "0");
			
			
			String prevcoil = ypdM.getCoilno();
			// 上道产线：
			String prevMachine = prevcoil.contains("S") ? "YTSX" : prevcoil.contains("L") ? "YTZZ" : prevcoil.contains("P") ? "YTPZ" : prevcoil.contains("T") ? "YTTH" : prevcoil.contains("K") ? "YTHJ" : prevcoil.contains("F") ? "YTZJ" : "YT1";
			cd.setRefnoA("YT1".equals(prevMachine) ? ypdM.getMaterailcoilno() : prevcoil); // 投料卷号
			cd.setSysId("IA");
			cd.setOrderItem(ypdM.getOrderno());
			cd.setCrntMill(currentMachine); // 填当前产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
			cd.setBeTransUnit("t");
			cd.setExecJobFunc("D");
			ComBaseSteel cbs = this.getMapper(ComBaseSteelMapper.class).findById(ypdM.getSteelcode());
			if (cbs != null) {
				cd.setAlloyNo(cbs.getSteel_name()); // 牌号
			}
			
			cd.setAcctDate(new SimpleDateFormat("yyyyMMdd").format(now));
			cd.setLastMill(prevMachine); // 填上道工序产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
			cd.setBeTransWgt(ypdM.getFactweight() != null ? ypdM.getFactweight() / 1000 : ypdM.getFactweight());
			cd.setProdTypeNo("CTR");
			cd.setAppId("优特钢平整取消上料");
			cd.setInvId("YT1".equals(currentMachine) ? ypdM.getMaterailcoilno() : ypdM.getCoilno());
			cd.setInvQty("1");

			// setSrcFac根据卷的物料属性去判断：20231031刘侣
			cd.setSrcFac("507101".equals(ypdM.getObject_attr()) ? "1" : "3");
			
			cd.setGrade("40740801".equals(ypdM.getJudgeresult()) ? "1" : "1"); // 正品　1　协议　3　次品　5
			cd.setProdClassNo("H");
			
			// 存入表：1、上料一抛：原料转库（47）（原料上料准备生产时抛送）
			cd.setActivityId("55A");
			cd.setExecJobFunc("D");
			cd.setDataTypeIdx("O");
			cd.setProdTypeNo("YT1".equals(prevMachine) && cd.getInvId().startsWith("L") ? "CCR" : "YT1".equals(prevMachine) ? "HCR" : "CTR");
			cd.setCoilStus("0"); // 综判前算半成品0，综判入库后算成品1
			cd.setCrntMill(prevMachine); // 填上道产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
			cd.setManageip(prevMachine); // 填上道产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
			cd.setLocNo(prevMachine); // 填上道产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
//			String currentMName = ypdM.getCoilno().contains("S") ? "酸洗" : ypdM.getCoilno().contains("L") ? "冷轧" : ypdM.getCoilno().contains("P") ? "平整" : ypdM.getCoilno().contains("T") ? "退火" : ypdM.getCoilno().contains("K") ? "横剪" : ypdM.getCoilno().contains("F") ? "分条" : "原料";
			String prevMName = prevcoil.contains("S") ? "酸洗" : prevcoil.contains("L") ? "冷轧" : prevcoil.contains("P") ? "平整" : prevcoil.contains("T") ? "退火" : prevcoil.contains("K") ? "开平" : prevcoil.contains("F") ? "分条" : "原料";
			cd.setAppId("优特" + prevMName + "取消转库");
			
			// 一次结算后第一次生产点上料的时候，不抛 转库和接收原料  改抛 12AB
			// 该卷是否刚刚一次结算完：可以根据提单里是否有这卷的一次结算数据进行判断：
//			int isYcJs = this.getMapper(YdmProductDetailMapper.class).isHasYcJs(ypdM.getCoilno());
//			if (isYcJs <= 0) {
				this.getBean(SlmFundFirstDetailService.class).doCbDataIns(cd, cd.getActivityId(), ypdM.getMaterailcoilno());
//			}
			
			// 二抛：酸洗接收原料（17）(此时原料还未上酸洗产线) 
			// 对已有数据进行修改：
			cd.setDataTypeIdx("N");
//			cd.setProdTypeNo("CTR");
			cd.setManageip("YTPZ");
			cd.setLocNo("YTPZ");
			cd.setAppId("平整取消接收原料");
			
			// 20231130刘侣
//			if (isYcJs > 0) {
//				cd.setActivityId("12AB");
//				cd.setAppId("取消来料加工");
//			}
			// end
			this.getBean(SlmFundFirstDetailService.class).doCbDataIns(cd, cd.getActivityId(), ypdM.getMaterailcoilno());
			// 三抛：酸洗上料（41，开始生产
			cd.setActivityId("41A");
			cd.setDataTypeIdx("O");
			cd.setAppId("平整取消上料");
			cd.setLastMill("YTPZ");
			this.getBean(SlmFundFirstDetailService.class).doCbDataIns(cd, cd.getActivityId(), ypdM.getMaterailcoilno());
			// end
		}
		
		//日志
		MesOprLog mol = new MesOprLog("车间MES", "平整机作业管理", "恢复计划", username, opr_time, v_rec_tpm.getMaterial_no(), null, null, null, null);
		this.getMapper(MesOprLogMapper.class).insert(mol);
		//  --(3)、提交事务
		r.setState("200");
		r.setMsgInfo("恢复计划成功");
		return r;
	}
	
	/**
	 * 保存  * 
	 * object中：
	 * schedule_no作业计划号
	 * material_no_vt虚拟卷号
	 * material_no原料卷号
	 * 详见文档
	 * -----
	 * memo1：机台代码，
	 * memo2:登录用户名
	 * */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel  doSaveWeb(CommonPage<MesTpmM> sum) throws Exception{
		ResultModel r=new ResultModel();
		Date now = new Date();
		String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(now); //操作时间
		String username = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		MesTpmM mcm = sum.getObject();
		
		if(mcm==null){
			r.setState("500");
			r.setMsgInfo("请传入参数！");
			return r;
		}
		Integer v_cnt;
		if(mcm.getEntry_tension_avg()!=null && mcm.getEntry_tension_avg()>999){
			r.setState("500");
			r.setMsgInfo("前张力平均值（10^-2kn）应小于999");
			return r;
		}
		if(mcm.getEntry_tension_max()!=null && mcm.getEntry_tension_max()>999){
			r.setState("500");
			r.setMsgInfo("前张力最大值（10^-2kn）应小于999");
			return r;
		}
		if(mcm.getEntry_tension_min()!=null && mcm.getEntry_tension_min()>999){
			r.setState("500");
			r.setMsgInfo("前张力最小值（10^-2kn）应小于999");
			return r;
		}
		if(mcm.getExit_tension_avg()!=null && mcm.getExit_tension_avg()>999){
			r.setState("500");
			r.setMsgInfo("后张力平均值（10^-2kn）应小于999");
			return r;
		}
		if(mcm.getExit_tension_max()!=null && mcm.getExit_tension_max()>999){
			r.setState("500");
			r.setMsgInfo("后张力最大值（10^-2kn）应小于999");
			return r;
		}
		if(mcm.getExit_tension_min()!=null && mcm.getExit_tension_min()>999){
			r.setState("500");
			r.setMsgInfo("后张力最小值（10^-2kn）应小于999");
			return r;
		}		
		// --(1)、验证平整作业计划主记录存在
		PlnSkinrollingPlan pcp=new PlnSkinrollingPlan();
		pcp.setMachine_code(sum.getMemo1());
		pcp.setSr_plan_no(mcm.getSchedule_no());
		int count = this.getMapper(PlnSkinrollingPlanMapper.class).count(pcp);
		if (count<=0) {
			throw new Exception("机台代码："+sum.getMemo1()+"\n作业计划号："+mcm.getSchedule_no()+"\n作业计划主记录不存在！");
		}
		//(2.2)、验证平整作业计划明细记录存在
		PlnSkinrollingPlanDetail pcpd=new PlnSkinrollingPlanDetail();
		pcpd.setMachine_code(sum.getMemo1());
		pcpd.setSr_plan_no(mcm.getSchedule_no());
		pcpd.setObject_no_vt(mcm.getMaterial_no_vt());
		pcpd.setObject_no(mcm.getMaterial_no());
		int count2 = this.getMapper(PlnSkinrollingPlanDetailMapper.class).count(pcpd);
		if (count2<=0) {
			throw new Exception("机台代码："+sum.getMemo1()+"\n作业计划号："+mcm.getSchedule_no()+"\n虚拟卷号："+mcm.getMaterial_no_vt()+""
					+ "\n原料卷号："+mcm.getMaterial_no()+"\n作业计划明细记录不存在！");
		}
		//(3)、验证原料卷对应的平整主实绩存在，且为“未交工”状态
		MesTpmM mCross = new MesTpmM();
		mCross.setMachine_code(sum.getMemo1());
		mCross.setSchedule_no(mcm.getSchedule_no());
		mCross.setMaterial_no_vt(mcm.getMaterial_no_vt());
		mCross.setMaterial_no(mcm.getMaterial_no());
		v_cnt = this.getBean(MesTpmMMapper.class).count(mCross);
		if (v_cnt<=0) {
			r.setState("500");
			r.setMsgInfo("原料卷号：" +mcm.getMaterial_no()+ "，当前不存在平整作业实绩！");
			return r;
		}
	    List<MesTpmM> lmcam = this.getMapper(MesTpmMMapper.class).find(mCross, 0, 0);
	    MesTpmM v_rec_tpm =lmcam.get(0);
	    if(v_rec_tpm.getHand_over_status()!=null && !v_rec_tpm.getHand_over_status().equals("0")){
	    	r.setState("500");
	    	r.setMsgInfo("原料卷号："+mcm.getMaterial_no()+"当前已生产交工，不能修改生产实绩！可取消交工，再进行此操作！");
			return r;
	    }
	    //(4)、如果前端参数 V_PARTIAL_REJECTED = '1'，表示部分原料卷吊销，则要按规则创建吊销的原料卷号信息
	    String v_rejected_coil_no=null;
	    if("1".equals(mcm.getPartial_rejected())){
	    	//(4.1)、验证机台基础信息存在
			ComBaseMachine machine = new ComBaseMachine();
			machine.setMachine_code(sum.getMemo1());
			v_cnt = this.getMapper(ComBaseMachineMapper.class).count(machine);
			if (v_cnt <= 0) {
				r.setMsgInfo("机台代码：" + sum.getMemo1() + "，\n机台基础信息不存在！");
				r.setState("500");
				return r;
			}
			//（4.2)、获取机台基础信息表中，配置的机台设备代号（设备编号，如1,2,3）
			ComBaseMachine machine2 = new ComBaseMachine();
			machine2.setMachine_code(sum.getMemo1());
			List<ComBaseMachine> lcbm = this.getMapper(ComBaseMachineMapper.class).find(machine2, 0, 0);
			String v_mch_mark=lcbm.get(0).getMachine_mark();
			if (v_mch_mark == null) {
				r.setMsgInfo("机台代码：" + sum.getMemo1() + "\n设备编号未配置，无法处理！");
				r.setState("500");
				return r;
			}
			//(4.3)、1位流水（1 - 9）：从小到大的序号排查，不存在则占用
			//String v_rejected_coil_no=null;
			for(int i=1;i<=9;i++){
				//(4.4)、吊销卷编码规则：原料卷号（最初始原料卷号） + 1位工序代号（平整P）+ 2位设备代号（01-99）+ 'R' + 1位流水（1 - 9）
				v_rejected_coil_no=mcm.getMaterial_no().substring(0, 8) + "P"+ lpad(v_mch_mark, 2, "0")+"R"+i;
				count=this.getMapper(MesTpmMMapper.class).doCount1(v_rejected_coil_no,mcm.getSchedule_no(),mcm.getMaterial_no_vt(),mcm.getMaterial_no());
			    //(4.5)、吊销卷号未占用
				if(count==0){
					break;
				}
			}
	    	//(4.6)、吊销卷号无法生成（1-9序号全部被使用）
			if(count>0){
				r.setMsgInfo("原料卷号："+mcm.getMaterial_no()+"，部分原料卷吊销卷号生成失败，序号已全部占用！");
				r.setState("500");
				return r;
			}
	    }else if("0".equals(mcm.getPartial_rejected())){
	    	mcm.setRejected_coil_act_wgt(null);
	    	mcm.setRejected_coil_len(null);
	    	mcm.setRejected_coil_no(null);
	    	mcm.setRejected_coil_out_dia(null);
	    	mcm.setRejected_coil_thr_wgt(null);
		}
	    	    
	    mcm.setRejected_coil_no(v_rejected_coil_no);
	    mcm.setUpdate_opr(username);
	    mcm.setMachine_code(sum.getMemo1());
	    //(5)、修改平整生产实绩主记录（所有字段都可能为空值，注意SQL的处理）
	    this.getMapper(MesTpmMMapper.class).doUpdate(mcm);
	    //（5）、新加功能：同步横剪/开平出口卷实绩作业日期、班次、班组
	    MesTpmD med=new MesTpmD();
	    med.setSchedule_no(mcm.getSchedule_no());
	    med.setMaterial_no(mcm.getMaterial_no());
	    if(mcm.getWrk_date()!=null){
	    	med.setWrk_date(mcm.getWrk_date());
	    }
	    if(mcm.getWrk_ord()!=null){
	    	med.setWrk_ord(mcm.getWrk_ord());
	    }
	    if(mcm.getWrk_grp()!=null){
	    	med.setWrk_grp(mcm.getWrk_grp());
	    }
	    med.setUpdate_opr(username);
	    this.getMapper(MesTpmDMapper.class).doUpdate(med);
	    //日志
	    MesOprLog mol = new MesOprLog("车间MES", "平整机作业管理", "保存", username, opr_time, mcm.getMaterial_no(), null, null, null, null);
	    this.getMapper(MesOprLogMapper.class).insert(mol);
	    //--  --(6)、提交事务
	    r.setState("200");
	    r.setMsgInfo("保存成功！");
		return r;
	}
	
	/***
	 * 动作处理--交工按钮   
	 * object中：
	 * sr_plan_no 作业计划号【平整计划号】
	 * object_no_vt 虚拟卷号
	 * material_no 原料卷号
	 * memo1:mch_code机台代码
	 * memo2:登录用户名
	 * @throws Exception 
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel signOff(CommonPage<PlnSkinrollingPlan> sum) throws Exception {
		ResultModel r=new ResultModel();
		Date now = new Date();
		String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(now); //操作时间
		String username = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		String work_ord = (String) this.getSession().getAttribute(HomeService.SESSION_WORK_ORD);
		String work_grp = (String) this.getSession().getAttribute(HomeService.SESSION_WORK_GRP);
		String work_date = (String) this.getSession().getAttribute(HomeService.SESSION_WORK_TIME);
		work_date = work_date.substring(0, 10);
		PlnSkinrollingPlan psp = sum.getObject();
		
		String nextP = "";
		
		Integer v_cnt;
		// (1)、验证前端传入参数的基本有效性
		if("".equals(psp.getSr_plan_no()) || "".equals(psp.getSr_plan_no())){
			r.setState("500");
			r.setMsgInfo("参数错误：作业计划号为空");
			return r;
		}
		// (1)、验证平整作业计划主记录存在
		PlnSkinrollingPlan pcp=new PlnSkinrollingPlan();
		pcp.setMachine_code(sum.getMemo1());
		pcp.setSr_plan_no(psp.getSr_plan_no());
		int count = this.getMapper(PlnSkinrollingPlanMapper.class).count(pcp);
		if (count<=0) {
			throw new Exception("机台代码："+sum.getMemo1()+"\n作业计划号："+psp.getSr_plan_no()+"\n作业计划主记录不存在！");
		}
		// (2.2)、验证平整作业计划明细记录存在
		PlnSkinrollingPlanDetail pcpd=new PlnSkinrollingPlanDetail();
		pcpd.setMachine_code(sum.getMemo1());
		pcpd.setSr_plan_no(psp.getSr_plan_no());
		pcpd.setObject_no_vt(psp.getObject_no_vt());
		pcpd.setObject_no(psp.getMaterial_no());
		int count2 = this.getMapper(PlnSkinrollingPlanDetailMapper.class).count(pcpd);
		if (count2<=0) {
			throw new Exception("机台代码："+sum.getMemo1()+"\n作业计划号："+psp.getSr_plan_no()+"\n虚拟卷号："+psp.getObject_no_vt()+""
				+ "\n原料卷号："+psp.getMaterial_no()+"\n作业计划明细记录不存在！");
		}
		v_cnt=this.getMapper(PlnMaterielDetailMapper.class).countWithCondition(null, "object_no_vt='"+psp.getObject_no_vt()+"'");
		if (v_cnt<=0) {
			throw new Exception("虚拟卷号："+psp.getObject_no_vt()+"原料卷虚拟物料信息不存在！");
		}
		//???
		v_cnt=this.getMapper(PlnMaterielDetailMapper.class).countWithCondition(null, "mat_object_no_vt='"+psp.getObject_no_vt()+"'");
		if (v_cnt<=0) {
			throw new Exception("虚拟卷号："+psp.getObject_no_vt()+"出口卷虚拟物料信息不存在！");
		}
		//  --(3)、验证原料卷对应的平整主实绩存在，且为“未交工”状态
		MesTpmM mCross = new MesTpmM();
		mCross.setMachine_code(sum.getMemo1());
		mCross.setSchedule_no(psp.getSr_plan_no());
		mCross.setMaterial_no_vt(psp.getObject_no_vt());
		mCross.setMaterial_no(psp.getMaterial_no());
		v_cnt = this.getBean(MesTpmMMapper.class).count(mCross);
		if (v_cnt<=0) {
			r.setState("500");
			r.setMsgInfo("原料卷号：" +psp.getMaterial_no()+ "，当前不存在平整作业实绩！请确认是否已操作上料！");
			return r;
		}
	    List<MesTpmM> lmcam = this.getMapper(MesTpmMMapper.class).find(mCross, 0, 0);
	    MesTpmM v_rec_tpm =lmcam.get(0);
	    if(v_rec_tpm.getHand_over_status()!=null && !v_rec_tpm.getHand_over_status().equals("0")){
	    	r.setState("500");
	    	r.setMsgInfo("原料卷号："+psp.getMaterial_no()+"当前已生产交工，不能重复操作！");
			return r;
	    }
	    // 6.、验证原料卷，当前已有出口卷实绩
		MesTpmD mcccd=new MesTpmD();
		mcccd.setSchedule_no(v_rec_tpm.getSchedule_no());
		mcccd.setMaterial_no(v_rec_tpm.getMaterial_no());
		List<MesTpmD> lmcsd =this.getMapper(MesTpmDMapper.class).findWithCondition(mcccd,"substr(coil_no,-1,1) not in ('B','H')", " coil_no ", 0, 0);
		if(lmcsd==null||lmcsd.size()==0){
			throw new Exception("作业计划原料卷不存在出口卷实绩!");
		}
	    
		Double mtrWgt = v_rec_tpm.getMtr_act_wgt();//投料重量
		Double sumWgt = this.getMapper(MesTpmMMapper.class).doQueryMesTpmDSumWgt(v_rec_tpm.getSchedule_no(),v_rec_tpm.getMaterial_no());
		Double wgt = Math.abs(mtrWgt-sumWgt);
		if (!"2".equals(sum.getMemo6())) {			
			if (wgt > 100) {
				r.setState("500");
				r.setMsgInfo("平整交工重量相差"+wgt+"Kg,超过100Kg,无法交工");
				return r;
			}			
			//20201125 交工重量差异超过0.3%且不超过200KG时,进行异重交工
			if (StringUtils.isEmpty(sum.getMemo6()) || !"1".equals(sum.getMemo6())) {
				Double a = Math.abs(sumWgt-mtrWgt) / mtrWgt;
				if (a > 0.003) {
					r.setState("500");
					r.setMsgInfo("平整交工重量相差"+new DecimalFormat("#.0").format(a*100) +"%,超过0.3%,无法交工");
					return r;
				}			
			}
		}		
	    	    
	    PlnMaterielDetail pmd=new PlnMaterielDetail();
		pmd.setMat_object_no_vt(psp.getObject_no_vt());
		List<PlnMaterielDetail> lpmd=this.getMapper(PlnMaterielDetailMapper.class).findWithCondition(pmd, "", " serial_no ", 0, 0);
		int k=0,n=lpmd.size()-1;
		//（10）、逐一循环出口卷实绩（废副品物料除外），验证各出口卷的 厚、宽、长、实重 都＞0
		List<MesTpmD> listD=	this.getMapper(MesTpmDMapper.class).FindMescrcrDByprocessNo(v_rec_tpm.getSchedule_no(),v_rec_tpm.getMaterial_no());
		for (MesTpmD  cur_01 : listD) {
			if(cur_01.getAct_thk() ==null || cur_01.getAct_thk() <= 0){
				throw new Exception("出口卷:"+cur_01.getCoil_no()+"厚度必须大于0！");
			}
			if(cur_01.getAct_wdt() ==null || cur_01.getAct_wdt() <= 0){
				throw new Exception("出口卷:"+cur_01.getCoil_no()+"宽度必须大于0！");
			}
			/*if(cur_01.getAct_len() ==null || cur_01.getAct_len() <= 0){
				throw new Exception("出口卷:"+cur_01.getCoil_no()+"长度必须大于0！");
			}*/
			if(cur_01.getCoil_act_wgt()==null||cur_01.getCoil_act_wgt()<=0){
				throw new Exception("出口卷["+cur_01.getCoil_no()+"]重量需大于0");
			}
			/*if(cur_01.getAct_thk().doubleValue()>v_rec_tpm.getMtr_thk().doubleValue()){
				v_ret="出口卷:"+cur_01.getCoil_no()+"厚度【"+cur_01.getAct_thk().doubleValue()+"】不能大于入口卷厚度【"+v_rec_tpm.getMtr_thk().doubleValue()+"】";
				throw new Exception(v_ret);
			}*/
			//调用物流模块（仓库管理）接口，验证产生的吊销卷号 在库存信息中不存在
			YdmProductDetail ypd=new YdmProductDetail();
			ypd.setCoilno(cur_01.getCoil_no());
			List<YdmProductDetail> lypd=this.getMapper(YdmProductDetailMapper.class).find(ypd, 0, 0);
			if(lypd!=null&&lypd.size()>0){
				throw new Exception("钢卷号唯一，不能重复");
			}

			//---------------2018-03-15----------------------
			if(k<=n){
				MesTpmD mcd=new MesTpmD();
				mcd.setCoil_no(cur_01.getCoil_no());
				//如果【(出口卷实绩厚度 == 计划厚度) AND (出口卷实绩宽度 - 计划宽度) <= dUpper AND (出口卷实绩宽度 - 计划宽度) >= dLower】
				//2018-08-22 如果【(出口卷实绩厚度 >0) AND (出口卷实绩宽度 - 计划宽度) <= dUpper AND (出口卷实绩宽度 - 计划宽度) >= dLower】
				//if(mcsdc.getAct_thk()!=null && mcsdc.getAct_thk()>0
				//		&&(mcsdc.getAct_wdt().doubleValue()-lpmd.get(k).getWidth().doubleValue()<=dUpper)
				//		&&(mcsdc.getAct_wdt().doubleValue()-lpmd.get(k).getWidth().doubleValue()>=dLower)){
				//则SET 实绩.COIL_NO_VT = 计划.OBJECT_NO_VT, 实绩.PROD_ORDER_NO = 计划.PROD_ORDER_NO, 实绩.ORDER_NO = 计划.ORDER_NO；
					mcd.setCoil_no_vt(lpmd.get(k).getObject_no_vt());
					mcd.setOrder_no(lpmd.get(k).getOrder_no());
					mcd.setProd_order_no(lpmd.get(k).getProd_order_no());
					this.getMapper(MesTpmDMapper.class).update(mcd);
//				}else{
					//否则SET 实绩.COIL_NO_VT = NULL, 实绩.PROD_ORDER_NO = NULL, 实绩.ORDER_NO = NULL
//					this.getMapper(MesTpmDMapper.class).doUpdateNulls(mcd);
//				}
			}
			k++;			
		}
  		
		MesTpmM mmm=new MesTpmM();
		mmm.setSchedule_no(v_rec_tpm.getSchedule_no());
		mmm.setMaterial_no(v_rec_tpm.getMaterial_no());
  		mmm.setWrk_grp(work_grp);
  		mmm.setWrk_ord(work_ord);
  		mmm.setWrk_date(work_date);
  		this.getMapper(MesTpmMMapper.class).update(mmm);
  				
		//更新子表班组
  		MesTpmD mdd=new MesTpmD();
  		mdd.setSchedule_no(v_rec_tpm.getSchedule_no());
  		mdd.setMaterial_no(v_rec_tpm.getMaterial_no());
		List<MesTpmD> lmddq=this.getMapper(MesTpmDMapper.class).findWithCondition(mdd, "", " coil_no ", 0, 0);
		for(MesTpmD mc : lmddq){
			MesTpmD mcsd=new MesTpmD();
  			mcsd.setCoil_no(mc.getCoil_no());
  			mcsd.setWrk_grp(work_grp);
  			mcsd.setWrk_ord(work_ord);
  			mcsd.setWrk_date(work_date);
  			this.getMapper(MesTpmDMapper.class).update(mcsd);
  			
  			if (StringUtils.isNotEmpty(sum.getMemo6()) && "1".equals(sum.getMemo6())) {
  				MesOprInfo moi = new MesOprInfo();
  				moi.setOpr_id(mc.getCoil_no()+opr_time);
  				moi.setCoil_no(mc.getCoil_no());
  				moi.setMat_coil_no(v_rec_tpm.getMaterial_no());//投料卷号
  				moi.setOpr_desc("平整交工重量差异相差"+wgt+"Kg,进行异重交工");
  				moi.setOpr_type("异重交工");
  				moi.setMemo(sum.getMemo5());//异重交工的原因
  				moi.setCreate_man(username);
  				moi.setCreate_time(now);
  				this.getMapper(MesOprInfoMapper.class).insert(moi);
  			}
  			if (StringUtils.isNotEmpty(sum.getMemo6()) && "2".equals(sum.getMemo6())) {
  				MesOprInfo moi = new MesOprInfo();
  				moi.setOpr_id(mc.getCoil_no()+opr_time);
  				moi.setCoil_no(mc.getCoil_no());
  				moi.setMat_coil_no(v_rec_tpm.getMaterial_no());//投料卷号
  				moi.setOpr_desc("平整交工重量差异相差"+wgt+"Kg,进行强制交工");
  				moi.setOpr_type("强制交工");
  				moi.setMemo(sum.getMemo5());//强制交工的原因
  				moi.setCreate_man(username);
  				moi.setCreate_time(now);
  				this.getMapper(MesOprInfoMapper.class).insert(moi);
  			}
		}
  		 		
	    //   --(2.7)、如果产生了部分原卷吊销，则调用物流模块接口，将吊销原卷（新卷号）入库（接口由物流模块提供）                                                                              
	    if("1".equals(v_rec_tpm.getPartial_rejected()) && v_rec_tpm.getRejected_coil_no()!=null){
	    	YdmProductDetail ypd=new YdmProductDetail();
			ypd.setCoilno(v_rec_tpm.getRejected_coil_no());
			ypd.setTheoryweight(v_rec_tpm.getRejected_coil_thr_wgt());
			ypd.setFactweight(v_rec_tpm.getRejected_coil_act_wgt());
			ypd.setLength(v_rec_tpm.getRejected_coil_len());
			ypd.setDiameter_inn(v_rec_tpm.getMtr_inn_dia());
			ypd.setDiameter_out(v_rec_tpm.getMtr_out_dia());
            //2018-09-26 机台代码，机台名称
			ypd.setMachine_code(v_rec_tpm.getMachine_code());
			List<ComBaseMachine> listcom=this.getMapper(ComBaseMachineMapper.class).findWithCondition(null, "machine_code='"+v_rec_tpm.getMachine_code()+"'", null, 0, 0);
			if(listcom!=null && listcom.size()>0){
				ypd.setMachine_name(listcom.get(0).getMachine_name());
			}
			ResultModel rmValid = this.getBean(LmsApiServiceImpl.class).doInsertRevoke(psp.getMaterial_no(),ypd);
			if(!"200".equals(rmValid.getState())){
				throw new Exception(rmValid.getMsgInfo());
			}
	    }
	    	    
	    try{	    	
	  		/*2019-02-21
	  		检验批分批规则：
	  			同炉次号向下相同牌号、相同尺寸（厚度、宽度）的物料集合生成一个检验批号
	  			检验批号编码规则：炉次号+两位流水号，示例：2619000401） 
	  		 */
		    Map<String, List<MesTpmD>> mc_list =new HashMap<String, List<MesTpmD>>();
	  		if(v_rec_tpm.getSchedule_no()!=null && !"".equals(v_rec_tpm.getSchedule_no())){
	  			List<MesTpmD> mcdlist=new ArrayList<MesTpmD>();
  				List<MesTpmD> lll = this.getMapper(MesTpmDMapper.class).findWithCondition(null, "schedule_no='"+v_rec_tpm.getSchedule_no()+"' and material_no='"+v_rec_tpm.getMaterial_no()+"'and coil_no not like '%B'", null, 0, 0);
  				for(MesTpmD mccc:lll){
  					mcdlist.add(mccc);	
  				}
  				List<MesTpmM> v_rec_baf_mList = this.getMapper(MesTpmMMapper.class).findWithCondition(null,"schedule_no='"+v_rec_tpm.getSchedule_no()+"'", null, 0, 0);
	  			if(v_rec_baf_mList!=null && v_rec_baf_mList.size()>0 && mcdlist.size()>0){
  					try{
  						mc_list = groupBillingDataByExcpBatchCode(mcdlist,v_rec_tpm.getSchedule_no());
  					}catch(Exception e){
  						
  					}
	  			}
	  		}
	  		if(mc_list!=null && mc_list.size()>0){
				for(Map.Entry<String, List<MesTpmD>> grouplist :mc_list.entrySet()){
					List<MesTpmD> listCes = grouplist.getValue();
					for(MesTpmD mcam:listCes){
						MesTpmD mCrossleo = new MesTpmD();
						mCrossleo.setCoil_no(mcam.getCoil_no());
						mCrossleo.setInspection_lot(mcam.getInspection_lot());
						this.getMapper(MesTpmDMapper.class).update(mCrossleo);
					}
				}
			}	    	
	    }catch(Exception e){
	    	
	    }
	    	    
	    //循环平整出口卷实绩（MES_CR_SLITTING_D，此时，出口卷已完成匹配虚拟出口卷号，需要重新获取出口卷实绩集合
	    MesTpmD mc=new MesTpmD();
	    mc.setSchedule_no(v_rec_tpm.getSchedule_no());
	    mc.setMaterial_no(v_rec_tpm.getMaterial_no());
	  	List<MesTpmD> lmcsq=this.getMapper(MesTpmDMapper.class).find(mc, 0, 0);
	  	for(MesTpmD mcsq:lmcsq){  			
  			//  2018-6-21 将下面注解的东西修改成上面的
  			if (mcsq.getCoil_no() !=null && "B".equals(mcsq.getCoil_no().substring(mcsq.getCoil_no().length()-1))) {
  				if (mcsq.getCoil_act_wgt()==null || mcsq.getCoil_act_wgt().intValue()<=0) {
  					continue;
  				}
  			}
  			if(mcsq.getCoil_act_wgt()==null || mcsq.getCoil_act_wgt().intValue()<=0){
  				throw new Exception("出口卷["+mcsq.getCoil_no()+"]实重异常！");
  			}
  			CommonPage<MesTpmD> cp=new CommonPage<MesTpmD>();
  			MesTpmD mcsd=new MesTpmD();
  			mcsd.setCoil_no(mcsq.getCoil_no());
  			mcsd.setCoil_no_vt(mcsq.getCoil_no_vt());
  			cp.setObject(mcsq);
  			//调用物流模块（仓库管理）接口，逐一将平整出口卷实绩各出口卷，插入库存记录（待入库状态）；	
  			try{
  				//下道工序不为空，入库仓库为中间品库，为空（最后一道工序了），就如成品库         ？？？？
  				//code 当前工序代码 1 平整/2 开平/3 罩退/4 平整
  				String nextProcessCode = this.getBean(MesApiDesignInfoImpl.class).getNextProcessCode("4", psp.getObject_no_vt());
  				nextP = nextProcessCode;
  				if(nextProcessCode==null || "".equals(nextProcessCode)){
  					cp.setMemo1("500203");//成品库
  				    //生产订单统计 统计量并修改生产订单状态
  				    try{
//  				    	this.getBean(PlnProdorderStatisticServiceImpl.class).prod_Stats(mcsq.getCoil_no(),1,true);
  				    }catch(Exception e){
  				    	System.out.println("生产订单统计 统计量并修改生产订单状态出错");
  				    	e.printStackTrace();
  				    }
  				}else{
  					cp.setMemo1("500202");//在制品库
  				}
  			}catch(Exception ex){
	  			throw new Exception("获取下道工序异常");
  			}
	  			
  			try{			
  				//2019-02-21修改
  				PlnMaterielDetail pmd_21=new PlnMaterielDetail();
  				pmd_21.setObject_no_vt(psp.getObject_no_vt());
  				List<PlnMaterielDetail> list_pmd = this.getMapper(PlnMaterielDetailMapper.class).find(pmd_21, 0, 0);
  				boolean flag_Ct = false;
  				if(list_pmd!=null && list_pmd.size()>0){
  					flag_Ct=this.getBean(MesApiDesignInfoImpl.class).getContractType(list_pmd.get(0).getProd_order_no());
  				}
  				if(flag_Ct && !"B".equals(mcsq.getCoil_no().substring(mcsq.getCoil_no().length()-1))){
  					cp.setMemo3("507101");//物料属性，优特钢带
  				}
  				ResultModel rm = this.getBean(YdmProductDetailServiceImpl.class).interfaceInsertCoil(cp);
  				if ("200".equals(rm.getState())) {
  					//成功
  					
  					// 写入库存表后去更新生产订单状态：20230909刘侣；
  					YdmProductDetail ypdQ = this.getMapper(YdmProductDetailMapper.class).doFind(mcsq.getCoil_no(), null);
  					if (ypdQ != null && "500203".equals(ypdQ.getStorageattr())) {
  						this.getBean(PlnProdorderStatisticServiceImpl.class).prod_Stats(ypdQ.getCoilno(),1,true);
  					}
  					
  				// 检验委托：如果是最后一道工序才需要送样，去做检验委托：
  					// 待判信息发送：如果是最后一道工序（进成品库），那么就给isfinal ： 1， 否则就是：0；
  					if (ypdQ != null && "500203".equals(ypdQ.getStorageattr())) {
  						
  						// 发送检验委托信息：20230909刘侣：最后一道工序才送样
  						if (mcsq.getCoil_no() != null && ("B".equals(mcsq.getCoil_no().substring(mcsq.getCoil_no().length()-1))
  								 || "H".equals(mcsq.getCoil_no().substring(mcsq.getCoil_no().length()-1)))) {
  							
  							this.getBean(SlmFundFirstDetailServiceImpl.class).sendToPD(mcsq.getCoil_no(), true, "1");
  						} else {
  							this.getBean(SlmFundFirstDetailServiceImpl.class).sendToPD(mcsq.getCoil_no(), false, "1");
  						}
  						
  						// 只有以6开头的订单才去发送检验委托：
  						if (ypdQ.getOrderno() != null ) {
  							ResultModel rmwt = this.getBean(SlmFundFirstDetailServiceImpl.class).sendToJYWT(mcsq.getCoil_no(), true);
  	  						if ("500".equals(rmwt.getState())) {
  	  							throw new Exception(rmwt.getMsgInfo());
  	  						}
  						}
  						
  						// end
  					} else {
  						// 非最后一道：
  						if (mcsq.getCoil_no() != null && ("B".equals(mcsq.getCoil_no().substring(mcsq.getCoil_no().length()-1))
  								 || "H".equals(mcsq.getCoil_no().substring(mcsq.getCoil_no().length()-1)))) {
  							
  							this.getBean(SlmFundFirstDetailServiceImpl.class).sendToPD(mcsq.getCoil_no(), true, "0");
  						} else {
  							this.getBean(SlmFundFirstDetailServiceImpl.class).sendToPD(mcsq.getCoil_no(), false, "0");
  						}
  					}
  					// end
  					// end
  					
  				}else {
  					//失败
  					throw new Exception("入库出错"+rm.getMsgInfo());//失败原因，信息或提示
  				}
  			}catch(Exception ex){
  				ex.printStackTrace();
  				throw new Exception("物流入库接口出错"+ ex.getMessage());
  			}
	  			
			// 2019-09-23 panbin 增加校验质量判定结果,空则不允许交工 
			ResultModel tmp_rst = new ResultModel();
			// 工序点信息
			List<ComBaseInfo> infoi = this.getMapper(ComBaseInfoMapper.class).findWithCondition(null,
					"sort_code = '2002' AND validflag = '1'", null, 0, 0);
			ProcessPoint processpoint = new ProcessPoint(infoi);
			try {
				tmp_rst = this.getBean(MesApiServiceImpl.class).hasJudegeResult(mcsq.getCoil_no(),mcsq.getProd_order_no(),processpoint.smooth_code);
			} catch(Exception ex) {
				// 暂时先注释：2019101 刘侣
//				throw new Exception("获取质量判定信息接口报错!"+ ex.getMessage());
			}
			if(!"200".equals(tmp_rst.getState())){
				// 暂时先注释：2019101 刘侣
//				throw new Exception(tmp_rst.getData().toString());
			}
				
  			try{
				ResultModel rmxx = this.getBean(QmsApiServiceImpl.class).doQueryJudegeResult(mcsq.getCoil_no());
				if(rmxx!=null && rmxx.getData()!=null && (rmxx.getData() instanceof JudgeResult)){
					JudgeResult jr=(JudgeResult)rmxx.getData();
					YdmProductDetail ypd=new YdmProductDetail();
					ypd.setCoilno(mcsq.getCoil_no());
					boolean falgggg=false;
					if(jr.getMarginal_result()!=null){
						ypd.setMarginal_result(jr.getMarginal_result());
						falgggg=true;
					}
					if(jr.getMarginal_result_id()!=null){
						ypd.setMarginal_result_id(jr.getMarginal_result_id());
						falgggg=true;
					}
					if(jr.getMeasure_result()!=null){
						ypd.setMeasure_result(jr.getMeasure_result());
						falgggg=true;
					}
					if(jr.getMeasure_result_id()!=null){
						ypd.setMeasure_result_id(jr.getMeasure_result_id());
						falgggg=true;
					}
					if(jr.getSfd_is_lock()!=null){
						ypd.setSfd_is_lock(jr.getSfd_is_lock());
						falgggg=true;
					}
					if(jr.getSfe_is_lock()!=null){
						ypd.setSfe_is_lock(jr.getSfe_is_lock());
						falgggg=true;
					}
					if(jr.getSfu_is_lock()!=null){
						ypd.setSfu_is_lock(jr.getSfu_is_lock());
						falgggg=true;
					}
					if(jr.getSic_is_lock()!=null){
						ypd.setSic_is_lock(jr.getSic_is_lock());
						falgggg=true;
					}
					if(jr.getSizeResult()!=null){
						ypd.setSizeresult(jr.getSizeResult());
						falgggg=true;
					}
					if(jr.getUd_surface_result()!=null){
						ypd.setUd_surface_result(jr.getUd_surface_result());
						falgggg=true;
					}
					if(jr.getUd_surface_result_id()!=null){
						ypd.setUd_surface_result_id(jr.getUd_surface_result_id());
						falgggg=true;
					}
					if(jr.getUp_surface_result()!=null){
						ypd.setUp_surface_result(jr.getUp_surface_result());
						falgggg=true;
					}
					if(jr.getUp_surface_result_id()!=null){
						ypd.setUp_surface_result_id(jr.getUp_surface_result_id());
						falgggg=true;
					}
					if(jr.getUp_surface_flaw() != null) {
						ypd.setUp_surface_flaw(jr.getUp_surface_flaw());
						falgggg= true;
					}
					if(jr.getUd_surface_flaw() != null) {
						ypd.setUd_surface_flaw(jr.getUd_surface_flaw());
						falgggg= true;
					}
					if(jr.getMarginal_flaw()!= null) {
						ypd.setMarginal_flaw(jr.getMarginal_flaw());
						falgggg= true;
					}
					if(falgggg){
//						this.getMapper(YdmProductDetailMapper.class).update(ypd);
					}
				}
			}catch(Exception e){
				System.out.println("调用质量接口报错");
				e.printStackTrace();
			}
	  			
  			try{
	  			//循环平整出口卷实绩（MES_CR_SLITTING_D，此时，出口卷已完成匹配虚拟出口卷号，需要重新获取出口卷实绩集合
	  			//如果此出口卷的虚拟出口卷号不为空（COIL_NO_VT，即满足切割计划）
	  			if(mcsq.getCoil_no_vt()!=null&&!"".equals(mcsq.getCoil_no_vt())){
	  				//  --(2.10)、调用生产管理接口，执行作业计划、原料卷、出口钢卷相关进程状态处理逻辑（接口由生产管理模块提供）；
	  			    // 处理出口卷
	  				List<PlnMaterielDetail> lpmdc=this.getMapper(PlnMaterielDetailMapper.class).findWithCondition(null, "mat_object_no_vt = '"+v_rec_tpm.getMaterial_no_vt()+"' and nvl(invalid_flg,0) = '0'", null, 0, 1);
	  				if (Utils.isEmpty(lpmdc)) {
	  					throw new Exception("未找到虚拟出口卷信息!");
	  				}
	  				PlnMaterielDetail pmdq=new PlnMaterielDetail();
	  				pmdq.setObject_no(v_rec_tpm.getMaterial_no());
	  				pmdq.setObject_no_vt(mcsq.getCoil_no_vt());
	  				pmdq.setMaterial_no(v_rec_tpm.getMaterial_no());//投料卷号 material_no   由页面交工按钮传入
	  				pmdq.setSub_object_no(mcsq.getCoil_no()); // 出口卷号
	  				// 传入操作时间 2018-06-19
	  				pmdq.setCreate_time(now);
	  				this.getBean(MesApiSkinrollingPlanImpl.class).SkinrollingFinsh_Relation(pmdq);	  				
	  			}else if (mcsq.getCoil_no() != null && ("B".equals(mcsq.getCoil_no().substring(mcsq.getCoil_no().length()-1))
	  					 || "H".equals(mcsq.getCoil_no().substring(mcsq.getCoil_no().length()-1))
	  					)){
	  				//则调用生产管理的【平整完成——实物 生成接口】 2018-06-22
	  				PrcMaterielRelation pmr=new PrcMaterielRelation();
	  				pmr.setObject_no(psp.getMaterial_no());//投料卷号 material_no   由页面交工按钮传入
	  				pmr.setSub_object_no(mcsq.getCoil_no());//MES_CR_SLITTING_D表的出口卷号
	  				pmr.setRelation_seq(3);
	  				this.getBean(MesApiSkinrollingPlanImpl.class).SkinrollingFinsh_PrcMatRelAdd(pmr);//有insert插入prc_materiel_relation的操作
	  			}else{//如果此出口卷的虚拟出口卷号为空（COIL_NO_VT，即为非计划）
	  				//则调用生产管理的【平整完成——实物 生成接口】
	  				//第二卷
					PlnMaterielDetail pmdq2=new PlnMaterielDetail();
					pmdq2.setObject_no(v_rec_tpm.getMaterial_no());
					pmdq2.setMaterial_no(v_rec_tpm.getMaterial_no());//投料卷号 material_no   由页面交工按钮传入
					pmdq2.setSub_object_no(mcsq.getCoil_no());//MES_CR_SLITTING_D表的出口卷号
					// 传入操作时间 2018-06-22
					pmdq2.setCreate_time(now);
					this.getBean(MesApiSkinrollingPlanImpl.class).SkinrollingFinsh_No_Plan(pmdq2);//有insert插入PLN_MATERIEL_DETAIL的操作	  				
	  			}
  			}catch(Exception ex){
  				throw new Exception("计划接口出错"+ ex.getMessage());
  			}
	  			
	  			//===============2019-03-12========质量检验委托开始=============================
  		    if(v_rec_tpm.getSchedule_no()!=null && !"".equals(v_rec_tpm.getSchedule_no())){//作业计划号不为空
  		    	try{
  		    		QcmJhySampleFromPlan ajsfp=new QcmJhySampleFromPlan();
					List<PlnMaterielDetail> lpmdq22 = this.getMapper(PlnMaterielDetailMapper.class).findWithCondition(null,
							"object_no_vt = '" + v_rec_tpm.getMaterial_no_vt() + "' and nvl(invalid_flg,0) = '0'", null, 0, 1);
					String prod_order_no=lpmdq22.get(0).getProd_order_no();
					List<PlnProdorder> lpp = this.getMapper(PlnProdorderMapper.class).findWithCondition(null, "prod_order_no='"+prod_order_no+"'", null, 0, 0);
					if(lpp!=null && lpp.size()>0){
						
						int judge_Contain_Qcm = this.getBean(MesApiDesignInfoImpl.class).Judge_Contain_Qcm(v_rec_tpm.getMaterial_no_vt(), "C");
						// 获取工艺路径包含成分或者材质类
						if(judge_Contain_Qcm!=-1){
							ajsfp.setPline_seq((long)judge_Contain_Qcm);
  					  	ajsfp.setInspection_lot(mcsq.getInspection_lot());//检验号
	  					  	ajsfp.setBatch_no(v_rec_tpm.getSchedule_no());//轧批号    炉次号
							//ajsfp.setContract_line_no(lpp.get(0).getContract_line_no());//合同行信息
							List<PlnProcessPlan> list_plnP = this.getMapper(PlnProcessPlanMapper.class).findWithCondition(null, "produce_no='"+lpp.get(0).getProduce_no()+"' and cut_order_no = 1", "", 0, 0);
							if(list_plnP!=null && list_plnP.size()>0){
								ajsfp.setContract_line_no(list_plnP.get(0).getPlan_no());//合同行信息  销售的订单的加工计划号
							}
							ajsfp.setDesign_key(lpp.get(0).getDesign_key());//design_key的集合
							ajsfp.setJudge("0");//用于判断是改判还是原判 0：原判；1：改判  no
							ajsfp.setMaterial_no(mcsq.getCoil_no());//取样材料号   
							ajsfp.setMsc_pline(lpp.get(0).getMsc_pline());//全程产线号  制成号
							ajsfp.setOrder_no(lpp.get(0).getOrder_no());//销售订单号(合同号+订单行号，示例:YT-66G66001)
							ajsfp.setBoard_no(v_rec_tpm.getMaterial_no());
							
							ComBaseMachine cbm = this.getMapper(ComBaseMachineMapper.class).findById(v_rec_tpm.getMachine_code());
							ComBasePline cbp = this.getMapper(ComBasePlineMapper.class).findById(cbm.getPline_code());
							ajsfp.setPline_code(cbm.getPline_code());//产线代码
							ajsfp.setPline_name(cbp.getPline_name());// 产线名称
							//后期需要修改
							ajsfp.setProcess_code("C");//工序代码    com_base_process表
							ajsfp.setPsc(lpp.get(0).getPsc());//物料编码，
							List<QcmJhySampleFromPlan> lqsfp=new ArrayList<>();
							lqsfp.add(ajsfp);
							CommonPage<QcmJhySampleFromPlan>  cpqjsfp=new CommonPage<QcmJhySampleFromPlan>();
							cpqjsfp.setObjectList(lqsfp);
							ResultModel reModel = this.getBean(QcmJhySampleConsignDItemServiceImpl.class).AutoGenerationSampleInfo(cpqjsfp);
							if(reModel!=null){
								System.out.println(reModel.getState());
								System.out.println(reModel.getMsgInfo());
							}
  						}
  					}
  				}catch(Exception e){
  					e.printStackTrace();
  				}
  		    }
	  			//==========================质量检验委托结束==================================	  			
		}
		
		// 处理母卷
		List<PlnMaterielDetail> lpmdq = this.getMapper(PlnMaterielDetailMapper.class).findWithCondition(null,
				"object_no_vt = '" + v_rec_tpm.getMaterial_no_vt() + "' and nvl(invalid_flg,0) = '0'", null, 0, 1);
		try{
			this.getBean(MesApiSkinrollingPlanImpl.class).SkinrollingFinsh_Sum(lpmdq.get(0));
		}catch(Exception ex){
			throw new Exception("计划接口出错"+ ex.getMessage());
		}
		
	    //  --(2.11)、修改平整作业主实绩交工状态
	    MesTpmM mes=new MesTpmM();
	    mes.setHand_over_status("1");
	    mes.setHand_over_time(now);
	    mes.setHand_over_opr(username);
	    mes.setUpdate_opr(username);
	    mes.setUpdate_time(now);
	    mes.setMachine_code(sum.getMemo1());
	    mes.setSchedule_no(psp.getSr_plan_no());
	    mes.setMaterial_no_vt(psp.getObject_no_vt());
	    mes.setMaterial_no(psp.getMaterial_no());
	    this.getMapper(MesTpmMMapper.class).doUpdate2(mes);
	    //日志
	    MesOprLog mol = new MesOprLog("车间MES", "平整机作业管理", "交工", username, opr_time, mes.getMaterial_no(), null, null, null, "下道工序为：" + nextP);
	    this.getMapper(MesOprLogMapper.class).insert(mol);
	    //(3)、提交事务
		r.setState("200");		
		r.setMsgInfo("交工成功!");
		return r;
	}
	
	
	/***
	 * 动作处理--取消交工按钮   
	 * object中：
	 * sr_plan_no 作业计划号
	 * object_no_vt 虚拟卷号
	 * material_no 原料卷号
	 * memo1:mch_code机台代码
	 * memo2:登录用户名
	 * @throws Exception 
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel signOutOff(CommonPage<PlnSkinrollingPlan> sum) throws Exception {
		ResultModel r=new ResultModel();
		Date now = new Date();
		String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(now); //操作时间
		String username = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		
		PlnSkinrollingPlan psp = sum.getObject();
		Integer v_cnt;
		//  --(1)、验证前端传入参数的基本有效性
		if(sum.getMemo1()==null || sum.getMemo1().length()<=0){
			r.setMsgInfo("参数错误：机台代码不能为空！");
			r.setState("500");
			return r;
		}
		if("".equals(psp.getSr_plan_no()) || "".equals(psp.getSr_plan_no())){
			r.setState("500");
			r.setMsgInfo("参数错误：作业计划号为空");
			return r;
		}
		// --(1)、验证平整作业计划主记录存在
		PlnSkinrollingPlan pcp=new PlnSkinrollingPlan();
		pcp.setMachine_code(sum.getMemo1());
		pcp.setSr_plan_no(psp.getSr_plan_no());
		int count = this.getMapper(PlnSkinrollingPlanMapper.class).count(pcp);
		if (count<=0) {
			throw new Exception("机台代码："+sum.getMemo1()+"\n作业计划号："+psp.getSr_plan_no()+"\n作业计划主记录不存在！");
		}
		//    --(2.2)、验证平整作业计划明细记录存在
		PlnSkinrollingPlanDetail pcpd=new PlnSkinrollingPlanDetail();
		pcpd.setMachine_code(sum.getMemo1());
		pcpd.setSr_plan_no(psp.getSr_plan_no());
		pcpd.setObject_no_vt(psp.getObject_no_vt());
		pcpd.setObject_no(psp.getMaterial_no());
		int count2 = this.getMapper(PlnSkinrollingPlanDetailMapper.class).count(pcpd);
		if (count2<=0) {
			throw new Exception("机台代码："+sum.getMemo1()+"\n作业计划号："+psp.getSr_plan_no()+"\n虚拟卷号："+psp.getObject_no_vt()+""
					+ "\n原料卷号："+psp.getMaterial_no()+"\n作业计划明细记录不存在！");
		}
		v_cnt=this.getMapper(PlnMaterielDetailMapper.class).countWithCondition(null, "object_no_vt='"+psp.getObject_no_vt()+"'");
		if (v_cnt<=0) {
			throw new Exception("虚拟卷号："+psp.getObject_no_vt()+"原料卷虚拟物料信息不存在！");
		}
		//???
		v_cnt=this.getMapper(PlnMaterielDetailMapper.class).countWithCondition(null, "mat_object_no_vt='"+psp.getObject_no_vt()+"'");
		if (v_cnt<=0) {
			throw new Exception("虚拟卷号："+psp.getObject_no_vt()+"出口卷虚拟物料信息不存在！");
		}
		//  --(3)、验证原料卷对应的平整主实绩存在，且为“未交工”状态
		MesTpmM mCross = new MesTpmM();
		mCross.setMachine_code(sum.getMemo1());
		mCross.setSchedule_no(psp.getSr_plan_no());
		mCross.setMaterial_no_vt(psp.getObject_no_vt());
		mCross.setMaterial_no(psp.getMaterial_no());
		v_cnt = this.getBean(MesTpmMMapper.class).count(mCross);
		if (v_cnt<=0) {
			r.setState("500");
			r.setMsgInfo("原料卷号：" +psp.getMaterial_no()+ "，当前不存在平整作业实绩！请确认是否已操作上料！");
			return r;
		}
	    List<MesTpmM> lmcam = this.getMapper(MesTpmMMapper.class).find(mCross, 0, 0);
	    MesTpmM v_rec_tpm =lmcam.get(0);
	    if(v_rec_tpm.getHand_over_status()!=null && !v_rec_tpm.getHand_over_status().equals("1")){
	    	r.setState("500");
	    	r.setMsgInfo("原料卷号："+psp.getMaterial_no()+"还未生产交工！");
			return r;
	    }
	    MesTpmD v_rec_tpd=new MesTpmD();
	    v_rec_tpd.setSchedule_no(v_rec_tpm.getSchedule_no());
	    v_rec_tpd.setMaterial_no(v_rec_tpm.getMaterial_no());
	    List<MesTpmD> list_tpd = this.getMapper(MesTpmDMapper.class).find(v_rec_tpd, 0, 0);
	    if(list_tpd==null||list_tpd.size()==0){
			r.setState("500");
			r.setMsgInfo("作业计划原料卷不存在出口卷实绩!");
			return r;
		}
    	for(MesTpmD mcsq:list_tpd){
    		try{
	    		// 如果出口卷是边丝或者虚拟物料号为空,则按非计划执行
				if (Utils.isNotEmpty(mcsq.getCoil_no())  && ("B".equals(mcsq.getCoil_no().substring(mcsq.getCoil_no().length()-1))
						|| "H".equals(mcsq.getCoil_no().substring(mcsq.getCoil_no().length()-1))
	  					)){
					if (Utils.isNotEmpty(mcsq.getCoil_act_wgt()) && mcsq.getCoil_act_wgt().intValue()>0) {
						//则调用生产管理的【平整完成——实物 生成接口】 2018-06-22
						PrcMaterielRelation pmr=new PrcMaterielRelation();
						pmr.setObject_no(psp.getMaterial_no());//投料卷号 material_no   由页面交工按钮传入
						pmr.setSub_object_no(mcsq.getCoil_no());//MES_CR_SLITTING_D表的出口卷号
						this.getBean(MesApiSkinrollingPlanImpl.class).SkinrollingFinsh_PrcMatRelRemove(pmr);
					}
					//或者虚拟物料号为空,则按非计划执行
				}else if (Utils.isEmpty(mcsq.getCoil_no_vt())) {
					//第二卷
					PrcMaterielRelation pmr2=new PrcMaterielRelation();
					pmr2.setObject_no(v_rec_tpm.getMaterial_no());//投料卷号 material_no   由页面交工按钮传入
					pmr2.setSub_object_no(mcsq.getCoil_no());//MES_CR_SLITTING_D表的出口卷号
					// 由于在交工的时候,生成对应的虚拟出口卷信息取消的时候将其直接删除 2018-09-10
					PlnMaterielDetail pmddetele2 = new PlnMaterielDetail();
					pmddetele2.setObject_no(mcsq.getCoil_no());
					pmddetele2.setOrd_flg("2");
					this.getMapper(PlnMaterielDetailMapper.class).doDeleteByOrdflg(pmddetele2);
					this.getBean(MesApiSkinrollingPlanImpl.class).SkinrollingFinsh_PrcMatRelRemove(pmr2);
					
				}else {
				//  --(2.10)、调用生产管理接口，执行作业计划、原料卷、出口钢卷相关进程状态处理逻辑（接口由生产管理模块提供）；
					PlnMaterielDetail pmdq=new PlnMaterielDetail();
					pmdq.setObject_no(mcsq.getCoil_no());
					pmdq.setObject_no_vt(mcsq.getCoil_no_vt());
					this.getBean(MesApiSkinrollingPlanImpl.class).SkinrollingFinsh_RelationCancel(pmdq);
				}
    		}catch(Exception ex){
    			throw new Exception("计划接口出错"+ ex.getMessage());
    		}
			// --------------------------------2018-06-22--------------------------------
						
			//清空所有出口卷实绩的虚拟出口卷号信息
			MesTpmD mcsd=new MesTpmD();
			mcsd.setUpdate_opr(username);
			mcsd.setUpdate_time(now);
			mcsd.setCoil_no(mcsq.getCoil_no());
			this.getMapper(MesTpmDMapper.class).doUpdate111(mcsd);		
			
			//===============2019-03-12========质量检验委托开始=============================
  		    if(v_rec_tpm.getSchedule_no()!=null && !"".equals(v_rec_tpm.getSchedule_no())){//作业计划号不为空
  		    	if (mcsq.getCoil_no() !=null && "B".equals(mcsq.getCoil_no().substring(mcsq.getCoil_no().length()-1))) {
	  				if (mcsq.getCoil_act_wgt()==null || mcsq.getCoil_act_wgt().intValue()<=0) {
	  					continue;
	  				}
	  			}
  		    	try{
  		    		QcmJhySampleFromPlan ajsfp=new QcmJhySampleFromPlan();
					List<PlnMaterielDetail> lpmdq22 = this.getMapper(PlnMaterielDetailMapper.class).findWithCondition(null,
							"object_no_vt = '" + v_rec_tpm.getMaterial_no_vt() + "' and nvl(invalid_flg,0) = '0'", null, 0, 1);
					String prod_order_no=lpmdq22.get(0).getProd_order_no();
					List<PlnProdorder> lpp = this.getMapper(PlnProdorderMapper.class).findWithCondition(null, "prod_order_no='"+prod_order_no+"'", null, 0, 0);
					if(lpp!=null && lpp.size()>0){
						
						int judge_Contain_Qcm = this.getBean(MesApiDesignInfoImpl.class).Judge_Contain_Qcm(v_rec_tpm.getMaterial_no_vt(), "C");
						// 获取工艺路径包含成分或者材质类
						if(judge_Contain_Qcm!=-1){
							ajsfp.setPline_seq((long)judge_Contain_Qcm);
  					  		ajsfp.setInspection_lot(mcsq.getInspection_lot());//检验号
	  					  	ajsfp.setBatch_no(v_rec_tpm.getSchedule_no());//轧批号    炉次号
							//ajsfp.setContract_line_no(lpp.get(0).getContract_line_no());//合同行信息
	  					    List<PlnProcessPlan> list_plnP = this.getMapper(PlnProcessPlanMapper.class).findWithCondition(null, "produce_no='"+lpp.get(0).getProduce_no()+"' and cut_order_no = 1", "", 0, 0);
							if(list_plnP!=null && list_plnP.size()>0){
								ajsfp.setContract_line_no(list_plnP.get(0).getPlan_no());//合同行信息  销售的订单的加工计划号
							}
	  					  	ajsfp.setDesign_key(lpp.get(0).getDesign_key());//design_key的集合
							ajsfp.setJudge("0");//用于判断是改判还是原判 0：原判；1：改判  no
							ajsfp.setMaterial_no(mcsq.getCoil_no());//取样材料号   
							ajsfp.setMsc_pline(lpp.get(0).getMsc_pline());//全程产线号  制成号
							ajsfp.setOrder_no(lpp.get(0).getOrder_no());//销售订单号(合同号+订单行号，示例:YT-66G66001)
							
							ComBaseMachine cbm = this.getMapper(ComBaseMachineMapper.class).findById(v_rec_tpm.getMachine_code());
							ComBasePline cbp = this.getMapper(ComBasePlineMapper.class).findById(cbm.getPline_code());
							ajsfp.setPline_code(cbm.getPline_code());//产线代码
							ajsfp.setPline_name(cbp.getPline_name());// 产线名称
							//后期需要修改
							ajsfp.setProcess_code("C");//工序代码    com_base_process表
							ajsfp.setPsc(lpp.get(0).getPsc());//物料编码，
							//ajsfp.setPline_seq(3l);//产线顺序  计划上道工序?还是计划下道工序？  当前工序点代码 1 平整/2 开平/3 罩退/4 平整
							List<QcmJhySampleFromPlan> lqsfp=new ArrayList<>();
							lqsfp.add(ajsfp);
							CommonPage<QcmJhySampleFromPlan>  cpqjsfp=new CommonPage<QcmJhySampleFromPlan>();
							cpqjsfp.setObjectList(lqsfp);
							
							QcmJhySampleFromPlan qjsprem=new QcmJhySampleFromPlan();
							qjsprem.setDesign_key(lpp.get(0).getDesign_key());
							qjsprem.setInspection_lot(mcsq.getInspection_lot());
							CommonPage<QcmJhySampleFromPlan> sum22=new CommonPage<QcmJhySampleFromPlan>();
							sum22.setObject(qjsprem);
							this.getBean(QmsApiServiceImpl.class).removeInspection(sum22);						
  						}
  					}
  				}catch(Exception e){
  					e.printStackTrace();
  				}
  		    }
  			//==========================质量检验委托结束==================================
		    String nextProcessCode = this.getBean(MesApiDesignInfoImpl.class).getNextProcessCode("4", psp.getObject_no_vt());
				if(nextProcessCode==null || "".equals(nextProcessCode) 
						|| (mcsq.getCoil_no() !=null && "B".equals(mcsq.getCoil_no().substring(mcsq.getCoil_no().length()-1)))){
					//生产订单统计 统计量并修改生产订单状态
				    try{
				    	this.getBean(PlnProdorderStatisticServiceImpl.class).prod_Stats(mcsq.getCoil_no(),1,false);
				    }catch(Exception e){
				    	System.out.println("生产订单统计 统计量并修改生产订单状态出错");
				    	e.printStackTrace();
				    }				    
			}			
    	}
	    	
	    
	    //    --(2.6)、如果产生了部分原卷吊销，则调用物流模块接口，
	    //验证吊销原卷（新卷号）为待入库状态（可撤销或删除库存数据），否则，返回错误信息到前端，结束操作（接口由物流模块提供）；                                                                        
	    if("1".equals(v_rec_tpm.getPartial_rejected()) && v_rec_tpm.getRejected_coil_no()!=null){
	    	YdmProductDetail ypd=new YdmProductDetail();
			ypd.setCoilno(v_rec_tpm.getRejected_coil_no());
			ypd.setState("0");
			List<YdmProductDetail> lypd=this.getMapper(YdmProductDetailMapper.class).find(ypd, 0, 0);
			if(lypd==null||lypd.size()==0){
				throw new Exception("吊销卷["+v_rec_tpm.getRejected_coil_no()+"]不为待入库状态");
			}else{
				//开始事务
				//如果平整产生了吊销的原料卷，调用物流模块（仓库管理）接口，吊销卷撤销库存实绩
				ResultModel rmValid = this.getBean(LmsApiServiceImpl.class).doInsertRevokeCanl(v_rec_tpm.getRejected_coil_no());
				if(!"200".equals(rmValid.getState())){
					throw new Exception(rmValid.getMsgInfo());
				}
			}
	    }
	    
	    for(MesTpmD mcsd:list_tpd){
			// 排除实重<=0的边丝
			if (mcsd.getCoil_no() != null && "B".equals(mcsd.getCoil_no().substring(mcsd.getCoil_no().length()-1))){
				if (mcsd.getCoil_act_wgt()==null || mcsd.getCoil_act_wgt().intValue()<=0) {
					continue;
				}
			}
			//   --(2.7)、调用物流模块接口，验证出口钢卷（coil_no）为待入库状态（可撤销或删除库存数据），否则，返回错误信息到前端，结束操作（接口由物流模块提供）；
		    YdmProductDetail ypd=new YdmProductDetail();
			ypd.setCoilno(mcsd.getCoil_no());
			ypd.setState("-1");
			List<YdmProductDetail> lypd=this.getMapper(YdmProductDetailMapper.class).find(ypd, 0, 0);
			if(lypd==null||lypd.size()==0){
				throw new Exception("出口钢卷["+mcsd.getCoil_no()+"]不为待入库状态");
			}else{
				//开始事务
				//调用物流模块（仓库管理）接口，删除钢卷库存实绩；
				YdmProductDetail ypdu=new YdmProductDetail();
				ypdu.setCoilno(mcsd.getCoil_no());
				CommonPage<YdmProductDetail> cp1=new CommonPage<YdmProductDetail>();
				cp1.setObject(ypd);
				ResultModel rmValid = this.getBean(LmsApiServiceImpl.class).doDeleteFinishedRoll(cp1);
				if(!"200".equals(rmValid.getState())){
					throw new Exception(rmValid.getMsgInfo());
				}
			}
		}
	    // 释放虚拟母卷
	    PlnMaterielDetail pmdq=new PlnMaterielDetail();
		pmdq.setObject_no_vt(psp.getObject_no_vt());
		List<PlnMaterielDetail> lpmdq=this.getMapper(PlnMaterielDetailMapper.class).find(pmdq, 0, 1);
		try{
			this.getBean(MesApiSkinrollingPlanImpl.class).SkinrollingFinsh_SumCancel(lpmdq.get(0));
		}catch(Exception ex){
			//throw new Exception("计划接口出错"+ ex.getMessage());
		}
	    //  --(2.11)、修改平整作业主实绩交工状态
	    MesTpmM mes=new MesTpmM();
	    mes.setHand_over_status("0");
	    mes.setUpdate_opr(username);
	    mes.setUpdate_time(now);
	    mes.setMachine_code(sum.getMemo1());
	    mes.setSchedule_no(psp.getSr_plan_no());
	    mes.setMaterial_no_vt(psp.getObject_no_vt());
	    mes.setMaterial_no(psp.getMaterial_no());
	    this.getMapper(MesTpmMMapper.class).doUpdate3(mes);
	    //日志
	    MesOprLog mol = new MesOprLog("车间MES", "平整机作业管理", "取消交工", username, opr_time, mes.getMaterial_no(), null, null, null, null);
	    this.getMapper(MesOprLogMapper.class).insert(mol);
	    //业务处理在sql中
		r.setState("200");
		r.setMsgInfo("取消交工成功！");
		return r;
	}
	
	
	/***
	 * 动作处理--交工按钮   
	 * object中：
	 * sr_plan_no 作业计划号【平整计划号】
	 * object_no_vt 虚拟卷号
	 * material_no 原料卷号
	 * memo1:mch_code机台代码
	 * memo2:登录用户名
	 * @throws Exception 
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel signOffNew(CommonPage<PlnSkinrollingPlan> sum) throws Exception {
		ResultModel r=new ResultModel();
		Date now = new Date();
		String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(now); //操作时间
		String username = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		String work_ord = (String) this.getSession().getAttribute(HomeService.SESSION_WORK_ORD);
		String work_grp = (String) this.getSession().getAttribute(HomeService.SESSION_WORK_GRP);
		String work_date = (String) this.getSession().getAttribute(HomeService.SESSION_WORK_TIME);
		work_date = work_date.substring(0, 10);
		PlnSkinrollingPlan psp = sum.getObject();
		
		String nextP = "";
		
		Integer v_cnt;
		// (1)、验证前端传入参数的基本有效性
		if("".equals(psp.getSr_plan_no()) || "".equals(psp.getSr_plan_no())){
			r.setState("500");
			r.setMsgInfo("参数错误：作业计划号为空");
			return r;
		}
		// (1)、验证平整作业计划主记录存在
		PlnSkinrollingPlan pcp=new PlnSkinrollingPlan();
		pcp.setMachine_code(sum.getMemo1());
		pcp.setSr_plan_no(psp.getSr_plan_no());
		int count = this.getMapper(PlnSkinrollingPlanMapper.class).count(pcp);
		if (count<=0) {
			throw new Exception("机台代码："+sum.getMemo1()+"\n作业计划号："+psp.getSr_plan_no()+"\n作业计划主记录不存在！");
		}
		// (2.2)、验证平整作业计划明细记录存在
		PlnSkinrollingPlanDetail pcpd=new PlnSkinrollingPlanDetail();
		pcpd.setMachine_code(sum.getMemo1());
		pcpd.setSr_plan_no(psp.getSr_plan_no());
		pcpd.setObject_no_vt(psp.getObject_no_vt());
		pcpd.setObject_no(psp.getMaterial_no());
		int count2 = this.getMapper(PlnSkinrollingPlanDetailMapper.class).count(pcpd);
		if (count2<=0) {
			throw new Exception("机台代码："+sum.getMemo1()+"\n作业计划号："+psp.getSr_plan_no()+"\n虚拟卷号："+psp.getObject_no_vt()+""
				+ "\n原料卷号："+psp.getMaterial_no()+"\n作业计划明细记录不存在！");
		}
		v_cnt=this.getMapper(PlnMaterielDetailMapper.class).countWithCondition(null, "object_no_vt='"+psp.getObject_no_vt()+"'");
		if (v_cnt<=0) {
			throw new Exception("虚拟卷号："+psp.getObject_no_vt()+"原料卷虚拟物料信息不存在！");
		}
		//???
		v_cnt=this.getMapper(PlnMaterielDetailMapper.class).countWithCondition(null, "mat_object_no_vt='"+psp.getObject_no_vt()+"'");
		if (v_cnt<=0) {
			throw new Exception("虚拟卷号："+psp.getObject_no_vt()+"出口卷虚拟物料信息不存在！");
		}
		//  --(3)、验证原料卷对应的平整主实绩存在，且为“未交工”状态
		MesTpmM mCross = new MesTpmM();
		mCross.setMachine_code(sum.getMemo1());
		mCross.setSchedule_no(psp.getSr_plan_no());
		mCross.setMaterial_no_vt(psp.getObject_no_vt());
		mCross.setMaterial_no(psp.getMaterial_no());
		v_cnt = this.getBean(MesTpmMMapper.class).count(mCross);
		if (v_cnt<=0) {
			r.setState("500");
			r.setMsgInfo("原料卷号：" +psp.getMaterial_no()+ "，当前不存在平整作业实绩！请确认是否已操作上料！");
			return r;
		}
	    List<MesTpmM> lmcam = this.getMapper(MesTpmMMapper.class).find(mCross, 0, 0);
	    MesTpmM v_rec_tpm =lmcam.get(0);
	    if(v_rec_tpm.getHand_over_status()!=null && !v_rec_tpm.getHand_over_status().equals("0")){
	    	r.setState("500");
	    	r.setMsgInfo("原料卷号："+psp.getMaterial_no()+"当前已生产交工，不能重复操作！");
			return r;
	    }
	    // 6.、验证原料卷，当前已有出口卷实绩
		MesTpmD mcccd=new MesTpmD();
		mcccd.setSchedule_no(v_rec_tpm.getSchedule_no());
		mcccd.setMaterial_no(v_rec_tpm.getMaterial_no());
		List<MesTpmD> lmcsd =this.getMapper(MesTpmDMapper.class).findWithCondition(mcccd,"substr(coil_no,-1,1) not in ('B','H')", " coil_no ", 0, 0);
		if(lmcsd==null||lmcsd.size()==0){
			throw new Exception("作业计划原料卷不存在出口卷实绩!");
		}
	    
		Double mtrWgt = v_rec_tpm.getMtr_act_wgt();//投料重量
		Double sumWgt = this.getMapper(MesTpmMMapper.class).doQueryMesTpmDSumWgt(v_rec_tpm.getSchedule_no(),v_rec_tpm.getMaterial_no());
		Double wgt = Math.abs(mtrWgt-sumWgt);
		if (!"2".equals(sum.getMemo6())) {			
			if (wgt > 100) {
				r.setState("500");
				r.setMsgInfo("平整交工重量相差"+wgt+"Kg,超过100Kg,无法交工");
				return r;
			}			
			//20201125 交工重量差异超过0.3%且不超过200KG时,进行异重交工
			if (StringUtils.isEmpty(sum.getMemo6()) || !"1".equals(sum.getMemo6())) {
				Double a = Math.abs(sumWgt-mtrWgt) / mtrWgt;
				if (a > 0.003) {
					r.setState("500");
					r.setMsgInfo("平整交工重量相差"+new DecimalFormat("#.0").format(a*100) +"%,超过0.3%,无法交工");
					return r;
				}			
			}
		}		
	    	    
	    PlnMaterielDetail pmd=new PlnMaterielDetail();
		pmd.setMat_object_no_vt(psp.getObject_no_vt());
		List<PlnMaterielDetail> lpmd=this.getMapper(PlnMaterielDetailMapper.class).findWithCondition(pmd, "", " serial_no ", 0, 0);
		int k=0,n=lpmd.size()-1;
		//（10）、逐一循环出口卷实绩（废副品物料除外），验证各出口卷的 厚、宽、长、实重 都＞0
		List<MesTpmD> listD=	this.getMapper(MesTpmDMapper.class).FindMescrcrDByprocessNo(v_rec_tpm.getSchedule_no(),v_rec_tpm.getMaterial_no());
		for (MesTpmD  cur_01 : listD) {
			if(cur_01.getAct_thk() ==null || cur_01.getAct_thk() <= 0){
				throw new Exception("出口卷:"+cur_01.getCoil_no()+"厚度必须大于0！");
			}
			if(cur_01.getAct_wdt() ==null || cur_01.getAct_wdt() <= 0){
				throw new Exception("出口卷:"+cur_01.getCoil_no()+"宽度必须大于0！");
			}
			/*if(cur_01.getAct_len() ==null || cur_01.getAct_len() <= 0){
				throw new Exception("出口卷:"+cur_01.getCoil_no()+"长度必须大于0！");
			}*/
			if(cur_01.getCoil_act_wgt()==null||cur_01.getCoil_act_wgt()<=0){
				throw new Exception("出口卷["+cur_01.getCoil_no()+"]重量需大于0");
			}
			/*if(cur_01.getAct_thk().doubleValue()>v_rec_tpm.getMtr_thk().doubleValue()){
				v_ret="出口卷:"+cur_01.getCoil_no()+"厚度【"+cur_01.getAct_thk().doubleValue()+"】不能大于入口卷厚度【"+v_rec_tpm.getMtr_thk().doubleValue()+"】";
				throw new Exception(v_ret);
			}*/
			//调用物流模块（仓库管理）接口，验证产生的吊销卷号 在库存信息中不存在
			YdmProductDetail ypd=new YdmProductDetail();
			ypd.setCoilno(cur_01.getCoil_no());
			List<YdmProductDetail> lypd=this.getMapper(YdmProductDetailMapper.class).find(ypd, 0, 0);
			if(lypd!=null&&lypd.size()>0){
				throw new Exception("钢卷号唯一，不能重复");
			}

			//---------------2018-03-15----------------------
			if(k<=n){
				MesTpmD mcd=new MesTpmD();
				mcd.setCoil_no(cur_01.getCoil_no());
				//如果【(出口卷实绩厚度 == 计划厚度) AND (出口卷实绩宽度 - 计划宽度) <= dUpper AND (出口卷实绩宽度 - 计划宽度) >= dLower】
				//2018-08-22 如果【(出口卷实绩厚度 >0) AND (出口卷实绩宽度 - 计划宽度) <= dUpper AND (出口卷实绩宽度 - 计划宽度) >= dLower】
				//if(mcsdc.getAct_thk()!=null && mcsdc.getAct_thk()>0
				//		&&(mcsdc.getAct_wdt().doubleValue()-lpmd.get(k).getWidth().doubleValue()<=dUpper)
				//		&&(mcsdc.getAct_wdt().doubleValue()-lpmd.get(k).getWidth().doubleValue()>=dLower)){
				//则SET 实绩.COIL_NO_VT = 计划.OBJECT_NO_VT, 实绩.PROD_ORDER_NO = 计划.PROD_ORDER_NO, 实绩.ORDER_NO = 计划.ORDER_NO；
					mcd.setCoil_no_vt(lpmd.get(k).getObject_no_vt());
					mcd.setOrder_no(lpmd.get(k).getOrder_no());
					mcd.setProd_order_no(lpmd.get(k).getProd_order_no());
					this.getMapper(MesTpmDMapper.class).update(mcd);
//				}else{
					//否则SET 实绩.COIL_NO_VT = NULL, 实绩.PROD_ORDER_NO = NULL, 实绩.ORDER_NO = NULL
//					this.getMapper(MesTpmDMapper.class).doUpdateNulls(mcd);
//				}
			}
			k++;			
		}
  		
		MesTpmM mmm=new MesTpmM();
		mmm.setSchedule_no(v_rec_tpm.getSchedule_no());
		mmm.setMaterial_no(v_rec_tpm.getMaterial_no());
  		mmm.setWrk_grp(work_grp);
  		mmm.setWrk_ord(work_ord);
  		mmm.setWrk_date(work_date);
  		this.getMapper(MesTpmMMapper.class).update(mmm);
  				
		//更新子表班组
  		MesTpmD mdd=new MesTpmD();
  		mdd.setSchedule_no(v_rec_tpm.getSchedule_no());
  		mdd.setMaterial_no(v_rec_tpm.getMaterial_no());
		List<MesTpmD> lmddq=this.getMapper(MesTpmDMapper.class).findWithCondition(mdd, "", " coil_no ", 0, 0);
		for(MesTpmD mc : lmddq){
			MesTpmD mcsd=new MesTpmD();
  			mcsd.setCoil_no(mc.getCoil_no());
  			mcsd.setWrk_grp(work_grp);
  			mcsd.setWrk_ord(work_ord);
  			mcsd.setWrk_date(work_date);
  			this.getMapper(MesTpmDMapper.class).update(mcsd);
  			
  			if (StringUtils.isNotEmpty(sum.getMemo6()) && "1".equals(sum.getMemo6())) {
  				MesOprInfo moi = new MesOprInfo();
  				moi.setOpr_id(mc.getCoil_no()+opr_time);
  				moi.setCoil_no(mc.getCoil_no());
  				moi.setMat_coil_no(v_rec_tpm.getMaterial_no());//投料卷号
  				moi.setOpr_desc("平整交工重量差异相差"+wgt+"Kg,进行异重交工");
  				moi.setOpr_type("异重交工");
  				moi.setMemo(sum.getMemo5());//异重交工的原因
  				moi.setCreate_man(username);
  				moi.setCreate_time(now);
  				this.getMapper(MesOprInfoMapper.class).insert(moi);
  			}
  			if (StringUtils.isNotEmpty(sum.getMemo6()) && "2".equals(sum.getMemo6())) {
  				MesOprInfo moi = new MesOprInfo();
  				moi.setOpr_id(mc.getCoil_no()+opr_time);
  				moi.setCoil_no(mc.getCoil_no());
  				moi.setMat_coil_no(v_rec_tpm.getMaterial_no());//投料卷号
  				moi.setOpr_desc("平整交工重量差异相差"+wgt+"Kg,进行强制交工");
  				moi.setOpr_type("强制交工");
  				moi.setMemo(sum.getMemo5());//强制交工的原因
  				moi.setCreate_man(username);
  				moi.setCreate_time(now);
  				this.getMapper(MesOprInfoMapper.class).insert(moi);
  			}
		}
  		 		
	    //   --(2.7)、如果产生了部分原卷吊销，则调用物流模块接口，将吊销原卷（新卷号）入库（接口由物流模块提供）                                                                              
	    if("1".equals(v_rec_tpm.getPartial_rejected()) && v_rec_tpm.getRejected_coil_no()!=null){
	    	YdmProductDetail ypd=new YdmProductDetail();
			ypd.setCoilno(v_rec_tpm.getRejected_coil_no());
			ypd.setTheoryweight(v_rec_tpm.getRejected_coil_thr_wgt());
			ypd.setFactweight(v_rec_tpm.getRejected_coil_act_wgt());
			ypd.setLength(v_rec_tpm.getRejected_coil_len());
			ypd.setDiameter_inn(v_rec_tpm.getMtr_inn_dia());
			ypd.setDiameter_out(v_rec_tpm.getMtr_out_dia());
            //2018-09-26 机台代码，机台名称
			ypd.setMachine_code(v_rec_tpm.getMachine_code());
			List<ComBaseMachine> listcom=this.getMapper(ComBaseMachineMapper.class).findWithCondition(null, "machine_code='"+v_rec_tpm.getMachine_code()+"'", null, 0, 0);
			if(listcom!=null && listcom.size()>0){
				ypd.setMachine_name(listcom.get(0).getMachine_name());
			}
			ResultModel rmValid = this.getBean(LmsApiServiceImpl.class).doInsertRevoke(psp.getMaterial_no(),ypd);
			if(!"200".equals(rmValid.getState())){
				throw new Exception(rmValid.getMsgInfo());
			}
	    }
	    	    
	    try{	    	
	  		/*2019-02-21
	  		检验批分批规则：
	  			同炉次号向下相同牌号、相同尺寸（厚度、宽度）的物料集合生成一个检验批号
	  			检验批号编码规则：炉次号+两位流水号，示例：2619000401） 
	  		 */
		    Map<String, List<MesTpmD>> mc_list =new HashMap<String, List<MesTpmD>>();
	  		if(v_rec_tpm.getSchedule_no()!=null && !"".equals(v_rec_tpm.getSchedule_no())){
	  			List<MesTpmD> mcdlist=new ArrayList<MesTpmD>();
  				List<MesTpmD> lll = this.getMapper(MesTpmDMapper.class).findWithCondition(null, "schedule_no='"+v_rec_tpm.getSchedule_no()+"' and material_no='"+v_rec_tpm.getMaterial_no()+"'and coil_no not like '%B'", null, 0, 0);
  				for(MesTpmD mccc:lll){
  					mcdlist.add(mccc);	
  				}
  				List<MesTpmM> v_rec_baf_mList = this.getMapper(MesTpmMMapper.class).findWithCondition(null,"schedule_no='"+v_rec_tpm.getSchedule_no()+"'", null, 0, 0);
	  			if(v_rec_baf_mList!=null && v_rec_baf_mList.size()>0 && mcdlist.size()>0){
  					try{
  						mc_list = groupBillingDataByExcpBatchCode(mcdlist,v_rec_tpm.getSchedule_no());
  					}catch(Exception e){
  						
  					}
	  			}
	  		}
	  		if(mc_list!=null && mc_list.size()>0){
				for(Map.Entry<String, List<MesTpmD>> grouplist :mc_list.entrySet()){
					List<MesTpmD> listCes = grouplist.getValue();
					for(MesTpmD mcam:listCes){
						MesTpmD mCrossleo = new MesTpmD();
						mCrossleo.setCoil_no(mcam.getCoil_no());
						mCrossleo.setInspection_lot(mcam.getInspection_lot());
						this.getMapper(MesTpmDMapper.class).update(mCrossleo);
					}
				}
			}	    	
	    }catch(Exception e){
	    	
	    }
	    	    
	    //循环平整出口卷实绩（MES_CR_SLITTING_D，此时，出口卷已完成匹配虚拟出口卷号，需要重新获取出口卷实绩集合
	    MesTpmD mc=new MesTpmD();
	    mc.setSchedule_no(v_rec_tpm.getSchedule_no());
	    mc.setMaterial_no(v_rec_tpm.getMaterial_no());
	  	List<MesTpmD> lmcsq=this.getMapper(MesTpmDMapper.class).find(mc, 0, 0);
	  	for(MesTpmD mcsq:lmcsq){  			
  			//  2018-6-21 将下面注解的东西修改成上面的
  			if (mcsq.getCoil_no() !=null && "B".equals(mcsq.getCoil_no().substring(mcsq.getCoil_no().length()-1))) {
  				if (mcsq.getCoil_act_wgt()==null || mcsq.getCoil_act_wgt().intValue()<=0) {
  					continue;
  				}
  			}
  			if(mcsq.getCoil_act_wgt()==null || mcsq.getCoil_act_wgt().intValue()<=0){
  				throw new Exception("出口卷["+mcsq.getCoil_no()+"]实重异常！");
  			}
  			CommonPage<MesTpmD> cp=new CommonPage<MesTpmD>();
  			MesTpmD mcsd=new MesTpmD();
  			mcsd.setCoil_no(mcsq.getCoil_no());
  			mcsd.setCoil_no_vt(mcsq.getCoil_no_vt());
  			cp.setObject(mcsq);
  			//调用物流模块（仓库管理）接口，逐一将平整出口卷实绩各出口卷，插入库存记录（待入库状态）；	
  			try{
  				//下道工序不为空，入库仓库为中间品库，为空（最后一道工序了），就如成品库         ？？？？
  				//code 当前工序代码 1 平整/2 开平/3 罩退/4 平整
  				String nextProcessCode = this.getBean(MesApiDesignInfoImpl.class).getNextProcessCode("4", psp.getObject_no_vt());
  				nextP = nextProcessCode;
  				if(nextProcessCode==null || "".equals(nextProcessCode)){
  					cp.setMemo1("500203");//成品库
  				    //生产订单统计 统计量并修改生产订单状态
  				    try{
//  				    	this.getBean(PlnProdorderStatisticServiceImpl.class).prod_Stats(mcsq.getCoil_no(),1,true);
  				    }catch(Exception e){
  				    	System.out.println("生产订单统计 统计量并修改生产订单状态出错");
  				    	e.printStackTrace();
  				    }
  				}else{
  					cp.setMemo1("500202");//在制品库
  				}
  			}catch(Exception ex){
	  			throw new Exception("获取下道工序异常");
  			}
	  			
  			try{			
  				//2019-02-21修改
  				PlnMaterielDetail pmd_21=new PlnMaterielDetail();
  				pmd_21.setObject_no_vt(psp.getObject_no_vt());
  				List<PlnMaterielDetail> list_pmd = this.getMapper(PlnMaterielDetailMapper.class).find(pmd_21, 0, 0);
  				boolean flag_Ct = false;
  				if(list_pmd!=null && list_pmd.size()>0){
  					flag_Ct=this.getBean(MesApiDesignInfoImpl.class).getContractType(list_pmd.get(0).getProd_order_no());
  				}
  				if(flag_Ct && !"B".equals(mcsq.getCoil_no().substring(mcsq.getCoil_no().length()-1))){
  					cp.setMemo3("507101");//物料属性，优特钢带
  				}
  				ResultModel rm = this.getBean(YdmProductDetailServiceImpl.class).interfaceInsertCoil(cp);
  				if ("200".equals(rm.getState())) {
  					//成功
  					
  					// 写入库存表后去更新生产订单状态：20230909刘侣；
  					YdmProductDetail ypdQ = this.getMapper(YdmProductDetailMapper.class).doFind(mcsq.getCoil_no(), null);
  					if (ypdQ != null && "500203".equals(ypdQ.getStorageattr())) {
  						this.getBean(PlnProdorderStatisticServiceImpl.class).prod_Stats(ypdQ.getCoilno(),1,true);
  					}
  					
  				// 检验委托：如果是最后一道工序才需要送样，去做检验委托：
  					// 待判信息发送：如果是最后一道工序（进成品库），那么就给isfinal ： 1， 否则就是：0；
  					if (ypdQ != null && "500203".equals(ypdQ.getStorageattr())) {
  						
  						// 发送检验委托信息：20230909刘侣：最后一道工序才送样
  						if (mcsq.getCoil_no() != null && ("B".equals(mcsq.getCoil_no().substring(mcsq.getCoil_no().length()-1))
  								 || "H".equals(mcsq.getCoil_no().substring(mcsq.getCoil_no().length()-1)))) {
  							
  							this.getBean(SlmFundFirstDetailServiceImpl.class).sendToPD(mcsq.getCoil_no(), true, "1");
  						} else {
  							this.getBean(SlmFundFirstDetailServiceImpl.class).sendToPD(mcsq.getCoil_no(), false, "1");
  						}
  						
  						// 只有以6开头的订单才去发送检验委托：
  						if (ypdQ.getOrderno() != null) {
  							ResultModel rmwt = this.getBean(SlmFundFirstDetailServiceImpl.class).sendToJYWT(mcsq.getCoil_no(), true);
  	  						if ("500".equals(rmwt.getState())) {
  	  							throw new Exception(rmwt.getMsgInfo());
  	  						}
  						}
  						
  						// end
  					} else {
  						// 非最后一道：
  						if (mcsq.getCoil_no() != null && ("B".equals(mcsq.getCoil_no().substring(mcsq.getCoil_no().length()-1))
  								 || "H".equals(mcsq.getCoil_no().substring(mcsq.getCoil_no().length()-1)))) {
  							
  							this.getBean(SlmFundFirstDetailServiceImpl.class).sendToPD(mcsq.getCoil_no(), true, "0");
  						} else {
  							this.getBean(SlmFundFirstDetailServiceImpl.class).sendToPD(mcsq.getCoil_no(), false, "0");
  						}
  					}
  					// end
  					// end
  					
  				}else {
  					//失败
  					throw new Exception("入库出错"+rm.getMsgInfo());//失败原因，信息或提示
  				}
  			}catch(Exception ex){
  				ex.printStackTrace();
  				throw new Exception("物流入库接口出错"+ ex.getMessage());
  			}
	  			
			// 2019-09-23 panbin 增加校验质量判定结果,空则不允许交工 
			ResultModel tmp_rst = new ResultModel();
			// 工序点信息
			List<ComBaseInfo> infoi = this.getMapper(ComBaseInfoMapper.class).findWithCondition(null,
					"sort_code = '2002' AND validflag = '1'", null, 0, 0);
			ProcessPoint processpoint = new ProcessPoint(infoi);
//			try {
//				tmp_rst = this.getBean(MesApiServiceImpl.class).hasJudegeResult(mcsq.getCoil_no(),mcsq.getProd_order_no(),processpoint.smooth_code);
//			} catch(Exception ex) {
//				throw new Exception("获取质量判定信息接口报错!"+ ex.getMessage());
//			}
//			if(!"200".equals(tmp_rst.getState())){
//				throw new Exception(tmp_rst.getData().toString());
//			}
				
  			try{
//				ResultModel rmxx = this.getBean(QmsApiServiceImpl.class).doQueryJudegeResult(mcsq.getCoil_no());
//				if(rmxx!=null && rmxx.getData()!=null && (rmxx.getData() instanceof JudgeResult)){
//					JudgeResult jr=(JudgeResult)rmxx.getData();
//					YdmProductDetail ypd=new YdmProductDetail();
//					ypd.setCoilno(mcsq.getCoil_no());
//					boolean falgggg=false;
//					if(jr.getMarginal_result()!=null){
//						ypd.setMarginal_result(jr.getMarginal_result());
//						falgggg=true;
//					}
//					if(jr.getMarginal_result_id()!=null){
//						ypd.setMarginal_result_id(jr.getMarginal_result_id());
//						falgggg=true;
//					}
//					if(jr.getMeasure_result()!=null){
//						ypd.setMeasure_result(jr.getMeasure_result());
//						falgggg=true;
//					}
//					if(jr.getMeasure_result_id()!=null){
//						ypd.setMeasure_result_id(jr.getMeasure_result_id());
//						falgggg=true;
//					}
//					if(jr.getSfd_is_lock()!=null){
//						ypd.setSfd_is_lock(jr.getSfd_is_lock());
//						falgggg=true;
//					}
//					if(jr.getSfe_is_lock()!=null){
//						ypd.setSfe_is_lock(jr.getSfe_is_lock());
//						falgggg=true;
//					}
//					if(jr.getSfu_is_lock()!=null){
//						ypd.setSfu_is_lock(jr.getSfu_is_lock());
//						falgggg=true;
//					}
//					if(jr.getSic_is_lock()!=null){
//						ypd.setSic_is_lock(jr.getSic_is_lock());
//						falgggg=true;
//					}
//					if(jr.getSizeResult()!=null){
//						ypd.setSizeresult(jr.getSizeResult());
//						falgggg=true;
//					}
//					if(jr.getUd_surface_result()!=null){
//						ypd.setUd_surface_result(jr.getUd_surface_result());
//						falgggg=true;
//					}
//					if(jr.getUd_surface_result_id()!=null){
//						ypd.setUd_surface_result_id(jr.getUd_surface_result_id());
//						falgggg=true;
//					}
//					if(jr.getUp_surface_result()!=null){
//						ypd.setUp_surface_result(jr.getUp_surface_result());
//						falgggg=true;
//					}
//					if(jr.getUp_surface_result_id()!=null){
//						ypd.setUp_surface_result_id(jr.getUp_surface_result_id());
//						falgggg=true;
//					}
//					if(jr.getUp_surface_flaw() != null) {
//						ypd.setUp_surface_flaw(jr.getUp_surface_flaw());
//						falgggg= true;
//					}
//					if(jr.getUd_surface_flaw() != null) {
//						ypd.setUd_surface_flaw(jr.getUd_surface_flaw());
//						falgggg= true;
//					}
//					if(jr.getMarginal_flaw()!= null) {
//						ypd.setMarginal_flaw(jr.getMarginal_flaw());
//						falgggg= true;
//					}
//					if(falgggg){
//						this.getMapper(YdmProductDetailMapper.class).update(ypd);
//					}
//				}
			}catch(Exception e){
				System.out.println("调用质量接口报错");
				e.printStackTrace();
			}
	  			
  			try{
	  			//循环平整出口卷实绩（MES_CR_SLITTING_D，此时，出口卷已完成匹配虚拟出口卷号，需要重新获取出口卷实绩集合
	  			//如果此出口卷的虚拟出口卷号不为空（COIL_NO_VT，即满足切割计划）
	  			if(mcsq.getCoil_no_vt()!=null&&!"".equals(mcsq.getCoil_no_vt())){
	  				//  --(2.10)、调用生产管理接口，执行作业计划、原料卷、出口钢卷相关进程状态处理逻辑（接口由生产管理模块提供）；
	  			    // 处理出口卷
	  				List<PlnMaterielDetail> lpmdc=this.getMapper(PlnMaterielDetailMapper.class).findWithCondition(null, "mat_object_no_vt = '"+v_rec_tpm.getMaterial_no_vt()+"' and nvl(invalid_flg,0) = '0'", null, 0, 1);
	  				if (Utils.isEmpty(lpmdc)) {
	  					throw new Exception("未找到虚拟出口卷信息!");
	  				}
	  				PlnMaterielDetail pmdq=new PlnMaterielDetail();
	  				pmdq.setObject_no(v_rec_tpm.getMaterial_no());
	  				pmdq.setObject_no_vt(mcsq.getCoil_no_vt());
	  				pmdq.setMaterial_no(v_rec_tpm.getMaterial_no());//投料卷号 material_no   由页面交工按钮传入
	  				pmdq.setSub_object_no(mcsq.getCoil_no()); // 出口卷号
	  				// 传入操作时间 2018-06-19
	  				pmdq.setCreate_time(now);
	  				this.getBean(MesApiSkinrollingPlanImpl.class).SkinrollingFinsh_Relation(pmdq);	  				
	  			}else if (mcsq.getCoil_no() != null && ("B".equals(mcsq.getCoil_no().substring(mcsq.getCoil_no().length()-1))
	  					 || "H".equals(mcsq.getCoil_no().substring(mcsq.getCoil_no().length()-1))
	  					)){
	  				//则调用生产管理的【平整完成——实物 生成接口】 2018-06-22
	  				PrcMaterielRelation pmr=new PrcMaterielRelation();
	  				pmr.setObject_no(psp.getMaterial_no());//投料卷号 material_no   由页面交工按钮传入
	  				pmr.setSub_object_no(mcsq.getCoil_no());//MES_CR_SLITTING_D表的出口卷号
	  				pmr.setRelation_seq(3);
	  				this.getBean(MesApiSkinrollingPlanImpl.class).SkinrollingFinsh_PrcMatRelAdd(pmr);//有insert插入prc_materiel_relation的操作
	  			}else{//如果此出口卷的虚拟出口卷号为空（COIL_NO_VT，即为非计划）
	  				//则调用生产管理的【平整完成——实物 生成接口】
	  				//第二卷
					PlnMaterielDetail pmdq2=new PlnMaterielDetail();
					pmdq2.setObject_no(v_rec_tpm.getMaterial_no());
					pmdq2.setMaterial_no(v_rec_tpm.getMaterial_no());//投料卷号 material_no   由页面交工按钮传入
					pmdq2.setSub_object_no(mcsq.getCoil_no());//MES_CR_SLITTING_D表的出口卷号
					// 传入操作时间 2018-06-22
					pmdq2.setCreate_time(now);
					this.getBean(MesApiSkinrollingPlanImpl.class).SkinrollingFinsh_No_Plan(pmdq2);//有insert插入PLN_MATERIEL_DETAIL的操作	  				
	  			}
  			}catch(Exception ex){
  				throw new Exception("计划接口出错"+ ex.getMessage());
  			}
	  			
	  			//===============2019-03-12========质量检验委托开始=============================
  		    if(v_rec_tpm.getSchedule_no()!=null && !"".equals(v_rec_tpm.getSchedule_no())){//作业计划号不为空
  		    	try{
//  		    		QcmJhySampleFromPlan ajsfp=new QcmJhySampleFromPlan();
//					List<PlnMaterielDetail> lpmdq22 = this.getMapper(PlnMaterielDetailMapper.class).findWithCondition(null,
//							"object_no_vt = '" + v_rec_tpm.getMaterial_no_vt() + "' and nvl(invalid_flg,0) = '0'", null, 0, 1);
//					String prod_order_no=lpmdq22.get(0).getProd_order_no();
//					List<PlnProdorder> lpp = this.getMapper(PlnProdorderMapper.class).findWithCondition(null, "prod_order_no='"+prod_order_no+"'", null, 0, 0);
//					if(lpp!=null && lpp.size()>0){
//						
//						int judge_Contain_Qcm = this.getBean(MesApiDesignInfoImpl.class).Judge_Contain_Qcm(v_rec_tpm.getMaterial_no_vt(), "C");
//						// 获取工艺路径包含成分或者材质类
//						if(judge_Contain_Qcm!=-1){
//							ajsfp.setPline_seq((long)judge_Contain_Qcm);
//  					  	ajsfp.setInspection_lot(mcsq.getInspection_lot());//检验号
//	  					  	ajsfp.setBatch_no(v_rec_tpm.getSchedule_no());//轧批号    炉次号
//							//ajsfp.setContract_line_no(lpp.get(0).getContract_line_no());//合同行信息
//							List<PlnProcessPlan> list_plnP = this.getMapper(PlnProcessPlanMapper.class).findWithCondition(null, "produce_no='"+lpp.get(0).getProduce_no()+"' and cut_order_no = 1", "", 0, 0);
//							if(list_plnP!=null && list_plnP.size()>0){
//								ajsfp.setContract_line_no(list_plnP.get(0).getPlan_no());//合同行信息  销售的订单的加工计划号
//							}
//							ajsfp.setDesign_key(lpp.get(0).getDesign_key());//design_key的集合
//							ajsfp.setJudge("0");//用于判断是改判还是原判 0：原判；1：改判  no
//							ajsfp.setMaterial_no(mcsq.getCoil_no());//取样材料号   
//							ajsfp.setMsc_pline(lpp.get(0).getMsc_pline());//全程产线号  制成号
//							ajsfp.setOrder_no(lpp.get(0).getOrder_no());//销售订单号(合同号+订单行号，示例:YT-66G66001)
//							ajsfp.setBoard_no(v_rec_tpm.getMaterial_no());
//							
//							ComBaseMachine cbm = this.getMapper(ComBaseMachineMapper.class).findById(v_rec_tpm.getMachine_code());
//							ComBasePline cbp = this.getMapper(ComBasePlineMapper.class).findById(cbm.getPline_code());
//							ajsfp.setPline_code(cbm.getPline_code());//产线代码
//							ajsfp.setPline_name(cbp.getPline_name());// 产线名称
//							//后期需要修改
//							ajsfp.setProcess_code("C");//工序代码    com_base_process表
//							ajsfp.setPsc(lpp.get(0).getPsc());//物料编码，
//							List<QcmJhySampleFromPlan> lqsfp=new ArrayList<>();
//							lqsfp.add(ajsfp);
//							CommonPage<QcmJhySampleFromPlan>  cpqjsfp=new CommonPage<QcmJhySampleFromPlan>();
//							cpqjsfp.setObjectList(lqsfp);
//							ResultModel reModel = this.getBean(QcmJhySampleConsignDItemServiceImpl.class).AutoGenerationSampleInfo(cpqjsfp);
//							if(reModel!=null){
//								System.out.println(reModel.getState());
//								System.out.println(reModel.getMsgInfo());
//							}
//  						}
//  					}
  				}catch(Exception e){
  					e.printStackTrace();
  				}
  		    }
	  			//==========================质量检验委托结束==================================	  			
		}
		
		// 处理母卷
		List<PlnMaterielDetail> lpmdq = this.getMapper(PlnMaterielDetailMapper.class).findWithCondition(null,
				"object_no_vt = '" + v_rec_tpm.getMaterial_no_vt() + "' and nvl(invalid_flg,0) = '0'", null, 0, 1);
		try{
			this.getBean(MesApiSkinrollingPlanImpl.class).SkinrollingFinsh_Sum(lpmdq.get(0));
		}catch(Exception ex){
			throw new Exception("计划接口出错"+ ex.getMessage());
		}
		
	    //  --(2.11)、修改平整作业主实绩交工状态
	    MesTpmM mes=new MesTpmM();
	    mes.setHand_over_status("1");
	    mes.setHand_over_time(now);
	    mes.setHand_over_opr(username);
	    mes.setUpdate_opr(username);
	    mes.setUpdate_time(now);
	    mes.setMachine_code(sum.getMemo1());
	    mes.setSchedule_no(psp.getSr_plan_no());
	    mes.setMaterial_no_vt(psp.getObject_no_vt());
	    mes.setMaterial_no(psp.getMaterial_no());
	    this.getMapper(MesTpmMMapper.class).doUpdate2(mes);
	    //日志
	    MesOprLog mol = new MesOprLog("车间MES", "平整机作业管理", "交工", username, opr_time, mes.getMaterial_no(), null, null, null, "下道工序为：" + nextP);
	    this.getMapper(MesOprLogMapper.class).insert(mol);
	    //(3)、提交事务
		r.setState("200");		
		r.setMsgInfo("交工成功!");
		return r;
	}
	
	
	/***
	 * 动作处理--取消交工按钮   
	 * object中：
	 * sr_plan_no 作业计划号
	 * object_no_vt 虚拟卷号
	 * material_no 原料卷号
	 * memo1:mch_code机台代码
	 * memo2:登录用户名
	 * @throws Exception 
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel signOutOffNew(CommonPage<PlnSkinrollingPlan> sum) throws Exception {
		ResultModel r=new ResultModel();
		Date now = new Date();
		String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(now); //操作时间
		String username = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		
		PlnSkinrollingPlan psp = sum.getObject();
		Integer v_cnt;
		//  --(1)、验证前端传入参数的基本有效性
		if(sum.getMemo1()==null || sum.getMemo1().length()<=0){
			r.setMsgInfo("参数错误：机台代码不能为空！");
			r.setState("500");
			return r;
		}
		if("".equals(psp.getSr_plan_no()) || "".equals(psp.getSr_plan_no())){
			r.setState("500");
			r.setMsgInfo("参数错误：作业计划号为空");
			return r;
		}
		// --(1)、验证平整作业计划主记录存在
		PlnSkinrollingPlan pcp=new PlnSkinrollingPlan();
		pcp.setMachine_code(sum.getMemo1());
		pcp.setSr_plan_no(psp.getSr_plan_no());
		int count = this.getMapper(PlnSkinrollingPlanMapper.class).count(pcp);
		if (count<=0) {
			throw new Exception("机台代码："+sum.getMemo1()+"\n作业计划号："+psp.getSr_plan_no()+"\n作业计划主记录不存在！");
		}
		//    --(2.2)、验证平整作业计划明细记录存在
		PlnSkinrollingPlanDetail pcpd=new PlnSkinrollingPlanDetail();
		pcpd.setMachine_code(sum.getMemo1());
		pcpd.setSr_plan_no(psp.getSr_plan_no());
		pcpd.setObject_no_vt(psp.getObject_no_vt());
		pcpd.setObject_no(psp.getMaterial_no());
		int count2 = this.getMapper(PlnSkinrollingPlanDetailMapper.class).count(pcpd);
		if (count2<=0) {
			throw new Exception("机台代码："+sum.getMemo1()+"\n作业计划号："+psp.getSr_plan_no()+"\n虚拟卷号："+psp.getObject_no_vt()+""
					+ "\n原料卷号："+psp.getMaterial_no()+"\n作业计划明细记录不存在！");
		}
		v_cnt=this.getMapper(PlnMaterielDetailMapper.class).countWithCondition(null, "object_no_vt='"+psp.getObject_no_vt()+"'");
		if (v_cnt<=0) {
			throw new Exception("虚拟卷号："+psp.getObject_no_vt()+"原料卷虚拟物料信息不存在！");
		}
		//???
		v_cnt=this.getMapper(PlnMaterielDetailMapper.class).countWithCondition(null, "mat_object_no_vt='"+psp.getObject_no_vt()+"'");
		if (v_cnt<=0) {
			throw new Exception("虚拟卷号："+psp.getObject_no_vt()+"出口卷虚拟物料信息不存在！");
		}
		//  --(3)、验证原料卷对应的平整主实绩存在，且为“未交工”状态
		MesTpmM mCross = new MesTpmM();
		mCross.setMachine_code(sum.getMemo1());
		mCross.setSchedule_no(psp.getSr_plan_no());
		mCross.setMaterial_no_vt(psp.getObject_no_vt());
		mCross.setMaterial_no(psp.getMaterial_no());
		v_cnt = this.getBean(MesTpmMMapper.class).count(mCross);
		if (v_cnt<=0) {
			r.setState("500");
			r.setMsgInfo("原料卷号：" +psp.getMaterial_no()+ "，当前不存在平整作业实绩！请确认是否已操作上料！");
			return r;
		}
	    List<MesTpmM> lmcam = this.getMapper(MesTpmMMapper.class).find(mCross, 0, 0);
	    MesTpmM v_rec_tpm =lmcam.get(0);
	    if(v_rec_tpm.getHand_over_status()!=null && !v_rec_tpm.getHand_over_status().equals("1")){
	    	r.setState("500");
	    	r.setMsgInfo("原料卷号："+psp.getMaterial_no()+"还未生产交工！");
			return r;
	    }
	    MesTpmD v_rec_tpd=new MesTpmD();
	    v_rec_tpd.setSchedule_no(v_rec_tpm.getSchedule_no());
	    v_rec_tpd.setMaterial_no(v_rec_tpm.getMaterial_no());
	    List<MesTpmD> list_tpd = this.getMapper(MesTpmDMapper.class).find(v_rec_tpd, 0, 0);
	    if(list_tpd==null||list_tpd.size()==0){
			r.setState("500");
			r.setMsgInfo("作业计划原料卷不存在出口卷实绩!");
			return r;
		}
    	for(MesTpmD mcsq:list_tpd){
    		try{
	    		// 如果出口卷是边丝或者虚拟物料号为空,则按非计划执行
				if (Utils.isNotEmpty(mcsq.getCoil_no())  && ("B".equals(mcsq.getCoil_no().substring(mcsq.getCoil_no().length()-1))
						|| "H".equals(mcsq.getCoil_no().substring(mcsq.getCoil_no().length()-1))
	  					)){
					if (Utils.isNotEmpty(mcsq.getCoil_act_wgt()) && mcsq.getCoil_act_wgt().intValue()>0) {
						//则调用生产管理的【平整完成——实物 生成接口】 2018-06-22
						PrcMaterielRelation pmr=new PrcMaterielRelation();
						pmr.setObject_no(psp.getMaterial_no());//投料卷号 material_no   由页面交工按钮传入
						pmr.setSub_object_no(mcsq.getCoil_no());//MES_CR_SLITTING_D表的出口卷号
						this.getBean(MesApiSkinrollingPlanImpl.class).SkinrollingFinsh_PrcMatRelRemove(pmr);
					}
					//或者虚拟物料号为空,则按非计划执行
				}else if (Utils.isEmpty(mcsq.getCoil_no_vt())) {
					//第二卷
					PrcMaterielRelation pmr2=new PrcMaterielRelation();
					pmr2.setObject_no(v_rec_tpm.getMaterial_no());//投料卷号 material_no   由页面交工按钮传入
					pmr2.setSub_object_no(mcsq.getCoil_no());//MES_CR_SLITTING_D表的出口卷号
					// 由于在交工的时候,生成对应的虚拟出口卷信息取消的时候将其直接删除 2018-09-10
					PlnMaterielDetail pmddetele2 = new PlnMaterielDetail();
					pmddetele2.setObject_no(mcsq.getCoil_no());
					pmddetele2.setOrd_flg("2");
					this.getMapper(PlnMaterielDetailMapper.class).doDeleteByOrdflg(pmddetele2);
					this.getBean(MesApiSkinrollingPlanImpl.class).SkinrollingFinsh_PrcMatRelRemove(pmr2);
					
				}else {
				//  --(2.10)、调用生产管理接口，执行作业计划、原料卷、出口钢卷相关进程状态处理逻辑（接口由生产管理模块提供）；
					PlnMaterielDetail pmdq=new PlnMaterielDetail();
					pmdq.setObject_no(mcsq.getCoil_no());
					pmdq.setObject_no_vt(mcsq.getCoil_no_vt());
					this.getBean(MesApiSkinrollingPlanImpl.class).SkinrollingFinsh_RelationCancel(pmdq);
				}
    		}catch(Exception ex){
    			throw new Exception("计划接口出错"+ ex.getMessage());
    		}
			// --------------------------------2018-06-22--------------------------------
						
			//清空所有出口卷实绩的虚拟出口卷号信息
			MesTpmD mcsd=new MesTpmD();
			mcsd.setUpdate_opr(username);
			mcsd.setUpdate_time(now);
			mcsd.setCoil_no(mcsq.getCoil_no());
			this.getMapper(MesTpmDMapper.class).doUpdate111(mcsd);		
			
			//===============2019-03-12========质量检验委托开始=============================
  		    if(v_rec_tpm.getSchedule_no()!=null && !"".equals(v_rec_tpm.getSchedule_no())){//作业计划号不为空
  		    	if (mcsq.getCoil_no() !=null && "B".equals(mcsq.getCoil_no().substring(mcsq.getCoil_no().length()-1))) {
	  				if (mcsq.getCoil_act_wgt()==null || mcsq.getCoil_act_wgt().intValue()<=0) {
	  					continue;
	  				}
	  			}
  		    	try{
  		    		QcmJhySampleFromPlan ajsfp=new QcmJhySampleFromPlan();
					List<PlnMaterielDetail> lpmdq22 = this.getMapper(PlnMaterielDetailMapper.class).findWithCondition(null,
							"object_no_vt = '" + v_rec_tpm.getMaterial_no_vt() + "' and nvl(invalid_flg,0) = '0'", null, 0, 1);
					String prod_order_no=lpmdq22.get(0).getProd_order_no();
					List<PlnProdorder> lpp = this.getMapper(PlnProdorderMapper.class).findWithCondition(null, "prod_order_no='"+prod_order_no+"'", null, 0, 0);
					if(lpp!=null && lpp.size()>0){
						
//						int judge_Contain_Qcm = this.getBean(MesApiDesignInfoImpl.class).Judge_Contain_Qcm(v_rec_tpm.getMaterial_no_vt(), "C");
//						// 获取工艺路径包含成分或者材质类
//						if(judge_Contain_Qcm!=-1){
//							ajsfp.setPline_seq((long)judge_Contain_Qcm);
//  					  		ajsfp.setInspection_lot(mcsq.getInspection_lot());//检验号
//	  					  	ajsfp.setBatch_no(v_rec_tpm.getSchedule_no());//轧批号    炉次号
//							//ajsfp.setContract_line_no(lpp.get(0).getContract_line_no());//合同行信息
//	  					    List<PlnProcessPlan> list_plnP = this.getMapper(PlnProcessPlanMapper.class).findWithCondition(null, "produce_no='"+lpp.get(0).getProduce_no()+"' and cut_order_no = 1", "", 0, 0);
//							if(list_plnP!=null && list_plnP.size()>0){
//								ajsfp.setContract_line_no(list_plnP.get(0).getPlan_no());//合同行信息  销售的订单的加工计划号
//							}
//	  					  	ajsfp.setDesign_key(lpp.get(0).getDesign_key());//design_key的集合
//							ajsfp.setJudge("0");//用于判断是改判还是原判 0：原判；1：改判  no
//							ajsfp.setMaterial_no(mcsq.getCoil_no());//取样材料号   
//							ajsfp.setMsc_pline(lpp.get(0).getMsc_pline());//全程产线号  制成号
//							ajsfp.setOrder_no(lpp.get(0).getOrder_no());//销售订单号(合同号+订单行号，示例:YT-66G66001)
//							
//							ComBaseMachine cbm = this.getMapper(ComBaseMachineMapper.class).findById(v_rec_tpm.getMachine_code());
//							ComBasePline cbp = this.getMapper(ComBasePlineMapper.class).findById(cbm.getPline_code());
//							ajsfp.setPline_code(cbm.getPline_code());//产线代码
//							ajsfp.setPline_name(cbp.getPline_name());// 产线名称
//							//后期需要修改
//							ajsfp.setProcess_code("C");//工序代码    com_base_process表
//							ajsfp.setPsc(lpp.get(0).getPsc());//物料编码，
//							//ajsfp.setPline_seq(3l);//产线顺序  计划上道工序?还是计划下道工序？  当前工序点代码 1 平整/2 开平/3 罩退/4 平整
//							List<QcmJhySampleFromPlan> lqsfp=new ArrayList<>();
//							lqsfp.add(ajsfp);
//							CommonPage<QcmJhySampleFromPlan>  cpqjsfp=new CommonPage<QcmJhySampleFromPlan>();
//							cpqjsfp.setObjectList(lqsfp);
//							
//							QcmJhySampleFromPlan qjsprem=new QcmJhySampleFromPlan();
//							qjsprem.setDesign_key(lpp.get(0).getDesign_key());
//							qjsprem.setInspection_lot(mcsq.getInspection_lot());
//							CommonPage<QcmJhySampleFromPlan> sum22=new CommonPage<QcmJhySampleFromPlan>();
//							sum22.setObject(qjsprem);
//							this.getBean(QmsApiServiceImpl.class).removeInspection(sum22);						
//  						}
  					}
  				}catch(Exception e){
  					e.printStackTrace();
  				}
  		    }
  			//==========================质量检验委托结束==================================
		    String nextProcessCode = this.getBean(MesApiDesignInfoImpl.class).getNextProcessCode("4", psp.getObject_no_vt());
				if(nextProcessCode==null || "".equals(nextProcessCode) 
						|| (mcsq.getCoil_no() !=null && "B".equals(mcsq.getCoil_no().substring(mcsq.getCoil_no().length()-1)))){
					//生产订单统计 统计量并修改生产订单状态
				    try{
				    	this.getBean(PlnProdorderStatisticServiceImpl.class).prod_Stats(mcsq.getCoil_no(),1,false);
				    }catch(Exception e){
				    	System.out.println("生产订单统计 统计量并修改生产订单状态出错");
				    	e.printStackTrace();
				    }				    
			}			
    	}
	    	
	    
	    //    --(2.6)、如果产生了部分原卷吊销，则调用物流模块接口，
	    //验证吊销原卷（新卷号）为待入库状态（可撤销或删除库存数据），否则，返回错误信息到前端，结束操作（接口由物流模块提供）；                                                                        
	    if("1".equals(v_rec_tpm.getPartial_rejected()) && v_rec_tpm.getRejected_coil_no()!=null){
	    	YdmProductDetail ypd=new YdmProductDetail();
			ypd.setCoilno(v_rec_tpm.getRejected_coil_no());
			ypd.setState("0");
			List<YdmProductDetail> lypd=this.getMapper(YdmProductDetailMapper.class).find(ypd, 0, 0);
			if(lypd==null||lypd.size()==0){
				throw new Exception("吊销卷["+v_rec_tpm.getRejected_coil_no()+"]不为待入库状态");
			}else{
				//开始事务
				//如果平整产生了吊销的原料卷，调用物流模块（仓库管理）接口，吊销卷撤销库存实绩
				ResultModel rmValid = this.getBean(LmsApiServiceImpl.class).doInsertRevokeCanl(v_rec_tpm.getRejected_coil_no());
				if(!"200".equals(rmValid.getState())){
					throw new Exception(rmValid.getMsgInfo());
				}
			}
	    }
	    
	    for(MesTpmD mcsd:list_tpd){
			// 排除实重<=0的边丝
			if (mcsd.getCoil_no() != null && "B".equals(mcsd.getCoil_no().substring(mcsd.getCoil_no().length()-1))){
				if (mcsd.getCoil_act_wgt()==null || mcsd.getCoil_act_wgt().intValue()<=0) {
					continue;
				}
			}
			//   --(2.7)、调用物流模块接口，验证出口钢卷（coil_no）为待入库状态（可撤销或删除库存数据），否则，返回错误信息到前端，结束操作（接口由物流模块提供）；
		    YdmProductDetail ypd=new YdmProductDetail();
			ypd.setCoilno(mcsd.getCoil_no());
			ypd.setState("-1");
			List<YdmProductDetail> lypd=this.getMapper(YdmProductDetailMapper.class).find(ypd, 0, 0);
			if(lypd==null||lypd.size()==0){
				throw new Exception("出口钢卷["+mcsd.getCoil_no()+"]不为待入库状态");
			}else{
				//开始事务
				//调用物流模块（仓库管理）接口，删除钢卷库存实绩；
				YdmProductDetail ypdu=new YdmProductDetail();
				ypdu.setCoilno(mcsd.getCoil_no());
				CommonPage<YdmProductDetail> cp1=new CommonPage<YdmProductDetail>();
				cp1.setObject(ypd);
				ResultModel rmValid = this.getBean(LmsApiServiceImpl.class).doDeleteFinishedRoll(cp1);
				if(!"200".equals(rmValid.getState())){
					throw new Exception(rmValid.getMsgInfo());
				}
			}
		}
	    // 释放虚拟母卷
	    PlnMaterielDetail pmdq=new PlnMaterielDetail();
		pmdq.setObject_no_vt(psp.getObject_no_vt());
		List<PlnMaterielDetail> lpmdq=this.getMapper(PlnMaterielDetailMapper.class).find(pmdq, 0, 1);
		try{
			this.getBean(MesApiSkinrollingPlanImpl.class).SkinrollingFinsh_SumCancel(lpmdq.get(0));
		}catch(Exception ex){
			//throw new Exception("计划接口出错"+ ex.getMessage());
		}
	    //  --(2.11)、修改平整作业主实绩交工状态
	    MesTpmM mes=new MesTpmM();
	    mes.setHand_over_status("0");
	    mes.setUpdate_opr(username);
	    mes.setUpdate_time(now);
	    mes.setMachine_code(sum.getMemo1());
	    mes.setSchedule_no(psp.getSr_plan_no());
	    mes.setMaterial_no_vt(psp.getObject_no_vt());
	    mes.setMaterial_no(psp.getMaterial_no());
	    this.getMapper(MesTpmMMapper.class).doUpdate3(mes);
	    //日志
	    MesOprLog mol = new MesOprLog("车间MES", "平整机作业管理", "取消交工", username, opr_time, mes.getMaterial_no(), null, null, null, null);
	    this.getMapper(MesOprLogMapper.class).insert(mol);
	    //业务处理在sql中
		r.setState("200");
		r.setMsgInfo("取消交工成功！");
		return r;
	}
	
	
	
	/**
	 * 动作处理_下发PDI
	 * object中：
	 * schedule_no 作业计划号
	 * material_no 入口卷号
	 * memo1:mch_code机台代码
	 * memo2:登录用户名
	 * @throws Exception 
	 * */
	public ResultModel Tpm01L3SendPdi(CommonPage<MesTpmM> sum) throws Exception{
		ResultModel rm=new ResultModel();
		Date now = new Date();
		String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(now); //操作时间
		String username = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		MesTpmM mtm=sum.getObject();
		
		if(sum.getMemo1()==null || "".equals(sum.getMemo1())){
			rm.setState("500");
			rm.setMsgInfo("参数错误：机台代码不能为空！");
			return rm;
		}
		if(sum.getObject()==null){
			rm.setState("500");
			rm.setMsgInfo("请输入参数");
			return rm;
		}
		if(mtm.getSchedule_no()==null || "".equals(mtm.getSchedule_no())){
			rm.setState("500");
			rm.setMsgInfo("参数错误：未指定作业计划号！");
			return rm;
		}
		if(mtm.getMaterial_no()==null || "".equals(mtm.getMaterial_no())){
			rm.setState("500");
			rm.setMsgInfo("参数错误：未指定需要下发PDI数据的入口卷号！");
			return rm;
		}
		//  --(2)、调用L3指示删除下发函数
		String v_message="";
		try{
			v_message=this.getBean(MesApiTpmPdiPdoImpl.class).Tpm01L3SendPdi_d(sum.getMemo1(), mtm.getSchedule_no(), mtm.getMaterial_no(), username, v_message);
		}catch(Exception e){
			e.printStackTrace();
			v_message=e.getMessage();
		}
		String v_param="机台代码 {"+sum.getMemo1()+"} 作业计划号 {"+mtm.getSchedule_no()+"}"+ 
				"入口卷号 ENTRY_COIL_NO {"+mtm.getMaterial_no() +"} 操作人 {"+username+"}";
		// --(3)、写接口日志：与业务处理分开，单独的事务
		try{
			this.getMapper(IfTpm01LogMapper.class).doInsert("","Tpm01L3SendPdi",v_param,v_message);
		}catch(Exception e){
			e.printStackTrace();
		}
		
		//日志
		MesOprLog mol = new MesOprLog("车间MES", "平整机作业管理", "下发PDI", username, opr_time, mtm.getMaterial_no(), null, null, null, null);
		this.getMapper(MesOprLogMapper.class).insert(mol);
		rm.setMsgInfo(v_message);
		rm.setState("200");
		return rm;
	}
	
	/**
	 * 动作处理_撤销PDI
	 * object中：
	 * schedule_no 作业计划号
	 * material_no 入口卷号
	 * memo1:mch_code机台代码
	 * memo2:登录用户名
	 * @throws Exception 
	 * */
	public ResultModel Tpm01L3Revoke(CommonPage<MesTpmM> sum) throws Exception{
		ResultModel rm=new ResultModel();
		Date now = new Date();
		String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(now); //操作时间
		String username = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		MesTpmM mtm=sum.getObject();
		
		if(sum.getMemo1()==null || "".equals(sum.getMemo1())){
			rm.setState("500");
			rm.setMsgInfo("参数错误：机台代码不能为空！");
			return rm;
		}
		if(sum.getObject()==null){
			rm.setState("500");
			rm.setMsgInfo("请输入参数");
			return rm;
		}
		if(mtm.getSchedule_no()==null || "".equals(mtm.getSchedule_no())){
			rm.setState("500");
			rm.setMsgInfo("参数错误：未指定作业计划号！");
			return rm;
		}
		if(mtm.getMaterial_no()==null || "".equals(mtm.getMaterial_no())){
			rm.setState("500");
			rm.setMsgInfo("参数错误：未指定需要撤销PDI的入口卷号！");
			return rm;
		}
		//(2)、调用L3指示删除撤销下发函数
		String v_message="";
		try{
			Integer v_success=null;
			v_message=this.getBean(MesApiTpmPdiPdoImpl.class).Tpm01L3Revoke_d(sum.getMemo1(), mtm.getSchedule_no(), mtm.getMaterial_no(), username, v_success, v_message);
		}catch(Exception e){
			e.printStackTrace();
			v_message=e.getMessage();
		}
		String v_param="机台代码 {"+sum.getMemo1()+"} 作业计划号 {"+mtm.getSchedule_no()+"}"+ 
				"入口卷号 ENTRY_COIL_NO {"+mtm.getMaterial_no() +"} 操作人 {"+username+"}";
		//(3)、写接口日志：与业务处理分开，单独的事务
		try{
			this.getMapper(IfTpm01LogMapper.class).doInsert("","Tpm01L3Revoke",v_param,v_message);
		}catch(Exception e){
			e.printStackTrace();
		}
		//日志
		MesOprLog mol = new MesOprLog("车间MES", "平整机作业管理", "撤销PDI", username, opr_time, mtm.getMaterial_no(), null, null, null, null);
		this.getMapper(MesOprLogMapper.class).insert(mol);
		rm.setMsgInfo(v_message);
		rm.setState("200");
		return rm;
	}
	
	
	/**
	 * 重量分配  lw_plan_no改为sr_plan_no
	 * @param memo1 重量
	 * @param memo2 重量来源 （1：采集、2：人工）
	 * @throws Exception 
	 * */
	@Deprecated
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doWeightDistribution1(CommonPage<PlnSkinPlanDetailAndMesTpmD> oci) throws Exception{
		ResultModel rm=new ResultModel();
		Date now = new Date();
		String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(now); //操作时间
		String username = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		
		if(oci.getMemo1()==null || "".equals(oci.getMemo1().trim())){
			rm.setState("500");
			rm.setMsgInfo("请输入重量！");
			return rm;
		}
		//验证选中的作业计划主表记录存在
		PlnSkinrollingPlan plp=new PlnSkinrollingPlan();
		plp.setMachine_code(oci.getObject().getMain().getMachine_code());
		plp.setSr_plan_no(oci.getObject().getMain().getSr_plan_no());
		List<PlnSkinrollingPlan> lplp=this.getMapper(PlnSkinrollingPlanMapper.class).find(plp, 0, 0);
		if(lplp==null||lplp.size()==0){
			rm.setState("500");
			rm.setMsgInfo("选中的作业计划记录不存在");
			return rm;
		}
		//验证选中的作业计划明细表记录存在
		PlnSkinrollingPlanDetail plpd=new PlnSkinrollingPlanDetail();
		plpd.setMachine_code(oci.getObject().getMain().getMachine_code());
		plpd.setSr_plan_no(oci.getObject().getMain().getSr_plan_no());
		plpd.setObject_no_vt(oci.getObject().getMain().getObject_no_vt());
		plpd.setObject_no(oci.getObject().getMain().getObject_no());
		List<PlnSkinrollingPlanDetail> lplpd=this.getMapper(PlnSkinrollingPlanDetailMapper.class).find(plpd, 0, 0);
		if(lplpd==null||lplpd.size()==0){
			rm.setState("500");
			rm.setMsgInfo("选中的作业计划明细记录不存在");
			return rm;
		}

		//验证选中的作业计划对应的平整主实绩存在
		MesTpmM mcsm=new MesTpmM();
		mcsm.setMachine_code(oci.getObject().getMain().getMachine_code());
		mcsm.setSchedule_no(oci.getObject().getMain().getSr_plan_no());
		mcsm.setMaterial_no_vt(oci.getObject().getMain().getObject_no_vt());
		mcsm.setMaterial_no(oci.getObject().getMain().getObject_no());
		List<MesTpmM> lmcsm=this.getMapper(MesTpmMMapper.class).find(mcsm, 0, 0);
		if(lmcsm==null||lmcsm.size()==0){
			rm.setState("500");
			rm.setMsgInfo("["+mcsm.getMaterial_no_vt()+"]平整主实绩不存在！");
			return rm;
		}
		if(!"0".equals(lmcsm.get(0).getHand_over_status())
				&&lmcsm.get(0).getHand_over_status()!=null){
			rm.setState("500");
			rm.setMsgInfo("["+mcsm.getMaterial_no_vt()+"]平整已生产交工！");
			return rm;
		}
		//验证作业计划原料卷存在出口卷实绩
		MesTpmD mcccd=new MesTpmD();
		mcccd.setSchedule_no(lmcsm.get(0).getSchedule_no());
		mcccd.setMaterial_no(lmcsm.get(0).getMaterial_no());
		List<MesTpmD> lmcsdxxx =this.getMapper(MesTpmDMapper.class).findWithCondition(mcccd,"coil_no not like '%B'", " coil_no ", 0, 0);
		if(lmcsdxxx==null||lmcsdxxx.size()==0){
			throw new Exception("作业计划原料卷不存在出口卷实绩!");
		}	
						
		//开始事务：
		int icount=0;
		String dt=new SimpleDateFormat("yyMMdd").format(now);
		List<MesTpmWgt> lmcw=this.getMapper(MesTpmWgtMapper.class).findWithCondition(null, " substr(serial_no,1,6)='"+dt+"'", " serial_no desc", 0, 1);
		if(lmcw==null||lmcw.size()==0){
			icount=1;
		}else{
			icount=Integer.parseInt(lmcw.get(0).getSerial_no().substring(6,11))+1;
		}
		//创建平整出口卷线上称重实绩记录，即将前端传入的重量信息插入一条记录到MES_CR_SLITTING_WGT表中
		MesTpmWgt mcsw=new MesTpmWgt();
		mcsw.setSerial_no(dt+String.format("%05d", icount++));
		mcsw.setDivide_flag("1");
		mcsw.setDivide_opr(username);
		mcsw.setDivide_time(now);
		mcsw.setSchedule_no(oci.getObject().getMain().getSr_plan_no());
		mcsw.setMaterial_no(oci.getObject().getMain().getObject_no());
		mcsw.setWgt_source(oci.getMemo2());
		mcsw.setWgt_time(now);
		mcsw.setWgt_value(Double.parseDouble(oci.getMemo1()));
		this.getMapper(MesTpmWgtMapper.class).insert(mcsw);
				
		//查询所有出口卷实绩
		MesTpmD mcsdqq=new MesTpmD();
		mcsdqq.setSchedule_no(oci.getObject().getMain().getSr_plan_no());
		mcsdqq.setMaterial_no(oci.getObject().getMain().getObject_no());
		List<MesTpmD> lmcsdq = this.getMapper(MesTpmDMapper.class).findWithCondition(mcsdqq, " coil_no not like '%B' ", "coil_no", 0, 0);
		double v_sum=0;//理重计算值
		for(MesTpmD cur_01:lmcsdq){
        	if(cur_01.getAct_thk() ==null || cur_01.getAct_thk() <= 0){
				throw new Exception("出口卷:"+cur_01.getCoil_no()+"厚度必须大于0！");
			}
			if(cur_01.getAct_wdt() ==null || cur_01.getAct_wdt() <= 0){
				throw new Exception("出口卷:"+cur_01.getCoil_no()+"宽度必须大于0！");
			}
			if(cur_01.getAct_len() ==null || cur_01.getAct_len() <= 0){
				throw new Exception("出口卷:"+cur_01.getCoil_no()+"长度必须大于0！");
			}
			v_sum+=(cur_01.getAct_wdt()==null?0:cur_01.getAct_wdt())*(cur_01.getAct_len()==null?0:cur_01.getAct_len())*(cur_01.getAct_thk()==null?0:cur_01.getAct_thk());
        }
		
	   // （10'）、逐一循环出口卷实绩（废副品物料除外），重新计算各出口卷理重值：= 原卷理重 * （宽度*长度*块数）/ ∑（宽度*长度*块数）
	   double lastWgt=0;
	   double sumWeight=Double.parseDouble(oci.getMemo1());//总重量
	   List<MesTpmD> lmccd = this.getMapper(MesTpmDMapper.class).doQueryMes(oci.getObject().getMain().getSr_plan_no(),
			   oci.getObject().getMain().getObject_no());
	   for(MesTpmD d:lmccd){
		   // （10.1'）、前N-1个出口卷理重 = 原卷理重 * （宽度*长度*厚度）/ ∑（宽度*长度*厚度）
			//四舍五入
		   BigDecimal b=null;
		   double f1=0;
		   if(Integer.parseInt(d.getXh())<Integer.parseInt(d.getCnt())){
			   b= new BigDecimal(sumWeight*d.getAct_wdt()*d.getAct_len()*d.getAct_thk()/v_sum);  
			   f1 = b.setScale(0, BigDecimal.ROUND_HALF_UP).doubleValue();
			   lastWgt+=f1;
		   }else if(Integer.parseInt(d.getXh())==Integer.parseInt(d.getCnt())){
			   b= new BigDecimal(sumWeight-lastWgt);  
			   f1 = b.setScale(0, BigDecimal.ROUND_HALF_UP).doubleValue();
		   }
			MesTpmD mccccd=new MesTpmD();
			mccccd.setCoil_no(d.getCoil_no());
			mccccd.setCoil_thr_wgt(f1);
			this.getMapper(MesTpmDMapper.class).update(mccccd);
	   	}
	   	//日志
	   	MesOprLog mol = new MesOprLog("车间MES", "平整机作业管理", "重量分配", username, opr_time, lmcsm.get(0).getMaterial_no(), null, null, null, null);
	   	this.getMapper(MesOprLogMapper.class).insert(mol);
		rm.setState("200");
		return rm;
	}
	
	/**
	 * 动作处理_称重保存  --仿照4mm平整   Sr_plan_no改为sr_plan_no 机台代码什么的
	 * @param memo1 重量
	 * @param memo2 重量来源 （1：采集、2：人工）
	 * memo3  pk_ask_code 
	 * memo4  pk_ask_desc
	 * @throws Exception 
	 * */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doWeightSave(CommonPage<PlnSkinPlanDetailAndMesTpmD> oci) throws Exception{
		ResultModel rm=new ResultModel();
		Date now = new Date();
		String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(now); //操作时间
		String username = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		
		//验证选中的作业计划主表记录存在
		PlnSkinrollingPlan plp=new PlnSkinrollingPlan();
		plp.setMachine_code(oci.getObject().getMain().getMachine_code());
		plp.setSr_plan_no(oci.getObject().getMain().getSr_plan_no());
		List<PlnSkinrollingPlan> lplp=this.getMapper(PlnSkinrollingPlanMapper.class).find(plp, 0, 0);
		if(lplp==null||lplp.size()==0){
			rm.setState("500");
			rm.setMsgInfo("选中的作业计划记录不存在");
			return rm;
		}
		//验证选中的作业计划明细表记录存在
		PlnSkinrollingPlanDetail plpd=new PlnSkinrollingPlanDetail();
		plpd.setMachine_code(oci.getObject().getMain().getMachine_code());
		plpd.setSr_plan_no(oci.getObject().getMain().getSr_plan_no());
		plpd.setObject_no_vt(oci.getObject().getMain().getObject_no_vt());
		plpd.setObject_no(oci.getObject().getMain().getObject_no());
		List<PlnSkinrollingPlanDetail> lplpd=this.getMapper(PlnSkinrollingPlanDetailMapper.class).find(plpd, 0, 0);
		if(lplpd==null||lplpd.size()==0){
			rm.setState("500");
			rm.setMsgInfo("选中的作业计划明细记录不存在");
			return rm;
		}

		//验证选中的作业计划对应的平整主实绩存在
		MesTpmM mcsm=new MesTpmM();
		mcsm.setMachine_code(oci.getObject().getMain().getMachine_code());
		mcsm.setSchedule_no(oci.getObject().getMain().getSr_plan_no());
		mcsm.setMaterial_no_vt(oci.getObject().getMain().getObject_no_vt());
		mcsm.setMaterial_no(oci.getObject().getMain().getObject_no());
		List<MesTpmM> lmcsm=this.getMapper(MesTpmMMapper.class).find(mcsm, 0, 0);
		if(lmcsm==null||lmcsm.size()==0){
			rm.setState("500");
			rm.setMsgInfo("["+mcsm.getMaterial_no()+"]平整主实绩不存在！");
			return rm;
		}
		if(!"0".equals(lmcsm.get(0).getHand_over_status())
				&&lmcsm.get(0).getHand_over_status()!=null){
			rm.setState("500");
			rm.setMsgInfo("["+mcsm.getMaterial_no_vt()+"]平整已生产交工！");
			return rm;
		}
		//验证作业计划原料卷存在出口卷实绩
		MesTpmD mcccd=new MesTpmD();
		mcccd.setSchedule_no(lmcsm.get(0).getSchedule_no());
		mcccd.setMaterial_no(lmcsm.get(0).getMaterial_no());
		List<MesTpmD> lmcsdxxx =this.getMapper(MesTpmDMapper.class).findWithCondition(mcccd,"coil_no not like '%B'", " coil_no ", 0, 0);
		if(lmcsdxxx==null||lmcsdxxx.size()==0){
			throw new Exception("作业计划原料卷不存在出口卷实绩!");
		}
							
		//验证作业计划原料卷当前勾选选中的出口卷实绩都存在
		for(MesTpmD mcsd:oci.getObject().getChild()){
			//只有一条
			MesTpmD mcsdq=this.getMapper(MesTpmDMapper.class).findById(mcsd.getCoil_no());
			if(mcsdq==null||mcsdq.getCoil_no()==null){
				rm.setState("500");
				rm.setMsgInfo("当前勾选选中的出口卷["+mcsd.getCoil_no()+"]实绩不存在");
				return rm;
			}
		}
		int icount=0;
		String dt=new SimpleDateFormat("yyMMdd").format(now);
		List<MesTpmWgt> lmcw=this.getMapper(MesTpmWgtMapper.class).findWithCondition(null, " substr(serial_no,1,6)='"+dt+"'", " serial_no desc", 0, 1);
		if(lmcw==null||lmcw.size()==0){
			icount=1;
		}else{
			icount=Integer.parseInt(lmcw.get(0).getSerial_no().substring(6,11))+1;
		}
		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		if(userName==null){
			userName="";
		}
		//开始事务：
		//创建平整出口卷线上称重实绩记录，即将前端传入的重量信息插入一条记录到MES_CR_SLITTING_WGT表中
		MesTpmWgt mcsw=new MesTpmWgt();
		mcsw.setSerial_no(dt+String.format("%05d", icount++));
		mcsw.setDivide_flag("1");
		mcsw.setDivide_opr(userName);
		mcsw.setDivide_time(now);
		mcsw.setMaterial_no(oci.getObject().getMain().getObject_no());
		mcsw.setSchedule_no(oci.getObject().getMain().getSr_plan_no());
		mcsw.setWgt_source("2");
		mcsw.setWgt_time(now);
		mcsw.setCoil_no(oci.getObject().getChild().get(0).getCoil_no());
		mcsw.setWgt_value(Double.parseDouble(oci.getMemo1()));
		this.getMapper(MesTpmWgtMapper.class).insert(mcsw);

		MesTpmD mcs=this.getMapper(MesTpmDMapper.class).findById(oci.getObject().getChild().get(0).getCoil_no());
		double sumWeight=Double.parseDouble(oci.getMemo1());//重量
		mcs.setCoil_act_wgt(sumWeight);
		mcs.setCoil_thr_wgt(sumWeight);
		mcs.setUpdate_opr(userName);
		mcs.setUpdate_time(now);
		mcs.setCoil_wgt_time(now);//出口卷称重时间
		mcs.setPk_ask_code(oci.getMemo3());
		mcs.setPk_ask_desc(oci.getMemo4());
		this.getMapper(MesTpmDMapper.class).update(mcs);		
		//日志
		MesOprLog mol = new MesOprLog("车间MES", "平整机作业管理", "保存修改", username, opr_time, mcs.getCoil_no(), null, null, null, null);
		this.getMapper(MesOprLogMapper.class).insert(mol);
		
		rm.setState("200");
		return rm;
	}
	
	
	/**
	 *  同炉次号向下相同牌号、相同尺寸（厚度、宽度）的物料集合生成一个检验批号
		检验批号编码规则：炉次号+两位流水号，示例：2619000401）
	 * @param billingList
	 * @return
	 * @throws Exception
	 */
	private Map<String, List<MesTpmD>> groupBillingDataByExcpBatchCode(List<MesTpmD> billingList,String schedule) throws Exception{
		Map<String, List<MesTpmD>> resultMap = new HashMap<String, List<MesTpmD>>();
		try{
			int i=0;
			Integer max=this.getMapper(MesCrAnnealMMapper.class).findMaxInstpm(schedule);
			if(max!=null){
				i=max;
			}
			for(MesTpmD tmExcpNew : billingList){
				String key=tmExcpNew.getSteel_code()+"P"+tmExcpNew.getAct_thk()+"P"+tmExcpNew.getAct_wdt();
				if(resultMap.containsKey(key)){//map中异常批次已存在，将该数据存放到同一个key（key存放的是异常批次）的map中
					List<MesTpmD> list = resultMap.get(key);
					if(list!=null && list.size()>0){
						tmExcpNew.setInspection_lot(list.get(0).getInspection_lot());
					}
					resultMap.get(key).add(tmExcpNew);
				}else{//map中不存在，新建key，用来存放数据
					i++;
					String inspection_lot=schedule+lpad(i+"", 2, "0");
					tmExcpNew.setInspection_lot(inspection_lot);
					List<MesTpmD> tmpList = new ArrayList<MesTpmD>();
					tmpList.add(tmExcpNew);
					resultMap.put(key, tmpList);
				}
			}
		}catch(Exception e){
			 System.out.println("炉次号向下相同牌号、相同尺寸（厚度、宽度）的物料集合生成一个检验批号进行分组时出现异常");
			 return resultMap;
		}
		return resultMap;
	}
		
	// 补零
	public static String lpad(String str, int num, String pad) {
		String n_str = str;
		if (str == null && "".equals(str))
			n_str = " ";
		for (int i = str.length(); i < num; i++) {
			n_str = pad + n_str;
		}
		return n_str;
	}

}
