/***文档注释***********************************************
 * 作者            ：
 * 创建日期     ：2018-03-31
 * 描述            ：卡量检验实绩表
 * 注意事项     ：
 * 遗留BUG   ：
 * 修改日期     ：
 * 修改人员     ：
 * 修改内容     ：
***********************************************************/
package market.Qms.qcm.service.impl;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TreeSet;

import market.Api.Lms.impl.LmsApiServiceImpl;
import market.Api.Mes.impl.MesApiServiceImpl;
import market.Com.mapper.ComBaseToleranceMapper;
import market.Com.vo.ComBaseTolerance;
import market.Com.vo.CommonPage;
import market.Com.vo.ResultModel;
import market.Lms.Warehouse.mapper.YdmProductDetailMapper;
import market.Lms.Warehouse.vo.YdmProductDetail;
import market.Mes.Lengthwise.Plan.vo.PlnMaterielDetail;
import market.Mes.Opr.mapper.MesOprLogMapper;
import market.Mes.Opr.vo.MesOprLog;
import market.Qms.com.service.impl.ComBaseConfigServiceImpl;
import market.Qms.com.vo.ComBaseConfig;
import market.Qms.common.DataHelper;
import market.Qms.qcm.mapper.QcmJhySampleConsignMMapper;
import market.Qms.qcm.mapper.QcmJhySampleROrdMapper;
import market.Qms.qcm.mapper.QcmJudgeMeasureMapper;
import market.Qms.qcm.mapper.QcmJudgeUltimateReasonMapper;
import market.Qms.qcm.service.QcmJudgeMeasureService;
import market.Qms.qcm.vo.Composition_standard2;
import market.Qms.qcm.vo.Composition_standard3;
import market.Qms.qcm.vo.QcmJhySampleConsignM;
import market.Qms.qcm.vo.QcmJhySampleROrd;
import market.Qms.qcm.vo.QcmJudgeMeasure;
import market.Qms.qcm.vo.QcmJudgeUltimateReason;
import market.Qms.slmord.mapper.QcmJudgeBlockadeInfoMapper;
import market.Qms.slmord.mapper.SlmOrdDesignMscMapper;
import market.Qms.slmord.mapper.SlmOrdDesignStdMapper;
import market.Qms.slmord.mapper.SlmOrdDesignStdSicMapper;
import market.Qms.slmord.vo.QcmJudgeBlockadeInfo;
import market.Qms.slmord.vo.SlmOrdDesignMsc;
import market.Qms.slmord.vo.SlmOrdDesignStd;
import market.Qms.slmord.vo.SlmOrdDesignStdSic;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

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

@RemoteService(path="QcmJudgeMeasureService")
public class QcmJudgeMeasureServiceImpl extends BaseServiceImpl<QcmJudgeMeasure,Object> implements QcmJudgeMeasureService {
	/**
	 * 质量判定-卡量检测-查询检验实绩
	 * sum.heat_no 炉号
	 * sum.batch_no 轧批号
	 * sum.material_no 材料号
	 * startTime 检验日期下限
	 * endTime 检验日期上限
	 * */
	public ResultModel getQcmJudgeMeasure(CommonPage<QcmJudgeMeasure> sum){
		ResultModel rm=new ResultModel();
		QcmJudgeMeasure qm=sum.getObject();
		
		if(qm==null){
			rm.setState("500");
			rm.setMsgInfo("请传入参数！");
			return rm;
		}
		try {
			int pageIndex = sum.getPageIndex();
			int pageSize = sum.getPageSize();
			String Str="1=1";
			if(qm.getHeat_no()!=null&&!qm.getHeat_no().trim().equals("")){
				Str+=" and HEAT_NO like '%"+qm.getHeat_no()+"%'";
			}
			if(qm.getBatch_no()!=null&&!qm.getBatch_no().trim().equals("")){
				Str+=" and BATCH_NO like '%"+qm.getBatch_no()+"%'";
			}
			if(qm.getMaterial_no()!=null&&!qm.getMaterial_no().trim().equals("")){
				Str+=" and MATERIAL_NO like '%"+qm.getMaterial_no()+"%'";
			}
			if(qm.getSic_result_code()!=null&&!qm.getSic_result_code().trim().equals("")){
				Str+=" and SIC_RESULT_CODE = '"+qm.getSic_result_code()+"'";
			}
			if(sum.getStartTime()!=null&&!sum.getStartTime().equals("")){
				Str+=" and judge_time>=to_date(concat('"+sum.getStartTime()+"',' 00:00:00'),'yyyy-MM-dd HH24:mi:ss')"; 
			}
			if(sum.getEndTime()!=null&&!sum.getEndTime().equals("")){
				Str+=" and judge_time<=to_date(concat('"+sum.getEndTime()+"',' 23:59:59'),'yyyy-MM-dd HH24:mi:ss') ";
			}
			List<QcmJudgeMeasure> qmlist=this.getMapper(QcmJudgeMeasureMapper.class).findWithCondition(null, Str, "judge_time desc", (pageIndex-1)*pageSize,pageSize);
			PageModel<QcmJudgeMeasure> pm=new PageModel<>(pageIndex, pageSize);
			pm.setRows(qmlist);
			pm.setTotal(this.getMapper(QcmJudgeMeasureMapper.class).countWithCondition(null, Str));
			rm.setData(pm);
			rm.setState("200");
		} catch (Exception e) {
			rm.setState("500");
			rm.setMsgInfo("检验实绩查询失败！"+e.getMessage());
			e.printStackTrace();
		}
		return rm;
	}
	
