/***文档注释***********************************************
 * 作者            ：
 * 创建日期     ：2018-04-03
 * 描述            ：检验委托主表
 * 注意事项     ：
 * 遗留BUG   ：
 * 修改日期     ：
 * 修改人员     ：
 * 修改内容     ：
***********************************************************/
package market.Qms.qcm.service.impl;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import market.Com.mapper.ComBasePhyMapper;
import market.Com.mapper.ComBasePlineMapper;
import market.Com.mapper.ComPscMapper;
import market.Com.vo.ComBasePhy;
import market.Com.vo.ComBasePline;
import market.Com.vo.ComPsc;
import market.Com.vo.CommonPage;
import market.Com.vo.ResultModel;
import market.Qms.common.DataHelper;
import market.Qms.qcm.mapper.QcmJhySampleConsignDItemMapper;
import market.Qms.qcm.mapper.QcmJhySampleConsignDMapper;
import market.Qms.qcm.mapper.QcmJhySampleConsignMMapper;
import market.Qms.qcm.mapper.QcmJhySampleROrdMapper;
import market.Qms.qcm.mapper.SlmOrdDesignSampleMMapper;
import market.Qms.qcm.service.QcmJhySampleConsignMService;
import market.Qms.qcm.vo.QcmJhySampleConsignD;
import market.Qms.qcm.vo.QcmJhySampleConsignDItem;
import market.Qms.qcm.vo.QcmJhySampleConsignM;
import market.Qms.qcm.vo.QcmJhySampleFromPlan;
import market.Qms.qcm.vo.QcmJhySampleROrd;
import market.Qms.qcm.vo.SlmOrdDesignSampleM;
import market.Qms.qcm.vo.list;
import market.Qms.slmord.mapper.SlmOrdDesignMscMapper;
import market.Qms.slmord.mapper.SlmOrdDesignMscPlStiMapper;
import market.Qms.slmord.mapper.SlmOrdDesignStdCicSmpMapper;
import market.Qms.slmord.mapper.SlmOrdDesignStdMapper;
import market.Qms.slmord.vo.SlmOrdDesignMsc;
import market.Qms.slmord.vo.SlmOrdDesignMscPlSti;
import market.Qms.slmord.vo.SlmOrdDesignStd;
import market.Qms.slmord.vo.SlmOrdDesignStdCicSmp;

import org.springframework.transaction.annotation.Propagation;
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="QcmJhySampleConsignMService")
public class QcmJhySampleConsignMServiceImpl extends BaseServiceImpl<QcmJhySampleConsignM,Object> implements QcmJhySampleConsignMService {

	/**
	 * 检验委托管理-根据Design_key获取产品码
	 * Design_key
	 * */
	public ResultModel getPSC(CommonPage<SlmOrdDesignSampleM> sum){
		ResultModel rm=new ResultModel();
		try {
			SlmOrdDesignSampleM sm=sum.getObject();
			List<SlmOrdDesignSampleM> smlist=this.getMapper(SlmOrdDesignSampleMMapper.class).find(sm, 0, 0);
			Set<String> psclist=new HashSet<>();
			for(SlmOrdDesignSampleM ssm:smlist){
				psclist.add(ssm.getPsc());
			}
			rm.setData(psclist);
			rm.setState("200");
		} catch (Exception e) {
			rm.setState("500");
			rm.setMsgInfo("获取失败！"+e.getMessage());
		}
		return rm;
	}
	/**
	 *  检验委托管理-根据Design_key和产品码获取认证机构
	 *  Design_key
	 *  psc 产品码
	 * */
 	public ResultModel getRZJG(CommonPage<SlmOrdDesignSampleM> sum){
		ResultModel rm=new ResultModel();
		try {
			SlmOrdDesignSampleM ssm=sum.getObject();
			String Str="design_key='"+ssm.getDesign_key()+"' and psc='"+ssm.getPsc()+"'";
			List<SlmOrdDesignSampleM> smlist=this.getMapper(SlmOrdDesignSampleMMapper.class).findWithCondition(null, Str, null, 0, 0);
			Set<list> rzlist=new HashSet<>();
			for(SlmOrdDesignSampleM sm:smlist){
				list l=new list(sm.getOrg_code(),sm.getOrg_name());
				rzlist.add(l);
			}
			rm.setData(rzlist);
			rm.setState("200");
		} catch (Exception e) {
			rm.setMsgInfo("获取失败！"+e.getMessage());
			rm.setState("500");
		}
		return rm;
	}
	/**
	 *  检验委托管理-根据Design_key和产品码获取试样类型
	 *  Design_key
	 *  psc 产品码
	 * */
	public ResultModel getSYLX(CommonPage<SlmOrdDesignSampleM> sum){
		ResultModel rm=new ResultModel();
		try {
			SlmOrdDesignSampleM ssm=sum.getObject();
			String Str="design_key='"+ssm.getDesign_key()+"' and psc='"+ssm.getPsc()+"'";
			List<SlmOrdDesignSampleM> smlist=this.getMapper(SlmOrdDesignSampleMMapper.class).findWithCondition(null, Str, null, 0, 0);
			Set<list> rzlist=new HashSet<>();
			for(SlmOrdDesignSampleM sm:smlist){
				list l=new list(sm.getSample_style_code(), sm.getSample_style_name());
				rzlist.add(l);
			}
			rm.setData(rzlist);
			rm.setState("200");
		} catch (Exception e) {
			rm.setMsgInfo("获取失败！"+e.getMessage());
			rm.setState("500");
		}
		return rm;
	}
	/**
	 * 检验委托管理-查询检验委托信息
	 * sum.smp_no 试样号
	 * sum.heat_no 炉号
	 * sum.inspection_lot 检验号
	 * sum.cert_inst_name 认证机构名称
	 * */
	public ResultModel getInspectCom(CommonPage<QcmJhySampleConsignM> sum){
		ResultModel rm=new ResultModel();
		try {
			QcmJhySampleConsignM qm=sum.getObject();
			if(qm==null){
				rm.setState("500");
				rm.setMsgInfo("请传入参数！");
				return rm;
			}
			String Str="1=1";
			if(qm.getSmp_no()!=null&&!qm.getSmp_no().trim().equals("")){
				Str+=" and SMP_NO like '%"+qm.getSmp_no()+"%'";
			}
			if(qm.getHeat_no()!=null&&!qm.getSmp_no().trim().equals("")){
				Str+=" and HEAT_NO like '%"+qm.getHeat_no()+"%'";
			}
			if(qm.getInspection_lot()!=null&&!qm.getInspection_lot().trim().equals("")){
				Str+=" and INSPECTION_LOT like '%"+qm.getInspection_lot()+"%'";
			}
			if(qm.getCert_inst_name()!=null&&!qm.getCert_inst_name().trim().equals("")){
				Str+=" and CERT_INST_NAME  like '%"+qm.getCert_inst_name()+"%'";
			}
			List<QcmJhySampleConsignM> qsm=this.getMapper(QcmJhySampleConsignMMapper.class).findWithCondition(null, Str, "SMP_NO", 0, 0);
			for(QcmJhySampleConsignM m:qsm){
				String Str2=Str+" and SMP_TYPE_CODE='"+m.getSmp_type_code()+"'";
				List<QcmJhySampleROrd> qolist=this.getMapper(QcmJhySampleROrdMapper.class).findWithCondition(null, Str2, null, 0, 1);
				QcmJhySampleROrd qo=new QcmJhySampleROrd();
				if(qolist!=null&&qolist.size()!=0){
					qo=qolist.get(0);
				}
				m.setDesign_key(qo.getDesign_key());
				m.setContract_line_no(qo.getContract_line_no());
			}
			rm.setData(qsm);
			rm.setState("200");
		} catch (Exception e) {
			rm.setMsgInfo("获取失败!"+e.getMessage());
			rm.setState("500");
			e.printStackTrace();
		}
		return rm;
	}
	/**
	 * 检验委托管理-获取检验委托明细信息
	 * sum.smp_no 试样号
	 * memo1  判定状态
	 * */
	public ResultModel getEntrustCom(CommonPage<QcmJhySampleConsignD> sum){
		ResultModel rm=new ResultModel();
		try {
			QcmJhySampleConsignD qd=sum.getObject();
			if(qd==null||"".equals(qd.getSmp_no())){
				rm.setMsgInfo("请传入参数！");
				rm.setState("500");
				return rm;
			}
			String Str="1=1";
			if(qd.getSmp_no()!=null&&!qd.getSmp_no().trim().equals("")){
				Str+=" and SMP_NO='"+qd.getSmp_no()+"'";
			}
			if(sum.getMemo1()!=null&&!sum.getMemo1().trim().equals("")){
				Str+=" and STATUS='"+sum.getMemo1()+"'";
			}
			rm.setData(this.getMapper(QcmJhySampleConsignDMapper.class).findWithCondition(null, Str, "SPECIMEN_NO", 0, 0));
			rm.setState("200");
		} catch (Exception e) {
			rm.setMsgInfo("获取失败!");
			rm.setState("500");
			e.printStackTrace();
		}
		return rm;
	}
	
	/**
	 * 检验委托管理-验证试样号向下是否存在委托明细记录
	 * sum.smp_no 试样号
	 * */
	public ResultModel judgeInspectCom(CommonPage<QcmJhySampleConsignD> sum){
		ResultModel rm=new ResultModel();
		QcmJhySampleConsignD qd=sum.getObject();
		try {
			if(qd==null){
				rm.setMsgInfo("请传入参数！");
				rm.setState("500");
				return rm;
			}
			rm.setData(this.getMapper(QcmJhySampleConsignDMapper.class).count(qd)>=1);
			rm.setState("200");
		} catch (Exception e) {
			rm.setState("500");
			rm.setMsgInfo("获取失败！");
			e.printStackTrace();
		}
		return rm;
	}
	
