package market.Qms.slmord.impl;

import java.util.ArrayList;
import java.util.List;

import market.Com.vo.CommonPage;
import market.Com.vo.ResultModel;
import market.Qms.common.DataHelper;
import market.Qms.common.ReturnMsg;
import market.Qms.metallurgy.mapper.ComMscCicSampleMapper;
import market.Qms.metallurgy.mapper.ComMscStdChemMapper;
import market.Qms.metallurgy.mapper.ComMscStdCicMapper;
import market.Qms.metallurgy.vo.ComMsc;
import market.Qms.metallurgy.vo.ComMscCicSample;
import market.Qms.metallurgy.vo.ComMscStdChem;
import market.Qms.metallurgy.vo.ComMscStdCic;
import market.Qms.slmord.mapper.SlmOrdDesignStdCicMapper;
import market.Qms.slmord.mapper.SlmOrdDesignStdCicSmpMapper;
import market.Qms.slmord.mapper.SlmOrdDesignStdMapper;
import market.Qms.slmord.service.QualityDesignStdCicService;
import market.Qms.slmord.vo.SlmOrdDesignStd;
import market.Qms.slmord.vo.SlmOrdDesignStdCic;
import market.Qms.slmord.vo.SlmOrdDesignStdCicSmp;
import market.Slm.OrderManagement.vo.SlmContractProcessPlan;