	/**
	 * 质量判定-卡量检测-查询公差标准
	 * design_key 质量设计主键
	 * psc 产品规范码
	 * */
	public ResultModel getTolerance(CommonPage<SlmOrdDesignStd> sum){
		ResultModel rm=new ResultModel();
		try {
			// 查询计划规格
			PlnMaterielDetail pln = this.getService(MesApiServiceImpl.class).getDsnSizeOfMat(sum.getMemo1());
			// 查询公差基础项目
			List<ComBaseTolerance> cbtList = this.getMapper(ComBaseToleranceMapper.class).findWithCondition(null, "VALIDFLAG='1'", null, 0, 0);
			
			SlmOrdDesignStd std=sum.getObject();
			List<SlmOrdDesignStdSic> siclist=new ArrayList<SlmOrdDesignStdSic>();
//			DESIGN_KEY、PSC查询质量设计-交付标准SLM_ORD_DESIGN_STD获取公差标准索引号SIC、SIC_K；
			List<SlmOrdDesignStd> liststdd=this.getMapper(SlmOrdDesignStdMapper.class).find(std,0,0);
			SlmOrdDesignMsc msc=new SlmOrdDesignMsc();
			if (std.getDesign_key()!=null && !"".equals(std.getDesign_key())) {
				msc=this.getMapper(SlmOrdDesignMscMapper.class).findById(std.getDesign_key());
			}
			SlmOrdDesignStd stdd=new SlmOrdDesignStd();
			//获取DESIGN_KEY、PSC对应所有公差标准
	        if (liststdd.size()>0) {
	        	stdd=liststdd.get(0);
	//			SIC、SIC_K同时存在，相同项目对应标准值以SIC_K对应的标准为准
				if(stdd.getSic_k()==null || stdd.getSic_k().equals("")){
					SlmOrdDesignStdSic sic=new SlmOrdDesignStdSic();
					sic.setDesign_key(stdd.getDesign_key());
					sic.setSic(stdd.getSic());
					List<SlmOrdDesignStdSic> siclist2=this.getMapper(SlmOrdDesignStdSicMapper.class).find(sic, 0, 0);
					for(SlmOrdDesignStdSic s:siclist2){
						siclist.add(s);
					}
				} else {
					//如果sic_k存在，这取sic与sic_k两套结果的并集，以sic_k为准
					List<SlmOrdDesignStdSic> listSic = this.getMapper(SlmOrdDesignStdSicMapper.class).findWithCondition(null, "DESIGN_KEY='"+stdd.getDesign_key()+"' and sic='"+stdd.getSic()+"'", null, 0, 0);
					List<SlmOrdDesignStdSic> listsick = this.getMapper(SlmOrdDesignStdSicMapper.class).findWithCondition(null, "DESIGN_KEY='"+stdd.getDesign_key()+"' and sic='"+stdd.getSic_k()+"'", null, 0, 0);
					for (SlmOrdDesignStdSic slmOrdDesignStdSic : listSic) {
						siclist.add(slmOrdDesignStdSic);
					}
					for (SlmOrdDesignStdSic slmOrdDesignStdSic : listsick) {
						siclist.add(slmOrdDesignStdSic);
					}
					for (SlmOrdDesignStdSic sic : listSic) {
						for (SlmOrdDesignStdSic sick : listsick) {
							if (sic.getBias_code().equals(sick.getBias_code())) {
								listSic.remove(sic);
							}
						}
					}
				}
			}
	        List<SlmOrdDesignStdSic> sodList = new ArrayList<>();
	        
	        for(ComBaseTolerance cbt: cbtList){
	        	boolean flag = true;
	        	for(SlmOrdDesignStdSic sod1: siclist){
	        		if(cbt.getTol_code().equals(sod1.getBias_code())){
	        			flag = false;
	        			break;
	        		}
	        	}
	        	if(flag){
	        		SlmOrdDesignStdSic sod = new SlmOrdDesignStdSic();
					sod.setBias_code(cbt.getTol_code());
					sod.setBias_name(cbt.getTol_name());
					sodList.add(sod);
	        	}
			}
	        siclist.addAll(sodList);
//	        if(pln != null){
	        	for(SlmOrdDesignStdSic sod: siclist){
	        		// 计划规格赋值
	        		if("T0001".equals(sod.getBias_code())){
	        			sod.setThick(pln!=null?pln.getThick():msc.getThick());
	        		}else if("T0002".equals(sod.getBias_code())){
	        			sod.setWidth(pln!=null?pln.getWidth():msc.getWidth());
	        		}else if("T0003".equals(sod.getBias_code())){
	        			sod.setLength(pln!=null?pln.getLength():msc.getLength());
	        		}
	        	}
//	        }
			//调用质量设计接口获取标准上下限传出siclist,写入siclist并传回
			
	        List<SlmOrdDesignStdSic> orderSic=new ArrayList<SlmOrdDesignStdSic>();
	        
	        if (siclist!=null && siclist.size()>0) {
	        	List<SlmOrdDesignStdSic> pri=new ArrayList<SlmOrdDesignStdSic>();
	        	for (int i = 0; i < siclist.size(); i++) {
	        		if ("1".equals(siclist.get(i).getIscheck())) {
		        		pri.add(siclist.get(i));
		        		siclist.remove(i);
		        		i--;
					}
				}
	        	
	        	if (pri!=null && pri.size()>0) {
	        		TreeSet<String> priOne=new TreeSet<String>();
					for (SlmOrdDesignStdSic p : pri) {
						priOne.add(p.getBias_code());
					}
					for (String one : priOne) {
						for (SlmOrdDesignStdSic sic : pri) {
							if (one.equals(sic.getBias_code())) {
								orderSic.add(sic);
								break;
							}
						}
					}
				}
	        	
	        	if (siclist!=null && siclist.size()>0) {
	        		TreeSet<String> onlyOne=new TreeSet<String>();
	        		for (SlmOrdDesignStdSic slmOrdDesignStdSic : siclist) {
			        	onlyOne.add(slmOrdDesignStdSic.getBias_code());
					}
			        for (String set : onlyOne) {
						for (SlmOrdDesignStdSic sic : siclist) {
							if (set.equals(sic.getBias_code())) {
								orderSic.add(sic);
								break;
							}
						}
					}
	        	}
	        	
	        	
			}	
			rm.setData(orderSic);
			rm.setState("200");
			
		} catch (Exception e) {
			rm.setState("500");
			rm.setMsgInfo("公差项查询失败！"+e.getMessage());
		}
		return rm;
	}