	/**
	 * 检验委托管理-修改检验委托信息
	 * smp_no 试样号
	 * heat_no 炉号
	 * batch_no 轧批号
	 * inspection_lot 检验号
	 * smp_catg 试样类别（A：成分，B：材质）
	 * cert_inst_code 认证机构代码 
	 * cert_inst_name 认证机构名称 
	 * smp_type_code 试样类型代码 
	 * smp_type_name 试样类型名称 
	 * memo 备注
	 * psc 产品规范码
	 * */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doUpdateInspectCom(CommonPage<QcmJhySampleConsignM> sum)
	throws Exception{
		ResultModel rm=new ResultModel();
		String username = (String) this.getSession().getAttribute(
				HomeService.SESSION_USER_NAME);
		try {
			QcmJhySampleConsignM qm=sum.getObject();
			if(qm==null||qm.getSmp_no().trim().equals("")){
				rm.setMsgInfo("请传入参数！");
				rm.setState("500");
				return rm;
			}
			QcmJhySampleConsignM qmttt=this.getMapper(QcmJhySampleConsignMMapper.class).findById(qm.getSmp_no());
			if(qmttt==null||qmttt.getSmp_no().trim().equals("")){
				rm.setMsgInfo("对应试样号数据不存在！");
				rm.setState("500");
				return rm;
			}
//			判断传入参数是否正确
			if(qm.getSmp_catg().equals("B")){
				if(qm.getCert_inst_code()!=null||qm.getSmp_type_code()!=null){
					rm.setMsgInfo("【认证机构】、【试样类型】应为空");
					rm.setState("500");
					return rm;
				}
			}else{
				if(qm.getCert_inst_code()==null||qm.getSmp_type_code()==null){
					rm.setMsgInfo("【认证机构】、【试样类型】不能为空");
					rm.setState("500");
					return rm;
				}
			}
//			验证检验号向下是否已存在【认证机构】、【试样类型】分别等于传入的对应参数值的检验委托主信息
			String Str="1=1";
			if(qm.getCert_inst_code()!=null&&qm.getSmp_type_code()!=null){
				Str+=" and INSPECTION_LOT='"+qm.getInspection_lot()+"'";
				Str+=" and PSC='"+qm.getPsc()+"'";
				Str+=" and CERT_INST_CODE='"+qm.getCert_inst_code()+"'";
				Str+=" and SMP_TYPE_CODE='"+qm.getSmp_type_code()+"'";
			}
			List<QcmJhySampleConsignM> qmlist=this.getMapper(QcmJhySampleConsignMMapper.class).findWithCondition(null,Str, "SMP_NO", 0, 1);
			if(qmlist!=null&&qmlist.size()>0){
				rm.setState("500");
				rm.setMsgInfo(qm.getInspection_lot()+"向下已存在"+qm.getCert_inst_name()+"+"+
				qm.getSmp_type_name()+"的试样号记录！试样号："+qmlist.get(0).getSmp_no());
				return rm;
			}
//			更新主表
			QcmJhySampleConsignM qm2=this.getMapper(QcmJhySampleConsignMMapper.class).findById(qm.getSmp_no());
			qm2.setSmp_no(qm.getSmp_no());
			qm2.setHeat_no(qm.getHeat_no());
			qm2.setBatch_no(qm.getBatch_no());
			qm2.setInspection_lot(qm.getInspection_lot());
			qm2.setPsc(qm.getPsc());
			qm2.setSmp_catg(qm.getSmp_catg());
			qm2.setCert_inst_code(qm.getCert_inst_code());
			qm2.setCert_inst_name(qm.getCert_inst_name());
			qm2.setSmp_type_code(qm.getSmp_type_code());
			qm2.setSmp_type_name(qm.getSmp_type_name());
			qm2.setMemo(qm.getMemo());
			qm2.setUpdate_name(username);
			qm2.setUpdate_time(new Date());
			this.getMapper(QcmJhySampleConsignMMapper.class).update(qm2);
//			更新关系表
			List<QcmJhySampleROrd> qo=this.getMapper(QcmJhySampleROrdMapper.class).findWithCondition(null, "SMP_NO='"+qm.getSmp_no()+"'", null, 0, 0);
			for(QcmJhySampleROrd qr:qo){
			qr.setSmp_no(qm.getSmp_no());
			qr.setHeat_no(qm.getHeat_no());
			qr.setBatch_no(qm.getBatch_no());
			qr.setInspection_lot(qm.getInspection_lot());
			qr.setCert_inst_code(qm.getCert_inst_code());
			qr.setCert_inst_name(qm.getCert_inst_name());
			qr.setSmp_type_code(qm.getSmp_type_code());
			qr.setSmp_type_name(qm.getSmp_type_name());
			this.getMapper(QcmJhySampleROrdMapper.class).update(qr);
			}
			rm.setState("200");
		} catch (Exception e) {
			rm.setState("500");
			rm.setMsgInfo("修改失败！");
			e.printStackTrace();
			throw new Exception();
		}
		return rm;
	}
	
	/**
	 * 检验委托管理-删除检验委托信息
	 * smp_no 试样号
	 * */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doDeleteInspectCom(CommonPage<QcmJhySampleConsignM> sum)
	throws Exception{
		ResultModel rm=new ResultModel();
		try {
			List<QcmJhySampleConsignM> qmlist=sum.getObjectList();
			if(qmlist==null||qmlist.size()==0){
				rm.setMsgInfo("请传入参数！");
				rm.setState("500");
				return rm;
			}
			for(QcmJhySampleConsignM qm:qmlist){
				if(qm.getSmp_no().trim().equals("")){
					rm.setMsgInfo("请传入参数！");
					rm.setState("500");
					return rm;
				}
			List<QcmJhySampleConsignD> qd=this.getMapper(QcmJhySampleConsignDMapper.class).findWithCondition(null, "SMP_NO='"+qm.getSmp_no()+"'", null, 0, 0);
			if(qd.size()>0){
				rm.setMsgInfo("选中记录向下存在明细信息!");
				rm.setState("500");
				return rm;
			}
//			删除检验委托主表与试样号与合同信息关系表中对应记录
			this.getMapper(QcmJhySampleConsignMMapper.class).delete(qm.getSmp_no());
			this.getMapper(QcmJhySampleROrdMapper.class).doDeleteROrd(qm);
			}
			rm.setState("200");
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception();
		}
		return rm;
	}
	
