/***文档注释***********************************************
 * 作者            ：      易鑫
 * 创建日期     ：2018-02-6
 * 描述            ：材质判定记录表
 * 注意事项     ：
 * 遗留BUG   ：
 * 修改日期     ：
 * 修改人员     ：
 * 修改内容     ：
***********************************************************/
package market.Qms.qcm.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import market.Com.mapper.ComBaseInfoMapper;
import market.Com.mapper.ComBaseSteelMapper;
import market.Com.mapper.PbModelDbMapper;
import market.Com.vo.ComBaseCbYdd;
import market.Com.vo.ComBaseSteel;
import market.Com.vo.CommonPage;
import market.Com.vo.ResultModel;
import market.Lms.Warehouse.mapper.YdmProductDetailMapper;
import market.Lms.Warehouse.service.YdmProductInlistService;
import market.Lms.Warehouse.vo.YdmProductDetail;
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.QcmJudgeSurfaceFlawMapper;
import market.Qms.qcm.mapper.QcmJudgeSurfaceMapper;
import market.Qms.qcm.mapper.QcmJudgeUltimateReasonMapper;
import market.Qms.qcm.service.QcmJudgeSurfaceService;
import market.Qms.qcm.vo.Composition_standard;
import market.Qms.qcm.vo.QcmJhySampleConsignM;
import market.Qms.qcm.vo.QcmJhySampleROrd;
import market.Qms.qcm.vo.QcmJudgeSurface;
import market.Qms.qcm.vo.QcmJudgeSurfaceFlaw;
import market.Qms.qcm.vo.QcmJudgeUltimateReason;
import market.Qms.slmord.mapper.QcmJudgeBlockadeInfoMapper;
import market.Qms.slmord.vo.QcmJudgeBlockadeInfo;
import market.Slm.FundManagement.service.SlmFundFirstDetailService;

import org.apache.commons.collections.CollectionUtils;
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="QcmJudgeSurfaceService")
public class QcmJudgeSurfaceServiceImpl extends BaseServiceImpl<QcmJudgeSurface, String> implements QcmJudgeSurfaceService {

	/**
	 * 质量判定-根据材料号获取主缺陷名
	 * sum.material_no 材料号
	 * memo1 表面检验类型
	 * */
	public ResultModel findNameByMN(CommonPage<QcmJudgeSurface> sum){
		ResultModel rm=new ResultModel();
		try {
			QcmJudgeSurface qsf=sum.getObject();
			if(qsf==null){
				rm.setMsgInfo("请传入参数！");
				rm.setState("500");
				return rm;
			}
			rm.setData(this.getMapper(QcmJudgeSurfaceFlawMapper.class).findNameByMN(sum.getObject(),sum.getMemo1()));
			rm.setState("200");
		} catch (Exception e) {
			rm.setMsgInfo("查询失败");
			rm.setState("500");
			e.printStackTrace();
		}
		return rm;
		
	}
	/**
	 * 质量判定-上、下、边部表检测查询
	 * sum.heat_no 炉号
	 * sum.batch_no 轧批号
	 * sum.material_no 材料号
	 * startTime 起始时间
	 * endTime 终止时间
	 * memo1 检测类别“E、边部，U、上表,D、下表”
	 * pageIndex 页码
	 * pageSize 页大小
	 * */
	public ResultModel doQueryQJS(CommonPage<QcmJudgeSurface> sum){
		ResultModel rm=new ResultModel();
		QcmJudgeSurface qjs=sum.getObject();
		try {
			if(qjs==null){
				rm.setState("500");
				rm.setMsgInfo("请传入数据！");
				return rm;
			}
			int pageIndex = sum.getPageIndex();
			int pageSize = sum.getPageSize();
			String Str = "";
			if(qjs.getSf_result_code()!=null && !"".equals(qjs.getSf_result_code().trim())){
				Str+=" and t.sf_result_code like '%"+qjs.getSf_result_code()+"%'";
			}
			if(qjs.getBatch_no()!=null && !"".equals(qjs.getBatch_no().trim())){
				Str+=" and ypd.batch_no like '%"+qjs.getBatch_no()+"%'";
			}
			if(qjs.getHeat_no()!=null && !qjs.getHeat_no().trim().equals("")){
				Str+=" and ypd.heat_no like '%"+qjs.getHeat_no()+"%'";
			}
			if(qjs.getMaterial_no()!=null && !qjs.getMaterial_no().trim().equals("")){
				Str+=" and t.material_no like '%"+qjs.getMaterial_no()+"%'";
			}
			if(qjs.getPline_code()!=null && !qjs.getPline_code().equals("")){
				if ("M000T".equals(qjs.getPline_code())) {
					Str+=" and cbm.machine_code in ('M0004','M0005','M0006','M0009')";
				}else {					
					Str+=" and cbm.machine_code = '"+qjs.getPline_code()+"'";
				}
			}
			if(sum.getStartTime()!=null&&!sum.getStartTime().equals("")){
				Str+=" and t.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 t.judge_time<=to_date(concat('"+sum.getEndTime()+"',' 23:59:59'),'yyyy-MM-dd HH24:mi:ss') ";
			}
			
			PageModel<QcmJudgeSurface> pm=new PageModel<>(pageIndex, pageSize);
			List<QcmJudgeSurface> list = this.getMapper(QcmJudgeSurfaceMapper.class).doQueryQjsNew(Str,(pageIndex-1)*pageSize,pageSize*pageIndex);
			pm.setTotal(this.getMapper(QcmJudgeSurfaceMapper.class).doQueryQjsNewCount(Str));
			pm.setRows(list);
			rm.setData(pm);
			rm.setState("200");
		} catch (Exception e) {
			rm.setState("500");
			rm.setMsgInfo("查询失败！");
			e.printStackTrace();
		}
		return rm;
		
	}

