/***文档注释***********************************************
 * 作者            ：
 * 创建日期     ：2019-03-26
 * 描述            ：可逆轧机出口卷实绩
 * 注意事项     ：
 * 遗留BUG   ：
 * 修改日期     ：
 * 修改人员     ：
 * 修改内容     ：
***********************************************************/
package market.Mes.Rolling.Performance.impl;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import market.Com.mapper.ComBaseMachineMapper;
import market.Com.vo.ComBaseMachine;
import market.Com.vo.CommonPage;
import market.Com.vo.ResultModel;
import market.Mes.Lengthwise.Performance.vo.MesCrSlittingDSum;
import market.Mes.Lengthwise.Plan.mapper.PlnMaterielDetailMapper;
import market.Mes.Lengthwise.Plan.vo.PlnMaterielDetail;
import market.Mes.Opr.mapper.MesOprLogMapper;
import market.Mes.Opr.vo.MesOprLog;
import market.Mes.Rolling.Performance.mapper.MesRcmDMapper;
import market.Mes.Rolling.Performance.mapper.MesRcmMMapper;
import market.Mes.Rolling.Performance.service.MesRcmDService;
import market.Mes.Rolling.Performance.vo.MesRcmD;
import market.Mes.Rolling.Performance.vo.MesRcmM;
import market.Mes.Rolling.Performance.vo.RollingPrintView;
import market.Mes.Rolling.Plan.mapper.PlnRollingPlanDetailMapper;
import market.Mes.Rolling.Plan.mapper.PlnRollingPlanMapper;
import market.Mes.Rolling.Plan.vo.PlnRollingPlan;
import market.Mes.Rolling.Plan.vo.PlnRollingPlanDetail;
import market.Mes.Tpm.mapper.MesTpmPrintLogMapper;
import market.Mes.Tpm.vo.MesTpmPrintLog;

import org.springframework.beans.BeanUtils;
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="MesRcmDService")
public class MesRcmDServiceImpl extends BaseServiceImpl<MesRcmD,Object> implements MesRcmDService {
	
	/**
	 * 作业实绩数据查询
	 * */
	public ResultModel doQueryWeb22(CommonPage<MesRcmM> oci){
		ResultModel rm=new ResultModel();
		try{
			rm.setState("200");
			List<MesCrSlittingDSum> list=this.getMapper(MesRcmDMapper.class).doQuery(oci.getObject());
			double thr=0,act=0;
			for(MesCrSlittingDSum sum:list){
				if(sum.getCoil_thr_wgt()!=null){
					thr+=sum.getCoil_thr_wgt();
				}
				if(sum.getCoil_act_wgt()!=null){
					act+=sum.getCoil_act_wgt();
				}
			}
			if(Math.abs((thr-act)/thr)>0.003){
				for(MesCrSlittingDSum sum:list){
					sum.setColor("1");
				}
			}
			rm.setData(list);
		}catch(Exception ex){
			ex.printStackTrace();
			rm.setState("500");
			rm.setMsgInfo("查询失败!"+ex.getMessage());
		}
		return rm;
	}
	
	/**
	 * 作业称重页面
	 * 作业实绩数据查询
	 * */
	public ResultModel doQueryWeb22_wgt(CommonPage<MesRcmM> oci){
		ResultModel rm=new ResultModel();
		try{
			rm.setState("200");
			rm.setData(this.getMapper(MesRcmDMapper.class).doQuery_wgt(oci.getObject()));
		}catch(Exception ex){
			ex.printStackTrace();
			rm.setState("500");
			rm.setMsgInfo("查询失败!"+ex.getMessage());
		}
		return rm;
	}
	
	/**
	 *左下角出口卷计划（表格数据）处理：- 轧机计划      仿照3mm开平
	 * @param V_OBJECT_NO_VT
	 * @return
	 */
	public ResultModel doQueryWeb(CommonPage<PlnMaterielDetail> oci){
		ResultModel rm=new ResultModel(); 
		try{
			PlnMaterielDetail mcsm = oci.getObject();
			rm.setData(this.getMapper(MesRcmDMapper.class).doQueryWeb(mcsm));
			rm.setState("200");
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo("查询失败！");
			ex.printStackTrace();
			rm.setErrorInfo(ex.getMessage());
		}
		return rm;
	}
	