	/**
	 * 检验委托管理-新增检验委托信息
	 * heat_no 炉号
	 * batch_no 轧批号
	 * inspection_lot 检验号
	 * smp_catg 试样类别（A：成分，B：材质）
	 * cert_inst_code 认证机构代码 
	 * cert_inst_name 认证机构名称 
	 * smp_type_code 试样类型代码 
	 * smp_type_name 试样类型名称 
	 * memo 备注
	 * 
	 * grade_code 炼钢牌号代码（通过检验号获取，计划模块提供）
	 * grade_name 炼钢牌号名称
	 * pline_code 产线代码（通过检验号获取，计划模块提供）
	 * pline_name 产线描述
     
	 * design_key DESIGN_KEY（来源于计划模块）
	 * contract_line_no 合同行号PK码（改判-改产品码写产品码PSC）
	 * psc 产品规范码
	 * */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doAddInspectCom(CommonPage<QcmJhySampleConsignM> sum)
	throws Exception{
		ResultModel rm=new ResultModel();
		String username = (String) this.getSession().getAttribute(
				HomeService.SESSION_USER_NAME);
		try {
			QcmJhySampleConsignM qm=sum.getObject();
			if(qm==null){
				rm.setMsgInfo("请传入参数！");
				rm.setState("500");
				return rm;
			}
//			判断传入参数是否正确
			if(qm.getSmp_catg().equals("B")){
				if(qm.getCert_inst_code()!=null||qm.getSmp_type_code()!=null){
					rm.setMsgInfo("【认证机构】、【试样类型】应为空");
					rm.setState("500");
					return rm;
				}
			}else{
				if(qm.getCert_inst_code()==null||qm.getSmp_type_code()==null){
					rm.setMsgInfo("【认证机构】、【试样类型】不能为空");
					rm.setState("500");
					return rm;
				}
			}
//			验证检验号向下是否已存在【认证机构】、【试样类型】分别等于传入的对应参数值的检验委托主信息
			String Str="1=1";
			if(qm.getCert_inst_code()!=null&&qm.getSmp_type_code()!=null){
				Str+=" and INSPECTION_LOT='"+qm.getInspection_lot()+"'";
				Str+=" and CERT_INST_CODE='"+qm.getCert_inst_code()+"'";
				Str+=" and SMP_TYPE_CODE='"+qm.getSmp_type_code()+"'";
			}
			List<QcmJhySampleConsignM> qmlist=this.getMapper(QcmJhySampleConsignMMapper.class)
					.findWithCondition(null,Str, "SMP_NO", 0, 0);
//			存在
			if(qmlist!=null&&qmlist.size()>=1){
//				获取关系表对应信息
				List<QcmJhySampleROrd> qolist=this.getMapper(QcmJhySampleROrdMapper.class)
						.findWithCondition(null,Str, "SMP_NO", 0, 0);
//				验证试样号向下是否包含选择的检验号对应的订单PK码信息
				for(QcmJhySampleROrd qo:qolist){
					String Str2="1=1";
					Str2+=" and SMP_NO='"+qo.getSmp_no()+"'";
					Str2+=" and CONTRACT_LINE_NO='"+qo.getContract_line_no()+"'";
					List<QcmJhySampleROrd> qdd=this.getMapper(QcmJhySampleROrdMapper.class)
							.findWithCondition(null, Str2, null, 0, 0);
//					如果包含
					if(qdd.size()>=1){
						rm.setState("500");
						rm.setMsgInfo(qm.getInspection_lot()+"向下已存在"+qm.getCert_inst_name()+"+"+
						qm.getSmp_type_name()+"的试样号记录！试样号："+qo.getSmp_no());
						return rm;
					}
				}	
//				如果不包含
//				插入试样号与合同信息关系表
				QcmJhySampleConsignM qtt=qmlist.get(0);
				QcmJhySampleROrd qord=new QcmJhySampleROrd();
				qord.setSmp_no(qtt.getSmp_no());
				qord.setBatch_no(qm.getBatch_no());
				qord.setHeat_no(qm.getHeat_no());
				qord.setInspection_lot(qm.getInspection_lot());
				qord.setCert_inst_code(qm.getCert_inst_code());
				qord.setCert_inst_name(qm.getCert_inst_name());
				qord.setSmp_type_code(qm.getSmp_type_code());
				qord.setSmp_type_name(qm.getSmp_type_name());
				qord.setPsc(qm.getPsc());
				qord.setDesign_key(qm.getDesign_key());
				qord.setContract_line_no(qm.getContract_line_no());
				this.getMapper(QcmJhySampleROrdMapper.class).insert(qord);
			}else{
//				不存在
//			创建试样号记录
			int count=0;
			List<QcmJhySampleConsignM> qlist=this.getMapper(QcmJhySampleConsignMMapper.class)
					.findWithCondition(null, null,"SMP_NO desc", 0, 0);
			if(qlist!=null&&qlist.size()>=1){
				String sn=qlist.get(0).getSmp_no();
				count=Integer.parseInt(sn.substring(sn.length()-3, sn.length()));
			}
			count++;
//			获取产线简写码
			//ComBasePline cp=this.getMapper(ComBasePlineMapper.class).findById("C013");
			SimpleDateFormat sdf=new SimpleDateFormat("yyMMdd");
			//String syh="Y"+cp.getPline_abbr()+"P"+sdf.format(new Date())+String.format("%03d",count);
			String syh="Y"+"123"+"P"+sdf.format(new Date())+String.format("%03d",count);
			
//			插入检验委托主表
			qm.setPline_code("998");
			qm.setSmp_no(syh);
			qm.setCreate_name(username);
			qm.setCreate_time(new Date());
			this.getMapper(QcmJhySampleConsignMMapper.class).insert(qm);
			
//			插入试样号与合同信息关系表
			QcmJhySampleROrd qord=new QcmJhySampleROrd();
			qord.setSmp_no(syh);
			qord.setBatch_no(qm.getBatch_no());
			qord.setHeat_no(qm.getHeat_no());
			qord.setInspection_lot(qm.getInspection_lot());
			qord.setDesign_key(qm.getDesign_key());
			qord.setContract_line_no("666");
			qord.setPsc(qm.getPsc());
			qord.setCert_inst_code(qm.getCert_inst_code());
			qord.setCert_inst_name(qm.getCert_inst_name());
			qord.setSmp_type_code(qm.getSmp_type_code());
			qord.setSmp_type_name(qm.getSmp_type_name());	
			this.getMapper(QcmJhySampleROrdMapper.class).insert(qord);
			}
			rm.setState("200");
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception();
		}
		return rm;
	}
	
/**
 * 检验委托管理-根据传入参数获取检验项
 * sum.design_key design_key
 * sum.psc 产品码
 * sum.org_code 认证机构
 * sum.sample_style_code 试样类型
 * */
	public ResultModel getPHYS(CommonPage<SlmOrdDesignSampleM> sum){
		ResultModel rm=new ResultModel();
		List<SlmOrdDesignSampleM> qjsm=sum.getObjectList();
		try {
			Set<SlmOrdDesignSampleM> sls=new HashSet<SlmOrdDesignSampleM>();
			for(SlmOrdDesignSampleM qm:qjsm){
				List<SlmOrdDesignSampleM> sl=this.getMapper(QcmJhySampleConsignMMapper.class).getPHYS(qm.getDesign_key(),qm.getOrg_code(),qm.getSample_style_code(),qm.getPsc());
				for(SlmOrdDesignSampleM qm2:sl){
					sls.add(qm2);
				}
				sls.add(sl.get(0));
			}
			rm.setState("200");
			rm.setData(sls);
		} catch (Exception e) {
			rm.setMsgInfo("获取失败！");
			rm.setState("500");
			e.printStackTrace();
		}
		return rm;
	}
	
	
/**
 * 自动生成检验委托信息
 * QCM_JHY_SAMPLE_R_ORD表和
 * QCM_JHY_SAMPLE_CONSIGN_M表信息
 * sum.design_key design_key
 * */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel getSYH(CommonPage<SlmOrdDesignSampleM> sum)
			throws Exception{
		String username = (String) this.getSession().getAttribute(
				HomeService.SESSION_USER_NAME);
		ResultModel rm=new ResultModel();
		try {
			QcmJhySampleConsignD ddd=new QcmJhySampleConsignD();
			ddd.setHeat_no("J71-10184A");
			ddd.setBatch_no("Batch001");
			ddd.setInspection_lot("Y1820177");
			ddd.setPline_code("C032");
			ddd.setPline_name("产线名称");
			
			SlmOrdDesignSampleM sm=sum.getObject();
			//插入到QCM_JHY_SAMPLE_R_ORD表的信息
			List<QcmJhySampleROrd> ord=new ArrayList<>();
//			插入QCM_JHY_SAMPLE_CONSIGN_M表的信息
			List<QcmJhySampleConsignM> qcm=new ArrayList<>();
			
			//design_key+认证机构+试样类型
			Set<QcmJhySampleROrd> slist=new HashSet<QcmJhySampleROrd>();
			//design_key+psc+认证机构+试样类型
			List<QcmJhySampleROrd> slist2=new ArrayList<>();
			//design_key->获取design_key对应的psc
			List<SlmOrdDesignSampleM> sl=this.getMapper(SlmOrdDesignSampleMMapper.class)
					.findWithCondition(null, "DESIGN_KEY='"+sm.getDesign_key()+"'", null, 0, 0);
			for(SlmOrdDesignSampleM s:sl){
				QcmJhySampleROrd slt=new QcmJhySampleROrd();
					slt.setDesign_key(s.getDesign_key());
//					认证机构					
					slt.setCert_inst_code(s.getOrg_code());
					slt.setCert_inst_name(s.getOrg_name());
//					试样类型				
					slt.setSmp_type_code(s.getSample_style_code());
					slt.setSmp_type_name(s.getSample_style_name());
					slist.add(slt);
					slt.setPsc(s.getPsc());
					slist2.add(slt);
			}
//			创建试样号记录
			int count=0;
			List<QcmJhySampleConsignM> qlist=this.getMapper(QcmJhySampleConsignMMapper.class)
					.findWithCondition(null, null,"SMP_NO desc", 0, 0);
			if(qlist!=null&&qlist.size()>=1){
				String sn=qlist.get(0).getSmp_no();
				count=Integer.parseInt(sn.substring(sn.length()-3, sn.length()));
			}
//			获取产线简写码
			ComBasePline cp=this.getMapper(ComBasePlineMapper.class).findById(ddd.getPline_code());
			SimpleDateFormat sdf=new SimpleDateFormat("yyMMdd");
			for(QcmJhySampleROrd q:slist){
				count++;
				String syh="Y"+cp.getPline_abbr()+"P"+sdf.format(new Date())+String.format("%03d",count);	
				q.setSmp_no(syh);	
			}
			for(QcmJhySampleROrd q:slist2){
				for(QcmJhySampleROrd q2:slist){
					if(q.equals(q2)){
						q.setSmp_no(q2.getSmp_no());
					}
				}
			}
			int counttt=0;
			for(QcmJhySampleROrd q:slist2){
//				插入QCM_JHY_SAMPLE_R_ORD表
				counttt++;
//				q.setAssay_no_cp("b");
//				q.setAssay_no_rl("b");
				q.setBatch_no(ddd.getBatch_no());
//				q.setCic_id("b");
				q.setContract_line_no("b"+counttt);
				q.setHeat_no(ddd.getHeat_no());
				q.setInspection_lot(ddd.getInspection_lot());
//				q.setJudge_memo("b");
//				q.setJudge_name("b");
//				q.setJudge_result_code("b");
//				q.setJudge_result_desc("b");
				q.setJudge_status("0");
//				q.setJudge_time(new Date());
//				q.setPhy_id("b");
//				q.setPic_id("b");
				q.setProduct_cnt(1L);
				q.setSmelting_cnt(1L);
				List<QcmJhySampleROrd> qpo=this.getMapper(QcmJhySampleROrdMapper.class).findWithCondition(null,
						"DESIGN_KEY='"+q.getDesign_key()
//						+"' and PSC='"+q.getPsc()
						+"' and CERT_INST_CODE='"+q.getCert_inst_code()
						+"' and SMP_TYPE_CODE='"+q.getSmp_type_code()
						+"'" , null, 0, 1);
				if(qpo.size()==0){
					ord.add(q);
				this.getMapper(QcmJhySampleROrdMapper.class).insert(q);
				}
//				插入QCM_JHY_SAMPLE_CONSIGN_M表
				QcmJhySampleConsignM q2=new QcmJhySampleConsignM();
				q2.setBatch_no(ddd.getBatch_no());
//				q2.setBoard_no("b");
				q2.setCert_inst_code(q.getCert_inst_code());
				q2.setCert_inst_name(q.getCert_inst_name());
				q2.setCreate_name(username);
				q2.setCreate_time(new Date());
				q2.setHeat_no(ddd.getHeat_no());
				q2.setInspection_lot(ddd.getInspection_lot());
//				q2.setMaterial_no("b");
				q2.setPline_code(ddd.getPline_code());
				q2.setPline_name(ddd.getPline_name());
				q2.setPsc(q.getPsc());
//				q2.setPsc_desc("b");
				q2.setSmp_catg("A");
				q2.setSmp_no(q.getSmp_no());
				q2.setSmp_type_code(q.getSmp_type_code());
				q2.setSmp_type_name(q.getSmp_type_name());
				q2.setValidflag("b");
				List<QcmJhySampleConsignM> qsm=this.getMapper(QcmJhySampleConsignMMapper.class).findWithCondition(null,
						"CERT_INST_CODE='"+q.getCert_inst_code()
						+"' and SMP_TYPE_CODE='"+q.getSmp_type_code()
						+"'" , null, 0, 1);
				if(qsm.size()==0)
				{
					qcm.add(q2);
					this.getMapper(QcmJhySampleConsignMMapper.class).insert(q2);
					}
			}		
			//根据插入的试样号的信息生成取样编号
		
//			ord为插入到QCM_JHY_SAMPLE_R_ORD表的数据
//			qcm为插入到QCM_JHY_SAMPLE_CONSIGN_M表的数据
//			循环试样号
			for(QcmJhySampleConsignM mmm:qcm){
				Set<SlmOrdDesignSampleM> slmSet=new HashSet<>();
//				获取试样号向下的检验项和取样频次
				for(QcmJhySampleROrd ooo:ord){
					if(mmm.getSmp_no().equals(ooo.getSmp_no())){
//						试样号对应SLM_ORD_DESIGN_SAMPLE_M表数据
						List<SlmOrdDesignSampleM> slm=this.getMapper(SlmOrdDesignSampleMMapper.class).findWithCondition(null, 
								"DESIGN_KEY='"+ooo.getDesign_key()
								+"' and PSC='"+ooo.getPsc()
								+"' and ORG_CODE='"+ooo.getCert_inst_code()
								+"' and SAMPLE_STYLE_CODE='"+ooo.getSmp_type_code()
								+"'", null, 0, 0);
//						检验项去重，检验项+取样频次相同则视为相同
						for(SlmOrdDesignSampleM slmt:slm){
							slmSet.add(slmt);
						}
					}
				}
//				检验项按取样频次分组
				Set<String> rate=new HashSet<>();
				for(SlmOrdDesignSampleM slm:slmSet){
					rate.add(slm.getRate_code());
				}
				
				int icount=0;
				Long qtt = 0L;
//				按组生成取样编号，并将信息插入
				for(String rt:rate){
					icount++;
//					取样编号
					String qyh=mmm.getSmp_no()+String.format("%02d", icount);
					
//					插入QCM_JHY_SAMPLE_CONSIGN_D表信息
					QcmJhySampleConsignD qd=new QcmJhySampleConsignD();
					qd.setSmp_no(mmm.getSmp_no());
					qd.setSpecimen_no(qyh);
//					qd.setAffirm_name("b");
//					qd.setAffirm_time(new Date());
//					qd.setAll_item_code("b");
					qd.setInspection_lot(mmm.getInspection_lot());
					qd.setBatch_no(mmm.getBatch_no());
					qd.setBoard_no(mmm.getBoard_no());
					qd.setFreq_code(mmm.getCert_inst_code());
					qd.setFreq_name(mmm.getCert_inst_name());
					qd.setHeat_no(mmm.getHeat_no());
					qd.setMaterial_no(mmm.getMaterial_no());
					qd.setPline_code(mmm.getPline_code());
					qd.setPline_name(mmm.getPline_name());
					qd.setSmp_type_code(mmm.getSmp_type_code());
					qd.setSmp_type_name(mmm.getSmp_type_name());
					this.getMapper(QcmJhySampleConsignDMapper.class).insert(qd);

					for(SlmOrdDesignSampleM slm:slmSet){
						if(slm.getRate_code().equals(rt)){
							
//														
//							插入QCM_JHY_SAMPLE_CONSIGN_D_ITEM表信息
							QcmJhySampleConsignDItem qdi=new QcmJhySampleConsignDItem();
							qdi.setSpecimen_no(qyh);
							qdi.setPhy_code_l(slm.getPhy_code_l());
							qdi.setPhy_code_m(slm.getPhy_code_m());
							qdi.setPhy_code_s(slm.getPhy_code_s());
							qdi.setPhy_name_l(slm.getPhy_name_m());
							qdi.setPhy_name_m(slm.getPhy_name_m());
							qdi.setPhy_name_s(slm.getPhy_name_s());
							qdi.setItem_code_d(slm.getItem_code_d());
							qdi.setItem_code_s(slm.getItem_code_s());
							qdi.setItem_code_t(slm.getItem_code_t());
							qdi.setItem_name_d(slm.getItem_name_d());
							qdi.setItem_name_s(slm.getItem_name_s());
							qdi.setItem_name_t(slm.getItem_name_t());
							qdi.setIs_send("0");
							qdi.setSeq(++qtt);
							this.getMapper(QcmJhySampleConsignDItemMapper.class).insert(qdi);
						}
					}
				}
			}
			rm.setState("200");
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception();	
		}
		return rm;
	}
	
	
	