	/**
	 * 质量判定-卡量检测-检验登记自动判定
	 * SlmOrdDesignStd：design_key 质量设计主键，psc 产品规范码
	 * QcmJudgeMeasure：judge_thick 判定厚度，judge_width 判定宽度，judge_length 判定长度
	 * */
	public ResultModel judgeByComputer(Composition_standard2 sum){
		ResultModel rm=new ResultModel();
		try {
			SlmOrdDesignStd std=sum.getObject1();
			List<SlmOrdDesignStdSic> siclist=new ArrayList<SlmOrdDesignStdSic>();
//			DESIGN_KEY、PSC查询质量设计-交付标准SLM_ORD_DESIGN_STD获取公差标准索引号SIC、SIC_K；
			List<SlmOrdDesignStd> liststdd=this.getMapper(SlmOrdDesignStdMapper.class).find(std,0,0);
			 SlmOrdDesignStd stdd=new SlmOrdDesignStd();
			//获取DESIGN_KEY、PSC对应所有公差标准
		         if (liststdd.size()>0) {
		        	 stdd=liststdd.get(0);
//						SIC、SIC_K同时存在，相同项目对应标准值以SIC_K对应的标准为准
					 if(stdd.getSic_k()==null || stdd.getSic_k().equals("")){
						SlmOrdDesignStdSic sic=new SlmOrdDesignStdSic();
						sic.setDesign_key(stdd.getDesign_key());
						sic.setSic(stdd.getSic());
						List<SlmOrdDesignStdSic> siclist2=this.getMapper(SlmOrdDesignStdSicMapper.class).find(sic, 0, 0);
						for(SlmOrdDesignStdSic s:siclist2){
							siclist.add(s);
						}
					}
					 else {
						//如果sic_k存在，这取sic与sic_k两套结果的并集，以sic_k为准
						 List<SlmOrdDesignStdSic> listSic = this.getMapper(SlmOrdDesignStdSicMapper.class).findWithCondition(null, "DESIGN_KEY='"+stdd.getDesign_key()+"' and sic='"+stdd.getSic()+"'", null, 0, 0);
						 List<SlmOrdDesignStdSic> listsick = this.getMapper(SlmOrdDesignStdSicMapper.class).findWithCondition(null, "DESIGN_KEY='"+stdd.getDesign_key()+"' and sic='"+stdd.getSic_k()+"'", null, 0, 0);
						 for (SlmOrdDesignStdSic e : listSic) {
							 siclist.add(e);
						} 
						 for (SlmOrdDesignStdSic e : listsick) {
							 siclist.add(e);
						}
						 for (SlmOrdDesignStdSic sic : listSic) {
							for (SlmOrdDesignStdSic sick : listsick) {
								if (sic.getBias_code().equals(sick.getBias_code())) {
									siclist.remove(sic);
								}
							}
					}
				}
				}

			//调用质量接口获取标准上下限
			

			QcmJudgeMeasure qjs=sum.getObject2();
//			厚宽长判定标识
			boolean t=true,w=true,l=true,bp=true,ld=true,tf=true,tx=true;
//			自动判定
			for(SlmOrdDesignStdSic sic:siclist){
//				double min=Double.parseDouble(sic.getStd_result_min());//最大值
//				double max=Double.parseDouble(sic.getStd_result_max());//最小值
				String upperDeciation=null;
				String drownDeciation=null;
				if (!DataHelper.IsNullOrSpace(sic.getStd_max_val())&&!"".equals(sic.getStd_max_val())) {
					if (sic.getStd_max_val().contains("+")) {
						 upperDeciation=sic.getStd_max_val().substring(1);//上偏差
					}else {
						 upperDeciation=sic.getStd_max_val();//上偏差
					}
					
				}
				if (!DataHelper.IsNullOrSpace(sic.getStd_min_val())&&!"".equals(sic.getStd_min_val())) {
					if (sic.getStd_min_val().contains("-")) {
						drownDeciation=sic.getStd_min_val().substring(1);//下偏差
					}else {
						drownDeciation=sic.getStd_min_val();//下偏差
					}
					 
				}
//				比较方式可能有问题。。。要与设计沟通一下
				if(sic.getBias_name().equals("厚度") && sic.getIscheck().equals("1")){
					double jt=qjs.getJudge_thick();
//					if(!(jt>(min-drownDeciation)&&jt<(max+upperDeciation))){
//						t=false;
//					}
					t=comOrtherVal(sic.getStd_result_max(), sic.getStd_result_min(), jt);
					//t=compareVal(sic.getStd_result_max(), sic.getStd_result_min(), jt, upperDeciation, drownDeciation);
				}
				if(sic.getBias_name().equals("宽度") && sic.getIscheck().equals("1")){
					double jw=qjs.getJudge_width();
//					if(!(jw>(min-drownDeciation)&&jw<(max+upperDeciation))){
//						w=false;
//					}
					w=comOrtherVal(sic.getStd_result_max(), sic.getStd_result_min(), jw);
					//w=compareVal(sic.getStd_result_max(), sic.getStd_result_min(), jw, upperDeciation, drownDeciation);
				}
				if(sic.getBias_name().equals("长度") && sic.getIscheck().equals("1")){
					double jl=qjs.getJudge_length();
					l=comOrtherVal(sic.getStd_result_max(), sic.getStd_result_min(), jl);
//					if(!(jl>(min-drownDeciation)&&jl<(max+upperDeciation))){
//						l=false;
//					}
					//l=compareVal(sic.getStd_result_max(), sic.getStd_result_min(), jl, upperDeciation, drownDeciation);
				}
				if ("T0004".equals(sic.getBias_code()) && sic.getIscheck().equals("1") ) {
					double jb=qjs.getJudge_unevenness();
					if ((sic.getStd_result_max()==null || "".equals(sic.getStd_result_max())) && (sic.getStd_result_min()==null || "".equals(sic.getStd_result_min()))) {
						bp=comOrtherVal(upperDeciation,drownDeciation,jb);
					}else{
						bp=comOrtherVal(sic.getStd_result_max(), sic.getStd_result_min(), jb);
					}
				}
				if ("T0005".equals(sic.getBias_code()) && sic.getIscheck().equals("1") ) {//镰刀
						double jd=qjs.getJudge_camber();
						if ((sic.getStd_result_max()==null || "".equals(sic.getStd_result_max())) && (sic.getStd_result_min()==null || "".equals(sic.getStd_result_min()))) {
							ld=comOrtherVal(upperDeciation,drownDeciation,jd);
						}else{
							ld=comOrtherVal(sic.getStd_result_max(), sic.getStd_result_min(), jd);
						}
					
				}
				if ("T0006".equals(sic.getBias_code()) && sic.getIscheck().equals("1") ) {//脱方
					double jt=qjs.getJudge_offsquare();						
					if ((sic.getStd_result_max()==null || "".equals(sic.getStd_result_max())) && (sic.getStd_result_min()==null || "".equals(sic.getStd_result_min()))) {
						tf=comOrtherVal(upperDeciation,drownDeciation,jt);
					}else{
						tf=comOrtherVal(sic.getStd_result_max(), sic.getStd_result_min(), jt);
					}
					
				}if ("T0007".equals(sic.getBias_code()) && sic.getIscheck().equals("1") ) {//塔形
					double jx=qjs.getJudge_turriform();
					if ((sic.getStd_result_max()==null || "".equals(sic.getStd_result_max())) && (sic.getStd_result_min()==null || "".equals(sic.getStd_result_min()))) {
						tx=comOrtherVal(upperDeciation,drownDeciation,jx);
					}else{
						tx=comOrtherVal(sic.getStd_result_max(), sic.getStd_result_min(), jx);
					}
				}
			}
			if(t&&w&&l&&tx&&tf&&ld&&bp){
				rm.setData(true);
			}
			else{
				rm.setData(false);
			}
			rm.setState("200");
		} catch (Exception e) {
			e.printStackTrace();
			rm.setState("500");
			rm.setMsgInfo("判定失败！"+e.getMessage());
		}
		return rm;
	}
	public boolean compareVal(String std_max,String std_min,double val,Double upperDeciation,Double drownDeciation){
		boolean flag=true;
//		double min=Double.parseDouble(std_min);//最大值
//		double max=Double.parseDouble(std_max);//最小值
//		double uDeciation=Double.parseDouble(upperDeciation);//上偏差
//		double dDeciation=Double.parseDouble(drownDeciation);//上偏差
		double jt=val;
		if (DataHelper.IsNullOrSpace(std_max)&&DataHelper.IsNullOrSpace(std_min)) {
			return flag;
		}else if (!DataHelper.IsNullOrSpace(std_max)&&DataHelper.IsNullOrSpace(std_min)) {
			if (jt<=Double.parseDouble(std_max)+upperDeciation) {
				return flag;
			}else {
				flag=false;
				return flag;
			}
		}else if(DataHelper.IsNullOrSpace(std_max)&&!DataHelper.IsNullOrSpace(std_min)){
			if (jt>=Double.parseDouble(std_min)-drownDeciation) {
				return flag;
			}else {
				flag=false;
				return flag;
			}
		}else {
			if (jt<=Double.parseDouble(std_max)+upperDeciation&&jt>=Double.parseDouble(std_min)-drownDeciation) {
			}else {
				flag=false;
				return flag;
			}
		}
		return flag;
	}	
	
	
	@SuppressWarnings("unchecked")
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doAddQcmJudgeMeasure(Composition_standard3 sum) throws Exception{
		ResultModel rm=new ResultModel();
		Date now = new Date();
		String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(now); //操作时间
		String username = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		String wrk_ord = (String) this.getSession().getAttribute(HomeService.SESSION_WORK_ORD);
		String wrk_grp = (String) this.getSession().getAttribute(HomeService.SESSION_WORK_GRP);
		List<QcmJudgeMeasure> qjmlist=sum.getObjectList();

		try {
			//物料信息集合
			if(qjmlist==null||qjmlist.size()==0){
				rm.setState("500");
				rm.setMsgInfo("请传入参数！");
				return rm;
			}else{
				//数据验证
				for (QcmJudgeMeasure q : qjmlist) {
					YdmProductDetail ydm=this.getMapper(YdmProductDetailMapper.class).findById(q.getMaterial_no());
					if(ydm != null){
						if (ydm.getJudgeresult()!=null&&!ydm.getJudgeresult().equals("")) {
							rm.setState("500");
							rm.setMsgInfo("存在综合判定结果，无法进行公差登记");
							return rm;
						}
						if ("1".equals(ydm.getSic_is_lock())) {
							rm.setState("500");
							rm.setMsgInfo("物料"+ydm.getCoilno()+"已经被公差锁定，请解锁再进行其他操作");
						    return rm;
						}
					}
					if (q.getDesign_key()==null || "".equals(q.getDesign_key())) {
						rm.setState("500");
						rm.setMsgInfo("物料["+q.getMaterial_no()+"]不属于生产完成状态，不能进行判定！");
						return rm;
					}
					
				}
				
			}
			// 获取检验索引码最大值
			int count=0;
			SimpleDateFormat sdf=new SimpleDateFormat("yyMMdd");
			String date=sdf.format(new Date());
			List<QcmJudgeMeasure> qjlist=this.getMapper(QcmJudgeMeasureMapper.class)
					.findWithCondition(null, "sic_ID like 'S"+date+"%'", "sic_ID DESC", 0, 0);
			if(qjlist!=null&&qjlist.size()>0){
				String s=qjlist.get(0).getSic_id();
				count=Integer.parseInt(s.substring(s.length()-4,s.length()));
			}
			List<YdmProductDetail> listydm=new ArrayList<>();
			// 插入QCM_JUDGE_MEASURE信息
			for(QcmJudgeMeasure qj:qjmlist){
				//QcmJudgeMeasure qjm=sum.getObject();
				count++;
				String mst_id="S"+date+String.format("%04d", count);
				qj.setSic_id(mst_id);
				if (qj.getMaterial_no()!=null&&!qj.getMaterial_no().equals("")) {
					qj.setMaterial_no(qj.getMaterial_no());
				}else {
					qj.setMaterial_no("NULL");
				}
				if("40740302".equals(qj.getSic_result_code())){
					qj.setSic_is_lock("1");
				}
				qj.setJudge_name(username);
				qj.setWrk_grp(wrk_grp);
				qj.setWrk_ord(wrk_ord);
				YdmProductDetail ypd=this.getMapper(YdmProductDetailMapper.class).findById(qj.getMaterial_no());
				if(ypd != null){
					qj.setKc_state(ypd.getState());
				}
				this.getMapper(QcmJudgeMeasureMapper.class).insert(qj);
				// 更新库存表公差检验结果和公差检验结果ID
				if (!"40740305".equals(qj.getSic_result_code())) {//待判业务不更新库存表
					YdmProductDetail y=new YdmProductDetail();
					y.setCoilno(qj.getMaterial_no());
					y.setMeasure_result(qj.getSic_result_code());
					y.setMeasure_result_id(mst_id);
					y.setSizeresult(qj.getSic_result_code());
					if("40740301".equals(qj.getSic_result_code())){
						YdmProductDetail ydm = this.getMapper(YdmProductDetailMapper.class).findById(qj.getMaterial_no());
						if(ydm != null && "6".equals(ydm.getState()) && "0".equals(ydm.getPic_is_lock()) && "0".equals(ydm.getSfd_is_lock()) && "0".equals(ydm.getSfe_is_lock()) && "0".equals(ydm.getSfu_is_lock())){
							y.setState("0");
						}
						y.setSic_is_lock("0");
					}
					listydm.add(y);
				}else{
					//待判业务清空库存表公差判定结果
					this.getMapper(QcmJudgeMeasureMapper.class).deleteYdmMeterimal(qj.getMaterial_no());
					
				}
				//异常材料处置，进行物料封锁
				// 不合格时，直接进行异常材料处置业务
				if ("40740302".equals(qj.getSic_result_code())) {
					MaterialAbnormalTreatment(qj);
					QcmJudgeUltimateReason qjr = new QcmJudgeUltimateReason();
			 		qjr.setMaterial_no(qj.getMaterial_no());
			 		qjr.setType_code("S");
			 		qjr.setRecord_id(mst_id);
			 		qjr.setSeq(1);
			 		qjr.setPhy_code_s("T0001");
			 		qjr.setPhy_name_s("厚度");
			 		qjr.setCreate_name(username);
			 		qjr.setCreate_time(new Date());
			 		List<SlmOrdDesignStdSic> siclist=new ArrayList<SlmOrdDesignStdSic>();
			 		SlmOrdDesignStd sod = new SlmOrdDesignStd(); 
			 		sod.setDesign_key(qj.getDesign_key());
			 		sod.setPsc(qj.getPsc());
			 		List<SlmOrdDesignStd> liststdd=this.getMapper(SlmOrdDesignStdMapper.class).find(sod,0,0);
			 		SlmOrdDesignStd stdd=new SlmOrdDesignStd();
			 		if (liststdd.size()>0) {
			        	 stdd=liststdd.get(0);
			        	 //	 SIC、SIC_K同时存在，相同项目对应标准值以SIC_K对应的标准为准
						 if(stdd.getSic_k()==null || stdd.getSic_k().equals("")){
							SlmOrdDesignStdSic sic=new SlmOrdDesignStdSic();
							sic.setDesign_key(stdd.getDesign_key());
							sic.setSic(stdd.getSic());
							List<SlmOrdDesignStdSic> siclist2=this.getMapper(SlmOrdDesignStdSicMapper.class).find(sic, 0, 0);
							for(SlmOrdDesignStdSic s:siclist2){
								siclist.add(s);
							}
						} else {
							//如果sic_k存在，这取sic与sic_k两套结果的并集，以sic_k为准
							 List<SlmOrdDesignStdSic> listSic = this.getMapper(SlmOrdDesignStdSicMapper.class).findWithCondition(null, "DESIGN_KEY='"+stdd.getDesign_key()+"' and sic='"+stdd.getSic()+"'", null, 0, 0);
							 List<SlmOrdDesignStdSic> listsick = this.getMapper(SlmOrdDesignStdSicMapper.class).findWithCondition(null, "DESIGN_KEY='"+stdd.getDesign_key()+"' and sic='"+stdd.getSic_k()+"'", null, 0, 0);
							 for (SlmOrdDesignStdSic e : listSic) {
								 siclist.add(e);
							} 
							 for (SlmOrdDesignStdSic e : listsick) {
								 siclist.add(e);
							}
							 for (SlmOrdDesignStdSic sic : listSic) {
								for (SlmOrdDesignStdSic sick : listsick) {
									if (sic.getBias_code().equals(sick.getBias_code())) {
										siclist.remove(sic);
									}
								}
							 }
						}
					}
			 		if(siclist!=null && siclist.size()>0) {
			 			qjr.setStdmax(siclist.get(0).getStd_result_max());
			 			qjr.setStdmax_sign(siclist.get(0).getZmax_sign());
			 			qjr.setStdmin(siclist.get(0).getStd_result_min());
			 			qjr.setStdmin_sign(siclist.get(0).getZmin_sign());
			 		}
			 		this.getMapper(QcmJudgeUltimateReasonMapper.class).insert(qjr);
				}
				// 判废时，根据代码配置决定是否发起异常材料处置业务
				if ("40740304".equals(qj.getSic_result_code())) {
					ArrayList<String> listconfig_id = new ArrayList<>();
					listconfig_id.add("QCM0005");
					List<ComBaseConfig> listcbc =(List<ComBaseConfig>) this.getBean(ComBaseConfigServiceImpl.class).getBaseConfigInfo(listconfig_id).getData();
					if ("1".equals(listcbc.get(0).getConfig_val())) {
						MaterialAbnormalTreatment(qj);
					} else {
						// 判废业务
					}
				}
			}
			for (YdmProductDetail ydm : listydm) {
				if (!"40740305".equals(ydm.getMeasure_result())) {
					List<YdmProductDetail> tarYdm=new ArrayList<>();
					tarYdm.add(ydm);
					CommonPage<YdmProductDetail> cydm=new CommonPage<>();
					cydm.setObjectList(tarYdm);
					this.getBean(LmsApiServiceImpl.class).doUpdateResultByCoilno(cydm);
				}
			}
			//日志
			for (QcmJudgeMeasure qjm:qjmlist) {
				MesOprLog mol = new MesOprLog("质量管理", "公差检验管理", "检验登记", username, opr_time, qjm.getMaterial_no(), null, null, null, "判定结果；"+qjm.getSic_result_desc());
				this.getMapper(MesOprLogMapper.class).insert(mol);
			}
			rm.setState("200");
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception();
		}
		return rm;
	}
	
	
	