	/**
	 * 质量判定-通过检验记录号获取主缺陷名
	 * sum.surface_id 检验记录号
	 * */
	public ResultModel findNameById(CommonPage<QcmJudgeSurfaceFlaw> sum) {
		ResultModel rm=new ResultModel();
		QcmJudgeSurfaceFlaw qjs=sum.getObject();
		try {
			if(qjs==null){
				rm.setState("500");
				rm.setMsgInfo("请传入数据！");
				return rm;
			}
			qjs.setPrimary_flag("1");
			rm.setData(this.getMapper(QcmJudgeSurfaceFlawMapper.class).findNameById(sum.getObject()));
			rm.setState("200");
		} catch (Exception e) {
			rm.setState("500");
			rm.setMsgInfo("查询失败！");
			e.printStackTrace();
		}
		return rm;
	}
	/**
	 * 质量判定-通过检验索引号查询表面缺陷实绩表
	 * sum.surface_id 检验记录号
	 * */
	public ResultModel doQueryFlaw(CommonPage<QcmJudgeSurfaceFlaw> sum){
		ResultModel rm=new ResultModel();
		QcmJudgeSurfaceFlaw qf=sum.getObject();
		try {
			if(qf==null){
				rm.setState("500");
				rm.setMsgInfo("请传入数据！");
				return rm;
			}
			rm.setData(this.getMapper(QcmJudgeSurfaceFlawMapper.class).doQueryFlaw(sum.getObject()));
			rm.setState("200");
		} catch (Exception e) {
			rm.setState("500");
			rm.setMsgInfo("查询失败！");
			e.printStackTrace();
		}
		return rm;
		
	}
	/**
	 * 质量判定-表面检验与表面:检验登记
	 * 检验实绩信息
	 * sum.heat_no 炉号
	 * sum.batch_no 轧批号
	 * sum.inspection_lot 检验号
	 * sum.material_no 材料号
	 * sum.surface_result_code 表面检验结果代码
	 * sum.surface_result_name 表面检验结果名称
	 * sum.surface_memo 表面检验备注
	 * sum.SF_TYPE 表面检验类型(U:上表面,D:下表面,E:边部)
	 * sum.respon_section_code 责任单位代码(物料生产产线对应的车间）
	 * sum.respon_section_name 责任单位名称
	 * sum.pline_code 产线代码
	 * sum.pline_name 产线名称
	 * 缺陷实绩信息
	 * sum.primary_flag 主缺陷标识
	 * sum.flaw_seq 缺陷序号
	 * sum.flaw_code 缺陷代码
	 * sum.flaw_desc 缺陷描述
	 * sum.flaw_type_code 缺陷类型代码
	 * sum.flaw_type_desc 缺陷类型名称
	 * sum.flaw_pos_code 缺陷位置代码
	 * sum.flaw_pos_desc 缺陷位置描述
	 * sum.flaw_weight 缺陷重量
	 * sum.flaw_quantity 缺陷数量
	 * sum.memo 备注
	 * */
	@SuppressWarnings("unchecked")
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doAddFlaw(Composition_standard sum) throws Exception {
		ResultModel rm=new ResultModel();
		Date now = new Date();
		String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(now); //操作时间
		String userId = (String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		String username = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);/* 编号、姓名、班次、班组 */
		String wrk_ord = (String) this.getSession().getAttribute(HomeService.SESSION_WORK_ORD);
		String wrk_grp = (String) this.getSession().getAttribute(HomeService.SESSION_WORK_GRP);
		List<QcmJudgeSurface> qjslist=sum.getObjectList1();
		List<QcmJudgeSurfaceFlaw> qjsflist=sum.getObjectList2();
				
		if(CollectionUtils.isEmpty(qjslist)){
			rm.setMsgInfo("请传入数据！");
			rm.setState("500");
			return rm;
		}
		try {
			for(QcmJudgeSurface qjs:qjslist){
				//验证材料信息是否存在综合判定结果
				//判断综合判定结果是否存在
				YdmProductDetail ydm=this.getMapper(YdmProductDetailMapper.class).findById(qjs.getMaterial_no());
				if(ydm != null){
					if (ydm.getJudgeresult()!=null && !ydm.getJudgeresult().equals("")) {
						rm.setState("500");
						rm.setMsgInfo("存在综合判定结果，无法进行表面检验!");
						return rm;
					}
					if ("1".equals(ydm.getSfu_is_lock())) {
						rm.setState("500");
						rm.setMsgInfo("物料["+qjs.getMaterial_no()+"],已经表面锁定，不能重新判定，请到异常材界面进行物料处理后操作！");
					    return rm;
					}
				}else{
					List<QcmJudgeSurface> oldSuf=this.getMapper(QcmJudgeSurfaceMapper.class).findWithCondition(null, "MATERIAL_NO='"+qjs.getMaterial_no()+"'", "SURFACE_ID desc", 0, 0);
					if (CollectionUtils.isNotEmpty(oldSuf)) {
						if ("1".equals(oldSuf.get(0).getSfu_is_lock())) {
							rm.setState("500");
							rm.setMsgInfo("物料["+qjs.getMaterial_no()+"],已经表面锁定，不能重新判定，请到异常材界面进行物料处理后操作！");
						    return rm;
						}
					}
				}			
			}
			
			String sid="";
			List<QcmJudgeSurface> qjslisttt=new ArrayList<QcmJudgeSurface>();
			for(QcmJudgeSurface qjs:qjslist){
				//找到索引码最大值icount
				String ymd = new SimpleDateFormat("yyMMdd").format(new Date());
				List<QcmJudgeSurface> list=this.getMapper(QcmJudgeSurfaceMapper.class).
						findWithCondition(null, " SURFACE_ID like 'U"+ ymd + "%' ", "SURFACE_ID desc", 0, 1);
				int icount = 0;
				if (list != null && list.size() > 0) {
					String s=list.get(0).getSurface_id();
					icount = Integer.parseInt(s.substring(s.length()-4,s.length()));
				}
				//生成检验索引码，编码规则：U/D/E+两位年/月/日+4位流水号,示例：E1803070001；
				icount++;
				sid="U"+ymd + String.format("%04d",icount);
				qjs.setSurface_id(sid);
				qjs.setWrk_grp(wrk_grp);//班组
				qjs.setWrk_ord(wrk_ord);//班次
				qjs.setJudge_name(username);//检验员
				qjs.setJudge_time(new Date());//检验日期
				this.getMapper(QcmJudgeSurfaceMapper.class).insert(qjs);
				qjslisttt.add(qjs);
				Long seq=0L;
				// 获取物料历史缺陷集合
				String conn = "and material_no = '"+ qjs.getMaterial_no() +"'";
				List<QcmJudgeSurface> qjsListOld = this.getMapper(QcmJudgeSurfaceMapper.class).findWithCondition(null, conn, null, 0, 0);
				if(qjsListOld!=null && qjsListOld.size()>0){
					String sufIdStr="";
					for(QcmJudgeSurface qjs1 : qjsListOld){
						if("".equals(sufIdStr))
							sufIdStr += "'"+qjs1.getSurface_id()+"'";
						else
							sufIdStr += ",'"+qjs1.getSurface_id()+"'";
					}
					String condition = "and surface_id in ("+sufIdStr+")";
					List<QcmJudgeSurfaceFlaw> qjsffList = this.getMapper(QcmJudgeSurfaceFlawMapper.class).findWithCondition(null, condition, null, 0, 0);
					String condition1 = "and surface_id in ("+sufIdStr+") and primary_flag ='1'";
					List<QcmJudgeSurfaceFlaw> qjsffList1 = this.getMapper(QcmJudgeSurfaceFlawMapper.class).findWithCondition(null, condition1, null, 0, 0);
					// 之前已经登记过缺陷，则将此次所有缺陷都改为非主缺陷
					if(qjsffList1!=null && qjsffList1.size()>0){
						for(QcmJudgeSurfaceFlaw qjsff1 : qjsflist){
							if(!qjsffList1.get(0).getFlaw_code().equals(qjsff1.getFlaw_code())){
								qjsff1.setPrimary_flag("0");
							}
						}
					}
					for(QcmJudgeSurfaceFlaw qjsf1:qjsffList){
						Boolean flag = false;
						for(QcmJudgeSurfaceFlaw qjsf2:qjsflist){
							if(qjsf1.getFlaw_code().equals(qjsf2.getFlaw_code())){
								flag = true;
								break;
							}
						}
						if(!flag)
							qjsflist.add(qjsf1);
					}
				}
				int seq1 = 0;
				for(QcmJudgeSurfaceFlaw qjsf:qjsflist){
					//将获取的缺陷实绩信息插入表面缺陷实绩表
					String[] strList = qjsf.getFlaw_area().split(",");
					for(String str : strList){
						qjsf.setSurface_id(sid);
						seq++;
						qjsf.setFlaw_seq(seq);
						qjsf.setFlaw_area(str);
						qjsf.setCreate_name(username);//创建人
						qjsf.setCreate_time(new Date());//创建时间
						this.getMapper(QcmJudgeSurfaceFlawMapper.class).insert(qjsf);
						seq1++;
					}
					QcmJudgeUltimateReason qjr = new QcmJudgeUltimateReason();
					qjr.setMaterial_no(qjs.getMaterial_no());
					qjr.setType_code("U");
					qjr.setRecord_id(sid);
					qjr.setSeq(seq1);
					qjr.setPhy_code_s(qjsf.getFlaw_code());
					qjr.setPhy_name_s(qjsf.getFlaw_desc());
					qjr.setCreate_name(username);
					qjr.setCreate_time(new Date());
					this.getMapper(QcmJudgeUltimateReasonMapper.class).insert(qjr);
				}
			}
			
			//更新库存表上表，下表，边部结果			
			for (QcmJudgeSurface qjs : qjslisttt) {
				if ("40740603".equals(qjs.getSf_result_code())) {//如果是待判、清空物料表检信息
					this.getMapper(QcmJudgeSurfaceMapper.class).cleanSuf(qjs.getMaterial_no());
				}else{
					this.getMapper(YdmProductDetailMapper.class).upresultU(qjs.getSf_result_code(), qjs.getMaterial_no(),sid);
				}			
			}
			
			//异常材料处置，进行物料封锁
			for (QcmJudgeSurface qjs:qjslisttt){
				// 不合格时，直接进行异常材料处置业务
				if ("40740602".equals(qjs.getSf_result_code())) {
					MaterialAbnormalTreatment(qjs);
				}
				// 判废时，根据代码配置决定是否发起异常材料处置业务
				if ("40740604".equals(qjs.getSf_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(qjs);
					} else {
						// 判废业务
					}
				}
			}
			
			//日志
			for (QcmJudgeSurface qjs : qjslisttt) {
				
//				String isOpen = this.getMapper(ComBaseInfoMapper.class).findById("9512").getMemo();
//				if ("1".equals(isOpen)) {
//				
//					// coilno, width,thick,length,orderno,steelcode,weight
//					// 记录成本异动点：20230811刘侣：外观及综合判定还没入库，所以得用实绩产出表；20230818
////					YdmProductDetail ypd = this.getMapper(YdmProductDetailMapper.class).doFind(qjs.getMaterial_no(), null);
//					HashMap hm = this.getBean(YdmProductInlistService.class).doQueryCchu(qjs.getMaterial_no());
//					ComBaseCbYdd cd = new ComBaseCbYdd();
//					cd.setCoilStus("0"); // 综判前算半成品0，综判入库后算成品1
//					cd.setInstDisp("01");
//					cd.setDataTypeIdx("O");
//					// 当前产线：
//					String currentMachine = qjs.getMaterial_no().contains("S") ? "YTSX" : qjs.getMaterial_no().contains("L") ? "YTZZ" : qjs.getMaterial_no().contains("P") ? "YTPZ" : qjs.getMaterial_no().contains("T") ? "YTTH" : qjs.getMaterial_no().contains("K") ? "YTHJ" : qjs.getMaterial_no().contains("F") ? "YTZJ" : "YT1";
//					cd.setLocNo(currentMachine); // 填当前产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
//					cd.setInvQtyUnit("块");
//					cd.setInvWidth(hm.get("width") != null ? String.valueOf(hm.get("width")) : "0");
//					cd.setCreateId(userId);
//					// 目前：不合格和次品都是：11AF
//					cd.setActivityId("40740601".equals(qjs.getSf_result_code()) ? "11AC" : "40740604".equals(qjs.getSf_result_code()) ? "11AZ" : "11AF");
//					cd.setInvLength(hm.get("length") != null ? String.valueOf(hm.get("length")) : "0");
//					cd.setManageip(currentMachine); // 填当前产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
//					cd.setProdName(qjs.getProd_name().contains("钢") ? qjs.getProd_name() : qjs.getProd_code());
//					cd.setInvThick(hm.get("thick") != null ? String.valueOf(hm.get("thick")) : "0");
//					
//					
//					String prevcoil = this.getBean(YdmProductInlistService.class).doQueryTl(qjs.getMaterial_no());
//					// 上道产线：
//					String prevMachine = prevcoil.contains("S") ? "YTSX" : prevcoil.contains("L") ? "YTZZ" : prevcoil.contains("P") ? "YTPZ" : prevcoil.contains("T") ? "YTTH" : prevcoil.contains("K") ? "YTHJ" : prevcoil.contains("F") ? "YTZJ" : "YT1";
//					cd.setRefnoA(prevcoil); // 投料卷号
//					cd.setSysId("IA");
//					cd.setOrderItem((String) hm.get("orderno"));
//					cd.setCrntMill(currentMachine); // 填当前产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
//					cd.setBeTransUnit("t");
//					cd.setExecJobFunc("N");
//					ComBaseSteel cbs = this.getMapper(ComBaseSteelMapper.class).findById(hm.get("steelcode"));
//					if (cbs != null) {
//						cd.setAlloyNo(cbs.getSteel_name()); // 牌号
//					}
//					
//					cd.setAcctDate(new SimpleDateFormat("yyyyMMdd").format(now));
//					cd.setLastMill(prevMachine); // 填上道工序产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
//					cd.setBeTransWgt((Double) hm.get("weight"));
//					cd.setProdTypeNo("CTR");
//					cd.setAppId("优特钢产出卷表面判定");
//					cd.setInvId(qjs.getMaterial_no());
//					cd.setInvQty("1");
//					cd.setSrcFac("1");
//					cd.setGrade("40740601".equals(qjs.getSf_result_code()) ? "1" : "5"); // 正品　1　协议　3　次品　5
//					cd.setProdClassNo("H");
//					// 存入表：
//					this.getBean(SlmFundFirstDetailService.class).doCbDataIns(cd, cd.getActivityId());
//					
//					// 再做综合判定异动点插入：
//					cd.setAppId("优特钢产出卷综合判定");
//					this.getBean(SlmFundFirstDetailService.class).doCbDataIns(cd, cd.getActivityId());
//					// end
//				}
				
				MesOprLog mol = new MesOprLog("质量管理", "外观检验管理", "检验登记", username, opr_time, qjs.getMaterial_no(), null, null, null, "判定结果："+qjs.getSf_result_desc()+";备注："+qjs.getSf_memo());
				this.getMapper(MesOprLogMapper.class).insert(mol);
			}			
	 		rm.setData(qjslisttt);
			rm.setState("200");
		} catch (Exception e) {
			rm.setState("500");
			rm.setMsgInfo("新增失败！");
			e.printStackTrace();
			throw new Exception();
		}
		return rm;
		
	}
	
	
	/**
	 * 异常材料处理--封锁物料
	 */
	public void MaterialAbnormalTreatment(QcmJudgeSurface qjs){
		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("U");
				//获取缺陷
				String flaw="";
				YdmProductDetail ydm=new YdmProductDetail();
				ydm.setCoilno(qjs.getMaterial_no());
				//ydm.setState("6");
				List<QcmJudgeSurfaceFlaw> listqjsf = this.getMapper(QcmJudgeSurfaceFlawMapper.class).findWithCondition(null, "SURFACE_ID='"+qjs.getSurface_id()+"'", null, 0, 0);
				for (QcmJudgeSurfaceFlaw qjsf : listqjsf) {
					flaw+=qjsf.getFlaw_desc()+",";
				}
				if (",".equals(flaw.substring(flaw.length()-1, flaw.length()))) {
					qjb.setBic_memo("表面:"+flaw.substring(0,flaw.length()-1));
					ydm.setSfu_is_lock("1");
				}else {
					qjb.setBic_memo("表面:"+flaw.substring(0,flaw.length()));
					ydm.setSfu_is_lock("1");
				}
				//获取合同行主键
				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(qjs.getHeat_no());
				qjb.setBatch_no(qjs.getBatch_no());
				
				qjb.setInspection_lot(qjs.getInspection_lot());
				qjb.setMaterial_no(qjs.getMaterial_no());
				qjb.setObject_no_pseudo(qjs.getVirtual_material_no()); //
				qjb.setCut_edge_type_name(qjs.getCut_edge_type_name());
				qjb.setCut_edge_type_no(qjs.getCut_edge_type_no());
				qjb.setWidth(qjb.getWidth());
				qjb.setThick(qjs.getThick());
				qjb.setLength(qjs.getLength());
//				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(qjs.getPsc());
		    	qjb.setOld_prod_code(qjs.getProd_code());
		    	qjb.setOld_prod_name(qjs.getProd_name());
		    	qjb.setOld_std_code(qjs.getStd_code());
		    	qjb.setOld_std_name(qjs.getStd_name());
		    	qjb.setOld_steel_code(qjs.getSteel_code());
		    	qjb.setOld_steel_name(qjs.getSteel_name());
		    	qjb.setOld_delivery_state_code(qjs.getDelivery_state_code());
		    	qjb.setOld_delivery_state_desc(qjs.getDelivery_state_desc());
		    	// 目标产品信息
		    	qjb.setPsc(qjs.getPsc_new());
		    	qjb.setProd_code(qjs.getProd_code_new());
		    	qjb.setProd_name(qjs.getProd_name_new());
		    	qjb.setStd_code(qjs.getStd_code_new());
		    	qjb.setStd_name(qjs.getStd_name_new());
		    	qjb.setSteel_code(qjs.getSteel_code_new());
		    	qjb.setSteel_name(qjs.getSteel_name_new());
		    	qjb.setDelivery_state_code(qjs.getDelivery_state_code_new());
		    	qjb.setDelivery_state_desc(qjs.getDelivery_state_desc_new());
		    	qjb.setCreate_time(new Date());
		    	qjb.setCreate_name((String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME));
		    	qjb.setPline_code(qjs.getPline_code());
		    	qjb.setPline_name(qjs.getPline_name());
		    	if (qjs.getWidth()!=null&&!(qjs.getWidth()).equals("")) {
		    		qjb.setWidth(qjs.getWidth());	
				}
		    	if (qjs.getThick()!=null&&!(qjs.getThick()).equals("")) {
		    		qjb.setThick(qjs.getThick());
				}
		    	if (qjs.getLength()!=null&&!(qjs.getLength()).equals("")) {
		    		qjb.setLength(qjs.getLength());	
				}
				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 findFlawData(String typeName,String flawName){
		ResultModel rm=new ResultModel();
		try {
			rm.setData(this.getMapper(ComBaseInfoMapper.class).findFlawData(typeName,flawName));
			rm.setState("200");
		} catch (Exception e) {
			rm.setMsgInfo("查询失败！");
			rm.setState("500");
		}
		return rm;
		
	}
	/**
	 * 质量判定-根据缺陷代码获取缺陷代码基础数据
	 * */
	public ResultModel findFlawDataByCode(String typeName,String flawName,String flawCode){
		ResultModel rm=new ResultModel();
		try {
			rm.setData(this.getMapper(ComBaseInfoMapper.class).findFlawDataByCode(typeName,flawName,flawCode));
			rm.setState("200");
		} catch (Exception e) {
			rm.setMsgInfo("查询失败！");
			rm.setState("500");
		}
		return rm;
		
	}
	/**
	 *
	 *综合判定-获取上，下，边部检验实绩信息
	 *
	 */
	public ResultModel getSurfaceSampleItem(CommonPage<YdmProductDetail> sum){
		ResultModel rm=new ResultModel();
		YdmProductDetail ydm=sum.getObject();
		 List<QcmJudgeSurface> listSur=new ArrayList<>();
		 if ("".equals(ydm.getUp_surface_result_id())) {
			 rm.setData(listSur);
	         rm.setState("200");
	         return rm;
		 }
		 try {
			 //获取上表信息  取最新的记录
			 if (!"".equals(ydm.getUp_surface_result_id())) {
				 List<QcmJudgeSurface> qjmUList=this.getMapper(QcmJudgeSurfaceMapper.class).findWithCondition(null, "SURFACE_ID = '"+ydm.getUp_surface_result_id()+"'", "SURFACE_ID desc", 0, 0);
				 listSur.add(qjmUList.get(0));
			 }
          rm.setData(listSur);
          rm.setState("200");
		} catch (Exception e) {
			rm.setState("500");
			rm.setErrorInfo(e.getMessage());
		}
		return rm;
	}
	/**
	 * 查询缺陷信息
	 * @param sum
	 * @return
	 */
	public ResultModel getFlawSample(CommonPage<QcmJudgeSurface> sum){
		ResultModel rm=new ResultModel();
		QcmJudgeSurface qjs=sum.getObject();
		try {
			List<QcmJudgeSurfaceFlaw> qjsf = this.getMapper(QcmJudgeSurfaceFlawMapper.class).findWithCondition(null, "SURFACE_ID='"+qjs.getSurface_id()+"'", null, 0, 0);
		   rm.setData(qjsf);
		   rm.setState("200");
		} catch (Exception e) {
			rm.setState("500");
			rm.setMsgInfo("查询失败");
			rm.setErrorInfo(e.getMessage());
		}
		return rm;
	}
	/**
	 * 
	 * @param sum
	 * sum.material_no 材料号
	 * @return
	 */
	public ResultModel getMainFlawSample(CommonPage<QcmJudgeSurface> sum){
		ResultModel rm=new ResultModel();
		QcmJudgeSurface qjsf=sum.getObject();
		QcmJudgeSurfaceFlaw q=new QcmJudgeSurfaceFlaw();
		String connect="";
		try {
			//获取各表面最大流水号
			List<QcmJudgeSurface> listU = this.getMapper(QcmJudgeSurfaceMapper.class).findWithCondition(null, "SF_TYPE='U' and SURFACE_ID like '%U%' and MATERIAL_NO='"+qjsf.getMaterial_no()+"'","SURFACE_ID desc", 0, 1);
		    List<QcmJudgeSurface> listD = this.getMapper(QcmJudgeSurfaceMapper.class).findWithCondition(null, "SF_TYPE='D' and SURFACE_ID like '%D%' and MATERIAL_NO='"+qjsf.getMaterial_no()+"'", "SURFACE_ID desc", 0, 1);
		    List<QcmJudgeSurface> listE = this.getMapper(QcmJudgeSurfaceMapper.class).findWithCondition(null, "SF_TYPE='E' and SURFACE_ID like '%E%' and MATERIAL_NO='"+qjsf.getMaterial_no()+"'", "SURFACE_ID desc", 0, 1);
            //根据最大流水号获取主缺陷
		    if (listU.size()>0) {
		    	List<QcmJudgeSurfaceFlaw> listFlawU = this.getMapper(QcmJudgeSurfaceFlawMapper.class).findWithCondition(null, "SURFACE_ID='"+listU.get(0).getSurface_id()+"'", null, 0, 1);
		        connect+="上表："+listFlawU.get(0).getFlaw_desc()+";";
		    }
		    if (listD.size()>0) {
		    	List<QcmJudgeSurfaceFlaw> listFlawD = this.getMapper(QcmJudgeSurfaceFlawMapper.class).findWithCondition(null, "SURFACE_ID='"+listD.get(0).getSurface_id()+"'", null, 0, 1);
		    	connect+="下表："+listFlawD.get(0).getFlaw_desc()+";";
		    }
		    
		    if (listE.size()>0) {
		    	List<QcmJudgeSurfaceFlaw> listFlawE = this.getMapper(QcmJudgeSurfaceFlawMapper.class).findWithCondition(null, "SURFACE_ID='"+listE.get(0).getSurface_id()+"'", null, 0, 1);
		    	connect+="边部："+listFlawE.get(0).getFlaw_desc()+";";
		    }
		    q.setFlaw_desc(connect);
		    rm.setData(q);
		    rm.setState("200");
		} catch (Exception e) {
			rm.setState("500");
			rm.setMsgInfo("查询失败");
			rm.setErrorInfo(e.getMessage());
		}
		return rm;
	}
	/**
	 * 查询修改类别
	 * @return
	 */
	public ResultModel getCategory(){
		ResultModel rm=new ResultModel();
		try {
			rm.setData(this.getMapper(ComBaseInfoMapper.class).findWithCondition(null, "sort_code='4104'", null, 0, 0));
		} catch (Exception e) {
		}
		return rm;
	}
	
	/**
	 * 查询修改类别
	 * @return
	 */
	public ResultModel getCategory2(){
		ResultModel rm=new ResultModel();
		try {
			rm.setData(this.getMapper(ComBaseInfoMapper.class).findWithCondition(null, "sort_code='4105'", null, 0, 0));
		} catch (Exception e) {
		}
		return rm;
	}
	/**
	 * 查询登记之后的缺陷，用于表检再次登记时进行对比 -----2018.12.29
	 * @param virtual_material_no
	 * @return
	 */
	public ResultModel getFlawAfterRegister(String virtual_material_no,String type){
		ResultModel rm=new ResultModel();
		try {
			List<QcmJudgeSurfaceFlaw> listqjsf =new ArrayList<>();
			List<QcmJudgeSurface> listqjs=new ArrayList<>();
			if ("U".equals(type)) {
				 listqjs = this.getMapper(QcmJudgeSurfaceMapper.class).findWithCondition(null, "material_no='"+virtual_material_no+"' and sf_type='U'", "judge_time desc", 0, 0);
			}else if ("D".equals(type)) {
				listqjs = this.getMapper(QcmJudgeSurfaceMapper.class).findWithCondition(null, "material_no='"+virtual_material_no+"' and sf_type='D'", "judge_time desc", 0, 0);
			}else if ("E".equals(type)) {
				listqjs = this.getMapper(QcmJudgeSurfaceMapper.class).findWithCondition(null, "material_no='"+virtual_material_no+"' and sf_type='E'", "judge_time desc", 0, 0);
			}
		  if (listqjs!=null&&listqjs.size()>0) {
			  if (!DataHelper.IsNullOrSpace(listqjs.get(0).getSurface_id())) {
				  listqjsf = this.getMapper(QcmJudgeSurfaceFlawMapper.class).findWithCondition(null, "surface_id='"+listqjs.get(0).getSurface_id()+"'", null, 0, 0);	
				}
		}
		  rm.setState("200");
		  rm.setData(listqjsf);
		} catch (Exception e) {
			 rm.setState("500");
			 rm.setErrorInfo(e.getMessage());
		}
		return rm;
	}
	/**
	 * 修复/取消修复缺陷 -----2019.5.7
	 * @param
	 * @return
	 */
	public ResultModel repairFlaw(String sufId,String FlawSeq,String flag){
		ResultModel rm=new ResultModel();
		try {
			this.getMapper(QcmJudgeSurfaceFlawMapper.class).repairFlaw(sufId, FlawSeq, flag);
			rm.setState("200");
		} catch (Exception e) {
			 rm.setState("500");
			 rm.setErrorInfo(e.getMessage());
		}
		return rm;
	}
	
	/**
	 * 酸洗的公差和外观检测管理：删除缺陷
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	public ResultModel doDeleteFlaw(CommonPage<QcmJudgeSurfaceFlaw> cp) 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);
		
		QcmJudgeSurfaceFlaw qjsf = cp.getObject();
		String sql = "delete from qcm_judge_surface_flaw t where t.surface_id = '"+qjsf.getSurface_id()+"' and t.flaw_seq = "+qjsf.getFlaw_seq();
		this.getMapper(PbModelDbMapper.class).doDeleteSql(sql);
		
		//日志
		MesOprLog mol = new MesOprLog("车间MES", "公差和外观检验管理", "删除缺陷", username, opr_time, null, null, null, null, null);
		this.getMapper(MesOprLogMapper.class).insert(mol);
		
		rm.setState("200");
		return rm;
	}
	//1036
}
