/***文档注释***********************************************
 * 作者            ：
 * 创建日期     ：2018-04-04
 * 描述            ：检验委托明细项目表
 * 注意事项     ：
 * 遗留BUG   ：
 * 修改日期     ：
 * 修改人员     ：
 * 修改内容     ：
***********************************************************/
package market.Qms.qcm.service.impl;
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.QcmJhyPhyresultMapper;
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.QcmJhySampleConsignDItemService;
import market.Qms.qcm.vo.QcmJhyPhyresult;
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.QcmRejudgeApplyItem;
import market.Qms.qcm.vo.SlmOrdDesignSampleM;
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.beans.BeanUtils;
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;
import com.ibm.icu.text.SimpleDateFormat;

@RemoteService(path="QcmJhySampleConsignDItemService")
public class QcmJhySampleConsignDItemServiceImpl extends BaseServiceImpl<QcmJhySampleConsignDItem,Object> implements QcmJhySampleConsignDItemService {


	
	@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();

		try {

			// 参数验证
			boolean pass = validPass(planAll, rm);
			if (!pass) {
				return rm;
			}

			List<SlmOrdDesignSampleM> qltyList = new ArrayList<SlmOrdDesignSampleM>();
			if ("1".equals(planAll.get(0).getJudge())) {
				// 数据源在改判批中获取
				
			for (QcmJhySampleFromPlan sl : planAll) {
				List<SlmOrdDesignSampleM> randomList = new ArrayList<SlmOrdDesignSampleM>();
				List<QcmRejudgeApplyItem> listItems = planAll.get(0).getListItems();
				for (QcmRejudgeApplyItem qi : listItems) {
					SlmOrdDesignSampleM sm = new SlmOrdDesignSampleM();
					sm.setPsc(planAll.get(0).getPsc());
					sm.setJudge("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.setQuote_specimen_no(qi.getQuote_specimen_no());
					sm.setQuote_phy_code_l(qi.getQuote_phy_code_l());
					sm.setQuote_phy_code_m(qi.getQuote_phy_code_m());
					sm.setQuote_phy_code_s(qi.getQuote_phy_code_s());
					sm.setQuote_item_code_d(qi.getQuote_item_code_d());
					sm.setQuote_item_code_t(qi.getQuote_item_code_t());
					sm.setQuote_item_code_s(qi.getQuote_item_code_s());
					sm.setVal1(qi.getRe_v1());
					sm.setVal2(qi.getRe_v2());
					sm.setVal3(qi.getRe_v3());
					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());
					
					randomList.add(sm);

				}
				
				copyInfo(randomList, sl);
				qltyList.addAll(randomList);
				
			}
				
			} 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) {

					// 用来保存当前的材质项目集合
					List<SlmOrdDesignSampleM> qltyRandom = new ArrayList<SlmOrdDesignSampleM>();
					// 判断当前工序是不是最后一道有材质检验工序点的最后一道工序
					Long count = slmOrdDesignSampleM.getPline_seq();
					List<SlmOrdDesignMscPlSti> allStation = new ArrayList<SlmOrdDesignMscPlSti>();

					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 != null && allStation.size() > 0) {
						// 判断当前工序后是否存在材质类的工序点
						pass = judgePhyStation(allStation);
						if (pass) {
							// 如果后面还存在材质类的工序点
							qltyRandom = slmMmapper.findWithCondition(null,
									"DESIGN_KEY='" + slmOrdDesignSampleM.getDesign_key() + "' and MSC_PLINE='"
											+ slmOrdDesignSampleM.getMsc_pline() + "' and BACKLOG_SEQ='"
											+ slmOrdDesignSampleM.getPline_seq() + "' and ISCHECK='1'",
									"INDEX_SEQ", 0, 0);
							
							if (qltyRandom==null || qltyRandom.size()<1) {
								qltyRandom.addAll(
										slmMmapper.findWithCondition(null, "DESIGN_KEY='" + slmOrdDesignSampleM.getDesign_key()
												+ "' and (BACKLOG_SEQ='0' or BACKLOG_SEQ is null) and ISCHECK='1'", "INDEX_SEQ", 0, 0));

							}
							// 给项目赋予炉号等值，便于参数传递
							copyInfo(qltyRandom, slmOrdDesignSampleM);
							qltyList.addAll(qltyRandom);
							break;
						}

					} else {
						// 添加当前工序的

						qltyRandom.addAll(slmMmapper.findWithCondition(null,
								"DESIGN_KEY='" + slmOrdDesignSampleM.getDesign_key() + "' and MSC_PLINE='"
										+ slmOrdDesignSampleM.getMsc_pline() + "' and BACKLOG_SEQ='"
										+ slmOrdDesignSampleM.getPline_seq() + "' and ISCHECK='1'",
								"INDEX_SEQ", 0, 0));

						qltyRandom.addAll(
								slmMmapper.findWithCondition(null, "DESIGN_KEY='" + slmOrdDesignSampleM.getDesign_key()
										+ "' and (BACKLOG_SEQ='0' or BACKLOG_SEQ is null) and ISCHECK='1'", "INDEX_SEQ", 0, 0));

						// 给项目赋予炉号等值，便于参数传递
						copyInfo(qltyRandom, slmOrdDesignSampleM);
						qltyList.addAll(qltyRandom);

						//break;

					}

				}

			}

			/**
			 * 生成材质试样信息
			 */

			if (qltyList != null && qltyList.size() > 0) {
				ResultModel qr = createQltyInfo(qltyList);
				//可插入日志表
			}
			// 过滤成分，待优化
			if ("0".equals(planAll.get(0).getJudge())) {

				ResultModel cr=createChemInfo(planAll);
				//可插入日志表

			}

			rm.setState("200");
			rm.setMsgInfo("生成检验委托成功");
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("生成检验委托失败");
		}

		return rm;

	}

	@Transactional(value = "tm", rollbackFor = Exception.class)
	private ResultModel createChemInfo(List<QcmJhySampleFromPlan> planAll) throws Exception {

		ResultModel rm=new ResultModel();
		try {

			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) {
					
					List<SlmOrdDesignSampleM> tar=new ArrayList<>();
					tar=this.getMapper(SlmOrdDesignSampleMMapper.class).findWithCondition(null,
							"DESIGN_KEY='" + pl2.getDesign_key() + "'", null, 0, 0);
					//赋予炉号、轧批号等
					copyInfo(tar, pl2);
					chemLists.addAll(tar);
				}

			}

			// 如果成分目标集合不为0，进行成分试样检验
			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='" + slmOrdDesignSampleM.getMsc_pline()
											+ "' and PROCESS_CODE='" + slmOrdDesignSampleM.getProcess_code() + "'",
									null, 0, 0);

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

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

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

						}

					}

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

					for (SlmOrdDesignSampleM chem : chemAl) {
						ComPsc psc = this.getMapper(ComPscMapper.class).findById(chem.getPsc());
						String pscDesc = psc.getPsc_desc();
						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);
							
							if (smp==null || smp.size()<1) {
								rm.setState("500");
								rm.setMsgInfo("订单成分索引号“"+CIC+"”,为查询到关联的取样要求");
								return rm;
							}
							
							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='" + chem.getInspection_lot() + "' and SMP_CATG='A'", null,
											0, 0);

							if (oldChemM == null || oldChemM.size() < 1) {

								String smp_no = createChemSmpNo(chem, chem.getPline_code());
								// 试样信息主表信息
								createMainInfo(smp_no, chem, pscDesc, "C");
								String specimen_no = createSpecimen_no(smp_no);
								// 合同表信息
								createContract(smp_no, chem, pscDesc, "C");
								// 把成分取样频率赋予对象
								chem.setRate_code(rate);
								chem.setRate_desc(desc_rate);
								createDetail(specimen_no, smp_no, chem);

							} 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 == null || old.size() < 1) {
										String smp_no = createChemSmpNo(chem, chem.getPline_code());
										// 试样信息主表信息
										createMainInfo(smp_no, chem, pscDesc, "C");
										String specimen_no = createSpecimen_no(smp_no);
										// 合同表信息
										createContract(smp_no, chem, pscDesc, "C");
										// 把成分取样频率赋予对象
										chem.setRate_code(rate);
										chem.setRate_desc(desc_rate);
										createDetail(specimen_no, smp_no, chem);

									}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) {
											//创建合同信息
											createContract(old.get(0).getSmp_no(), chem, pscDesc, "C");		
										}
										
										
									}

								}

							}

						}

					}

				}

			}
			
			rm.setState("200");
			rm.setMsgInfo("成分试样信息生成成功");
			return rm;

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

	}

	/**
	 * 创建成分试样号
	 * 
	 * @param chem
	 * @param pline_code
	 * @return
	 * @throws Exception
	 */
	private String createChemSmpNo(SlmOrdDesignSampleM chem, String pline_code) throws Exception {

		try {
			ComBasePline cp = this.getMapper(ComBasePlineMapper.class).findById(pline_code);
			SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
			// 获取最大流水号
			int i = GetMaxSerialNo("QCM_JHY_SAMPLE_CONSIGN_M", "SMP_NO",
					"Y" + cp.getPline_abbr() + "C" + sdf.format(new Date()));
			String syh = "Y" + cp.getPline_abbr() + "C" + sdf.format(new Date()) + String.format("%03d", i + 1);
			return syh;

		} catch (Exception e) {
			throw new Exception("生成材质试样号失败");
		}

	}

	/**
	 * 获取流水号（对于有后缀的列不适用，如"20180815RP" 且该列去除前缀之后的值都为数字值
	 * 
	 * @author 上次修订 18/08/15
	 * @param table_name表名 colunmn列名 prefix前缀名（ 如果不存在前缀，且为数字值时可传空）
	 * @return 如果返回结果为-1 则表示表名和列名为空
	 * @throws Exception
	 */
	public int GetMaxSerialNo(String table_name, String colunmn, String prefix) {
		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;
	}

	/**
	 * 创建材质试样信息
	 * 
	 * @param qltyList
	 * @return
	 * @throws Exception
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	private ResultModel createQltyInfo(List<SlmOrdDesignSampleM> qltyList) throws Exception {

		ResultModel rm = new ResultModel();
		try {
			QcmJhySampleConsignMMapper qmMapper = this.getMapper(QcmJhySampleConsignMMapper.class);
			QcmJhySampleROrdMapper qoMapper = this.getMapper(QcmJhySampleROrdMapper.class);
			for (SlmOrdDesignSampleM qlty : qltyList) {

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

				// 通过design_key获取Psc描述
				ComPsc psc = this.getMapper(ComPscMapper.class).findById(qlty.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 (qlty.getDesign_key() == null || "".equals(qlty.getDesign_key())) {
						// 用于改判批，可能出现脱单，无dk
						old = qoMapper.findWithCondition(null,
								"SMP_NO='" + smp_no + "' and PSC='" + qlty.getPsc() + "'", null, 0, 0);
					} else {

						old = qoMapper.findWithCondition(null, "SMP_NO='" + smp_no + "' and DESIGN_KEY='"
								+ qlty.getDesign_key() + "' and PSC='" + qlty.getPsc() + "'", null, 0, 0);
					}

					// 判断合同表是否存在记录
					if (old == null || old.size() < 1) {
						// 新增合同表信息
						createContract(smp_no, qlty, pscDesc, "Q");

					}

					// 验证明细表是否存在
					List<QcmJhySampleConsignD> detail = this.getMapper(QcmJhySampleConsignDMapper.class)
							.findWithCondition(null,
									"SMP_NO='" + smp_no + "' and FREQ_CODE='" + qlty.getRate_code() + "'", null, 0, 0);

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

						// 生成取样编号
						String targetItem = qlty.getPhy_code_s() + qlty.getPhy_code_l() + qlty.getPhy_code_m()
								+ qlty.getItem_code_d() + qlty.getItem_code_t() + qlty.getItem_code_s();

						List<QcmJhySampleConsignDItem> item = new ArrayList<QcmJhySampleConsignDItem>();

						// 数据库中的项目，此处新平台不兼容改为此方式remove方法
						List<QcmJhySampleConsignDItem> items = new ArrayList<QcmJhySampleConsignDItem>();
						items = this.getMapper(QcmJhySampleConsignDItemMapper.class)
								.findBySec(detail.get(0).getSpecimen_no());

						item.addAll(items);

						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--;
							}

						}
						// 若项目大于0，则项目存在，遍历下个项目
						if (item.size() > 0) {
							continue;

						}

						// 创建项目
						QcmJhySampleConsignDItem i=createQltyItems(detail.get(0).getSpecimen_no(), qlty);

						if ("408601".equals(qlty.getRate_code())) {
							//quoteByLu(qlty, smp_no, detail.get(0).getSpecimen_no(),i);
							//quoteItemByLu(qlty, smp_no, detail.get(0).getSpecimen_no(),i);
						}

					} else {
						// 创建取样编号
						String specimen_no = createSpecimen_no(smp_no);

						// 创建
						createDetail(specimen_no, smp_no, qlty);
						// 创建项目
						QcmJhySampleConsignDItem i=createQltyItems(specimen_no, qlty);

						if ("408601".equals(qlty.getRate_code())) {
						//quoteByLu(qlty, smp_no, specimen_no,i);
						//quoteItemByLu(qlty, smp_no, specimen_no,i);
						}
					}

				} else {
					// 创建材质试样号
					String smp_no = createQltySamNo(qlty.getPline_code());
					// 创建主表信息
					createMainInfo(smp_no, qlty, pscDesc, "Q");
					// 创建合同表信息
					createContract(smp_no, qlty, pscDesc, "Q");
					// 创建取样编号
					String specimen_no = createSpecimen_no(smp_no);
					// 创建
					createDetail(specimen_no, smp_no, qlty);
					// 创建项目
					QcmJhySampleConsignDItem i=createQltyItems(specimen_no, qlty);

					if ("408601".equals(qlty.getRate_code())) {
						//quoteByLu(qlty, smp_no, specimen_no,i);
						//quoteItemByLu(qlty, smp_no, specimen_no,i);
					}
				}

			}

			rm.setState("200");
			rm.setMsgInfo("材质试样信息生成成功");
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}

		return rm;
	}

	/**
	 * 创建材质试样主表信息
	 * 
	 * @param smp_no
	 * @param pscDesc
	 * @param slmM
	 * @param type
	 * @throws Exception
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	private void createMainInfo(String smp_no, SlmOrdDesignSampleM slmM, String pscDesc, String type) throws Exception {
		// 生成新的明细编号
		String username = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		try {

			QcmJhySampleConsignM newQm = new QcmJhySampleConsignM();
			newQm.setSmp_no(smp_no);
			newQm.setBatch_no(slmM.getBatch_no());
			newQm.setInspection_lot(slmM.getInspection_lot());
			newQm.setBoard_no(slmM.getBoard_no());
			newQm.setHeat_no(slmM.getHeat_no());
			newQm.setPsc(slmM.getPsc());
			newQm.setPsc_desc(pscDesc);
			// 成分试样信息
			if ("C".equals(type)) {
				newQm.setCert_inst_code("409601");
				newQm.setCert_inst_name("检测中心");
				newQm.setSmp_type_code("409401");
				newQm.setSmp_type_name("常规");
				newQm.setSmp_catg("A");
			} else {
				// 材质试样信息
				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.setSmp_catg("B");
			}
			newQm.setMaterial_no(slmM.getMaterial_no());
			newQm.setPline_code(slmM.getPline_code());
			newQm.setPline_name(slmM.getPline_name());
			newQm.setGrade_code(slmM.getGrade_code());
			newQm.setGrade_name(slmM.getGrade_name());
			newQm.setValidflag("1");
			newQm.setCreate_name(username);
			newQm.setCreate_time(new Date());
			this.getMapper(QcmJhySampleConsignMMapper.class).insert(newQm);

		} catch (Exception e) {
			throw new Exception("生成检验委托主表信息失败");
		}

	}

	/**
	 * 创建材质试样号
	 * 
	 * @param pline_code
	 * @return
	 * @throws Exception
	 */
	private String createQltySamNo(String pline_code) throws Exception {
		// 获取产线简写码

		try {
			ComBasePline cp = this.getMapper(ComBasePlineMapper.class).findById(pline_code);
			SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
			// 获取最大流水号
			int i = GetMaxSerialNo("QCM_JHY_SAMPLE_CONSIGN_M", "SMP_NO",
					"Y" + cp.getPline_abbr() + "P" + sdf.format(new Date()));
			String syh = "Y" + cp.getPline_abbr() + "P" + sdf.format(new Date()) + String.format("%03d", i + 1);
			return syh;

		} catch (Exception e) {
			throw new Exception("生成材质试样号失败");
		}

	}

	/**
	 * 创建明细项目
	 * 
	 * @param specimen_no
	 * @param smp_no
	 * @param qlty
	 * @throws Exception
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	private void createDetail(String specimen_no, String smp_no, SlmOrdDesignSampleM slmM) throws Exception {

		try {

			// 生成新的明细编号
			String username = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
			QcmJhySampleConsignD detailTable = new QcmJhySampleConsignD();
			detailTable.setSmp_no(smp_no);
			// 取样编号
			detailTable.setSpecimen_no(specimen_no);
			// 炉号
			detailTable.setHeat_no(slmM.getHeat_no());
			// 轧批号不为空
			detailTable.setBatch_no(slmM.getBatch_no());
			// 检验号
			detailTable.setInspection_lot(slmM.getInspection_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(slmM.getPline_code());
			detailTable.setPline_name(slmM.getPline_name());
			// 状态(0,未发送,1,已发送,2,已接收,3,已完成)
		    detailTable.setStatus("0");
			detailTable.setMaterial_no(slmM.getMaterial_no());
			// 有效标志(1:有效，0:无效)
			if ("409601".equals(slmM.getOrg_code())) {
				detailTable.setValidflag("1");
			} else {
				detailTable.setValidflag("0");
			}

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

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

		} catch (Exception e) {
			throw new Exception("插入检验委托明细表失败");
		}

	}

	private String createSpecimen_no(String smp_no) {

		int count = GetMaxSerialNo("QCM_JHY_SAMPLE_CONSIGN_D", "SPECIMEN_NO", smp_no);
		/*
		 * 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()));666 } count++;
		 */
		String specimen_no = smp_no + String.format("%02d", count + 1);

		return specimen_no;

	}

	/**
	 * 创建公差项目
	 * 
	 * @param specimen_no
	 * @param qlty
	 * @throws Exception
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	private QcmJhySampleConsignDItem createQltyItems(String specimen_no, SlmOrdDesignSampleM slmM) throws Exception {

		QcmJhySampleConsignDItem consignDItem = new QcmJhySampleConsignDItem();
		try {
			String username = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
			Long seq = getItemSeq(specimen_no);
			// 创建项目
			
			consignDItem.setSpecimen_no(specimen_no);
			consignDItem.setSeq(seq);
			// 检验大项
			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.setGroup_seq(slmM.getGroup_seq());
			consignDItem.setIs_send("0");
			consignDItem.setCreate_name(username);
			if ("1".equals(slmM.getJudge())) {
				//改判新增逻辑
				if (slmM.getQuote_specimen_no()!=null && !"".equals(slmM.getQuote_specimen_no())) {
					consignDItem.setQuote_specimen_no(slmM.getQuote_specimen_no());
					consignDItem.setQuote_phy_code_l(slmM.getQuote_phy_code_l());
					consignDItem.setQuote_phy_code_m(slmM.getQuote_phy_code_m());
					consignDItem.setQuote_phy_code_s(slmM.getQuote_phy_code_s());
					consignDItem.setQuote_item_code_d(slmM.getQuote_item_code_d());
					consignDItem.setQuote_item_code_t(slmM.getQuote_item_code_t());
					consignDItem.setQuote_item_code_s(slmM.getQuote_item_code_s());
					QcmJhyPhyresult result = new QcmJhyPhyresult();
					DataHelper.CopyEntity(slmM, result);
					result.setSpecimen_no(specimen_no);
					result.setTest_qty(Long.valueOf("1"));
					result.setCreate_name(username);
					result.setCreate_time(new Date());
					Long SEQ=this.getMapper(QcmJhyPhyresultMapper.class).findMaxSeq(specimen_no);
					if (SEQ==null) {
						SEQ=(long) 1;
					}else{
						SEQ++;
					}
					result.setSeq(SEQ);
					this.getMapper(QcmJhyPhyresultMapper.class).insert(result);
				}
				
				
			}
			this.getMapper(QcmJhySampleConsignDItemMapper.class).insert(consignDItem);

		} catch (Exception e) {
			throw new Exception("插入项目信息失败！");
		}
		return consignDItem;

	}
	/**
	 * 批量新增项目
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel addMoreItems(CommonPage<SlmOrdDesignSampleM> sum) throws Exception{
		ResultModel rm=new ResultModel();
		try {
			String specimen_no=sum.getMemo1();
			if (specimen_no==null || "".equals(specimen_no)) {
				rm.setMsgInfo("请传入取样编号");
				rm.setState("500");
				return rm;
			}
			List<SlmOrdDesignSampleM> sms=sum.getObjectList();
			if (sms==null || sms.size()<1) {
				rm.setMsgInfo("请传入需要添加的项目");
				rm.setState("500");
				return rm;	
			}
			for (SlmOrdDesignSampleM s : sms) {
				createQltyItems(specimen_no, s);	
			}
			
			rm.setData(sms);
			rm.setState("200");
			rm.setMsgInfo("添加成功！");
		} catch (Exception e) {
			throw new Exception("添加项目失败");
		}
		
		
		return rm;
		
		
	}

	/**
	 * 获取材质检验项目流水
	 * 
	 * @param specimen_no
	 * @return
	 */
	private Long getItemSeq(String specimen_no) {

		Long count = 1l;

		List<QcmJhySampleConsignDItem> items = this.getMapper(QcmJhySampleConsignDItemMapper.class)
				.findWithCondition(null, "SPECIMEN_NO='" + specimen_no + "'", "SEQ desc", 0, 0);

		if (items != null && items.size() > 0) {
			count = items.get(0).getSeq() + 1;
		}

		return count;
	}

	/**
	 * 创建合同表内容
	 * 
	 * @param smp_no
	 * @param pscDesc
	 * @param qlty
	 * @throws Exception
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	private void createContract(String smp_no, SlmOrdDesignSampleM slmM, String pscDesc, String type) throws Exception {
		try {

			QcmJhySampleROrd qord = new QcmJhySampleROrd();
			qord.setSmp_no(smp_no);
			qord.setBatch_no(slmM.getBatch_no());
			qord.setHeat_no(slmM.getHeat_no());
			qord.setInspection_lot(slmM.getInspection_lot());
			qord.setDesign_key(slmM.getDesign_key());
			qord.setPsc(slmM.getPsc());
			qord.setPsc_desc(pscDesc);
			if ("1".equals(slmM.getJudge())) {
				qord.setContract_line_no(slmM.getPsc());
			} else {
				qord.setContract_line_no(slmM.getContract_line_no());
			}

			if ("C".equals(type)) {

				SlmOrdDesignStd std = this.getMapper(SlmOrdDesignStdMapper.class).findById(slmM.getDesign_key(),
						slmM.getPsc());
				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.setCert_inst_code("409601");
				qord.setCert_inst_name("检测中心");
				qord.setSmp_type_code("409401");
				qord.setSmp_type_name("常规");

			} else {
				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());

			}

			qord.setProcess_code(slmM.getProcess_code());
			qord.setMsc_pline(slmM.getMsc_pline());
			qord.setOrder_no(slmM.getOrder_no());
			this.getMapper(QcmJhySampleROrdMapper.class).insert(qord);

		} catch (Exception e) {
			throw new Exception("插入合同表失败");
		}

	}

	/**
	 * 给项目信息赋予炉号等信息
	 * 
	 * @param samples
	 * @param slmOrdDesignSampleM
	 */
	private void copyInfo(List<SlmOrdDesignSampleM> samples, QcmJhySampleFromPlan slmOrdDesignSampleM) {

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

			for (SlmOrdDesignSampleM s : samples) {
				s.setBatch_no(slmOrdDesignSampleM.getBatch_no());
				s.setContract_line_no(slmOrdDesignSampleM.getContract_line_no());
				s.setGrade_code(slmOrdDesignSampleM.getGrade_code());
				s.setGrade_name(slmOrdDesignSampleM.getGrade_name());
				s.setHeat_no(slmOrdDesignSampleM.getHeat_no());
				s.setInspection_lot(slmOrdDesignSampleM.getInspection_lot());
				s.setMaterial_no(slmOrdDesignSampleM.getMaterial_no());
				s.setMsc_pline(slmOrdDesignSampleM.getMsc_pline());
				if (!"1".equals(s.getJudge())) {
					s.setIndex_seq(Long.valueOf(slmOrdDesignSampleM.getPline_seq()));	
				}
				
				s.setOrder_no(slmOrdDesignSampleM.getOrder_no());
				s.setProcess_code(slmOrdDesignSampleM.getProcess_code());
				s.setPline_code(slmOrdDesignSampleM.getPline_code());
				s.setPline_name(slmOrdDesignSampleM.getPline_name());
				s.setBoard_no(slmOrdDesignSampleM.getBoard_no());
				s.setJudge(s.getJudge());
			}

		}

	}

	/**
	 * 判定是成分、还是材质
	 */

	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() + "'";
		Str +=" and PROCESS_POINT_TYPE='"+testType+"'";
		// 需要添加工序顺序号
		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;
			}

		}*/
		if (lists!=null && lists.size()>0) {
			
			return true;
		}

		return false;
	}

	/**
	 * 数据验证
	 * 
	 * @param planAll
	 * @param rm
	 * @return
	 */
	private boolean validPass(List<QcmJhySampleFromPlan> planAll, ResultModel rm) {

		if (planAll == null || planAll.size() < 1) {
			rm.setMsgInfo("未寻到或无可生成检验委托的数据");
			rm.setState("500");
			return false;
		}

		// 验证是否是同一个检验批
		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 false;

		}

		// 判断检验号向下是否存在已发送数据
		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 false;
		}

		return true;
	}

	/**
	 * 判断后续是否包含材质类的工序点
	 * 
	 * @param allStation
	 * @return
	 */
	private boolean judgePhyStation(List<SlmOrdDesignMscPlSti> allStation) {

		for (SlmOrdDesignMscPlSti sti : allStation) {
			if (sti.getProcess_point_type().equals("403202")) {
				return true;
			}

		}

		return false;
	}
	
	private void quoteItemByLu(SlmOrdDesignSampleM qlty,String smp_no, String specimen_no, QcmJhySampleConsignDItem i) {
		//获取按炉取样的，除当前取样编号的全用明细
		QcmJhySampleConsignDMapper dMapper = this.getMapper(QcmJhySampleConsignDMapper.class);
		List<QcmJhySampleConsignD> des = this.getMapper(QcmJhySampleConsignDMapper.class)
				.findWithCondition(null, "HEAT_NO='" + qlty.getHeat_no()
					 	+ "' and FREQ_CODE='408601' and SPECIMEN_NO !='"+specimen_no+"'",
						null, 0, 0);
	
		
		QcmJhySampleConsignDItem tar=findQuoteItem(i, des);
		i.setSpecimen_no(specimen_no);
		if (tar!=null) {
			i.setQuote_specimen_no(tar.getSpecimen_no());
			i.setQuote_item_code_d(tar.getItem_code_d());
			i.setQuote_item_code_s(tar.getItem_code_s());
			i.setQuote_item_code_t(tar.getItem_code_t());
			i.setQuote_phy_code_l(tar.getPhy_code_l());
			i.setQuote_phy_code_m(tar.getPhy_code_m());
		}
		
	}

	private QcmJhySampleConsignDItem findQuoteItem(QcmJhySampleConsignDItem i, List<QcmJhySampleConsignD> des) {
		QcmJhySampleConsignDItem old=new QcmJhySampleConsignDItem();
		old=i;
		for (QcmJhySampleConsignD qcmJhySampleConsignD : des) {
			old.setSpecimen_no(qcmJhySampleConsignD.getSpecimen_no() );
			String condition=createItemSql(i);
			List<QcmJhySampleConsignDItem> itams=this.getMapper(QcmJhySampleConsignDItemMapper.class).findWithCondition(null, condition, null, 0, 0);
			if (itams!=null && itams.size()>0) {
				QcmJhySampleConsignDItem tar=createDiGuiItem(itams.get(0));
				if (tar!=null) {
					return tar;
				}
			}
		
		}
		return null;
	}
	
	
	private QcmJhySampleConsignDItem createDiGuiItem(QcmJhySampleConsignDItem i) {
		
		if (i.getQuote_specimen_no()==null || "".equals(i.getQuote_specimen_no())) {
			return i;
		}
		
		String condition=createQuoteItemSQl(i);
		List<QcmJhySampleConsignDItem> itams=this.getMapper(QcmJhySampleConsignDItemMapper.class).findWithCondition(null, condition, null, 0, 0);
		if (itams!=null && itams.size()>0) {
			return createDiGuiItem(itams.get(0));
		}
		
		return null;
		
	}
	
	private String createQuoteItemSQl(QcmJhySampleConsignDItem tr) {
		String condition="SPECIMEN_NO='"+tr.getQuote_specimen_no()+"'";
		if (tr.getPhy_code_l()!=null && !"".equals(tr.getPhy_code_l())) {
			condition+=" and PHY_CODE_L='"+tr.getQuote_phy_code_l()+"'";
		}
		
		if (tr.getPhy_code_m()!=null && !"".equals(tr.getPhy_code_m())) {
			condition+=" and PHY_CODE_M='"+tr.getQuote_phy_code_m()+"'";
		}
		
		if (tr.getPhy_code_s()!=null && !"".equals(tr.getPhy_code_s())) {
			condition+=" and PHY_CODE_S='"+tr.getQuote_phy_code_s()+"'";
		}
		
		if (tr.getItem_code_d()!=null && !"".equals(tr.getItem_code_d())) {
			condition+=" and ITEM_CODE_D='"+tr.getQuote_item_code_d()+"'";
		}
		
		if (tr.getItem_code_t()!=null && !"".equals(tr.getItem_code_t())) {
			condition+=" and ITEM_CODE_T='"+tr.getQuote_item_code_t()+"'";
		}
		
		if (tr.getItem_code_s()!=null && !"".equals(tr.getItem_code_s())) {
			condition+=" and ITEM_CODE_S='"+tr.getQuote_item_code_s()+"'";
		}
		return condition;
	}

	/**
	 * 检验委托按炉自动引用功能
	 * @param i 
	 */
	private void quoteByLu(SlmOrdDesignSampleM qlty, String smp_no, String specimen_no, QcmJhySampleConsignDItem i) {

		// 判断当前取样编号是否引用
		QcmJhySampleConsignDMapper dMapper = this.getMapper(QcmJhySampleConsignDMapper.class);
		QcmJhySampleConsignD detail = dMapper.findById(smp_no, specimen_no);
		String newItem = qlty.getPhy_code_l() + qlty.getPhy_code_m() + qlty.getPhy_code_s() + qlty.getItem_code_d()
				+ qlty.getItem_code_s() + qlty.getItem_code_t();
		if (detail != null) {

			// 判断引用取样编号是否为空
			if (detail.getQuote_consign_no() != null && !"".equals(detail.getQuote_consign_no())) {

				List<QcmJhySampleConsignDItem> items = this.getMapper(QcmJhySampleConsignDItemMapper.class)
						.findWithCondition(null, "SPECIMEN_NO='" + detail.getQuote_consign_no() + "'", null, 0, 0);
				// 验证取样编号对应的项目是否为空
				if (items != null && items.size() > 0) {
					getQuote(qlty, specimen_no, detail, newItem, items);

				}

			}
			// 没有查询到引用取样编号
			else {
				//
				List<QcmJhySampleConsignD> des = this.getMapper(QcmJhySampleConsignDMapper.class)
						.findWithCondition(null, "HEAT_NO='" + qlty.getHeat_no()
								+ "' and FREQ_CODE='408601' and SPECIMEN_NO !='"+specimen_no+"'",
								null, 0, 0);
				//如果按炉取样的取样编号就是自身，不引用；
				if (des==null || des.size()<1) {
						return;
					
				}

				//遍历集合去除不是该试样类型的
				//List<QcmJhySampleConsignD> de=new ArrayList<>();
				for (QcmJhySampleConsignD qcmJhySampleConsignD : des) {
					QcmJhySampleConsignM m=this.getMapper(QcmJhySampleConsignMMapper.class).findById(qcmJhySampleConsignD.getSmp_no());
					if (m!=null) {
						QcmJhySampleConsignD tar = selectQuote(qcmJhySampleConsignD);
						if (tar == null) {
							// 若无可引用，不引用
							continue;
						} else {
							//如果引用取样编号就是本身，退出循环，此取样编号为第一层
							if (specimen_no.equals(tar.getSpecimen_no())) {
								return;
							}
							
							
							QcmJhySampleConsignD qd = new QcmJhySampleConsignD();
							String quoteCode = tar.getSpecimen_no();
							qd.setSmp_no(smp_no);
							qd.setSpecimen_no(specimen_no);
							qd.setQuote_consign_no(quoteCode);
							this.getMapper(QcmJhySampleConsignDMapper.class).update(qd);

							List<QcmJhySampleConsignDItem> items = this.getMapper(QcmJhySampleConsignDItemMapper.class)
									.findWithCondition(null, "SPECIMEN_NO='" + quoteCode + "'", null, 0, 0);
							// 验证取样编号对应的项目是否为空

							if (items != null && items.size() > 0) {
								getQuote(qlty, specimen_no, qd, newItem, items);
								//获取引用后跳出循环
								break;
							}

						}
						
						/*de.add(qcmJhySampleConsignD);
						
						break;*/
					}
				}
				
				
				

			}

		}

	}

	/**
	 * 获取引用方法
	 * 
	 * @param qlty
	 * @param specimen_no
	 * @param detail
	 * @param newItem
	 * @param items
	 */
	private void getQuote(SlmOrdDesignSampleM qlty, String specimen_no, QcmJhySampleConsignD detail, String newItem,
			List<QcmJhySampleConsignDItem> items) {
		String username=(String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		for (int i = 0; i < items.size(); i++) {
			String oldItem = items.get(i).getPhy_code_l() + items.get(i).getPhy_code_m() + items.get(i).getPhy_code_s()
					+ items.get(i).getItem_code_d() + items.get(i).getItem_code_s() + items.get(i).getItem_code_t();
			if (newItem.equals(oldItem)) {
				// 查询材质判定结果表
				List<QcmJhyPhyresult> results = this.getMapper(QcmJhyPhyresultMapper.class).findWithCondition(null,
						"SPECIMEN_NO='" + detail.getQuote_consign_no() + "'", null, 0, 0);

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

					for (int j = 0; j < results.size(); j++) {
						String result = results.get(j).getPhy_code_l() + results.get(j).getPhy_code_m()
								+ results.get(j).getPhy_code_s() + results.get(j).getItem_code_d()
								+ results.get(j).getItem_code_s() + results.get(j).getItem_code_t();

						if (newItem.equals(result)) {
							QcmJhyPhyresult tarResult = new QcmJhyPhyresult();
							try {
								DataHelper.CopyEntity(results.get(j), tarResult);
								tarResult.setSpecimen_no(specimen_no);
								List<QcmJhyPhyresult> order = this.getMapper(QcmJhyPhyresultMapper.class)
										.findWithCondition(null, "SPECIMEN_NO='" + detail.getSpecimen_no() + "'",
												"SEQ desc", 0, 0);
								Long seq = 1l;
								if (order != null && order.size() > 0) {
									seq = order.get(0).getSeq() + 1;
								}
								tarResult.setTest_qty(1l);
								tarResult.setSeq(seq);
								tarResult.setCreate_name(username);
								tarResult.setCreate_time(new Date());
								this.getMapper(QcmJhyPhyresultMapper.class).insert(tarResult);
							} catch (Exception e) {

								e.printStackTrace();
							}

							break;

						}

						if (j == results.size() - 1) {

							QcmJhyPhyresult tarResult = new QcmJhyPhyresult();

							try {

								tarResult.setSpecimen_no(specimen_no);
								List<QcmJhyPhyresult> order = this.getMapper(QcmJhyPhyresultMapper.class).findWithCondition(
										null, "SPECIMEN_NO='" + detail.getSpecimen_no() + "'", "SEQ desc", 0, 0);
								Long seq = 1l;
								if (order != null && order.size() > 0) {
									seq = order.get(0).getSeq() + 1;
								}
								tarResult.setPhy_code_l(qlty.getPhy_code_l());
								tarResult.setPhy_code_m(qlty.getPhy_code_m());
								tarResult.setPhy_code_s(qlty.getPhy_code_s());
								tarResult.setPhy_name_l(qlty.getPhy_name_l());
								tarResult.setPhy_name_m(qlty.getPhy_name_m());
								tarResult.setPhy_name_s(qlty.getPhy_name_s());
								tarResult.setItem_code_d(qlty.getItem_code_d());
								tarResult.setItem_code_s(qlty.getItem_code_s());
								tarResult.setItem_code_t(qlty.getItem_code_t());
								tarResult.setItem_name_d(qlty.getItem_name_d());
								tarResult.setItem_name_s(qlty.getItem_name_s());
								tarResult.setItem_name_t(qlty.getItem_name_t());
								tarResult.setCreate_name(username);
								tarResult.setCreate_time(new Date());
								//试验次数
								tarResult.setTest_qty(1l);
								
								tarResult.setSeq(seq);
								this.getMapper(QcmJhyPhyresultMapper.class).insert(tarResult);
								break;
							} catch (Exception e) {
								System.out.println("引用失败");
							}

							
							
						}

					}

				} else {

					// 判定结果没返回
					QcmJhyPhyresult tarResult = new QcmJhyPhyresult();

					try {

						tarResult.setSpecimen_no(specimen_no);
						List<QcmJhyPhyresult> order = this.getMapper(QcmJhyPhyresultMapper.class).findWithCondition(
								null, "SPECIMEN_NO='" + detail.getQuote_consign_no() + "'", "SEQ desc", 0, 0);
						Long seq = 1l;
						if (order != null && order.size() > 0) {
							seq = order.get(0).getSeq() + 1;
						}
						tarResult.setPhy_code_l(qlty.getPhy_code_l());
						tarResult.setPhy_code_m(qlty.getPhy_code_m());
						tarResult.setPhy_code_s(qlty.getPhy_code_s());
						tarResult.setPhy_name_l(qlty.getPhy_name_l());
						tarResult.setPhy_name_m(qlty.getPhy_name_m());
						tarResult.setPhy_name_s(qlty.getPhy_name_s());
						tarResult.setItem_code_d(qlty.getItem_code_d());
						tarResult.setItem_code_s(qlty.getItem_code_s());
						tarResult.setItem_code_t(qlty.getItem_code_t());
						tarResult.setItem_name_d(qlty.getItem_name_d());
						tarResult.setItem_name_s(qlty.getItem_name_s());
						tarResult.setItem_name_t(qlty.getItem_name_t());
						//试验次数
						tarResult.setTest_qty(1l);
						
						tarResult.setSeq(seq);
						tarResult.setCreate_name(username);
						tarResult.setCreate_time(new Date());
						this.getMapper(QcmJhyPhyresultMapper.class).insert(tarResult);

						break;
					} catch (Exception e) {
						System.out.println("引用失败");
					}

				}

				break;
			}

		}
	}

	/**
	 * 递归查询是否引用
	 * 
	 * @param qcmJhySampleConsignD
	 * @return
	 */
	private QcmJhySampleConsignD selectQuote(QcmJhySampleConsignD qcmJhySampleConsignD) {

		if (qcmJhySampleConsignD.getQuote_consign_no() == null
				|| "".equals(qcmJhySampleConsignD.getQuote_consign_no())) {
			return qcmJhySampleConsignD;
		}

		List<QcmJhySampleConsignD> details = this.getMapper(QcmJhySampleConsignDMapper.class).findWithCondition(null,
				"SPECIMEN_NO='" + qcmJhySampleConsignD.getQuote_consign_no() + "'", null, 0, 0);
		if (details == null || details.size() < 1) {
			return null;
		}

		return selectQuote(details.get(0));
	}
	
	
	/**
	 * 判断是否可以引用
	 */
	public ResultModel judgeAndGetQuote(CommonPage<QcmJhySampleConsignD> sum) {
		ResultModel rm=new ResultModel();
		try {
			
			if (sum==null) {
				rm.setState("500");
				rm.setMsgInfo("请传入参数");
				return rm;
			}
			List<QcmJhySampleConsignDItem> tarItems=new ArrayList<>();
			QcmJhySampleConsignD detail=sum.getObject();
			String specimen_no=detail.getSpecimen_no();
			//试样组
			String phy_code_m=detail.getPhy_code_m();
			//按炉取样引用
			if ("408601".equals(detail.getFreq_code())) {
				String heat_no=detail.getHeat_no();
				//查找炉号向下的按炉取样的取样编号
				List<QcmJhySampleConsignDItem> qi=this.getMapper(QcmJhySampleConsignDItemMapper.class).findByQuote(heat_no,specimen_no,phy_code_m);
				tarItems.addAll(qi);
			}
			//按批取样引用
			else if ("408602".equals(detail.getFreq_code())) {
				String batch_no=detail.getBatch_no();
				//查找轧批号向下的按炉取样的取样编号
				/*List<QcmJhySampleConsignD> tarDetail=this.getMapper(QcmJhySampleConsignDMapper.class).findWithCondition(null,
						"BATCH_NO='"+batch_no+"' and FREQ_CODE='408602' and SPECIMEN_NO!='"+specimen_no+"'",null, 0, 0);
				for (QcmJhySampleConsignD qd : tarDetail) {
					List<QcmJhySampleConsignDItem> qi=this.getMapper(QcmJhySampleConsignDItemMapper.class).findWithCondition(null,
							"SPECIMEN_NO='"+qd.getSpecimen_no()+"' and PHY_CODE_M='"+phy_code_m+"'", null, 0, 0);
					tarItems.addAll(qi);
				}*/
				List<QcmJhySampleConsignDItem> qi=this.getMapper(QcmJhySampleConsignDItemMapper.class).findByBatch(batch_no,specimen_no,phy_code_m);
				tarItems.addAll(qi);
			}
			
			//给项目赋予值
			for (QcmJhySampleConsignDItem tr : tarItems) {
				getJHYValue(tr);
				
			}
			rm.setState("200");
			rm.setData(tarItems);
		} catch (Exception e) {
			rm.setState("500");
			rm.setMsgInfo("查询失败!");
			return rm;
		}
		
		return rm;
		
		
		
		
	}

	private void getJHYValue(QcmJhySampleConsignDItem tr) {
		String condition = createItemSql(tr);
		
		List<QcmJhyPhyresult> results=this.getMapper(QcmJhyPhyresultMapper.class).findWithCondition(null, condition, null, 0, 0);
		if (results!=null && results.size()>0) {
			tr.setVal1(results.get(0).getVal1());
			tr.setVal2(results.get(0).getVal2());
			tr.setVal3(results.get(0).getVal3());
		}
	}

	public String createItemSql(QcmJhySampleConsignDItem tr) {
		String condition="SPECIMEN_NO='"+tr.getSpecimen_no()+"'";
		if (tr.getPhy_code_l()!=null && !"".equals(tr.getPhy_code_l())) {
			condition+=" and PHY_CODE_L='"+tr.getPhy_code_l()+"'";
		}
		
		if (tr.getPhy_code_m()!=null && !"".equals(tr.getPhy_code_m())) {
			condition+=" and PHY_CODE_M='"+tr.getPhy_code_m()+"'";
		}
		
		if (tr.getPhy_code_s()!=null && !"".equals(tr.getPhy_code_s())) {
			condition+=" and PHY_CODE_S='"+tr.getPhy_code_s()+"'";
		}
		
		if (tr.getItem_code_d()!=null && !"".equals(tr.getItem_code_d())) {
			condition+=" and ITEM_CODE_D='"+tr.getItem_code_d()+"'";
		}
		
		if (tr.getItem_code_t()!=null && !"".equals(tr.getItem_code_t())) {
			condition+=" and ITEM_CODE_T='"+tr.getItem_code_t()+"'";
		}
		
		if (tr.getItem_code_s()!=null && !"".equals(tr.getItem_code_s())) {
			condition+=" and ITEM_CODE_S='"+tr.getItem_code_s()+"'";
		}
		return condition;
	}
	
	/**
	 * 检验信息引用逻辑
	 * @throws Exception 
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel quoteItemsSure(CommonPage<QcmJhySampleConsignDItem> sum) throws Exception {
		ResultModel rm=new ResultModel();
		try {
			
			List<QcmJhySampleConsignDItem> items=sum.getObjectList();
		
			for (QcmJhySampleConsignDItem tr : items) {
				
				if (tr.getSpecimen_no()==null || "".equals(tr.getSpecimen_no())) {
					rm.setState("500");
					rm.setMsgInfo("请传入取样编号");
					return rm;
				}
				
				if (tr.getSeq()==null ) {
					rm.setState("500");
					rm.setMsgInfo("请传入顺序号");
					return rm;
				}
				
				QcmJhySampleConsignDItem old=this.getMapper(QcmJhySampleConsignDItemMapper.class).findById(tr.getSpecimen_no(),tr.getSeq());
				if (old==null) {
					rm.setState("500");
					rm.setMsgInfo("需要引用的项目不存在");
					return rm;
				}
				
				this.getMapper(QcmJhySampleConsignDItemMapper.class).update(tr);
				//this.getMapper(QcmJhySampleConsignDItemMapper.class).updateQuote(tr.getSpecimen_no(),tr.getSeq(),tr.getQuote_specimen_no(),tr.getQuote_phy_code_l(),tr.getQuote_phy_code_m(),tr.getQuote_phy_code_s(),tr.getQuote_item_code_d(),tr.getQuote_item_code_s(),tr.getQuote_item_code_t());
				
				if (tr.getQuote_item_code_d()==null || "".equals(tr.getQuote_item_code_d())) {
					this.getMapper(QcmJhySampleConsignDItemMapper.class).updateDNull(tr.getSpecimen_no(),tr.getSeq());
				}
				
				if (tr.getQuote_item_code_s()==null || "".equals(tr.getQuote_item_code_s())) {
					this.getMapper(QcmJhySampleConsignDItemMapper.class).updateSNull(tr.getSpecimen_no(),tr.getSeq());
				}
				
				if (tr.getQuote_item_code_t()==null || "".equals(tr.getQuote_item_code_t())) {
					this.getMapper(QcmJhySampleConsignDItemMapper.class).updatTNull(tr.getSpecimen_no(),tr.getSeq());
				}
				
				
			}
				
			rm.setMsgInfo("引用成功");
			rm.setState("200");
			
			
			
		} catch (Exception e) {
			throw new Exception("引用失败！");
		}
		
		
		return rm;
	}
	
	  public ResultModel copyInspectionItems(String Spe){
		   ResultModel rm=new ResultModel();
		   try {
			List<QcmJhyPhyresult> listresult=new ArrayList<>();
			List<QcmJhySampleConsignDItem> listitem = this.getMapper(QcmJhySampleConsignDItemMapper.class).findWithCondition(null, "specimen_no='"+Spe+"'", null, 0, 0);
		    for (QcmJhySampleConsignDItem item : listitem) {
		    	QcmJhyPhyresult qjp=new QcmJhyPhyresult();
	    	    BeanUtils.copyProperties(item, qjp);
	    	    qjp.setTest_qty((long)1);
		    	listresult.add(qjp);
			}
		    for (QcmJhyPhyresult qjp : listresult) {
				this.getMapper(QcmJhyPhyresultMapper.class).insert(qjp);
			}
		    rm.setState("200");
		} catch (Exception e) {
			// TODO: handle exception
			rm.setState("500");
		}
		   return rm;
	   }

	
	


	
}