	/**
	 * 异常材料处理--封锁物料
	 */
	public void MaterialAbnormalTreatment(QcmJudgeMeasure qjm){
		try {
			//更新库存表
			 QcmJudgeBlockadeInfo qjb=new QcmJudgeBlockadeInfo();
			 //生成质量封锁记录号
			 int count=0;
				SimpleDateFormat sdf=new SimpleDateFormat("yyMMdd");
				String date=sdf.format(new Date());
				List<QcmJudgeBlockadeInfo> listqcbk = this.getMapper(QcmJudgeBlockadeInfoMapper.class).findWithCondition(null, "BIC like '%"+date+"%'", "BIC desc", 0, 0);
				if(listqcbk!=null&&listqcbk.size()>0){
					String s=listqcbk.get(0).getBic();
					count=Integer.parseInt(s.substring(s.length()-4, s.length()));
				}
				count++;
				String bic=sdf.format(new Date())+String.format("%04d",count);
				qjb.setBic(bic);
				qjb.setBic_type("S");
				//获取缺陷
				//String flaw="";
				//锁定物料
				YdmProductDetail ydm=new YdmProductDetail();
				ydm.setCoilno(qjm.getMaterial_no());
				// 公差判不合格时不需要公差锁定：傅杰 （20221102刘侣）start
				//ydm.setSic_is_lock("1");
				ydm.setSic_is_lock("0");
				// end
				//ydm.setState("6");
				ydm.setMeasure_result(qjm.getSic_result_code());
				ydm.setMeasure_result_id(qjm.getSic_id());
				//List<QcmJudgeSurfaceFlaw> listqjsf = this.getMapper(QcmJudgeSurfaceFlawMapper.class).findWithCondition(null, "SURFACE_ID='"+qjm.getSic_id()+"'", null, 0, 0);
				qjb.setBic_memo("厚度:"+qjm.getJudge_thick());
				//获取合同行主键
				if (!DataHelper.IsNullOrSpace(ydm.getSmpno())){
					QcmJhySampleConsignM qsc = this.getMapper(QcmJhySampleConsignMMapper.class).findById(ydm.getSmpno());
					QcmJhySampleROrd sdm= this.getMapper(QcmJhySampleROrdMapper.class).findById(ydm.getSmpno());
					if (sdm!=null) {
						qjb.setContract_line_no(sdm.getContract_line_no());
						qjb.setContract_line_desc(sdm.getOrder_no());
					}
					qjb.setBoard_no(qsc.getBoard_no()); //
				}
				
				
				qjb.setHeat_no(qjm.getHeat_no());
				qjb.setBatch_no(qjm.getBatch_no());
				
				qjb.setInspection_lot(qjm.getInspection_lot());
				qjb.setMaterial_no(qjm.getMaterial_no());
				qjb.setObject_no_pseudo(qjm.getVirtual_material_no()); //
//				qjb.setDis_result_code(qjs.getSf_result_code()); // 处置结果代码，此处应该不用写
//				qjb.setDis_result_desc(qjs.getSf_result_desc());
//				qjb.setDis_memo(qjs.getSf_memo());
				qjb.setOld_psc(qjm.getPsc());
		    	qjb.setOld_prod_code(qjm.getProd_code());
		    	qjb.setOld_prod_name(qjm.getProd_name());
		    	qjb.setOld_std_code(qjm.getStd_code());
		    	qjb.setOld_std_name(qjm.getStd_name());
		    	qjb.setOld_steel_code(qjm.getSteel_code());
		    	qjb.setOld_steel_name(qjm.getSteel_name());
		    	// 目标产品信息
		    	qjb.setPsc(qjm.getPsc_new());
		    	qjb.setProd_code(qjm.getProd_code_new());
		    	qjb.setProd_name(qjm.getProd_name_new());
		    	qjb.setStd_code(qjm.getStd_code_new());
		    	qjb.setStd_name(qjm.getStd_name_new());
		    	qjb.setSteel_code(qjm.getSteel_code_new());
		    	qjb.setSteel_name(qjm.getSteel_name_new());
		    	qjb.setDelivery_state_code(qjm.getDelivery_state_code_new());
		    	qjb.setDelivery_state_desc(qjm.getDelivery_state_desc_new());
		    	
		    	qjb.setCreate_time(new Date());
		    	qjb.setCreate_name((String) this.getSession().getAttribute(
						HomeService.SESSION_USER_NAME));
		    	qjb.setPline_code(qjm.getPline_code());
		    	qjb.setPline_name(qjm.getPline_name());
		    	if (qjm.getWidth()!=null&&!(qjm.getWidth()).equals("")) {
		    		qjb.setWidth(qjm.getWidth());	
				}
		    	if (qjm.getThick()!=null&&!(qjm.getThick()).equals("")) {
		    		qjb.setThick(qjm.getThick());
				}
		    	if (qjm.getLength()!=null&&!(qjm.getLength()).equals("")) {
		    		qjb.setLength(qjm.getLength());	
				}
		    	qjb.setCut_edge_type_name(qjm.getCut_edge_type_name());
		    	qjb.setCut_edge_type_no(qjm.getCut_edge_type_no());
				this.getMapper(QcmJudgeBlockadeInfoMapper.class).insert(qjb);
				this.getMapper(YdmProductDetailMapper.class).update(ydm);
		} catch (Exception e) {
			System.out.println(e.getMessage());
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
		}
	}
	/**
	 * 
	 * 获取综合判定卡量检验实绩信息
	 * 
	 * */
	public ResultModel getMeasureSampleItem(CommonPage<YdmProductDetail> sum){
		ResultModel rm=new ResultModel();
		YdmProductDetail ydm=sum.getObject();
		if (ydm==null) {
			rm.setState("403");
			rm.setMsgInfo("请传入参数");
			return rm;
		}
		if (DataHelper.IsNullOrSpace(ydm.getMeasure_result_id())) {
			rm.setState("403");
			rm.setMsgInfo("公差检验id不存在");
			return rm;
		}
		//从物流接口中获取卡量判定记录号
		try {
			 String mstid=ydm.getMeasure_result_id();
			 //根据销售卡量判定记录号查询检验实绩信息
			 QcmJudgeMeasure qjm=this.getMapper(QcmJudgeMeasureMapper.class).getMeasureSampleItem(mstid);
		     rm.setData(qjm);
		     rm.setState("200");
		} catch (Exception e) {
			rm.setState("500");
			rm.setErrorInfo(e.getMessage());
			rm.setMsgInfo("操作失败");
		}		
		return rm;
	}
	
	
	public boolean comOrtherVal(String std_max,String std_min,double val){
		boolean flag=true;
		double jt=val;
		if (std_max==null || "".equals(std_max)) {
			flag=true;
		}else{
			if (jt<=Double.parseDouble(std_max)) {
				flag=true;
			}else {
				flag=false;
				return flag;
			}
		}
		if (!flag) {
			return false;
		}
		
		if (std_min==null || "".equals(std_min)) {
			flag=true;
		}else{
			if (jt>=Double.parseDouble(std_min)) {
				flag=true;
			}else {
				flag=false;
				return flag;
			}
		}
		if (!flag) {
			return false;
		}else{
			return true;
		}
		
		
	}
	
	
	public String countThick(String w_head,String w_center,String w_foot){
		
		Double ave=0.0;
		String value="";
		int count=0;
		if (w_head!=null && !"".equals(w_head)) {
			ave+=Double.valueOf(w_head);
			count++;
		}
		if (w_center!=null && !"".equals(w_center)) {
			ave+=Double.valueOf(w_center);
			count++;
		}
		if (w_foot!=null && !"".equals(w_foot)) {
			ave+=Double.valueOf(w_foot);
			count++;
		}
		if (count!=0) {
			ave=ave/count;
			DecimalFormat deFormat = new DecimalFormat("######0.000");
			value=deFormat.format(ave);
		}
		
		
		return value;
	}
}