import com.hnshituo.basic.service.impl.BaseServiceImpl;
import com.hnshituo.basic.spring.remoting.annotation.RemoteService;
@RemoteService(path="QualityDesignStdCicService")
public class QualityDesignStdCicServiceImpl extends BaseServiceImpl<Object,Object> implements QualityDesignStdCicService{
	
	
	/**
	 * 过滤交货状态
	 * @param listCic 成分索引
	 * @param deliveryCode 交货状态编号
	 */
	@Override
	public boolean FilterDeliveryState(List<ComMscStdCic> listCic,String deliveryCode){
		for (int i = 0; i < listCic.size(); i++) {
			ComMscStdCic cic=listCic.get(i);
			if(cic.getValidflag().equals("0")){
				listCic.remove(i);
				i--;
				continue;
			}
			if(cic.getDelivery_state_code()!=null){
				if(!cic.getDelivery_state_code().contains(deliveryCode)){
					listCic.remove(i);
					i--;
				}
			}
		}
		return listCic.size()>0;
	}
	
	
	/**
	 * 验证成分标准
	 * @param msg 返回信息
	 * @param msc 冶金规范码
	 * @param orderLine 合同信息
	 * @param designKey 
	 * @param flag，0：国标，1：客户标准，2：内控标准
	 * @return
	 */
	@Override
	public boolean ValidationStdCIC(ReturnMsg msg,ComMsc msc,SlmContractProcessPlan orderLine,String designKey,String flag){
		ComMscStdCicMapper mapper=this.getMapper(ComMscStdCicMapper.class);
		List<ComMscStdCic> listCic=new ArrayList<>();
		// 如果冶金规范码已经生效，则查询已经审批通过的成分标准索引号
		ComMscStdCic _mscStdCic=new ComMscStdCic();
		_mscStdCic.setMsc(msc.getMsc());
		if(msc.getValidflag().equals("C")){
			_mscStdCic.setValidflag("3");
			listCic=mapper.find(_mscStdCic, 0, 0);
		}else{
			//如果没有生效，取有效成分索引号
			listCic=mapper.find(_mscStdCic, 0, 0);
			for(int index=0;index<listCic.size();index++){
				if(listCic.get(index).getValidflag().equals("0")){
					listCic.remove(listCic.get(index));
					index--;
				}
			}
		}
		//2018-05-28：改为只要有索引存在才验证向下的标准信息
/*		if(listCic.size()<1&&flag.equals("0")){//交付标准中必须有成分标准
			msg.setMessage("制造规范 ‘"+msc.getMsc()+"’ 找不到成分标准索引");
			return false;
		}else*/
		if(listCic.size()<1&&(flag.equals("1")||flag.equals("0"))){//客户标准中不存在标准索引则视为无标准要求
			msg.setMessage("无成分要求");
			return true;
		}
		boolean pass=FilterDeliveryState(listCic,orderLine.getDelivery_state_code());
		if(!pass){
			msg.setMessage("没有找到符合订单交货状态的成分标准索引信息");
			return false;
		}
		ComMscStdChemMapper chemMapper=this.getMapper(ComMscStdChemMapper.class);
		ComMscCicSampleMapper sampleMapper=this.getMapper(ComMscCicSampleMapper.class);
		List<String> listStdChem=new ArrayList<>();//用于存放唯一成分元素项
		for (ComMscStdCic mscStdCic : listCic) {
			ComMscStdChem chem=new ComMscStdChem();
			chem.setCic(mscStdCic.getCic());
			chem.setValidflag("1");
			List<ComMscStdChem> listChem=chemMapper.find(chem, 0, 0);
			if(listChem.size()<1){
				msg.setMessage("成分索引："+chem.getCic()+"，找不到成分标准");
				return false;
			}
			
			List<ComMscStdChem> chemAs=FilterSpec(listChem,orderLine);
			if(chemAs.size()<1){
				msg.setMessage("成分索引："+chem.getCic()+"，找不到符合订单规格的成分标准");
				return false;
			}
			
			// 验证成分标准的检验项目
			List<ComMscCicSample> smps = new ArrayList<ComMscCicSample>();
			List<ComMscCicSample> listSample=sampleMapper.GetSampleByCic(mscStdCic.getCic());
			if(listSample.size()<1){
				msg.setMessage("成分索引号：" + mscStdCic.getCic() + "没有找到取样要求");
				return false;
			}
			
			for (ComMscCicSample comMscCicSample : listSample) {
				ComMscCicSample smp = checkSmp(comMscCicSample,orderLine);
				if (smp == null) {
					msg.setMessage("成分索引号：" + mscStdCic.getCic() + "没有取样要求 (牌号：" + orderLine.getSteel_code() + ",宽度：" + orderLine.getWidth() + ",厚度：" + orderLine.getThick()+")");
					return false;
				}else{
					if(smp.getSmp_index().equals("")){
						msg.setMessage( "成分索引号:" + mscStdCic.getCic() + "没有取样要求(牌号：" + orderLine.getSteel_name()+ ",外径：" + orderLine.getWidth() + ",厚度：" + orderLine.getThick() + ")");
						return false;
					}
				}
				smp.setDesign_key(designKey);
				smps.add(smp);
			}
			
			// 录入理化标准检验项
			for (ComMscCicSample smp : smps) {
				//检查是标准取样要求是否已经存在
				//if (!phyDaoImp.checkSmp(con, smp)) {
				//保存取样要求
				SlmOrdDesignStdCicSmpMapper smpMapper=this.getMapper(SlmOrdDesignStdCicSmpMapper.class);
				SlmOrdDesignStdCicSmp _smp=new SlmOrdDesignStdCicSmp();
				try{
					DataHelper.CopyEntity(smp,_smp);
					_smp.setDesign_key(designKey);
					smpMapper.insert(_smp);
				}catch(Exception ex){
					msg.setMessage("成分取样要求验证出错："+ex.getMessage());
					return false;
					
				}
				//}
			}
			
			for (ComMscStdChem _chem : chemAs) {
				if(listStdChem.contains(_chem.getChemName())){
					msg.setMessage("成分索引号："+_chem.getCic()+"找到多条符合要求的化学元素项‘"+_chem.getChemName()+"’");
					return false;
				}else{
					listStdChem.add(_chem.getChemName());
				}				
				SlmOrdDesignStdCic stdCic=new SlmOrdDesignStdCic();
				try{
					DataHelper.CopyEntity(_chem, stdCic);
					// 是否特殊要求(0否;1是,2内控)
					if (flag.equals("1")) {
						stdCic.setAlpha_code(orderLine.getUse_code());
						stdCic.setAlpha_name(orderLine.getUse_desc());
					}
				}catch(Exception ex){}
				stdCic.setDesign_key(designKey);
				stdCic.setSpecl_fl(flag);
				this.getMapper(SlmOrdDesignStdCicMapper.class).insert(stdCic);
				
			}
			//修改标准索引号
			UpdateDesignStdCic(designKey,msc.getPsc(),mscStdCic.getCic(),flag);
		}
		msg.setMessage("成分标准验证通过");
		return true;
	}
	