	/**
	 * 自动生成检验委托
	 */
	@Transactional(propagation = Propagation.REQUIRES_NEW,value = "tm", rollbackFor = Exception.class)
	public ResultModel AutoGenerationSampleInfo(CommonPage<QcmJhySampleFromPlan> sum) throws Exception {

		ResultModel rm = new ResultModel();
		List<QcmJhySampleFromPlan> planAll = sum.getObjectList();
		String username = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);

		try {
			// 验证参数：1、判断参数是否存在；
			if (planAll == null || planAll.size() < 1) {
				rm.setMsgInfo("未寻到或无可生成检验委托的数据");
				rm.setState("500");
				return rm;
			}
			
			for (QcmJhySampleFromPlan plan : planAll) {
				
				if (plan.getInspection_lot()==null) {
					rm.setMsgInfo("存在检验号不存在的数据，请确认");
					rm.setState("500");
					return rm;
				}
				if (plan.getDesign_key()==null) {
					rm.setMsgInfo("存在design_key不存在的数据，请确认");
					rm.setState("500");
					return rm;
				}
				
				if (plan.getHeat_no()==null) {
					rm.setMsgInfo("存在炉号不存在的数据，请确认");
					rm.setState("500");
					return rm;
				}
				
				if (plan.getBatch_no()==null) {
					rm.setMsgInfo("存在扎批号不存在的数据，请确认");
					rm.setState("500");
					return rm;
				}
				
				if (plan.getMsc_pline()==null) {
					rm.setMsgInfo("存在全程产线号不存在的数据，请确认");
					rm.setState("500");
					return rm;
				}
				
				if (plan.getPline_code()==null) {
					rm.setMsgInfo("存在全程产线代码不存在的数据，请确认");
					rm.setState("500");
					return rm;
				}
				
				if (plan.getPline_name()==null) {
					rm.setMsgInfo("存在全程产线代码名称不存在的数据，请确认");
					rm.setState("500");
					return rm;
				}
				
				if (plan.getPline_seq()==null) {
					rm.setMsgInfo("存在全程工序顺序号不存在的数据，请确认");
					rm.setState("500");
					return rm;
				}
				
				if (plan.getProcess_code()==null) {
					rm.setMsgInfo("存在工序代码不存在的数据，请确认");
					rm.setState("500");
					return rm;
				}
				
				
				
			}
			
			

			// 验证是否是同一个检验批
			Set<String> Inspection_lotSet = new HashSet<String>();
			for (int i = 0; i < planAll.size(); i++) {
				Inspection_lotSet.add(planAll.get(i).getInspection_lot());

			}

			if (Inspection_lotSet.size() != 1) {
				rm.setMsgInfo("存在不属于同一检验批的数据");
				rm.setState("500");
				return rm;

			}

			// 判断检验号向下是否存在已发送数据
			List<QcmJhySampleConsignD> qd = this.getMapper(QcmJhySampleConsignDMapper.class).findWithCondition(null,
					"INSPECTION_LOT='" + planAll.get(0).getInspection_lot() + "' and STATUS!='0'", null, 0, 0);

			if (qd.size() > 0) {
				rm.setMsgInfo("检验批向下已经存在不属于未发送的数据，不能再组成检验批，请确认！");
				rm.setState("500");
				return rm;
			}

			// 判断是检验批还是改判批次
			List<SlmOrdDesignSampleM> qltyList = new ArrayList<SlmOrdDesignSampleM>();
			if ("1".equals(planAll.get(0).getJudge())) {
				// 数据源在改判批中获取

				/*
				 * List<QcmRejudgeApplyItem> listItems=planAll.get(0).getListItems(); for
				 * (QcmRejudgeApplyItem qi : listItems) { SlmOrdDesignSampleM sm=new
				 * SlmOrdDesignSampleM(); sm.setPsc(planAll.get(0).getPsc());
				 * sm.setIsjudge("1"); sm.setItem_code_d(qi.getItem_code_d());
				 * sm.setItem_code_s(qi.getItem_code_s());
				 * sm.setItem_code_t(qi.getItem_code_t());
				 * sm.setItem_name_d(qi.getItem_name_d());
				 * sm.setItem_name_s(qi.getItem_name_s());
				 * sm.setItem_name_t(qi.getItem_name_t()); sm.setPhy_code_l(qi.getPhy_code_l());
				 * sm.setPhy_code_m(qi.getPhy_code_m()); sm.setPhy_code_s(qi.getPhy_code_s());
				 * sm.setPhy_name_l(qi.getPhy_name_l()); sm.setPhy_name_m(qi.getPhy_name_m());
				 * sm.setPhy_name_s(qi.getPhy_name_s()); sm.setOrg_code("409601");
				 * sm.setOrg_name("检测中心"); sm.setSample_style_code(qi.getSample_style_code());
				 * sm.setSample_style_name(qi.getSample_style_name());
				 * sm.setRate_code(qi.getRate()); sm.setRate_desc(qi.getDesc_rate());
				 * qltyList.add(sm);
				 * 
				 * }
				 */

			} else {
				boolean judgement;
				// 过滤材质检验点
				List<QcmJhySampleFromPlan> qltyPlans = new ArrayList<QcmJhySampleFromPlan>();
				for (QcmJhySampleFromPlan qcmJhySampleFromPlan : planAll) {
					judgement = getJudgement(qcmJhySampleFromPlan, "403202");

					if (judgement == true) {
						qltyPlans.add(qcmJhySampleFromPlan);
					}

				}

				// 获取design_key的集合

				SlmOrdDesignSampleMMapper slmMmapper = this.getMapper(SlmOrdDesignSampleMMapper.class);

				for (QcmJhySampleFromPlan slmOrdDesignSampleM : qltyPlans) {
					
					//判断当前工序是不是最后一道有材质检验工序点的最后一道工序
					int count=slmOrdDesignSampleM.getPline_seq().intValue();
				    List<SlmOrdDesignMscPlSti> allStation=new ArrayList<SlmOrdDesignMscPlSti>();
				    count++;
				    	
				    for (; count < 100; count++) {
				    	allStation=this.getMapper(SlmOrdDesignMscPlStiMapper.class).findWithCondition(null, "DESIGN_KEY='"+slmOrdDesignSampleM.getDesign_key()+"' and MSC_PLINE=' "+slmOrdDesignSampleM.getMsc_pline()+"' and BACKLOG_SEQ='"+count+"'", null, 0, 0);
				    	
				    	if (allStation.size()>0) {
				    		boolean pass=judgePhyStation(allStation);
					    	if (pass) {
					    		//如果后面还存在材质类的工序点
								qltyList.addAll(slmMmapper.findWithCondition(null,
										"DESIGN_KEY='" + slmOrdDesignSampleM.getDesign_key() + "' and MSC_PLINE='"+slmOrdDesignSampleM.getMsc_pline()+"' and BACKLOG_SEQ='"+slmOrdDesignSampleM.getPline_seq().intValue()+"'", "INDEX_SEQ", 0, 0));
								break;
							}
							
						}else {
							//添加当前工序的
							qltyList.addAll(slmMmapper.findWithCondition(null,
									"DESIGN_KEY='" + slmOrdDesignSampleM.getDesign_key() + "' and MSC_PLINE='"+slmOrdDesignSampleM.getMsc_pline()+"' and BACKLOG_SEQ='"+slmOrdDesignSampleM.getPline_seq().intValue()+"'", "INDEX_SEQ", 0, 0));
				
							qltyList.addAll(slmMmapper.findWithCondition(null,
									"DESIGN_KEY='" + slmOrdDesignSampleM.getDesign_key() + "' and (BACKLOG_SEQ='0' or BACKLOG_SEQ is null)", "INDEX_SEQ", 0, 0));
				
							break;
							
						}
				    	
				    	
					}
				
					
						
					
					
					qltyList.addAll(slmMmapper.findWithCondition(null,
							"DESIGN_KEY='" + slmOrdDesignSampleM.getDesign_key() + "'", "INDEX_SEQ", 0, 0));
				}

			}

			// 材质试样信息的生成
			if (qltyList != null && qltyList.size() > 0) {

				// List<SlmOrdDesignSampleM> qltyOnlyOne = new
				// ArrayList<SlmOrdDesignSampleM>();
				// 去重

				// duplicateRemoval(qltyList, qltyOnlyOne);

				QcmJhySampleConsignMMapper qmMapper = this.getMapper(QcmJhySampleConsignMMapper.class);

				for (SlmOrdDesignSampleM slmM : qltyList) {

					String pline_code = null;
					String pline_name = null;
					String msc_pline = null;
					String heat_no = null;
					String batch_no = null;
					String inspection_lot = null;
					String design_key = slmM.getDesign_key();
					String grade_code = null;
					String grade_name = null;
					String contract_line_no = null;
					String order_no = null;
					String process_code = null;

					if (slmM.getDesign_key() == null) {
						for (QcmJhySampleFromPlan pl : planAll) {

							if (pl.getPsc().equals(slmM.getPsc())) {
								pline_code = pl.getPline_code();
								msc_pline = pl.getMsc_pline();
								heat_no = pl.getHeat_no();
								batch_no = pl.getBatch_no();
								grade_code = pl.getGrade_code();
								grade_name = pl.getGrade_name();
								pline_name = pl.getPline_name();
								contract_line_no = pl.getContract_line_no();
								inspection_lot = pl.getInspection_lot();
								order_no = pl.getOrder_no();
								process_code = pl.getProcess_code();
							}

						}

					} else {

						for (QcmJhySampleFromPlan pl : planAll) {

							if (pl.getDesign_key().equals(design_key)) {
								pline_code = pl.getPline_code();
								msc_pline = pl.getMsc_pline();
								heat_no = pl.getHeat_no();
								batch_no = pl.getBatch_no();
								grade_code = pl.getGrade_code();
								grade_name = pl.getGrade_name();
								pline_name = pl.getPline_name();
								contract_line_no = pl.getContract_line_no();
								inspection_lot = pl.getInspection_lot();
								order_no = pl.getOrder_no();
								process_code = pl.getProcess_code();
							}

						}

					}

					// 查询检验委托主表，检验号向下是否存在相同的试样类型和检验机构
					List<QcmJhySampleConsignM> searchMs = qmMapper.findWithCondition(
							null, "INSPECTION_LOT='" + inspection_lot + "' and SMP_TYPE_CODE='"
									+ slmM.getSample_style_code() + "' and CERT_INST_CODE='" + slmM.getOrg_code() + "'",
							null, 0, 0);

					// 通过design_key获取Psc描述
					ComPsc psc = this.getMapper(ComPscMapper.class).findById(slmM.getPsc());
					String pscDesc = psc.getPsc_desc();

					if (searchMs != null && searchMs.size() > 0) {

						String smp_no = searchMs.get(0).getSmp_no();

						List<QcmJhySampleROrd> old = new ArrayList<QcmJhySampleROrd>();

						if (slmM.getDesign_key() == null) {
							old = this.getMapper(QcmJhySampleROrdMapper.class).findWithCondition(null,
									"SMP_NO='" + smp_no + "' and PSC='" + slmM.getPsc() + "'", null, 0, 0);

						} else {
							old = this.getMapper(QcmJhySampleROrdMapper.class).findWithCondition(null,
									"SMP_NO='" + smp_no + "' and DESIGN_KEY='" + slmM.getDesign_key() + "' and PSC='"
											+ slmM.getPsc() + "'",
									null, 0, 0);
						}

						if (old.size() < 1) {

							// 添加到合同表
							QcmJhySampleROrd qord = new QcmJhySampleROrd();
							qord.setSmp_no(smp_no);
							qord.setBatch_no(batch_no);
							qord.setHeat_no(heat_no);
							qord.setInspection_lot(inspection_lot);
							qord.setDesign_key(design_key);
							qord.setPsc(slmM.getPsc());
							qord.setPsc_desc(pscDesc);
							if ("1".equals(planAll.get(0).getJudge())) {
								qord.setContract_line_no(slmM.getPsc());
							} else {
								qord.setContract_line_no(contract_line_no);
							}

							qord.setProcess_code(process_code);
							qord.setMsc_pline(msc_pline);
							qord.setOrder_no(order_no);
							qord.setCert_inst_code(slmM.getOrg_code());
							qord.setCert_inst_name(slmM.getOrg_name());
							qord.setSmp_type_code(slmM.getSample_style_code());
							qord.setSmp_type_name(slmM.getSample_style_name());
							this.getMapper(QcmJhySampleROrdMapper.class).insert(qord);
						}

						// 验证明细表是否存在

						List<QcmJhySampleConsignD> detail = this.getMapper(QcmJhySampleConsignDMapper.class)
								.findWithCondition(null,
										"SMP_NO='" + smp_no + "' and FREQ_CODE='" + slmM.getRate_code() + "'", null, 0,
										0);
						if (detail.size() > 0) {
							// 判断项目

							String targetItem = slmM.getPhy_code_s() + slmM.getPhy_code_l() + slmM.getPhy_code_m()
									+ slmM.getItem_code_d() + slmM.getItem_code_t() + slmM.getItem_code_s();

							List<QcmJhySampleConsignDItem> item = this.getMapper(QcmJhySampleConsignDItemMapper.class)
									.findWithCondition(null, "SPECIMEN_NO='" + detail.get(0).getSpecimen_no() + "'",
											null, 0, 0);

							for (int i = 0; i < item.size(); i++) {

								String oldItem = item.get(i).getPhy_code_s() + item.get(i).getPhy_code_l()
										+ item.get(i).getPhy_code_m() + item.get(i).getItem_code_d()
										+ item.get(i).getItem_code_t() + item.get(i).getItem_code_s();

								if (!targetItem.equals(oldItem)) {
									item.remove(item.get(i));
									i--;
								}

							}

							/*
							 * List<QcmJhySampleConsignDItem> item =
							 * this.getMapper(QcmJhySampleConsignDItemMapper. class)
							 * .findWithCondition(null, "SPECIMEN_NO='" + detail.get(0).getSpecimen_no() +
							 * "' and PHY_CODE_S='" + slmM.getPhy_code_s() + "' and PHY_CODE_L='" +
							 * slmM.getPhy_code_l() + "' and PHY_CODE_M='" + slmM.getPhy_code_m() +
							 * "' and ITEM_CODE_D='" + slmM.getItem_code_d() + "' and ITEM_CODE_T='" +
							 * slmM.getItem_code_t() + "' and ITEM_CODE_S='" + slmM.getItem_code_s() + "'",
							 * null, 0, 0);
							 */

							if (item.size() > 0) {
								continue;

							}

							// 创建项目
							QcmJhySampleConsignDItem consignDItem = new QcmJhySampleConsignDItem();
							// 取样编号
							consignDItem.setSpecimen_no(detail.get(0).getSpecimen_no());

							int count = this.getMapper(QcmJhySampleConsignDItemMapper.class).countWithCondition(null,
									"SPECIMEN_NO='" + detail.get(0).getSpecimen_no() + "'");
							long c = (long) ++count;
							consignDItem.setSeq(c);
							// 检验大项
							consignDItem.setPhy_code_l(slmM.getPhy_code_l());
							consignDItem.setPhy_name_l(slmM.getPhy_name_l());
							// 试样组代码
							consignDItem.setPhy_code_m(slmM.getPhy_code_m());
							consignDItem.setPhy_name_m(slmM.getPhy_name_m());
							// 检验项代码
							consignDItem.setPhy_code_s(slmM.getPhy_code_s());
							consignDItem.setPhy_name_s(slmM.getPhy_name_s());
							// 试验方向代码、试验温度代码、试样尺寸代码
							consignDItem.setItem_code_d(slmM.getItem_code_d());
							consignDItem.setItem_name_d(slmM.getItem_name_d());
							consignDItem.setItem_code_t(slmM.getItem_code_t());
							consignDItem.setItem_name_t(slmM.getItem_name_t());
							consignDItem.setItem_code_s(slmM.getItem_code_s());
							consignDItem.setItem_name_s(slmM.getItem_name_s());
							consignDItem.setPhy_item_code(DataHelper.Get00000(slmM.getPhy_code_l()) + "_"
									+ DataHelper.Get00000(slmM.getPhy_code_m()) + "_"
									+ DataHelper.Get00000(slmM.getPhy_code_s()) + "_"
									+ DataHelper.Get00000(slmM.getItem_code_d()) + "_"
									+ DataHelper.Get00000(slmM.getItem_code_t()) + "_"
									+ DataHelper.Get00000(slmM.getItem_code_s()));
							consignDItem.setPhy_item_desc(DataHelper.Get00000(slmM.getPhy_name_l()) + "_"
									+ DataHelper.Get00000(slmM.getPhy_name_m()) + "_"
									+ DataHelper.Get00000(slmM.getPhy_name_s()) + "_"
									+ DataHelper.Get00000(slmM.getItem_name_d()) + "_"
									+ DataHelper.Get00000(slmM.getItem_name_t()) + "_"
									+ DataHelper.Get00000(slmM.getItem_name_s()));

							// 根据材质检验项代码得到值单位
							if (slmM.getPhy_code_s() != null && !"".equals(slmM.getPhy_code_s())) {
								ComBasePhy comBasePhy = this.getMapper(ComBasePhyMapper.class)
										.findById(slmM.getPhy_code_s());
								consignDItem.setUnti(comBasePhy.getPhy_unit());

							}
							consignDItem.setIs_send("0");
							consignDItem.setCreate_name(username);
							this.getMapper(QcmJhySampleConsignDItemMapper.class).insert(consignDItem);

						} else {
							// 创建明细
							// 生成新的明细编号
							QcmJhySampleConsignD detailTable = new QcmJhySampleConsignD();
							// 取样编号
							String specimen_no = createSpecimen_no(smp_no, 1);
							// 试样号
							detailTable.setSmp_no(smp_no);

							// 取样编号
							detailTable.setSpecimen_no(specimen_no);
							// 炉号
							detailTable.setHeat_no(heat_no);
							// 轧批号不为空
							detailTable.setBatch_no(batch_no);
							// 检验号
							detailTable.setInspection_lot(inspection_lot);
							// 取样频率
							detailTable.setFreq_code(slmM.getRate_code());
							detailTable.setFreq_name(slmM.getRate_desc());
							// 样品类型代码
							detailTable.setSmp_type_code("409801");
							detailTable.setSmp_type_name("初样");
							// 委托编号
							detailTable.setConsign_no("");
							detailTable.setConsign_no_seq(null);
							// 试验次数
							detailTable.setTest_qty(1l);
							// 取样数量
							detailTable.setSmp_qty(1l);
							// 母板号
							// detailTable.setBatch_no(null);
							// 引用取样编号
							detailTable.setQuote_consign_no(null);
							// 初样取样编号（复样不能为空）
							detailTable.setOld_consign_no(null);
							// 产线代码
							detailTable.setPline_code(pline_code);
							detailTable.setPline_name(pline_name);
							// 状态(0,未发送,1,已发送,2,已接收,3,已完成)
							detailTable.setStatus("0");
							// 有效标志(1:有效，0:无效)
							if ("409601".equals(slmM.getOrg_code())) {
								detailTable.setValidflag("1");
							} else {
								detailTable.setValidflag("0");
							}

							if ("1".equals(planAll.get(0).getJudge())) {
								detailTable.setSource("1");
							} else {
								detailTable.setSource("0");
							}

							detailTable.setCreate_name(username);
							detailTable.setCreate_time(new Date());
							this.getMapper(QcmJhySampleConsignDMapper.class).insert(detailTable);

							int count = this.getMapper(QcmJhySampleConsignDItemMapper.class).countWithCondition(null,
									"SPECIMEN_NO='" + specimen_no + "'");
							// 创建项目
							QcmJhySampleConsignDItem consignDItem = new QcmJhySampleConsignDItem();
							// 取样编号
							consignDItem.setSpecimen_no(specimen_no);

							long c = (long) ++count;
							consignDItem.setSeq(c);
							// 检验大项
							consignDItem.setPhy_code_l(slmM.getPhy_code_l());
							consignDItem.setPhy_name_l(slmM.getPhy_name_l());
							// 试样组代码
							consignDItem.setPhy_code_m(slmM.getPhy_code_m());
							consignDItem.setPhy_name_m(slmM.getPhy_name_m());
							// 检验项代码
							consignDItem.setPhy_code_s(slmM.getPhy_code_s());
							consignDItem.setPhy_name_s(slmM.getPhy_name_s());
							// 试验方向代码、试验温度代码、试样尺寸代码
							consignDItem.setItem_code_d(slmM.getItem_code_d());
							consignDItem.setItem_name_d(slmM.getItem_name_d());
							consignDItem.setItem_code_t(slmM.getItem_code_t());
							consignDItem.setItem_name_t(slmM.getItem_name_t());
							consignDItem.setItem_code_s(slmM.getItem_code_s());
							consignDItem.setItem_name_s(slmM.getItem_name_s());
							consignDItem.setPhy_item_code(DataHelper.Get00000(slmM.getPhy_code_l()) + "_"
									+ DataHelper.Get00000(slmM.getPhy_code_m()) + "_"
									+ DataHelper.Get00000(slmM.getPhy_code_s()) + "_"
									+ DataHelper.Get00000(slmM.getItem_code_d()) + "_"
									+ DataHelper.Get00000(slmM.getItem_code_t()) + "_"
									+ DataHelper.Get00000(slmM.getItem_code_s()));
							consignDItem.setPhy_item_desc(DataHelper.Get00000(slmM.getPhy_name_l()) + "_"
									+ DataHelper.Get00000(slmM.getPhy_name_m()) + "_"
									+ DataHelper.Get00000(slmM.getPhy_name_s()) + "_"
									+ DataHelper.Get00000(slmM.getItem_name_d()) + "_"
									+ DataHelper.Get00000(slmM.getItem_name_t()) + "_"
									+ DataHelper.Get00000(slmM.getItem_name_s()));

							// 根据材质检验项代码得到值单位
							// 根据材质检验项代码得到值单位
							if (slmM.getPhy_code_s() != null && !"".equals(slmM.getPhy_code_s())) {
								ComBasePhy comBasePhy = this.getMapper(ComBasePhyMapper.class)
										.findById(slmM.getPhy_code_s());
								consignDItem.setUnti(comBasePhy.getPhy_unit());
							}
							consignDItem.setIs_send("0");
							consignDItem.setCreate_name(username);
							this.getMapper(QcmJhySampleConsignDItemMapper.class).insert(consignDItem);

						}

					} else {
						// 生成试样信息
						// 创建试样号

						String smp_no = createQltySamNo(pline_code);

						QcmJhySampleConsignM newQm = new QcmJhySampleConsignM();
						newQm.setSmp_no(smp_no);
						newQm.setBatch_no(batch_no);
						newQm.setInspection_lot(inspection_lot);
						newQm.setHeat_no(heat_no);
						newQm.setPsc(slmM.getPsc());
						newQm.setPsc_desc(pscDesc);
						newQm.setSmp_catg("B");
						newQm.setCert_inst_code(slmM.getOrg_code());
						newQm.setCert_inst_name(slmM.getOrg_name());
						newQm.setSmp_type_code(slmM.getSample_style_code());
						newQm.setSmp_type_name(slmM.getSample_style_name());
						// 通过计划模块获取，用检验号
						newQm.setPline_code(pline_code);
						newQm.setPline_name(pline_name);
						newQm.setGrade_code(grade_code);
						newQm.setGrade_name(grade_name);
						newQm.setValidflag("1");
						newQm.setCreate_name(username);
						newQm.setCreate_time(new Date());
						qmMapper.insert(newQm);

						// 插入试样号与合同信息关系表
						QcmJhySampleROrd qord = new QcmJhySampleROrd();
						qord.setSmp_no(smp_no);
						qord.setBatch_no(inspection_lot);
						qord.setHeat_no(heat_no);
						qord.setInspection_lot(inspection_lot);
						qord.setDesign_key(slmM.getDesign_key());
						qord.setPsc(slmM.getPsc());
						qord.setPsc_desc(pscDesc);
						qord.setMsc_pline(msc_pline);
						qord.setProcess_code(process_code);
						if ("1".equals(planAll.get(0).getJudge())) {
							qord.setContract_line_no(slmM.getPsc());
						} else {
							qord.setContract_line_no(contract_line_no);
						}
						qord.setOrder_no(order_no);
						qord.setCert_inst_code(slmM.getOrg_code());
						qord.setCert_inst_name(slmM.getOrg_name());
						qord.setSmp_type_code(slmM.getSample_style_code());
						qord.setSmp_type_name(slmM.getSample_style_name());
						this.getMapper(QcmJhySampleROrdMapper.class).insert(qord);

						// 生成新的明细编号
						QcmJhySampleConsignD detailTable = new QcmJhySampleConsignD();
						// 取样编号
						String specimen_no = createSpecimen_no(smp_no, 1);
						// 试样号
						detailTable.setSmp_no(smp_no);

						// 取样编号
						detailTable.setSpecimen_no(specimen_no);
						// 炉号
						detailTable.setHeat_no(heat_no);
						// 轧批号不为空
						detailTable.setBatch_no(batch_no);
						// 检验号
						detailTable.setInspection_lot(inspection_lot);
						// 取样频率
						detailTable.setFreq_code(slmM.getRate_code());
						detailTable.setFreq_name(slmM.getRate_desc());
						// 样品类型代码
						detailTable.setSmp_type_code("409801");
						detailTable.setSmp_type_name("初样");
						// 委托编号
						detailTable.setConsign_no("");
						detailTable.setConsign_no_seq(null);
						// 试验次数
						detailTable.setTest_qty(1l);
						// 取样数量
						detailTable.setSmp_qty(1l);
						// 母板号
						// detailTable.setBatch_no(null);
						// 引用取样编号
						detailTable.setQuote_consign_no(null);
						// 初样取样编号（复样不能为空）
						detailTable.setOld_consign_no(null);
						// 产线代码
						detailTable.setPline_code(pline_code);
						detailTable.setPline_name(pline_name);
						// 状态(0,未发送,1,已发送,2,已接收,3,已完成)
						detailTable.setStatus("0");
						// 有效标志(1:有效，0:无效)
						if ("1".equals(planAll.get(0).getJudge())) {
							detailTable.setSource("1");
						} else {
							detailTable.setSource("0");
						}
						// 有效标志(1:有效，0:无效)
						if ("409601".equals(slmM.getOrg_code())) {
							detailTable.setValidflag("1");
						} else {
							detailTable.setValidflag("0");
						}
						detailTable.setCreate_name(username);
						detailTable.setCreate_time(new Date());
						this.getMapper(QcmJhySampleConsignDMapper.class).insert(detailTable);

						int count = this.getMapper(QcmJhySampleConsignDItemMapper.class).countWithCondition(null,
								"SPECIMEN_NO='" + specimen_no + "'");
						// 创建项目
						QcmJhySampleConsignDItem consignDItem = new QcmJhySampleConsignDItem();
						// 取样编号
						consignDItem.setSpecimen_no(specimen_no);

						long c = (long) ++count;
						consignDItem.setSeq(c);
						// 检验大项
						consignDItem.setPhy_code_l(slmM.getPhy_code_l());
						consignDItem.setPhy_name_l(slmM.getPhy_name_l());
						// 试样组代码
						consignDItem.setPhy_code_m(slmM.getPhy_code_m());
						consignDItem.setPhy_name_m(slmM.getPhy_name_m());
						// 检验项代码
						consignDItem.setPhy_code_s(slmM.getPhy_code_s());
						consignDItem.setPhy_name_s(slmM.getPhy_name_s());
						// 试验方向代码、试验温度代码、试样尺寸代码
						consignDItem.setItem_code_d(slmM.getItem_code_d());
						consignDItem.setItem_name_d(slmM.getItem_name_d());
						consignDItem.setItem_code_t(slmM.getItem_code_t());
						consignDItem.setItem_name_t(slmM.getItem_name_t());
						consignDItem.setItem_code_s(slmM.getItem_code_s());
						consignDItem.setItem_name_s(slmM.getItem_name_s());
						consignDItem.setPhy_item_code(DataHelper.Get00000(slmM.getPhy_code_l()) + "_"
								+ DataHelper.Get00000(slmM.getPhy_code_m()) + "_"
								+ DataHelper.Get00000(slmM.getPhy_code_s()) + "_"
								+ DataHelper.Get00000(slmM.getItem_code_d()) + "_"
								+ DataHelper.Get00000(slmM.getItem_code_t()) + "_"
								+ DataHelper.Get00000(slmM.getItem_code_s()));
						consignDItem.setPhy_item_desc(DataHelper.Get00000(slmM.getPhy_name_l()) + "_"
								+ DataHelper.Get00000(slmM.getPhy_name_m()) + "_"
								+ DataHelper.Get00000(slmM.getPhy_name_s()) + "_"
								+ DataHelper.Get00000(slmM.getItem_name_d()) + "_"
								+ DataHelper.Get00000(slmM.getItem_name_t()) + "_"
								+ DataHelper.Get00000(slmM.getItem_name_s()));

						
						// 根据材质检验项代码得到值单位
						if (slmM.getPhy_code_s() != null && !"".equals(slmM.getPhy_code_s())) {
							ComBasePhy comBasePhy = this.getMapper(ComBasePhyMapper.class)
									.findById(slmM.getPhy_code_s());
							consignDItem.setUnti(comBasePhy.getPhy_unit());
						}
						// consignDItem.setUnti("998");
						consignDItem.setIs_send("0");
						consignDItem.setCreate_name(username);
						this.getMapper(QcmJhySampleConsignDItemMapper.class).insert(consignDItem);

					}

				}

			}

			/*
			 * 成分试样信息
			 */
			if ("0".equals(planAll.get(0).getJudge())) {

				List<SlmOrdDesignSampleM> chemLists = new ArrayList<SlmOrdDesignSampleM>();

				for (QcmJhySampleFromPlan pl2 : planAll) {

					// 查询质量设计主表
					SlmOrdDesignMsc slm = this.getMapper(SlmOrdDesignMscMapper.class).findById(pl2.getDesign_key());
					if (slm != null && slm.getSmp_index() != null) {
						chemLists.addAll(this.getMapper(SlmOrdDesignSampleMMapper.class).findWithCondition(null,
								"DESIGN_KEY='" + pl2.getDesign_key() + "'", null, 0, 0));
					}

				}

				// 创建试样号记录
				int counts = 0;
				List<QcmJhySampleConsignM> qlist = this.getMapper(QcmJhySampleConsignMMapper.class)
						.findWithCondition(null, "", " to_number(substr(smp_no,6)) desc", 0, 0);
				if (qlist != null && qlist.size() >= 1) {
					String sn = qlist.get(0).getSmp_no();
					counts = Integer.parseInt(sn.substring(sn.length() - 3, sn.length()));
				}
				counts++;

				// 获取产线简写码
				ComBasePline cp = this.getMapper(ComBasePlineMapper.class).findById(planAll.get(0).getPline_code());
				SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");

				if (chemLists != null && chemLists.size() > 0) {

					List<SlmOrdDesignSampleM> chemTargets = new ArrayList<SlmOrdDesignSampleM>();
					for (int j = 0; j < chemLists.size(); j++) {

						if (j == 0) {

							chemTargets.add(chemLists.get(j));
							continue;
						}
						String old = chemLists.get(j).getDesign_key() + chemLists.get(j).getPsc();
						for (int k = 0; k < chemTargets.size(); k++) {
							String test = chemTargets.get(k).getDesign_key() + chemTargets.get(k).getPsc();
							if (old.equals(test)) {
								break;
							}
							if (k == chemTargets.size() - 1) {
								chemTargets.add(chemLists.get(j));
							}
						}

					}

					for (SlmOrdDesignSampleM slmOrdDesignSampleM : chemTargets) {
						String design_key = slmOrdDesignSampleM.getDesign_key();
						List<SlmOrdDesignMscPlSti> slmOrdDesignMscPlSti = this
								.getMapper(SlmOrdDesignMscPlStiMapper.class).findWithCondition(null,
										"DESIGN_KEY='" + design_key + "' and MSC_PLINE='"
												+ planAll.get(0).getMsc_pline() + "' and PROCESS_CODE='"
												+ planAll.get(0).getProcess_code() + "'",
										null, 0, 0);
						List<SlmOrdDesignSampleM> chemAl = new ArrayList<SlmOrdDesignSampleM>();

						if (slmOrdDesignMscPlSti.size() > 0) {

							for (int i = 0; i < slmOrdDesignMscPlSti.size(); i++) {
								// 成分类检验工序
								if (slmOrdDesignMscPlSti.get(i).getProcess_point_type().equals("403201")) {

									chemAl.add(slmOrdDesignSampleM);
									break;
								}

							}

						}
						if (chemAl.size() < 1) {
							continue;
						}

						// 进行成分检验委托
						if (chemAl != null && chemAl.size() > 0) {

							int count = 0;

							for (SlmOrdDesignSampleM chem : chemAl) {

								String pline_code = null;
								String pline_name = null;
								String msc_pline = null;
								String heat_no = null;
								String batch_no = null;
								String inspection_lot = null;
								String grade_code = null;
								String grade_name = null;
								String contract_line_no = null;
								String order_no = null;
								String process_code = null;
								// 通过design_key获取Psc描述
								ComPsc psc = this.getMapper(ComPscMapper.class).findById(chem.getPsc());
								String pscDesc = psc.getPsc_desc();
								for (QcmJhySampleFromPlan pl : planAll) {

									if (pl.getDesign_key().equals(design_key)) {
										pline_code = pl.getPline_code();
										msc_pline = pl.getMsc_pline();
										heat_no = pl.getHeat_no();
										batch_no = pl.getBatch_no();
										grade_code = pl.getGrade_code();
										grade_name = pl.getGrade_name();
										pline_name = pl.getPline_name();
										contract_line_no = pl.getContract_line_no();
										order_no = pl.getOrder_no();
										inspection_lot = pl.getInspection_lot();
										process_code = pl.getProcess_code();
									}

								}

								String PSC = chem.getPsc();
								SlmOrdDesignStd slmOrdDesignStd = this.getMapper(SlmOrdDesignStdMapper.class)
										.findById(chem.getDesign_key(), PSC);
								if (slmOrdDesignStd != null) {
									String CIC = slmOrdDesignStd.getCic();

									List<SlmOrdDesignStdCicSmp> smp = this.getMapper(SlmOrdDesignStdCicSmpMapper.class)
											.findWithCondition(null,
													"DESIGN_KEY='" + chem.getDesign_key() + "' and CIC='" + CIC + "'",
													null, 0, 0);
									String rate = smp.get(0).getRate();
									String desc_rate = smp.get(0).getDesc_rate();

									List<QcmJhySampleConsignM> oldChemM = this
											.getMapper(QcmJhySampleConsignMMapper.class).findWithCondition(null,
													"INSPECTION_LOT='" + inspection_lot + "' and SMP_CATG='A'", null, 0,
													0);

									if (oldChemM.size() < 1) {

										String smp_no = "X" + cp.getPline_abbr() + "C" + sdf.format(new Date())
												+ String.format("%03d", counts++);
										QcmJhySampleConsignM qm = new QcmJhySampleConsignM();
										qm.setSmp_no(smp_no);
										qm.setBatch_no(batch_no);
										qm.setHeat_no(heat_no);
										qm.setCert_inst_code("409601");
										qm.setCert_inst_name("检测中心");
										qm.setSmp_type_code("409401");
										qm.setSmp_type_name("常规");
										qm.setInspection_lot(inspection_lot);
										qm.setPsc(PSC);
										qm.setPsc_desc(pscDesc);
										qm.setSmp_catg("A");
										qm.setPline_code(pline_code);
										qm.setPline_name(pline_name);
										qm.setGrade_code(grade_code);
										qm.setGrade_name(grade_name);
										qm.setValidflag("1");
										qm.setCreate_name(username);
										qm.setCreate_time(new Date());
										this.getMapper(QcmJhySampleConsignMMapper.class).insert(qm);

										// 插入试样号与合同信息关系表
										QcmJhySampleROrd qord = new QcmJhySampleROrd();

										SlmOrdDesignStd std = this.getMapper(SlmOrdDesignStdMapper.class)
												.findById(chem.getDesign_key(), PSC);
										Long product_cnt = std.getProduct_cnt() == null ? 0
												: std.getProduct_cnt() > (std.getProduct_cnt_k() == null ? 0
														: std.getProduct_cnt_k()) ? std.getProduct_cnt()
																: std.getProduct_cnt_k();
										Long smelting_cnt = std.getSmelting_cnt() == null ? 0
												: std.getSmelting_cnt() > (std.getSmelting_cnt_k() == null ? 0
														: std.getSmelting_cnt_k()) ? std.getSmelting_cnt()
																: std.getSmelting_cnt_k();
										qord.setProduct_cnt(product_cnt);
										qord.setSmelting_cnt(smelting_cnt);
										qord.setMsc_pline(msc_pline);
										qord.setProcess_code(process_code);
										qord.setSmp_no(smp_no);
										qord.setBatch_no(planAll.get(0).getBatch_no());
										qord.setHeat_no(planAll.get(0).getHeat_no());
										qord.setInspection_lot(planAll.get(0).getInspection_lot());
										qord.setDesign_key(chem.getDesign_key());
										qord.setPsc(PSC);
										qord.setContract_line_no(contract_line_no);
										qord.setOrder_no(order_no);
										qord.setPsc_desc(pscDesc);
										qord.setCert_inst_code("409601");
										qord.setCert_inst_name("检测中心");
										qord.setSmp_type_code("409401");
										qord.setSmp_type_name("常规");
										// 和同行pk码，暂用psc代替
										qord.setContract_line_no("测试");
										this.getMapper(QcmJhySampleROrdMapper.class).insert(qord);

										// 添加到明細表
										QcmJhySampleConsignD detailTable = new QcmJhySampleConsignD();

										detailTable.setSpecimen_no(createSpecimen_no(smp_no, count));
										detailTable.setSmp_no(smp_no);
										detailTable.setHeat_no(planAll.get(0).getHeat_no());
										detailTable.setBatch_no(planAll.get(0).getBatch_no());
										detailTable.setInspection_lot(planAll.get(0).getInspection_lot());
										detailTable.setFreq_code(rate);
										detailTable.setFreq_name(desc_rate);
										// detailTable.setMaterial_no(planAll.get(0).getMaterial_no());
										detailTable.setSmp_type_code("409801");
										detailTable.setSmp_type_name("初样");
										detailTable.setPline_code(pline_code);
										detailTable.setTest_qty(1l);
										detailTable.setSmp_qty(1l);
										detailTable.setPline_name(pline_name);
										detailTable.setCreate_name(username);
										detailTable.setCreate_time(new Date());
										this.getMapper(QcmJhySampleConsignDMapper.class).insert(detailTable);

									} else {

										for (QcmJhySampleConsignM qcmJhySampleConsignM : oldChemM) {
											List<QcmJhySampleConsignD> old = this
													.getMapper(QcmJhySampleConsignDMapper.class).findWithCondition(null,
															"SMP_NO='" + qcmJhySampleConsignM.getSmp_no()
																	+ "' and FREQ_CODE='" + rate + "'",
															null, 0, 0);

											if (old.size() < 1) {
												// 生成主表

												String smp_no = "X" + cp.getPline_abbr() + "C" + sdf.format(new Date())
														+ String.format("%03d", counts++);
												QcmJhySampleConsignM qm = new QcmJhySampleConsignM();
												qm.setSmp_no(smp_no);
												qm.setHeat_no(heat_no);
												qm.setBatch_no(batch_no);
												qm.setCert_inst_code("409601");
												qm.setCert_inst_name("检测中心");
												qm.setSmp_type_code("409401");
												qm.setSmp_type_name("常规");
												qm.setInspection_lot(inspection_lot);
												qm.setPsc(PSC);
												qm.setPsc_desc(pscDesc);
												qm.setSmp_catg("A");
												qm.setPline_code(pline_code);
												qm.setPline_name(pline_name);
												qm.setGrade_code(grade_code);
												qm.setGrade_name(grade_name);
												qm.setValidflag("1");
												qm.setCreate_name(username);
												qm.setCreate_time(new Date());
												this.getMapper(QcmJhySampleConsignMMapper.class).insert(qm);

												// 插入试样号与合同信息关系表
												QcmJhySampleROrd qord = new QcmJhySampleROrd();

												Long product_cnt = null;
												Long smelting_cnt = null;
												SlmOrdDesignStd std = this.getMapper(SlmOrdDesignStdMapper.class)
														.findById(chem.getDesign_key(), PSC);
												if (std.getProduct_cnt() == null && std.getProduct_cnt_k() == null) {
													product_cnt = 0l;
												} else if (std.getProduct_cnt() != null
														&& std.getProduct_cnt_k() != null) {
													product_cnt = std.getProduct_cnt() > std.getProduct_cnt_k()
															? std.getProduct_cnt()
															: std.getProduct_cnt_k();
												} else {
													if (std.getProduct_cnt() == null) {
														product_cnt = std.getProduct_cnt_k();
													} else {
														product_cnt = std.getProduct_cnt();
													}
												}
												if (std.getSmelting_cnt() == null && std.getSmelting_cnt_k() == null) {
													smelting_cnt = 0l;
												} else if (std.getSmelting_cnt() != null
														&& std.getSmelting_cnt_k() != null) {
													smelting_cnt = std.getSmelting_cnt() > std.getSmelting_cnt_k()
															? std.getSmelting_cnt()
															: std.getSmelting_cnt_k();
												} else {
													if (std.getSmelting_cnt() == null) {
														smelting_cnt = std.getSmelting_cnt_k();
													} else {
														smelting_cnt = std.getSmelting_cnt();
													}
												}

												qord.setProduct_cnt(product_cnt);
												qord.setSmelting_cnt(smelting_cnt);
												qord.setProcess_code(process_code);
												qord.setSmp_no(smp_no);
												qord.setBatch_no(batch_no);
												qord.setHeat_no(heat_no);
												qord.setInspection_lot(inspection_lot);
												qord.setDesign_key(chem.getDesign_key());
												qord.setPsc(PSC);
												qord.setMsc_pline(msc_pline);
												qord.setPsc_desc(pscDesc);
												qord.setCert_inst_code("409601");
												qord.setCert_inst_name("检测中心");
												qord.setSmp_type_code("409401");
												qord.setSmp_type_name("常规");
												// 和同行pk码，暂用psc代替
												qord.setContract_line_no(contract_line_no);
												qord.setOrder_no(order_no);
												this.getMapper(QcmJhySampleROrdMapper.class).insert(qord);

												// 添加到明細表
												QcmJhySampleConsignD detailTable = new QcmJhySampleConsignD();

												detailTable.setSpecimen_no(createSpecimen_no(smp_no, count));
												detailTable.setSmp_no(smp_no);
												detailTable.setPline_code(pline_code);
												detailTable.setHeat_no(heat_no);
												detailTable.setBatch_no(batch_no);
												detailTable.setInspection_lot(inspection_lot);
												detailTable.setFreq_code(rate);
												detailTable.setFreq_name(desc_rate);
												detailTable.setValidflag("1");
												detailTable.setStatus("0");
												detailTable.setTest_qty(1l);
												detailTable.setSmp_qty(1l);
												// detailTable.setMaterial_no(planAll.get(0).getMaterial_no());
												detailTable.setSmp_type_code("409801");
												detailTable.setSmp_type_name("初样");
												detailTable.setTest_qty(1l);
												detailTable.setSmp_qty(1l);

												detailTable.setCreate_name(username);
												detailTable.setCreate_time(new Date());
												this.getMapper(QcmJhySampleConsignDMapper.class).insert(detailTable);

											} else {

												// 验证合同关系表是否存在
												List<QcmJhySampleROrd> ords = this
														.getMapper(QcmJhySampleROrdMapper.class).findWithCondition(null,
																"SMP_NO='" + old.get(0).getSmp_no()
																		+ "' and DESIGN_KEY='" + chem.getDesign_key()
																		+ "' and PSC='" + PSC + "'",
																null, 0, 0);
												if (ords == null || ords.size() < 0) {

													// 生成合同表
													// 插入试样号与合同信息关系表
													QcmJhySampleROrd qord = new QcmJhySampleROrd();

													Long product_cnt = null;
													Long smelting_cnt = null;
													SlmOrdDesignStd std = this.getMapper(SlmOrdDesignStdMapper.class)
															.findById(chem.getDesign_key(), PSC);
													if (std.getProduct_cnt() == null
															&& std.getProduct_cnt_k() == null) {
														product_cnt = 0l;
													} else if (std.getProduct_cnt() != null
															&& std.getProduct_cnt_k() != null) {
														product_cnt = std.getProduct_cnt() > std.getProduct_cnt_k()
																? std.getProduct_cnt()
																: std.getProduct_cnt_k();
													} else {
														if (std.getProduct_cnt() == null) {
															product_cnt = std.getProduct_cnt_k();
														} else {
															product_cnt = std.getProduct_cnt();
														}
													}
													if (std.getSmelting_cnt() == null
															&& std.getSmelting_cnt_k() == null) {
														smelting_cnt = 0l;
													} else if (std.getSmelting_cnt() != null
															&& std.getSmelting_cnt_k() != null) {
														smelting_cnt = std.getSmelting_cnt() > std.getSmelting_cnt_k()
																? std.getSmelting_cnt()
																: std.getSmelting_cnt_k();
													} else {
														if (std.getSmelting_cnt() == null) {
															smelting_cnt = std.getSmelting_cnt_k();
														} else {
															smelting_cnt = std.getSmelting_cnt();
														}
													}
													qord.setProcess_code(process_code);
													qord.setProduct_cnt(product_cnt);
													qord.setSmelting_cnt(smelting_cnt);
													qord.setMsc_pline(msc_pline);
													qord.setSmp_no(old.get(0).getSmp_no());
													qord.setBatch_no(batch_no);
													qord.setHeat_no(heat_no);
													qord.setInspection_lot(inspection_lot);
													qord.setDesign_key(chem.getDesign_key());
													qord.setPsc(PSC);
													qord.setPsc_desc(pscDesc);
													qord.setCert_inst_code("409601");
													qord.setCert_inst_name("检测中心");
													qord.setSmp_type_code("409401");
													qord.setSmp_type_name("常规");
													// 和同行pk码，暂用psc代替
													qord.setContract_line_no(contract_line_no);
													qord.setOrder_no(order_no);
													this.getMapper(QcmJhySampleROrdMapper.class).insert(qord);

												}

											}

										}

									}

								}

							}

						}

					}

				}

			}

			rm.setState("200");
			rm.setMsgInfo("后台自动生成检验委托成功");

		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception(e.getMessage());

		}