	/**
	 * 按计划批量新增板朵按钮 doinsweb  仿照3mm开平
	 * @param sum
	 * @return
	 * @throws Exception 
	 */
	@SuppressWarnings("unused")
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doAddsWeb(String vPlanNo, String vObjectNoVt,
			String vMaterialNo, String vMchCode, String vOprname) 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);

		if(vPlanNo==null || "".equals(vPlanNo)){
			r.setMsgInfo("请输入计划号");
			return r;
		}
		if(vObjectNoVt==null || "".equals(vObjectNoVt)){
			r.setMsgInfo("请输入虚拟卷号");
			return r;
		}
		if(vMaterialNo==null || "".equals(vMaterialNo)){
			r.setMsgInfo("请输入原料卷号");
			return r;
		}
		if(vMchCode==null || "".equals(vMchCode)){
			r.setMsgInfo("请输入机台代码");
			return r;
		}

		Integer v_cnt;		
		// (4.1)、验证轧机作业计划主记录存在
		PlnRollingPlan psp=new PlnRollingPlan();
		psp.setMachine_code(vMchCode);
		psp.setRl_plan_no(vPlanNo);
		int count = this.getMapper(PlnRollingPlanMapper.class).count(psp);
		if (count<=0) {
			throw new Exception("机台代码："+vMchCode+"\n作业计划号："+vPlanNo+"\n作业计划主记录不存在！");
		}
			
		// (4.2)、验证轧机作业计划明细记录存在
		PlnRollingPlanDetail pcpd=new PlnRollingPlanDetail();
		pcpd.setMachine_code(vMchCode);
		pcpd.setRl_plan_no(vPlanNo);
		pcpd.setObject_no_vt(vObjectNoVt);
		pcpd.setObject_no(vMaterialNo);
		int count2 = this.getMapper(PlnRollingPlanDetailMapper.class).count(pcpd);
		if (count2<=0) {
			throw new Exception("机台代码："+vMchCode+"\n作业计划号："+vPlanNo+"\n虚拟卷号："+vObjectNoVt+""
					+ "\n原料卷号："+vMaterialNo+"\n作业计划明细记录不存在！");
		}
		// (4.3)、验证虚拟物料表中，原料卷计划信息存在
		PlnMaterielDetail pmd=new PlnMaterielDetail();
		pmd.setObject_no_vt(vObjectNoVt);
		int count3 = this.getMapper(PlnMaterielDetailMapper.class).count(pmd);
		if (count3<=0) {
			throw new Exception("虚拟卷号："+vObjectNoVt+"\n原料卷虚拟物料信息不存在！");
		}
		// (2.5)、验证轧机作业主实绩存在，且为“未交工”状态
		MesRcmM mCross = new MesRcmM();
		mCross.setMachine_code(vMchCode);
		mCross.setSchedule_no(vPlanNo);
		mCross.setMaterial_no_vt(vObjectNoVt);
		mCross.setMaterial_no(vMaterialNo);
		v_cnt = this.getBean(MesRcmMMapper.class).count(mCross);
		if (v_cnt<=0) {
			throw new Exception("原料卷号：" + vMaterialNo + "，当前不存在轧机作业主实绩，请确认是否已操作上料！");
		}
	    List<MesRcmM> lmcam = this.getMapper(MesRcmMMapper.class).find(mCross, 0, 0);
	    MesRcmM 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("原料卷号："+vMaterialNo+"当前已生产交工，不能批量新增出口卷！\n可取消交工，再进行此操作！");
	    }
	    // (2)、验证机台基础信息存在
		ComBaseMachine machine = new ComBaseMachine();
		machine.setMachine_code(vMchCode);
		v_cnt = this.getMapper(ComBaseMachineMapper.class).count(machine);
		if (v_cnt <= 0) {
			r.setMsgInfo("机台代码：" + vMchCode + "，\n机台基础信息不存在！");
			r.setState("500");
			return r;
		}
		//  --（2.1)、获取机台基础信息表中，配置的机台设备代号（设备编号，如1,2,3）
		ComBaseMachine machine2 = new ComBaseMachine();
		machine2.setMachine_code(vMchCode);
		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("机台代码：" + v_mch_mark + "\n设备编号未配置，无法处理！");
			r.setState("500");
			return r;
		}
		
		// 8。删除现有所有的出口卷实绩 (mes_cr_cross_cutting_d )              ？？
		this.getMapper(MesRcmDMapper.class).deleteByProcessNo(v_rec_tpm.getProcess_no());
		PlnMaterielDetail pmd22=new PlnMaterielDetail();
		pmd22.setMat_object_no_vt(vObjectNoVt);
		List<PlnMaterielDetail> lpmd=this.getMapper(PlnMaterielDetailMapper.class).findWithCondition(pmd22, ""," serial_no ",0,0);		
		
		// （9）、出口卷编码规则：原料卷号（最初始原料卷号） + 1位工序代号（轧机K）+ 2位设备代号（01-99） + 2位流水（01 - 99）
		String sNo=vMaterialNo.substring(0, 8) + "L"+ lpad(v_mch_mark, 2, "0");		
		List<MesRcmD> lm=this.getMapper(MesRcmDMapper.class).findWithCondition(null, " coil_no like '"+sNo+"%' and substr(coil_no, -1) <> 'B' and substr(coil_no, -1) <> 'H' ", "coil_no", 0, 0);
		//由于最大为99，且中间可能有删除数据的情况，导致只能循环而非一次获取最大
		ArrayList<Integer> ai=new ArrayList<Integer>();
		if(lm!=null&&lm.size()>0){
			for(MesRcmD md:lm){
				ai.add(Integer.parseInt(md.getCoil_no().substring(md.getCoil_no().length()-2, md.getCoil_no().length())));
			}
		}
		//原料卷已切割生成的子卷数大于等于99
		if(lpmd.size()+ai.size()>99){
			throw new Exception("原料卷已切割生成的子卷数加当前生成的子卷数大于99!");
		}
		int icount=1;
		//ai不为空
		boolean aiIsNoEpt=ai.size()==0?false:true;
		boolean flag=false;
		for(PlnMaterielDetail pmdc:lpmd){
			MesRcmD mc=new MesRcmD();
			if(aiIsNoEpt){//不为空则有的号已使用则需验证
				flag=false;
				for(int i:ai){
					if(!ai.contains(icount)){
						flag=true;
						break;
					}else{
						icount++;
					}
				}
				if(flag){//补号码
					ai.add(icount);
				}
			}
			
			//根据机器编号查询机器信息
			mc.setCoil_no(sNo+String.format("%02d", icount));
			mc.setProcess_no(v_rec_tpm.getProcess_no());
			mc.setWrk_date(v_rec_tpm.getWrk_date());
			mc.setWrk_grp(v_rec_tpm.getWrk_grp());
			mc.setWrk_ord(v_rec_tpm.getWrk_ord());
			mc.setSteel_code(pmdc.getSteel_code());//牌号
			//20200807 :易XP XG130QR(1173) 经过轧机 自动转换成 XG130Q(1204)
			if ("1173".equals(mc.getSteel_code())) {
				mc.setSteel_code("1204");
			}
			mc.setProd_order_no(pmdc.getProd_order_no());//生产订单号
			mc.setOrder_no(pmdc.getOrder_no());//订单号
			mc.setAim_inn_dia(pmdc.getDiameter_inn());//目标内径
			mc.setAct_inn_dia(pmdc.getDiameter_inn());//子卷内径
			mc.setAim_len(pmdc.getLength());
			mc.setAim_out_dia(pmdc.getDiameter_out());
			mc.setAct_out_dia(pmdc.getDiameter_out());
			mc.setAim_thk(pmdc.getThick());
			mc.setAim_wdt(pmdc.getWidth());//目标宽度取计划
			//20200610(易XP)轧机取投料卷的规格
			mc.setAct_len(v_rec_tpm.getMtr_len());
			mc.setAct_thk(v_rec_tpm.getMtr_thk());
			mc.setAct_wdt(v_rec_tpm.getMtr_wdt());
			mc.setCoil_thr_wgt(pmdc.getSingle_weight());
			mc.setReceive_opr(username);
			mc.setReceive_time(now);
			mc.setProduce_time(now);
			mc.setCreate_opr(username);
			// 2019-09-23 增加包装要求以便后续称重作业页面修改 panbin
			mc.setPk_ask_code(pmdc.getPk_ask_code());
			mc.setPk_ask_desc(pmdc.getPk_ask_desc());
			this.getMapper(MesRcmDMapper.class).insert(mc);
			icount++;			
		}

		String v_coil_no=null;
		List<MesRcmD> lm_biansi=this.getMapper(MesRcmDMapper.class).findWithCondition
				(null, " coil_no like '"+sNo+"%' and substr(coil_no, -1) = 'B' ", "coil_no", 0, 0);
		if(lm_biansi==null||lm_biansi.size()==0){
			v_cnt=0;
			v_coil_no=sNo+v_cnt+"B";
		}else{
			int i=0;
			for(MesRcmD msbe:lm_biansi){
				int m=Integer.parseInt(msbe.getCoil_no().substring(msbe.getCoil_no().length()-2,msbe.getCoil_no().length()-1));
				if(i!=m){
					v_coil_no=sNo+i+"B";
					break;
				}
				i++;
				if(i>9){
					throw new Exception("边丝物料编号超出规则范围，流水号超出最大值9！");
				}
			}
			if(i>=lm_biansi.size()){
				v_coil_no=sNo+i+"B";
			}
		}
			
	    // --(16.3)、边丝编码规则：边丝编码前缀【原料卷号（最初始原料卷号） + 1位工序代号（分条F）+ 2位设备代号（01-99）】+ 1位流水号（0-9） + 'B'
	    //String v_coil_no=sNo+v_cnt+"B";

	     MesRcmD mc=new MesRcmD();
		//边丝编码	
		//mc.setCoil_no(sNo+"0B");
		mc.setCoil_no(v_coil_no);
		mc.setProcess_no(v_rec_tpm.getProcess_no());
		mc.setWrk_date(v_rec_tpm.getWrk_date());
		mc.setWrk_grp(v_rec_tpm.getWrk_grp());
		mc.setWrk_ord(v_rec_tpm.getWrk_ord());
		mc.setSteel_code(lpmd.get(0).getSteel_code());//牌号
		//20200807 :易XP XG130QR(1173) 经过轧机 自动转换成 XG130Q(1204)
		if ("1173".equals(mc.getSteel_code())) {
			mc.setSteel_code("1204");
		}
		mc.setProd_order_no(lpmd.get(0).getProd_order_no());//生产订单号
		mc.setOrder_no(lpmd.get(0).getOrder_no());//订单号
		mc.setAim_inn_dia(lpmd.get(0).getDiameter_inn());//目标内径
		mc.setAim_len(lpmd.get(0).getLength());
		mc.setAim_out_dia(lpmd.get(0).getDiameter_out());
		mc.setAim_thk(lpmd.get(0).getThick());
		mc.setAim_wdt(lpmd.get(0).getWidth());
		mc.setReceive_opr(username);
		mc.setReceive_time(now);
		mc.setProduce_time(now);
		mc.setCreate_opr(username);
		this.getMapper(MesRcmDMapper.class).insert(mc);
		icount++;
			
		boolean flag_houkuanchang=true;//计划那边给足了厚、宽、长。
		// （10）、逐一循环出口卷实绩（边丝物料除外），验证各出口卷的 厚、宽、长、实重 都＞0
		double v_sum=0;//理重计算值
		List<MesRcmD> listD=	this.getMapper(MesRcmDMapper.class).FindMescrcrDByprocessNo(v_rec_tpm.getProcess_no());
		for (MesRcmD  cur_01 : listD) {
			if(cur_01.getAct_thk() ==null || cur_01.getAct_thk() <= 0){
				flag_houkuanchang=false;
			}
			if(cur_01.getAct_wdt() ==null || cur_01.getAct_wdt() <= 0){
				flag_houkuanchang=false;
			}
			if(cur_01.getAct_len() ==null || cur_01.getAct_len() <= 0){
				flag_houkuanchang=false;
			}
			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());
		}
		if(flag_houkuanchang){
		   // （10'）、逐一循环出口卷实绩（边丝物料除外），重新计算各出口卷理重值：= 原卷理重 * （宽度*长度*厚度）/ ∑（宽度*长度*厚度）
		   List<MesRcmD> lmccd = this.getMapper(MesRcmDMapper.class).doQueryMes(v_rec_tpm.getProcess_no());
		   double lastWgt=0;
		   for(MesRcmD d:lmccd){
			   // （10.1'）、前N-1个出口卷理重 = 原卷理重 * （宽度*长度*厚度）/ ∑（宽度*长度*厚度）
			   //this.getMapper(MesRcmDMapper.class).updateMdd(v_sum,d.getCoil_no());
				//四舍五入
			   BigDecimal b=null;
			   double f1=0;
			   if(Integer.parseInt(d.getXh())<Integer.parseInt(d.getCnt())){
				   b= new BigDecimal(v_rec_tpm.getMtr_thr_wgt()*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(v_rec_tpm.getMtr_thr_wgt()-lastWgt);  
				   f1 = b.setScale(0, BigDecimal.ROUND_HALF_UP).doubleValue();
			   }
				MesRcmD mccccd=new MesRcmD();
				mccccd.setCoil_no(d.getCoil_no());
				mccccd.setCoil_thr_wgt(f1);
				this.getMapper(MesRcmDMapper.class).update(mccccd);
		   }
		}
		//日志
		MesOprLog mol = new MesOprLog("车间MES", "可逆轧机作业管理", "批量新增出口卷", username, opr_time, v_rec_tpm.getMaterial_no(), null, null, null, null);
		this.getMapper(MesOprLogMapper.class).insert(mol);
		r.setState("200");
		r.setMsgInfo("按计划批量新增出口卷成功");
		return r;
	}
			
	/**
	 * 新增头尾卷按钮 pln_cuttolength_plan  doinsweb2
	 * @param vPlanNo
	 * @param vObjectNoVt
	 * @param vMaterialNo
	 * @param vSerialNo
	 * @param vMchCode
	 * @param vOprname
	 * @param len  长度
	 * @param thk  厚度
	 * @param neijing  内径
	 * @param waijing  外径
	 * @return
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doAddmaterielWeb_H(String vPlanNo, String vObjectNoVt,
			String vMaterialNo, Integer vSerialNo, String vMchCode, String vOprname,Double len,Double thk,String steel_code,
			Double width,Double neijing,Double waijing) 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);
				
		Integer v_cnt;	
		if(vPlanNo==null || "".equals(vPlanNo)){
			r.setMsgInfo("请输入计划号");
			return r;
		}
		if(vObjectNoVt==null || "".equals(vObjectNoVt)){
			r.setMsgInfo("请输入虚拟卷号");
			return r;
		}
		if(vMaterialNo==null || "".equals(vMaterialNo)){
			r.setMsgInfo("请输入原料卷号");
			return r;
		}
		if(vMchCode==null || "".equals(vMchCode)){
			r.setMsgInfo("请输入机台代码");
			return r;
		}
		//(4.1)、验证轧机作业计划主记录存在
		PlnRollingPlan psp=new PlnRollingPlan();
		psp.setMachine_code(vMchCode);
		psp.setRl_plan_no(vPlanNo);
		int count = this.getMapper(PlnRollingPlanMapper.class).count(psp);
		if (count<=0) {
			throw new Exception("机台代码："+vMchCode+"\n作业计划号："+vPlanNo+"\n作业计划主记录不存在！");
		}
			
		// (4.2)、验证轧机作业计划明细记录存在
		PlnRollingPlanDetail pcpd=new PlnRollingPlanDetail();
		pcpd.setMachine_code(vMchCode);
		pcpd.setRl_plan_no(vPlanNo);
		pcpd.setObject_no_vt(vObjectNoVt);
		pcpd.setObject_no(vMaterialNo);
		int count2 = this.getMapper(PlnRollingPlanDetailMapper.class).count(pcpd);
		if (count2<=0) {
			throw new Exception("机台代码："+vMchCode+"\n作业计划号："+vPlanNo+"\n虚拟卷号："+vObjectNoVt+""
					+ "\n原料卷号："+vMaterialNo+"\n作业计划明细记录不存在！");
		}
		// (4.3)、验证虚拟物料表中，原料卷计划信息存在
		PlnMaterielDetail pmd=new PlnMaterielDetail();
		pmd.setObject_no_vt(vObjectNoVt);
		int count3 = this.getMapper(PlnMaterielDetailMapper.class).count(pmd);
		if (count3<=0) {
			throw new Exception("虚拟卷号："+vObjectNoVt+"\n原料卷虚拟物料信息不存在！");
		}
		// -(2.5)、验证轧机作业主实绩存在，且为“未交工”状态
		MesRcmM mCross = new MesRcmM();
		mCross.setMachine_code(vMchCode);
		mCross.setSchedule_no(vPlanNo);
		mCross.setMaterial_no_vt(vObjectNoVt);
		mCross.setMaterial_no(vMaterialNo);
		v_cnt = this.getBean(MesRcmMMapper.class).count(mCross);
		if (v_cnt<=0) {
			throw new Exception("原料卷号：" + vMaterialNo + "，当前不存在轧机作业主实绩，请确认是否已操作上料！");
		}
			
		List<MesRcmM> lmcam = this.getMapper(MesRcmMMapper.class).find(mCross, 0, 0);
		MesRcmM 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("原料卷号："+vMaterialNo+"当前已生产交工，不能新增出口卷！\n可取消交工，再进行此操作！");
		}
		// (2)、验证机台基础信息存在
		ComBaseMachine machine = new ComBaseMachine();
		machine.setMachine_code(vMchCode);
		v_cnt = this.getMapper(ComBaseMachineMapper.class).count(machine);
		if (v_cnt <= 0) {
			r.setMsgInfo("机台代码：" + vMchCode + "，\n机台基础信息不存在！");
			r.setState("500");
			return r;
		}
		// （2.1)、获取机台基础信息表中，配置的机台设备代号（设备编号，如1,2,3）
		ComBaseMachine machine2 = new ComBaseMachine();
		machine2.setMachine_code(vMchCode);
		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("机台代码：" + v_mch_mark + "\n设备编号未配置，无法处理！");
			r.setState("500");
			return r;
		}	
	
		String sNo=v_rec_tpm.getMaterial_no().substring(0,8)+"L"+lpad(v_mch_mark,2,"0");
		String v_coil_no=null;
		List<MesRcmD> lm_biansi=this.getMapper(MesRcmDMapper.class).findWithCondition
				(null, " coil_no like '"+sNo+"%' and substr(coil_no, -1) = 'H' ", "coil_no", 0, 0);
		if(lm_biansi==null||lm_biansi.size()==0){
			v_cnt=0;
			v_coil_no=sNo+v_cnt+"H";
		}else{
			int i=0;
			for(MesRcmD msbe:lm_biansi){
				int m=Integer.parseInt(msbe.getCoil_no().substring(msbe.getCoil_no().length()-2,msbe.getCoil_no().length()-1));
				if(i!=m){
					v_coil_no=sNo+i+"H";
					break;
				}
				i++;
				if(i>9){
					throw new Exception("头尾卷编号超出规则范围，流水号超出最大值9！");
				}
			}
			if(i>=lm_biansi.size()){
				v_coil_no=sNo+i+"H";
			}
		}
		
	    // --(16.3)、边丝编码规则：边丝编码前缀【原料卷号（最初始原料卷号） + 1位工序代号（分条F）+ 2位设备代号（01-99）】+ 1位流水号（0-9） + 'B'
	    //String v_coil_no=sNo+v_cnt+"B";
		//插入子卷实绩表
		MesRcmD mc=new MesRcmD();
		//20200610 (易XP)取母卷的规格
		mc.setAct_len(v_rec_tpm.getMtr_len());
		mc.setAct_thk(v_rec_tpm.getMtr_thk());
		mc.setAct_wdt(v_rec_tpm.getMtr_wdt());
		mc.setAct_inn_dia(neijing);
		mc.setAct_out_dia(waijing);
		mc.setCoil_no(v_coil_no);
		mc.setProcess_no(v_rec_tpm.getProcess_no());
		mc.setWrk_date(v_rec_tpm.getWrk_date());
		mc.setWrk_grp(v_rec_tpm.getWrk_grp());
		mc.setWrk_ord(v_rec_tpm.getWrk_ord());
		mc.setSteel_code(steel_code);//牌号
		mc.setReceive_opr(username);
		mc.setReceive_time(now);
		mc.setProduce_time(now);
		mc.setCreate_opr(username);
		//---------------2018-03-12增加-----------------
		PlnMaterielDetail pmd22=new PlnMaterielDetail();
		pmd22.setMat_object_no_vt(vObjectNoVt);
		List<PlnMaterielDetail> lpmd=this.getMapper(PlnMaterielDetailMapper.class).findWithCondition(pmd22, ""," serial_no ",0,0);
		if(lpmd!=null&&lpmd.size()>0){
			mc.setProd_order_no(lpmd.get(0).getProd_order_no());//生产订单号
			mc.setOrder_no(lpmd.get(0).getOrder_no());//订单号
			//2018-09-10
			mc.setAim_inn_dia(lpmd.get(0).getDiameter_inn());//目标内径
			mc.setAim_len(lpmd.get(0).getLength());
			mc.setAim_out_dia(lpmd.get(0).getDiameter_out());
			mc.setAim_thk(lpmd.get(0).getThick());
			mc.setAim_wdt(lpmd.get(0).getWidth());
			mc.setPk_ask_code(lpmd.get(0).getPk_ask_code());
			mc.setPk_ask_desc(lpmd.get(0).getPk_ask_desc());
		}
		this.getMapper(MesRcmDMapper.class).insert(mc);
		
		boolean flag_houkuanchang=true;//计划那边给足了厚、宽、长。
		// （10）、逐一循环出口卷实绩（边丝物料除外），验证各出口卷的 厚、宽、长、实重 都＞0
		double v_sum=0;//理重计算值
		List<MesRcmD> listD=	this.getMapper(MesRcmDMapper.class).FindMescrcrDByprocessNo(v_rec_tpm.getProcess_no());
		for (MesRcmD  cur_01 : listD) {
			if(cur_01.getAct_thk() ==null || cur_01.getAct_thk() <= 0){
				flag_houkuanchang=false;
			}
			if(cur_01.getAct_wdt() ==null || cur_01.getAct_wdt() <= 0){
				flag_houkuanchang=false;
				throw new Exception("物料未指定宽度");
			}
			if(cur_01.getAct_len() ==null || cur_01.getAct_len() <= 0){
				flag_houkuanchang=false;
			}
			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());
		}
		if(flag_houkuanchang){
			   // （10'）、逐一循环出口卷实绩（边丝物料除外），重新计算各出口卷理重值：= 原卷理重 * （宽度*长度*块数）/ ∑（宽度*长度*块数）
			   List<MesRcmD> lmccd = this.getMapper(MesRcmDMapper.class).doQueryMes(v_rec_tpm.getProcess_no());
			   double lastWgt=0;
			   for(MesRcmD d:lmccd){
				   // （10.1'）、前N-1个出口卷理重 = 原卷理重 * （宽度*长度*厚度）/ ∑（宽度*长度*厚度）
				   //this.getMapper(MesRcmDMapper.class).updateMdd(v_sum,d.getCoil_no());
					//四舍五入
				   BigDecimal b=null;
				   double f1=0;
				   if(Integer.parseInt(d.getXh())<Integer.parseInt(d.getCnt())){
					   b= new BigDecimal(v_rec_tpm.getMtr_thr_wgt()*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(v_rec_tpm.getMtr_thr_wgt()-lastWgt);  
					   f1 = b.setScale(0, BigDecimal.ROUND_HALF_UP).doubleValue();
				   }
			   }
		}	
		//日志
		MesOprLog mol = new MesOprLog("车间MES", "可逆轧机作业管理", "新增头尾卷", username, opr_time, mc.getCoil_no(), null, null, null, null);
		this.getMapper(MesOprLogMapper.class).insert(mol);
		
		r.setState("200");
		r.setMsgInfo("新增头尾卷成功！");		
		return r;
	}
	
	/**
	 * 按计划批量新增板朵按钮 doinsweb
	 * @param sum
	 * @return
	 * @throws Exception 
	 */
	@SuppressWarnings("unused")
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doAddsWeb_PDO(String vPlanNo, String vObjectNoVt,
			String vMaterialNo, String vMchCode, String vOprname) throws Exception {
		ResultModel r=new ResultModel();
		vOprname = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		if(vOprname==null){
			vOprname="";
		}
		if(vPlanNo==null || "".equals(vPlanNo)){
			r.setMsgInfo("请输入计划号");
			return r;
		}
		if(vObjectNoVt==null || "".equals(vObjectNoVt)){
			r.setMsgInfo("请输入虚拟卷号");
			return r;
		}
		if(vMaterialNo==null || "".equals(vMaterialNo)){
			r.setMsgInfo("请输入原料卷号");
			return r;
		}
		if(vMchCode==null || "".equals(vMchCode)){
			r.setMsgInfo("请输入机台代码");
			return r;
		}
		String v_ret = "";
		Integer v_cnt;
		
//		    --(2.5)、验证轧机作业主实绩存在，且为“未交工”状态
		MesRcmM mCross = new MesRcmM();
		mCross.setMachine_code(vMchCode);
		mCross.setSchedule_no(vPlanNo);
		mCross.setMaterial_no_vt(vObjectNoVt);
		mCross.setMaterial_no(vMaterialNo);
		v_cnt = this.getBean(MesRcmMMapper.class).count(mCross);
		if (v_cnt<=0) {
			v_ret = ("原料卷号：" + vMaterialNo + "，当前不存在轧机作业主实绩，请确认是否已操作上料！");
			throw new Exception(v_ret);
		}
	    List<MesRcmM> lmcam = this.getMapper(MesRcmMMapper.class).find(mCross, 0, 0);
	    MesRcmM v_rec_tpm =lmcam.get(0);
	    if(v_rec_tpm.getHand_over_status()!=null && !v_rec_tpm.getHand_over_status().equals("0")){
	    	v_ret = "原料卷号："+vMaterialNo+"当前已生产交工，不能批量新增出口卷！\n可取消交工，再进行此操作！";
			throw new Exception(v_ret);
	    }
	//  --(2)、验证机台基础信息存在
	    ComBaseMachine machine = new ComBaseMachine();
		machine.setMachine_code(vMchCode);
		v_cnt = this.getMapper(ComBaseMachineMapper.class).count(machine);
		if (v_cnt <= 0) {
			v_ret = ("机台代码：" + vMchCode + "，\n机台基础信息不存在！");
			r.setMsgInfo(v_ret);
			r.setState("500");
			return r;
		}
		//  --（2.1)、获取机台基础信息表中，配置的机台设备代号（设备编号，如1,2,3）
		ComBaseMachine machine2 = new ComBaseMachine();
		machine2.setMachine_code(vMchCode);
		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) {
			v_ret = ("机台代码：" + v_mch_mark + "\n设备编号未配置，无法处理！");
			r.setMsgInfo(v_ret);
			r.setState("500");
			return r;
		}
		
		// 8。删除现有所有的出口卷实绩 (mes_cr_cross_cutting_d )              ？？
		this.getMapper(MesRcmDMapper.class).deleteByProcessNo(v_rec_tpm.getProcess_no());
		PlnMaterielDetail pmd22=new PlnMaterielDetail();
		pmd22.setMat_object_no_vt(vObjectNoVt);
		List<PlnMaterielDetail> lpmd=this.getMapper(PlnMaterielDetailMapper.class).findWithCondition(pmd22, ""," serial_no ",0,0);
				
		//（9）、出口卷编码规则：原料卷号（最初始原料卷号） + 1位工序代号（轧机K）+ 2位设备代号（01-99） + 2位流水（01 - 99）
		String sNo=vMaterialNo.substring(0, 8) + "L"+ lpad(v_mch_mark, 2, "0");
		
		List<MesRcmD> lm=this.getMapper(MesRcmDMapper.class).findWithCondition(null, " coil_no like '"+sNo+"%' and substr(coil_no, -1) <> 'B' and substr(coil_no, -1) <> 'H' ", "coil_no", 0, 0);
		//由于最大为99，且中间可能有删除数据的情况，导致只能循环而非一次获取最大
		ArrayList<Integer> ai=new ArrayList<Integer>();
		if(lm!=null&&lm.size()>0){
			for(MesRcmD md:lm){
				ai.add(Integer.parseInt(md.getCoil_no().substring(md.getCoil_no().length()-2, md.getCoil_no().length())));
			}
		}
		//原料卷已切割生成的子卷数大于等于99
		if(lpmd.size()+ai.size()>99){
			throw new Exception("原料卷已切割生成的子卷数加当前生成的子卷数大于99!");
		}
		int icount=1;
		//ai不为空
		boolean aiIsNoEpt=ai.size()==0?false:true;
		boolean flag=false;
		for(PlnMaterielDetail pmdc:lpmd){
			MesRcmD mc=new MesRcmD();
			if(aiIsNoEpt){//不为空则有的号已使用则需验证
				flag=false;
				for(int i:ai){
					if(!ai.contains(icount)){
						flag=true;
						break;
					}else{
						icount++;
					}
				}
				if(flag){//补号码
					ai.add(icount);
				}
			}
			
			//根据机器编号查询机器信息
			mc.setCoil_no(sNo+String.format("%02d", icount));
			mc.setProcess_no(v_rec_tpm.getProcess_no());
			mc.setWrk_date(v_rec_tpm.getWrk_date());
			mc.setWrk_grp(v_rec_tpm.getWrk_grp());
			mc.setWrk_ord(v_rec_tpm.getWrk_ord());
			mc.setSteel_code(pmdc.getSteel_code());//牌号
			mc.setProd_order_no(pmdc.getProd_order_no());//生产订单号
			mc.setOrder_no(pmdc.getOrder_no());//订单号
			mc.setAim_inn_dia(pmdc.getDiameter_inn());//目标内径
			mc.setAct_inn_dia(pmdc.getDiameter_inn());//子卷内径
			mc.setAim_len(pmdc.getLength());
			mc.setAim_out_dia(pmdc.getDiameter_out());
			mc.setAct_out_dia(pmdc.getDiameter_out());
			mc.setAim_thk(pmdc.getThick());
			mc.setAct_len(pmdc.getLength());//计划的长度
			//2018-08-19			
			//mc.setAct_thk(v_rec_tpm.getMtr_thk());//原料卷厚度 ？？？
			mc.setAct_thk(pmdc.getThick());
			mc.setAim_wdt(pmdc.getWidth());//目标宽度取计划
			//mc.setAct_wdt(v_rec_tpm.getMtr_wdt());//宽度取原料卷
			mc.setAct_wdt(pmdc.getWidth());//宽度取原料卷
			mc.setCoil_thr_wgt(pmdc.getSingle_weight());
			mc.setReceive_opr(vOprname);
			mc.setReceive_time(new Date());
			mc.setProduce_time(new Date());
			mc.setCreate_opr(vOprname);
			this.getMapper(MesRcmDMapper.class).insert(mc);
			icount++;			
		}
			
		String v_coil_no=null;
		List<MesRcmD> lm_biansi=this.getMapper(MesRcmDMapper.class).findWithCondition
				(null, " coil_no like '"+sNo+"%' and substr(coil_no, -1) = 'B' ", "coil_no", 0, 0);
		if(lm_biansi==null||lm_biansi.size()==0){
			v_cnt=0;
			v_coil_no=sNo+v_cnt+"B";
		}else{
			int i=0;
			for(MesRcmD msbe:lm_biansi){
				int m=Integer.parseInt(msbe.getCoil_no().substring(msbe.getCoil_no().length()-2,msbe.getCoil_no().length()-1));
				if(i!=m){
					v_coil_no=sNo+i+"B";
					break;
				}
				i++;
				if(i>9){
					throw new Exception("边丝物料编号超出规则范围，流水号超出最大值9！");
				}
			}
			if(i>=lm_biansi.size()){
				//sum.getObject().setEmp_no("E"+String.format("%03d", i));
				v_coil_no=sNo+i+"B";
			}
		}
		     
	     MesRcmD mc=new MesRcmD();
		//边丝编码	
		//mc.setCoil_no(sNo+"0B");
		mc.setCoil_no(v_coil_no);
		mc.setProcess_no(v_rec_tpm.getProcess_no());
		mc.setWrk_date(v_rec_tpm.getWrk_date());
		mc.setWrk_grp(v_rec_tpm.getWrk_grp());
		mc.setWrk_ord(v_rec_tpm.getWrk_ord());
		mc.setSteel_code(lpmd.get(0).getSteel_code());//牌号
		mc.setProd_order_no(lpmd.get(0).getProd_order_no());//生产订单号
		mc.setOrder_no(lpmd.get(0).getOrder_no());//订单号
		mc.setAim_inn_dia(lpmd.get(0).getDiameter_inn());//目标内径
		mc.setAim_len(lpmd.get(0).getLength());
		mc.setAim_out_dia(lpmd.get(0).getDiameter_out());
		mc.setAim_thk(lpmd.get(0).getThick());
		mc.setAim_wdt(lpmd.get(0).getWidth());
		mc.setReceive_opr(vOprname);
		mc.setReceive_time(new Date());
		mc.setProduce_time(new Date());
		mc.setCreate_opr(vOprname);
		this.getMapper(MesRcmDMapper.class).insert(mc);
		icount++;
			
		boolean flag_houkuanchang=true;//计划那边给足了厚、宽、长。
			// （10）、逐一循环出口卷实绩（边丝物料除外），验证各出口卷的 厚、宽、长、实重 都＞0
		double v_sum=0;//理重计算值
		List<MesRcmD> listD = this.getMapper(MesRcmDMapper.class).FindMescrcrDByprocessNo(v_rec_tpm.getProcess_no());
		for (MesRcmD  cur_01 : listD) {
			if(cur_01.getAct_thk() ==null || cur_01.getAct_thk() <= 0){
				flag_houkuanchang=false;
			}
			if(cur_01.getAct_wdt() ==null || cur_01.getAct_wdt() <= 0){
				flag_houkuanchang=false;
				throw new Exception("物料未指定宽度");
			}
			if(cur_01.getAct_len() ==null || cur_01.getAct_len() <= 0){
				flag_houkuanchang=false;
			}
			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());
		}
		if(flag_houkuanchang){
			   // （10'）、逐一循环出口卷实绩（边丝物料除外），重新计算各出口卷理重值：= 原卷理重 * （宽度*长度*块数）/ ∑（宽度*长度*块数）
			   List<MesRcmD> lmccd = this.getMapper(MesRcmDMapper.class).doQueryMes(v_rec_tpm.getProcess_no());
			   double lastWgt=0;
			   for(MesRcmD d:lmccd){
				   // （10.1'）、前N-1个出口卷理重 = 原卷理重 * （宽度*长度*厚度）/ ∑（宽度*长度*厚度）
				   //this.getMapper(MesRcmDMapper.class).updateMdd(v_sum,d.getCoil_no());
					//四舍五入
				   BigDecimal b=null;
				   double f1=0;
				   if(Integer.parseInt(d.getXh())<Integer.parseInt(d.getCnt())){
					   b= new BigDecimal(v_rec_tpm.getMtr_thr_wgt()*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(v_rec_tpm.getMtr_thr_wgt()-lastWgt);  
					   f1 = b.setScale(0, BigDecimal.ROUND_HALF_UP).doubleValue();
				   }
					MesRcmD mccccd=new MesRcmD();
					mccccd.setCoil_no(d.getCoil_no());
					mccccd.setCoil_thr_wgt(f1);
					this.getMapper(MesRcmDMapper.class).update(mccccd);
			   }
		}
		r.setState("200");
		r.setMsgInfo("按计划批量新增出口卷成功");
		return r;
	}
	
	/**
	 * 新增出口卷按钮 pln_cuttolength_plan  doinsweb2
	 * @param vPlanNo
	 * @param vObjectNoVt
	 * @param vMaterialNo
	 * @param vSerialNo
	 * @param vMchCode
	 * @param vOprname
	 * @param len  长度
	 * @param thk  厚度
	 * @param steel_code 牌号
	 * @param width  宽度
	 * @param neijing  内径
	 * @param waijing  外径
	 * @return
	 */
	@SuppressWarnings("unused")
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doAddmaterielWeb(String vPlanNo, String vObjectNoVt,
			String vMaterialNo, Integer vSerialNo, String vMchCode, String vOprname,Double len,Double thk,String steel_code,
			Double width,Double neijing,Double waijing) 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);
		
		Integer v_cnt;		
		if(vPlanNo==null || "".equals(vPlanNo)){
			r.setMsgInfo("请输入计划号");
			return r;
		}
		if(vObjectNoVt==null || "".equals(vObjectNoVt)){
			r.setMsgInfo("请输入虚拟卷号");
			return r;
		}
		if(vMaterialNo==null || "".equals(vMaterialNo)){
			r.setMsgInfo("请输入原料卷号");
			return r;
		}
		if(vMchCode==null || "".equals(vMchCode)){
			r.setMsgInfo("请输入机台代码");
			return r;
		}
		//(4.1)、验证轧机作业计划主记录存在
		PlnRollingPlan psp=new PlnRollingPlan();
		psp.setMachine_code(vMchCode);
		psp.setRl_plan_no(vPlanNo);
		int count = this.getMapper(PlnRollingPlanMapper.class).count(psp);
		if (count<=0) {
			throw new Exception("机台代码："+vMchCode+"\n作业计划号："+vPlanNo+"\n作业计划主记录不存在！");
		}
			
		// (4.2)、验证轧机作业计划明细记录存在
		PlnRollingPlanDetail pcpd=new PlnRollingPlanDetail();
		pcpd.setMachine_code(vMchCode);
		pcpd.setRl_plan_no(vPlanNo);
		pcpd.setObject_no_vt(vObjectNoVt);
		pcpd.setObject_no(vMaterialNo);
		int count2 = this.getMapper(PlnRollingPlanDetailMapper.class).count(pcpd);
		if (count2<=0) {
			throw new Exception("机台代码："+vMchCode+"\n作业计划号："+vPlanNo+"\n虚拟卷号："+vObjectNoVt+""
					+ "\n原料卷号："+vMaterialNo+"\n作业计划明细记录不存在！");
		}
		// (4.3)、验证虚拟物料表中，原料卷计划信息存在
		PlnMaterielDetail pmd=new PlnMaterielDetail();
		pmd.setObject_no_vt(vObjectNoVt);
		int count3 = this.getMapper(PlnMaterielDetailMapper.class).count(pmd);
		if (count3<=0) {
			throw new Exception("虚拟卷号："+vObjectNoVt+"\n原料卷虚拟物料信息不存在！");
		}
		// (2.5)、验证轧机作业主实绩存在，且为“未交工”状态
		MesRcmM mCross = new MesRcmM();
		mCross.setMachine_code(vMchCode);
		mCross.setSchedule_no(vPlanNo);
		mCross.setMaterial_no_vt(vObjectNoVt);
		mCross.setMaterial_no(vMaterialNo);
		v_cnt = this.getBean(MesRcmMMapper.class).count(mCross);
		if (v_cnt<=0) {
			throw new Exception("原料卷号：" + vMaterialNo + "，当前不存在轧机作业主实绩，请确认是否已操作上料！");
		}
			
		List<MesRcmM> lmcam = this.getMapper(MesRcmMMapper.class).find(mCross, 0, 0);
		MesRcmM 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("原料卷号："+vMaterialNo+"当前已生产交工，不能新增出口卷！\n可取消交工，再进行此操作！");
		}
		//  --(2)、验证机台基础信息存在
		ComBaseMachine machine = new ComBaseMachine();
		machine.setMachine_code(vMchCode);
		v_cnt = this.getMapper(ComBaseMachineMapper.class).count(machine);
		if (v_cnt <= 0) {
			r.setMsgInfo("机台代码：" + vMchCode + "，\n机台基础信息不存在！");
			r.setState("500");
			return r;
		}
			//  --（2.1)、获取机台基础信息表中，配置的机台设备代号（设备编号，如1,2,3）
		ComBaseMachine machine2 = new ComBaseMachine();
		machine2.setMachine_code(vMchCode);
		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("机台代码：" + v_mch_mark + "\n设备编号未配置，无法处理！");
			r.setState("500");
			return r;
		}
		
		String sNo=v_rec_tpm.getMaterial_no().substring(0,8)+"L"+lpad(v_mch_mark,2,"0");		
		List<MesRcmD> lm=this.getMapper(MesRcmDMapper.class).findWithCondition(null, " coil_no like '"+sNo+"%' and substr(coil_no, -1) <> 'B' and substr(coil_no, -1) <> 'H' ", "coil_no", 0, 0);
		//由于最大为99，且中间可能有删除数据的情况，导致只能循环而非一次获取最大
		ArrayList<Integer> ai=new ArrayList<Integer>();
		if(lm!=null&&lm.size()>0){
			for(MesRcmD md:lm){
				ai.add(Integer.parseInt(md.getCoil_no().substring(md.getCoil_no().length()-2, md.getCoil_no().length())));
			}
		}
		//原料卷已切割生成的子卷数大于等于99
		if(1+ai.size()>99){
			r.setState("500");
			r.setMsgInfo("原料卷已切割生成的子卷数加当前生成的子卷数大于99!");
			return r;
		}

		boolean aiIsNoEpt=ai.size()==0?false:true;
		Integer icount=1;
		if(aiIsNoEpt){//不为空则有的号已使用则需验证
			for(int i:ai){
				if(!ai.contains(icount)){
					break;
				}else{
					icount++;
				}
			}
		}

		//插入子卷实绩表
		MesRcmD mc=new MesRcmD();
		//20200610 (易XP)轧机取投料规格	
		mc.setAct_len(v_rec_tpm.getMtr_len());//修改了
		mc.setAct_thk(v_rec_tpm.getMtr_thk());//修改了
		mc.setAct_wdt(v_rec_tpm.getMtr_wdt());
		mc.setAct_inn_dia(neijing);
		mc.setAct_out_dia(waijing);
		mc.setCoil_no(sNo+String.format("%02d", icount));
		mc.setProcess_no(v_rec_tpm.getProcess_no());
		mc.setWrk_date(v_rec_tpm.getWrk_date());
		mc.setWrk_grp(v_rec_tpm.getWrk_grp());
		mc.setWrk_ord(v_rec_tpm.getWrk_ord());
		mc.setSteel_code(steel_code);//牌号
		mc.setReceive_opr(username);
		mc.setReceive_time(now);
		mc.setProduce_time(now);
		mc.setCreate_opr(username);
		//---------------2018-03-12增加-----------------
		PlnMaterielDetail pmd22=new PlnMaterielDetail();
		pmd22.setMat_object_no_vt(vObjectNoVt);
		List<PlnMaterielDetail> lpmd=this.getMapper(PlnMaterielDetailMapper.class).findWithCondition(pmd22, ""," serial_no ",0,0);
		if(lpmd!=null&&lpmd.size()>0){
			mc.setProd_order_no(lpmd.get(0).getProd_order_no());//生产订单号
			mc.setOrder_no(lpmd.get(0).getOrder_no());//订单号
			//2018-09-10
			mc.setAim_inn_dia(lpmd.get(0).getDiameter_inn());//目标内径
			mc.setAim_len(lpmd.get(0).getLength());
			mc.setAim_out_dia(lpmd.get(0).getDiameter_out());
			mc.setAim_thk(lpmd.get(0).getThick());
			mc.setAim_wdt(lpmd.get(0).getWidth());
			mc.setPk_ask_code(lpmd.get(0).getPk_ask_code());
			mc.setPk_ask_desc(lpmd.get(0).getPk_ask_desc());
		}
		this.getMapper(MesRcmDMapper.class).insert(mc);
					
		boolean flag_houkuanchang=true;//计划那边给足了厚、宽、长。
		// （10）、逐一循环出口卷实绩（边丝物料除外），验证各出口卷的 厚、宽、长、实重 都＞0
		double v_sum=0;//理重计算值
		List<MesRcmD> listD=	this.getMapper(MesRcmDMapper.class).FindMescrcrDByprocessNo(v_rec_tpm.getProcess_no());
		for (MesRcmD  cur_01 : listD) {
			if(cur_01.getAct_thk() ==null || cur_01.getAct_thk() <= 0){
				flag_houkuanchang=false;
			}
			if(cur_01.getAct_wdt() ==null || cur_01.getAct_wdt() <= 0){
				flag_houkuanchang=false;
				//throw new Exception("物料未指定宽度");
			}
			if(cur_01.getAct_len() ==null || cur_01.getAct_len() <= 0){
				flag_houkuanchang=false;
			}
			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());
		}
		if(flag_houkuanchang){
			// （10'）、逐一循环出口卷实绩（边丝物料除外），重新计算各出口卷理重值：= 原卷理重 * （宽度*长度*块数）/ ∑（宽度*长度*块数）
		   List<MesRcmD> lmccd = this.getMapper(MesRcmDMapper.class).doQueryMes(v_rec_tpm.getProcess_no());
		   double lastWgt=0;
		   for(MesRcmD d:lmccd){
			   // （10.1'）、前N-1个出口卷理重 = 原卷理重 * （宽度*长度*厚度）/ ∑（宽度*长度*厚度）
			   //this.getMapper(MesRcmDMapper.class).updateMdd(v_sum,d.getCoil_no());
				//四舍五入
			   BigDecimal b=null;
			   double f1=0;
			   if(Integer.parseInt(d.getXh())<Integer.parseInt(d.getCnt())){
				   b= new BigDecimal(v_rec_tpm.getMtr_thr_wgt()*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(v_rec_tpm.getMtr_thr_wgt()-lastWgt);  
				   f1 = b.setScale(0, BigDecimal.ROUND_HALF_UP).doubleValue();
			   }
				MesRcmD mccccd=new MesRcmD();
				mccccd.setCoil_no(d.getCoil_no());
				mccccd.setCoil_thr_wgt(f1);
				this.getMapper(MesRcmDMapper.class).update(mccccd);
		   }
		}
		//日志
		MesOprLog mol = new MesOprLog("车间MES", "可逆轧机作业管理", "新增单个卷", username, opr_time, mc.getCoil_no(), null, null, null, null);
		this.getMapper(MesOprLogMapper.class).insert(mol);
		
		r.setState("200");
		r.setMsgInfo("新增出口卷成功！");		
		return r;
	}
		
	/**
	 * 动作处理--删除所有出口卷按钮 deleteByProcessNo
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel deleteAllstack(String vPlanNo, String vObjectNoVt,
			String vMaterialNo, String vMchCode, String vOprName) 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);
		
		Integer v_cnt;
		if(vPlanNo==null || "".equals(vPlanNo)){
			r.setMsgInfo("请输入计划号");
			return r;
		}
		if(vObjectNoVt==null || "".equals(vObjectNoVt)){
			r.setMsgInfo("请输入虚拟卷号");
			return r;
		}
		if(vMaterialNo==null || "".equals(vMaterialNo)){
			r.setMsgInfo("请输入原料卷号");
			return r;
		}
		if(vMchCode==null || "".equals(vMchCode)){
			r.setMsgInfo("请输入机台代码");
			return r;
		}
		// 验证轧机作业计划主记录存在
		PlnRollingPlan psp=new PlnRollingPlan();
		psp.setMachine_code(vMchCode);
		psp.setRl_plan_no(vPlanNo);
		int count = this.getMapper(PlnRollingPlanMapper.class).count(psp);
		if (count<=0) {
			throw new Exception("机台代码："+vMchCode+"\n作业计划号："+vPlanNo+"\n作业计划主记录不存在！");
		}
			
		// (4.2)、验证轧机作业计划明细记录存在
		PlnRollingPlanDetail pcpd=new PlnRollingPlanDetail();
		pcpd.setMachine_code(vMchCode);
		pcpd.setRl_plan_no(vPlanNo);
		pcpd.setObject_no_vt(vObjectNoVt);
		pcpd.setObject_no(vMaterialNo);
		int count2 = this.getMapper(PlnRollingPlanDetailMapper.class).count(pcpd);
		if (count2<=0) {
			throw new Exception("机台代码："+vMchCode+"\n作业计划号："+vPlanNo+"\n虚拟卷号："+vObjectNoVt+""
					+ "\n原料卷号："+vMaterialNo+"\n作业计划明细记录不存在！");
		}
		// (4.3)、验证虚拟物料表中，原料卷计划信息存在
		PlnMaterielDetail pmd=new PlnMaterielDetail();
		pmd.setObject_no_vt(vObjectNoVt);
		int count3 = this.getMapper(PlnMaterielDetailMapper.class).count(pmd);
		if (count3<=0) {
			throw new Exception("虚拟卷号："+vObjectNoVt+"\n原料卷虚拟物料信息不存在！");
		}
		// (2.5)、验证轧机作业主实绩存在，且为“未交工”状态
		MesRcmM mCross = new MesRcmM();
		mCross.setMachine_code(vMchCode);
		mCross.setSchedule_no(vPlanNo);
		mCross.setMaterial_no_vt(vObjectNoVt);
		mCross.setMaterial_no(vMaterialNo);
		v_cnt = this.getBean(MesRcmMMapper.class).count(mCross);
		if (v_cnt<=0) {
			throw new Exception("原料卷号：" + vMaterialNo + "，当前不存在轧机作业主实绩，请确认是否已操作上料！");
		}
	    List<MesRcmM> lmcam = this.getMapper(MesRcmMMapper.class).find(mCross, 0, 0);
	    MesRcmM 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("原料卷号："+vMaterialNo+"当前已生产交工，不能删除出口卷！\n可取消交工，再进行此操作！");
	    }

		// 4、验证选中的出口卷实绩记录存在mes_cr_cross_cutting_d
		MesRcmD mcccd=new MesRcmD();
		mcccd.setProcess_no(v_rec_tpm.getProcess_no());
		count = this.getMapper(MesRcmDMapper.class).count(mcccd);
		if (count <= 0) {
			r.setMsgInfo("原料卷号：" + vMaterialNo + " 当前无出口卷实绩!");
			r.setState("500");
			return r;
		}
		// （5）、删除出口卷实绩记录
		this.getBean(MesRcmDMapper.class).deleteByProcessNo(v_rec_tpm.getProcess_no());
		
		//日志
		MesOprLog mol = new MesOprLog("车间MES", "可逆轧机作业管理", "删除所有出口卷", username, opr_time, v_rec_tpm.getMaterial_no(), null, null, null, null);
		this.getMapper(MesOprLogMapper.class).insert(mol);
		
		r.setState("200");
		r.setMsgInfo("删除所有出口卷成功!");		
		return r;
	}
	
	/***
	 * 动作处理--修改出口卷按钮  updateMescrcrossD  
	 * AIM_WDT  AIM_LEN  PACKING_TTL_WGT
	 * Coil_no()
	 *PACKING_BOX_WGT  PACKING_THR_WGT  	
       PLATE_CNT
	 * 
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel updateStack(MesRcmD ddd , String vPlanNo,String vObjectNoVt ,
			String vMaterialNo,String vMchCode,String vOprname) 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);
		
		Integer v_cnt;
		if(vPlanNo==null || "".equals(vPlanNo)){
			r.setMsgInfo("请输入计划号");
			return r;
		}
		if(vObjectNoVt==null || "".equals(vObjectNoVt)){
			r.setMsgInfo("请输入虚拟卷号");
			return r;
		}
		if(vMaterialNo==null || "".equals(vMaterialNo)){
			r.setMsgInfo("请输入原料卷号");
			return r;
		}
		if(vMchCode==null || "".equals(vMchCode)){
			r.setMsgInfo("请输入机台代码");
			return r;
		}
		if(ddd==null || ddd.getCoil_no()==null){
			r.setMsgInfo("请指定出口卷信息");
			return r;
		}
		
		// 1.验证轧机作业计划主记录存在
		PlnRollingPlan psp=new PlnRollingPlan();
		psp.setMachine_code(vMchCode);
		psp.setRl_plan_no(vPlanNo);
		int count = this.getMapper(PlnRollingPlanMapper.class).count(psp);
		if (count<=0) {
			throw new Exception("机台代码："+vMchCode+"\n作业计划号："+vPlanNo+"\n作业计划主记录不存在！");
		}			
		// 2验证轧机作业计划明细记录存在
		PlnRollingPlanDetail pcpd=new PlnRollingPlanDetail();
		pcpd.setMachine_code(vMchCode);
		pcpd.setRl_plan_no(vPlanNo);
		pcpd.setObject_no_vt(vObjectNoVt);
		pcpd.setObject_no(vMaterialNo);
		int count2 = this.getMapper(PlnRollingPlanDetailMapper.class).count(pcpd);
		if (count2<=0) {
			throw new Exception("机台代码："+vMchCode+"\n作业计划号："+vPlanNo+"\n虚拟卷号："+vObjectNoVt+""
					+ "\n原料卷号："+vMaterialNo+"\n作业计划明细记录不存在！");
		}
		// (4.3)、验证虚拟物料表中，原料卷计划信息存在
		PlnMaterielDetail pmd=new PlnMaterielDetail();
		pmd.setObject_no_vt(vObjectNoVt);
		int count3 = this.getMapper(PlnMaterielDetailMapper.class).count(pmd);
		if (count3<=0) {
			throw new Exception("虚拟卷号："+vObjectNoVt+"\n原料卷虚拟物料信息不存在！");
		}
		// (2.5)、验证轧机作业主实绩存在，且为“未交工”状态
		MesRcmM mCross = new MesRcmM();
		mCross.setMachine_code(vMchCode);
		mCross.setSchedule_no(vPlanNo);
		mCross.setMaterial_no_vt(vObjectNoVt);
		mCross.setMaterial_no(vMaterialNo);
		v_cnt = this.getBean(MesRcmMMapper.class).count(mCross);
		if (v_cnt<=0) {
			throw new Exception("原料卷号：" + vMaterialNo + "，当前不存在轧机作业主实绩，请确认是否已操作上料！");
		}
	    List<MesRcmM> lmcam = this.getMapper(MesRcmMMapper.class).find(mCross, 0, 0);
	    MesRcmM 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("原料卷号："+vMaterialNo+"当前已生产交工，不能修改出口卷！\n可取消交工，再进行此操作！");
	    }
		// 4 验证选中的出口卷实绩记录存在
		MesRcmD mcccd=new MesRcmD();
		mcccd.setProcess_no(v_rec_tpm.getProcess_no());
		v_cnt =this.getMapper(MesRcmDMapper.class).count(mcccd);
		if (v_cnt <= 0) {
			r.setMsgInfo("原料卷号：" + v_rec_tpm.getMaterial_no() + "，出口卷实绩记录不存在！");
			r.setState("500");
			return r;
		}		
		MesRcmD v_rec_ccd = this.getMapper(MesRcmDMapper.class).findById(ddd.getCoil_no());
		if (!v_rec_ccd.getProcess_no().equals(v_rec_tpm.getProcess_no())) {
			r.setMsgInfo("出口卷：" + ddd.getCoil_no() + "，原料卷号与轧机作业主实绩不匹配！");
			r.setState("500");
			return r;
		}
		//5、修改出口卷实绩记录
		MesRcmD mtd=new MesRcmD();
		mtd.setCoil_no(ddd.getCoil_no());
		mtd.setAct_len(ddd.getAct_len());
		mtd.setAct_thk(ddd.getAct_thk());
		mtd.setAct_inn_dia(ddd.getAct_inn_dia());
		mtd.setAct_out_dia(ddd.getAct_out_dia());
		mtd.setAct_wdt(ddd.getAct_wdt());
		mtd.setUpdate_opr(username);
		this.getMapper(MesRcmDMapper.class).doUpdate1(mtd);
			
		boolean flag_houkuanchang=true;//计划那边给足了厚、宽、长。
		// （10）、逐一循环出口卷实绩（边丝物料除外），验证各出口卷的 厚、宽、长、实重 都＞0
		double v_sum=0;//理重计算值
		List<MesRcmD> listD=	this.getMapper(MesRcmDMapper.class).FindMescrcrDByprocessNo(v_rec_tpm.getProcess_no());
		for (MesRcmD  cur_01 : listD) {
			if(cur_01.getAct_thk() ==null || cur_01.getAct_thk() <= 0){
				flag_houkuanchang=false;
			}
			if(cur_01.getAct_wdt() ==null || cur_01.getAct_wdt() <= 0){
				flag_houkuanchang=false;
			}
			if(cur_01.getAct_len() ==null || cur_01.getAct_len() <= 0){
				flag_houkuanchang=false;
			}
			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());
		}
		if(flag_houkuanchang){
			   // （10'）、逐一循环出口卷实绩（边丝物料除外），重新计算各出口卷理重值：= 原卷理重 * （宽度*长度*块数）/ ∑（宽度*长度*块数）
		   List<MesRcmD> lmccd = this.getMapper(MesRcmDMapper.class).doQueryMes(v_rec_tpm.getProcess_no());
		   double lastWgt=0;
		   for(MesRcmD d:lmccd){
			   // （10.1'）、前N-1个出口卷理重 = 原卷理重 * （宽度*长度*厚度）/ ∑（宽度*长度*厚度）
			   //this.getMapper(MesRcmDMapper.class).updateMdd(v_sum,d.getCoil_no());
				//四舍五入
			   BigDecimal b=null;
			   double f1=0;
			   if(Integer.parseInt(d.getXh())<Integer.parseInt(d.getCnt())){
				   b= new BigDecimal(v_rec_tpm.getMtr_thr_wgt()*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(v_rec_tpm.getMtr_thr_wgt()-lastWgt);  
				   f1 = b.setScale(0, BigDecimal.ROUND_HALF_UP).doubleValue();
			   }
				MesRcmD mccccd=new MesRcmD();
				mccccd.setCoil_no(d.getCoil_no());
		   }
		}
		//日志
		MesOprLog mol = new MesOprLog("车间MES", "可逆轧机作业管理", "保存修改", username, opr_time, mtd.getCoil_no(), null, null, null, null);
		this.getMapper(MesOprLogMapper.class).insert(mol);
		
		r.setState("200");
		r.setMsgInfo("出口卷：" + ddd.getCoil_no() + "修改成功！");		
		return r;
	}
	
	/***
	 * 动作处理--删除出口卷  
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel deletesTack(String vPlanNo,String vObjectNoVt ,	String vMaterialNo ,
			 String vCoil_no,String vMchCode,String vOprname) 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);

		Integer v_cnt;
		try {
			if(vPlanNo==null || "".equals(vPlanNo)){
				r.setMsgInfo("请输入计划号");
				return r;
			}
			if(vObjectNoVt==null || "".equals(vObjectNoVt)){
				r.setMsgInfo("请输入虚拟卷号");
				return r;
			}
			if(vMaterialNo==null || "".equals(vMaterialNo)){
				r.setMsgInfo("请输入原料卷号");
				return r;
			}
			if(vMchCode==null || "".equals(vMchCode)){
				r.setMsgInfo("请输入机台代码");
				return r;
			}
			if(vCoil_no==null || "".equals(vCoil_no)){
				r.setMsgInfo("请指定出口卷信息");
				return r;
			}			
			// 1.验证横剪/轧机作业计划主记录存在
			//  --(4.1)、验证轧机作业计划主记录存在
			PlnRollingPlan psp=new PlnRollingPlan();
			psp.setMachine_code(vMchCode);
			psp.setRl_plan_no(vPlanNo);
			int count = this.getMapper(PlnRollingPlanMapper.class).count(psp);
			if (count<=0) {
				throw new Exception("机台代码："+vMchCode+"\n作业计划号："+vPlanNo+"\n作业计划主记录不存在！");
			}
				
			// 2验证轧机作业计划明细记录存在
			PlnRollingPlanDetail pcpd=new PlnRollingPlanDetail();
			pcpd.setMachine_code(vMchCode);
			pcpd.setRl_plan_no(vPlanNo);
			pcpd.setObject_no_vt(vObjectNoVt);
			pcpd.setObject_no(vMaterialNo);
			int count2 = this.getMapper(PlnRollingPlanDetailMapper.class).count(pcpd);
			if (count2<=0) {
				throw new Exception("机台代码："+vMchCode+"\n作业计划号："+vPlanNo+"\n虚拟卷号："+vObjectNoVt+""
						+ "\n原料卷号："+vMaterialNo+"\n作业计划明细记录不存在！");
			}
			// -(4.3)、验证虚拟物料表中，原料卷计划信息存在
			PlnMaterielDetail pmd=new PlnMaterielDetail();
			pmd.setObject_no_vt(vObjectNoVt);
			int count3 = this.getMapper(PlnMaterielDetailMapper.class).count(pmd);
			if (count3<=0) {
				throw new Exception("虚拟卷号："+vObjectNoVt+"\n原料卷虚拟物料信息不存在！");
			}
			// (2.5)、验证轧机作业主实绩存在，且为“未交工”状态
			MesRcmM mCross = new MesRcmM();
			mCross.setMachine_code(vMchCode);
			mCross.setSchedule_no(vPlanNo);
			mCross.setMaterial_no_vt(vObjectNoVt);
			mCross.setMaterial_no(vMaterialNo);
			v_cnt = this.getBean(MesRcmMMapper.class).count(mCross);
			if (v_cnt<=0) {
				throw new Exception("原料卷号：" + vMaterialNo + "，当前不存在轧机作业主实绩，请确认是否已操作上料！");
			}
		    List<MesRcmM> lmcam = this.getMapper(MesRcmMMapper.class).find(mCross, 0, 0);
		    MesRcmM 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("原料卷号："+vMaterialNo+"当前已生产交工，不能修改出口卷！\n可取消交工，再进行此操作！");
		    }
			// 4 验证选中的出口卷实绩记录存在
			MesRcmD mcccd=new MesRcmD();
			mcccd.setProcess_no(v_rec_tpm.getProcess_no());
			v_cnt =this.getMapper(MesRcmDMapper.class).count(mcccd);
			if (v_cnt <= 0) {
				r.setMsgInfo("原料卷号：" + v_rec_tpm.getMaterial_no() + "，出口卷实绩记录不存在！");
				r.setState("500");
				return r;
			}
			
			MesRcmD v_rec_ccd = this.getMapper(MesRcmDMapper.class).findById(vCoil_no);
			if (!v_rec_ccd.getProcess_no().equals(v_rec_tpm.getProcess_no())) {
				r.setMsgInfo("出口卷：" + vCoil_no + "，原料卷号与轧机作业主实绩不匹配！");
				r.setState("500");
				return r;
			}
			//（5）、边丝物料信息不允许删除，通过出口卷号最后一位等于大写字母B来判断
			if("B".equals(vCoil_no.substring(vCoil_no.length()-1))){
				r.setMsgInfo("边丝物料信息不允许删除！");
				r.setState("500");
				return r;
			}
			//（6）、删除出口卷实绩记录
			this.getMapper(MesRcmDMapper.class).delete(vCoil_no);
				
			boolean flag_houkuanchang=true;//计划那边给足了厚、宽、长。
			// （10）、逐一循环出口卷实绩（边丝物料除外），验证各出口卷的 厚、宽、长、实重 都＞0
			double v_sum=0;//理重计算值
			List<MesRcmD> listD=	this.getMapper(MesRcmDMapper.class).FindMescrcrDByprocessNo(v_rec_tpm.getProcess_no());
			for (MesRcmD  cur_01 : listD) {
				if(cur_01.getAct_thk() ==null || cur_01.getAct_thk() <= 0){
					flag_houkuanchang=false;
				}
				if(cur_01.getAct_wdt() ==null || cur_01.getAct_wdt() <= 0){
					flag_houkuanchang=false;
				}
				if(cur_01.getAct_len() ==null || cur_01.getAct_len() <= 0){
					flag_houkuanchang=false;
				}
				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());
			}
			if(flag_houkuanchang){
			   // （10'）、逐一循环出口卷实绩（边丝物料除外），重新计算各出口卷理重值：= 原卷理重 * （宽度*长度*块数）/ ∑（宽度*长度*块数）
			   List<MesRcmD> lmccd = this.getMapper(MesRcmDMapper.class).doQueryMes(v_rec_tpm.getProcess_no());
			   double lastWgt=0;
			   for(MesRcmD d:lmccd){
				   // （10.1'）、前N-1个出口卷理重 = 原卷理重 * （宽度*长度*厚度）/ ∑（宽度*长度*厚度）
				   //this.getMapper(MesRcmDMapper.class).updateMdd(v_sum,d.getCoil_no());
					//四舍五入
				   BigDecimal b=null;
				   double f1=0;
				   if(Integer.parseInt(d.getXh())<Integer.parseInt(d.getCnt())){
					   b= new BigDecimal(v_rec_tpm.getMtr_thr_wgt()*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(v_rec_tpm.getMtr_thr_wgt()-lastWgt);  
					   f1 = b.setScale(0, BigDecimal.ROUND_HALF_UP).doubleValue();
				   }
					MesRcmD mccccd=new MesRcmD();
					mccccd.setCoil_no(d.getCoil_no());
					mccccd.setCoil_thr_wgt(f1);
					this.getMapper(MesRcmDMapper.class).update(mccccd);
			   }
			}
			//日志
			MesOprLog mol = new MesOprLog("车间MES", "可逆轧机作业管理", "删除选中卷", username, opr_time, vCoil_no, null, null, null, null);
			this.getMapper(MesOprLogMapper.class).insert(mol);	
			
			r.setState("200");
			r.setMsgInfo("删除出口卷{" + vCoil_no + "}成功！");
		} catch (Exception e) {
			r.setState("500");
			r.setMsgInfo("删除出口卷失败");
			r.setErrorInfo(e.getMessage());
			throw new Exception(e.getMessage());
		}
		return  r;
	}
	
	/***
	 * 动作处理--打印标签按钮
	 * MesRcmD 轧机实绩  findAllByLabel
	 * @throws Exception 
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel printLabel(List<MesRcmD> listLabel,String v_source) 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);
		
		Integer v_cnt;
		// 1.逐一验证传入的出口卷号，对应的出口卷实绩存在
		try {
			if (listLabel.size() != 0) {
				for (MesRcmD s1 : listLabel) {
					MesRcmD s2=new MesRcmD();
					s2.setCoil_no(s1.getCoil_no());
					v_cnt = this.getMapper(MesRcmDMapper.class).count(s2);
					if (v_cnt <= 0) {
						r.setMsgInfo("出口卷号：" + s1.getCoil_no() + "出口卷记录不存在！");
						r.setState("500");
						return r;
					}
					MesRcmD mcccd = this.getMapper(MesRcmDMapper.class).findById(s1.getCoil_no());
					MesRcmM mrm=new MesRcmM();
					mrm.setProcess_no(mcccd.getProcess_no());
					List<MesRcmM> lmrm = this.getMapper(MesRcmMMapper.class).find(mrm, 0, 0);
					MesRcmM v_rec_mrm=lmrm.get(0);
					if(lmrm==null || lmrm.size()<=0){
						r.setMsgInfo("出口卷号：" + s1.getCoil_no() + "主实绩不存在");
						r.setState("500");
						return r;
					}
					if(v_rec_mrm.getWrk_date()==null || "".equals(v_rec_mrm.getWrk_date())){
				    	r.setState("500");
				    	r.setMsgInfo("原料卷号："+v_rec_mrm.getMaterial_no()+"作业日期为空，不能打印标签，请先填写完整并保存！");
						return r;
				    }
				    if(v_rec_mrm.getWrk_ord()==null || "".equals(v_rec_mrm.getWrk_ord())){
				    	r.setState("500");
				    	r.setMsgInfo("原料卷号："+v_rec_mrm.getMaterial_no()+"作业班次为空，不能打印标签，请先填写完整并保存！");
						return r;
				    }
				    if(v_rec_mrm.getWrk_grp()==null || "".equals(v_rec_mrm.getWrk_grp())){
				    	r.setState("500");
				    	r.setMsgInfo("原料卷号："+v_rec_mrm.getMaterial_no()+"作业班组为空，不能打印标签，请先填写完整并保存！");
						return r;
				    }
					if(mcccd.getCoil_act_wgt()==null || mcccd.getCoil_act_wgt()<=0){
						r.setMsgInfo("出口卷号："+s1.getCoil_no()+"，还未过磅，不能打印！");
						r.setState("500");
						return r;
					}
				}
				List<String> strList = new ArrayList<String>();
				for (MesRcmD s4 : listLabel) {
					strList.add(s4.getCoil_no());					
				}
				HashMap<String,Object> param = new HashMap<String,Object>();
				param.put("list", strList);
				List<RollingPrintView> list=new ArrayList<>();
				if ("out".equals(v_source)) {
					//物流出厂打印标签
					list=this.getMapper(MesRcmDMapper.class).doQueryPrintRcmOut(strList,"");
					for (String str : strList) {
						//日志
						MesOprLog mol = new MesOprLog("物流管理", "提货单管理", "打印标签预览", username, opr_time, str, null, null, null, null);
						this.getMapper(MesOprLogMapper.class).insert(mol);
					}
				}else {					
					// 使用优特钢内部标牌
					list=this.getMapper(MesRcmDMapper.class).doQueryPrint1(strList,"");
					for (String str : strList) {
						//日志
						MesOprLog mol = new MesOprLog("车间MES", "可逆轧机作业管理", "打印标签预览", username, opr_time, str, null, null, null, null);
						this.getMapper(MesOprLogMapper.class).insert(mol);
					}
				}
				//保存打印记录
				for(RollingPrintView d:list){
					MesTpmPrintLog log=new MesTpmPrintLog();
					BeanUtils.copyProperties(d, log);
					log.setId(UUID.randomUUID().toString());
					String userName=(String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
					log.setPrintname(userName);
					SimpleDateFormat dfm=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					log.setPrinttime(dfm.format(now));
					this.getMapper(MesTpmPrintLogMapper.class).insert(log);
				}								
				r.setState("200");
				r.setMsgInfo("打印标签成功");	
				r.setData(list);				
				return r;
			}
		} catch (Exception e) {
			r.setState("500");
			r.setMsgInfo("打印标签失败");
			e.printStackTrace();
			throw new Exception("打印标签失败");
		}
		return r;
	}
	
	// 补零
	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;
	}

}