	/**
	 *  修改索引
	 * @param designKey
	 * @param psc 产品码
	 * @param cic 成分索引号
	 * @param flag 标准类型
	 */
	private void UpdateDesignStdCic(String designKey,String psc,String cic,String flag){
		SlmOrdDesignStdMapper stdMapper=this.getMapper(SlmOrdDesignStdMapper.class);
		SlmOrdDesignStd designStd=stdMapper.findById(designKey,psc);//根据designKey与psc找到当前标准索引信息
		ComMscStdCic stdCic=this.getMapper(ComMscStdCicMapper.class).findById(cic);
		SlmOrdDesignStd std=new SlmOrdDesignStd();
		std.setDesign_key(designKey);
		std.setPsc(psc);
		// 保存索引号
		if (flag.equals("0")) {
			std.setCic(designStd.getCic()==null?cic:designStd.getCic()+";"+cic);
			std.setSmelting_cnt(stdCic.getSmelting_cnt());
			std.setProduct_cnt(stdCic.getProduct_cnt());
		}else if(flag.equals("1")){
			std.setCic_k(designStd.getCic_k()==null?cic:designStd.getCic_k()+";"+cic);	
			std.setSmelting_cnt_k(stdCic.getSmelting_cnt());
			std.setProduct_cnt_k(stdCic.getProduct_cnt());
		}
		this.getMapper(SlmOrdDesignStdMapper.class).update(std);
	}
	