		return rm;
	}
	
	/**
	 * 判定是成分、还是材质
	 */

	public boolean getJudgement(QcmJhySampleFromPlan qcmObject, String testType) {

		String Str = "1=1";
		Str += "and DESIGN_KEY='" + qcmObject.getDesign_key() + "'";
		Str += "and PROCESS_CODE='" + qcmObject.getProcess_code() + "'";
		Str += "and MSC_PLINE='" + qcmObject.getMsc_pline() + "'";
		Str += "and BACKLOG_SEQ='" + qcmObject.getPline_seq() + "'";
		List<SlmOrdDesignMscPlSti> lists = this.getMapper(SlmOrdDesignMscPlStiMapper.class).findWithCondition(null, Str,
				null, 0, 0);
		for (int i = 0; i < lists.size(); i++) {

			if (lists.get(i).getProcess_point_type().equals(testType)) {
				return true;
			}

		}

		return false;
	}
	
	private boolean judgePhyStation(List<SlmOrdDesignMscPlSti> allStation) {
		
		for (SlmOrdDesignMscPlSti sti : allStation) {
			if (sti.getProcess_point_type().equals("403202")) {
				return true;
			}
			
			
		}
		
		
		return false;
	}
	
	/**
	 * 生成取样编号
	 */

	private String createSpecimen_no(String smp_no, int counts) {

		int count = 0;
		List<QcmJhySampleConsignD> qlist = this.getMapper(QcmJhySampleConsignDMapper.class).findWithCondition(null,
				"SMP_NO='" + smp_no + "'", "SPECIMEN_NO desc", 0, 0);
		if (qlist != null && qlist.size() >= 1) {
			String sn = qlist.get(0).getSpecimen_no();
			count = Integer.parseInt(sn.substring(sn.length() - 2, sn.length()));
		}
		count++;
		String specimen_no = smp_no + String.format("%02d", count);

		return specimen_no;
	}
	
	
	/**
	 * 创建材质试样号
	 * 
	 * @throws Exception
	 */
	private String createQltySamNo(String msc_pline) throws Exception {
		// 获取产线简写码
		ComBasePline cp = this.getMapper(ComBasePlineMapper.class).findById(msc_pline);
		SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
		// 获取最大流水号
		int i = GetMaxSerialNo("QCM_JHY_SAMPLE_CONSIGN_M", "SMP_NO",
				"X" + cp.getPline_abbr() + "P" + sdf.format(new Date()));
		String syh = "X" + cp.getPline_abbr() + "P" + sdf.format(new Date()) + String.format("%03d", i + 1);

		return syh;
	}
	
	/**
	 * 获取流水号（对于有后缀的列不适用，如"20180815RP" 且该列去除前缀之后的值都为数字值
	 * 
	 * @author 上次修订 18/08/15
	 * @param table_name表名 colunmn列名 prefix前缀名（ 如果不存在前缀，且为数字值时可传空）
	 * @return 如果返回结果为-1 则表示表名和列名为空
	 * @throws Exception
	 */
	public int GetMaxSerialNo(String table_name, String colunmn, String prefix) throws Exception {
		int result = -1;
		if (table_name != null && !"".equals(table_name) && colunmn != null && !colunmn.equals("")) {
			result = this.getMapper(QcmJhySampleConsignMMapper.class).GetMaxSerialNo(table_name, colunmn, prefix);
		}
		return result;
	}

}