	/**
	 * 过滤取样要求
	 * 
	 * @param smp
	 * @param orderLine
	 * @return
	 */
	@Override
	public ComMscCicSample checkSmp(ComMscCicSample smp,SlmContractProcessPlan orderLine) {
		String width=orderLine.getWidth().toString();
		String thick=orderLine.getThick().toString();
		ComMscCicSample returnData = null;
		if (DataHelper.checkStr(width, smp.getMin_d_sign(),smp.getMin_d())
				&& DataHelper.checkStr(width, smp.getMax_d_sign(),smp.getMax_d())
				&& DataHelper.checkStr(thick, smp.getMin_h_sign(),smp.getMin_h())
				&& DataHelper.checkStr(thick, smp.getMax_h_sign(),smp.getMax_h())) {
			returnData = smp;
		}else if(smp.getMin_d().equals("")
				&& smp.getMax_d().equals("") && smp.getMin_h().equals("")
				&& smp.getMax_h().equals("")) {
			returnData = smp;
		}
		return returnData;
	}
	
	
	/**
	 * 过滤限制规格
	 * @param listChem 
	 * @param orderLine
	 * @return
	 */
	@Override
	public List<ComMscStdChem> FilterSpec(List<ComMscStdChem> listChem,SlmContractProcessPlan orderLine)
	{
		List<ComMscStdChem> _listChem = new ArrayList<>();
		// 过滤限制规格 厚 400301， 宽 400302， 长 400306
		for (ComMscStdChem _stdChem : listChem) {
			if (!DataHelper.IsNullOrSpace(_stdChem.getSizeCode())) {// 为空则适用全部规格
				// 过滤限制规格一
				if (_stdChem.getSizeCode().equals("400301")) {
					boolean pass;

					if (_stdChem.getSizeMax() == null) {
						pass = true;
					} else {
						pass = DataHelper.checkSignAndValue(_stdChem.getSizeMaxSign(),
								Double.parseDouble(_stdChem.getSizeMax()), orderLine.getThick().toString());
					}
					if (!pass) {
						continue;
					}

					if (_stdChem.getSizeMin() == null) {
						pass = true;
					} else {
						pass = DataHelper.checkSignAndValue(_stdChem.getSizeMinSign(),
								Double.parseDouble(_stdChem.getSizeMin()), orderLine.getThick().toString());
					}

					if (!pass) {
						continue;
					}
				} else if (_stdChem.getSizeCode().equals("400302")) {

					boolean pass;
					if (_stdChem.getSizeMax() == null) {
						pass = true;
					} else {
						pass = DataHelper.checkSignAndValue(_stdChem.getSizeMaxSign(),
								Double.parseDouble(_stdChem.getSizeMax()), orderLine.getWidth().toString());
					}

					if (!pass) {
						continue;
					}

					if (_stdChem.getSizeMin() == null) {
						pass = true;
					} else {
						pass = DataHelper.checkSignAndValue(_stdChem.getSizeMinSign(),
								Double.parseDouble(_stdChem.getSizeMin()), orderLine.getWidth().toString());
					}

					if (!pass) {
						continue;
					}
				} else if (_stdChem.getSizeCode().equals("400306")) {

					boolean pass;
					if (_stdChem.getSizeMax() == null) {
						pass = true;
					} else {
						pass = DataHelper.checkSignAndValue(_stdChem.getSizeMaxSign(),
								Double.parseDouble(_stdChem.getSizeMax()), orderLine.getLength().toString());
					}

					if (!pass) {
						continue;
					}

					if (_stdChem.getSizeMin() == null) {
						pass = true;
					} else {
						pass = DataHelper.checkSignAndValue(_stdChem.getSizeMinSign(),
								Double.parseDouble(_stdChem.getSizeMin()), orderLine.getLength().toString());
					}

					if (!pass) {
						continue;
					}
				}
				// 验证限制规格二
				if (!DataHelper.IsNullOrSpace(_stdChem.getSizeCode2())) {
					if (_stdChem.getSizeCode2().equals("400301")) {
						boolean pass;

						if (_stdChem.getSizeMax2() == null) {
							pass = true;
						} else {
							pass = DataHelper.checkSignAndValue(_stdChem.getSizeMaxSign2(),
									Double.parseDouble(_stdChem.getSizeMax2()), orderLine.getThick().toString());
						}

						if (!pass) {
							continue;
						}

						if (_stdChem.getSizeMin2() == null) {
							pass = true;
						} else {
							pass = DataHelper.checkSignAndValue(_stdChem.getSizeMinSign2(),
									Double.parseDouble(_stdChem.getSizeMin2()), orderLine.getThick().toString());
						}

						if (!pass) {
							continue;
						}
					} else if (_stdChem.getSizeCode2().equals("400302")) {
						boolean pass;

						if (_stdChem.getSizeMax2() == null) {
							pass = true;
						} else {
							pass = DataHelper.checkSignAndValue(_stdChem.getSizeMaxSign2(),
									Double.parseDouble(_stdChem.getSizeMax2()), orderLine.getWidth().toString());
						}

						if (!pass) {
							continue;
						}

						if (_stdChem.getSizeMin2() == null) {
							pass = true;
						} else {
							pass = DataHelper.checkSignAndValue(_stdChem.getSizeMinSign2(),
									Double.parseDouble(_stdChem.getSizeMin2()), orderLine.getWidth().toString());
						}

						if (!pass) {
							continue;
						}
					} else if (_stdChem.getSizeCode2().equals("400306")) {
						boolean pass;

						if (_stdChem.getSizeMax2() == null) {
							pass = true;
						} else {
							pass = DataHelper.checkSignAndValue(_stdChem.getSizeMaxSign2(),
									Double.parseDouble(_stdChem.getSizeMax2()), orderLine.getLength().toString());
						}

						if (!pass) {
							continue;
						}

						if (pass) {
							pass = true;
						} else {
							pass = DataHelper.checkSignAndValue(_stdChem.getSizeMinSign2(),
									Double.parseDouble(_stdChem.getSizeMin2()), orderLine.getLength().toString());
						}

						if (!pass) {
							continue;
						}
					}
				}
			}
			_listChem.add(_stdChem);
		}
		return _listChem;
	}
	
	
	//查询质量设计取样要求
		public ResultModel getSample(CommonPage<SlmOrdDesignStdCicSmp> oci){
			ResultModel rm=new ResultModel();
			
			try {
				SlmOrdDesignStdCicSmp smp=oci.getObject();
				if (smp==null || smp.getDesign_key()==null) {
					rm.setState("500");
					rm.setMsgInfo("请传入designkey");
					return rm;
				}
				
				//得到psc
				if (oci.getMemo1()==null || "".equals(oci.getMemo1())) {
					rm.setState("500");
					rm.setMsgInfo("请传入psc");
					return rm;
				}
				//根据design_key+psc查询质量设计材质结果表
				SlmOrdDesignStd std=this.getMapper(SlmOrdDesignStdMapper.class).findById(smp.getDesign_key(),oci.getMemo1());
				//获取pic,以及pic_k取并集
				String cic=std.getCic();
				String cic_k=std.getCic_k();
				List<SlmOrdDesignStdCicSmp> smps=new ArrayList<>();
				if (cic!=null && !"".equals(cic)) {
					smps=this.getMapper(SlmOrdDesignStdCicSmpMapper.class).findWithCondition(null, "DESIGN_KEY='"+smp.getDesign_key()+"' and  CIC='"+cic+"'", null, 0, 0);
				}
				
				if (cic_k!=null && !"".equals(cic_k)) {
					smps=this.getMapper(SlmOrdDesignStdCicSmpMapper.class).findWithCondition(null, "DESIGN_KEY='"+smp.getDesign_key()+"' and CIC='"+cic_k+"'", null, 0, 0);
				}
				
				rm.setState("200");
			    rm.setData(smps);		
			} catch (Exception e) {
				 rm.setState("500");
				 rm.setMsgInfo("查询成分取样要求失败！");
				 return rm;	
			}
			
			return rm;
		}
}
