/***文档注释***********************************************
 * 作者            ：  周浴超
 * 创建日期     ：
 * 描述            ：  取样码基础
 * 注意事项     ：
 * 遗留BUG   ：
 * 修改日期     ：                  2018.2.5
 * 修改人员     ：                  
 * 修改内容     ：                   
***********************************************************/
package market.Com.impl;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import market.Com.mapper.ComBaseSampleMapper;
import market.Com.mapper.ComBaseSampleRProductMapper;
import market.Com.mapper.ComBaseSampleRStdMapper;
import market.Com.mapper.ComBaseSampleRSteelMapper;
import market.Com.service.ComBaseSampleService;
import market.Com.vo.ComBaseSample;
import market.Com.vo.ComBaseSampleRProduct;
import market.Com.vo.ComBaseSampleRStd;
import market.Com.vo.ComBaseSampleRSteel;
import market.Com.vo.CommonPage;
import market.Com.vo.ResultModel;
import market.Qms.common.DataHelper;

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="ComBaseSampleService")
public class ComBaseSampleServiceImpl extends BaseServiceImpl<ComBaseSample,Object> implements ComBaseSampleService {
	
	/**
	 * 查询所有有效记录
	 * @return
	 */
	public ResultModel doFindWeb(CommonPage<ComBaseSample> sum) {
		ResultModel rm =new ResultModel();
		ComBaseSample sample =sum.getObject();
		try {
			if(sample.getValidflag().equals("0")){//传0 则把无效数据也查出来
				sample.setValidflag(null);
			}
			int pageSize=sum.getPageSize();
			int pageIndex=sum.getPageIndex();
			List<ComBaseSample> smapleList=this.getMapper(ComBaseSampleMapper.class).find(sample, sum.getSkipResults(), sum.getPageSize());
			String[] listSmpIndex=new String[smapleList.size()];//取样索引
			int index=0;
			for (ComBaseSample comBaseSample : smapleList) {
				listSmpIndex[index]=comBaseSample.getSmp_index();
				index++;
			}
			String condition=DataHelper.CreateSqlCondition(listSmpIndex, "smp_index");
			List<ComBaseSampleRProduct> listPro=this.getMapper(ComBaseSampleRProductMapper.class).findWithCondition(null, condition, null, 0, 0);
			condition=DataHelper.CreateSqlCondition(listSmpIndex, "smp_index");
			List<ComBaseSampleRStd> listStd=this.getMapper(ComBaseSampleRStdMapper.class).findWithCondition(null, condition, null, 0, 0);
			condition=DataHelper.CreateSqlCondition(listSmpIndex, "smp_index");
			List<ComBaseSampleRSteel> listSteel=this.getMapper(ComBaseSampleRSteelMapper.class).findWithCondition(null, condition, null, 0, 0);
			for (ComBaseSample _sample : smapleList) {
				StringBuilder code=new StringBuilder();
				StringBuilder name=new StringBuilder();
				for (ComBaseSampleRSteel steel : listSteel) {
					if(_sample.getSmp_index().equals(steel.getSmp_index())){
						code.append(steel.getSteel_code()+",");
						name.append(steel.getSteel_name()+",");
					}
				}
				if(code.length()>0){
					_sample.setSteel_code(code.substring(0, code.length()-1));
					_sample.setSteel_name(name.substring(0, name.length()-1));
					code=new StringBuilder();
					name=new StringBuilder();
				}
				for (ComBaseSampleRStd std : listStd) {
					if(_sample.getSmp_index().equals(std.getSmp_index())){
						code.append(std.getStd_code()+",");
						name.append(std.getStd_name()+",");
					}
				}
				if(code.length()>0){
					_sample.setStd_code(code.substring(0, code.length()-1));
					_sample.setStd_name(name.substring(0, name.length()-1));
					code=new StringBuilder();
					name=new StringBuilder();
				}

				for (ComBaseSampleRProduct pro : listPro) {
					if(_sample.getSmp_index().equals(pro.getSmp_index())){
						code.append(pro.getProd_code()+",");
						name.append(pro.getProd_name()+",");
					}
				}
				if(code.length()>0){
					_sample.setProd_code(code.substring(0, code.length()-1));
					_sample.setProd_name(name.substring(0, name.length()-1));
				}

			}
			
			PageModel<ComBaseSample> pm = new PageModel<ComBaseSample>(pageIndex,pageSize);
			//List<ComBaseSample> smapleList= this.getMapper(ComBaseSampleMapper.class).GexList(State,(pageIndex-1)*pageSize,(pageIndex-1)*pageSize+pageSize+1,sum.getMemo1(),sum.getMemo2(),sum.getMemo3());
			Iterator<ComBaseSample> it = smapleList.iterator();
			if (sample.getMax_d_sign()!=null&&!"".equals(sample.getMax_d_sign())) {
				while(it.hasNext()){
					ComBaseSample x = it.next();
					boolean b= this.JudgmentRange(x.getMax_d_sign(),x.getMax_d(), x.getMin_d_sign(), x.getMin_d(), sample.getMax_d_sign(), sample.getMax_d(), sample.getMin_d_sign(), sample.getMin_d());
					boolean bl=this.JudgmentRange(x.getMax_h_sign(),x.getMax_h(), x.getMin_h_sign(), x.getMin_h(), sample.getMax_h_sign(), sample.getMax_h(), sample.getMin_h_sign(), sample.getMin_h());
					if (b&&bl) {
					}else {
						it.remove();
					}
				}
			}
			pm.setRows(smapleList);
			pm.setTotal(this.getMapper(ComBaseSampleMapper.class).count(sample));
			rm.setData(pm);
			rm.setState("200");
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			rm.setState("500");
			rm.setMsgInfo("查询失败");
			rm.setErrorInfo(e.getMessage());
		}
		return rm;
	}
	/**
	 * 查询对应牌号COM_BASE_SAMPLE_R_STEEL
	 */
	public ResultModel doFindSteel(CommonPage<ComBaseSample> sum) {
		ResultModel rm =new ResultModel();
		try {
			ComBaseSampleRSteel steel =new ComBaseSampleRSteel();
			steel.setSmp_index(sum.getObject().getSmp_index());
			rm.setData(this.getMapper(ComBaseSampleRSteelMapper.class).find(steel, 0, 0));
			rm.setState("200");
		} catch (Exception e) {
			// TODO: handle exception
			rm.setState("500");
			rm.setErrorInfo(e.getMessage());
			rm.setMsgInfo("获取牌号数据失败");
		}
		return rm;
	}
	/**
	 * 查询对应标准号COM_BASE_SAMPLE_R_STD
	 */
	public ResultModel doFindStd(CommonPage<ComBaseSample> sum) {
		ResultModel rm =new ResultModel();
		try {
			ComBaseSampleRStd std =new ComBaseSampleRStd();
			std.setSmp_index(sum.getObject().getSmp_index());
			rm.setData(this.getMapper(ComBaseSampleRStdMapper.class).find(std, 0, 0));
			rm.setState("200");
		} catch (Exception e) {
			// TODO: handle exception
			rm.setState("500");
			rm.setErrorInfo(e.getMessage());
			rm.setMsgInfo("获取标准号数据失败");
		}
		return rm;
	}
	/**
	 * 查询对应产品名称COM_BASE_SAMPLE_R_PRODUCT
	 */
	public ResultModel doFindProduct(CommonPage<ComBaseSample> sum) {
		ResultModel rm =new ResultModel();
		try {
			ComBaseSampleRProduct product =new ComBaseSampleRProduct();
			product.setSmp_index(sum.getObject().getSmp_index());
			rm.setData(this.getMapper(ComBaseSampleRProductMapper.class).find(product, 0, 0));
			rm.setState("200");
		} catch (Exception e) {
			// TODO: handle exception
			rm.setState("500");
			rm.setErrorInfo(e.getMessage());
			rm.setMsgInfo("获取产品数据失败");
		}
		return rm;
	}
	/**
	 * 试验样条数
	 */
	
	public ResultModel doSyt(CommonPage<ComBaseSample> sum) {
		ResultModel rm =new ResultModel();
		try {
			String id =sum.getMemo1();
			int i=this.getMapper(ComBaseSampleMapper.class).syt(id);
			rm.setData(i);
			rm.setState("200");
		} catch (Exception e) {
			// TODO: handle exception
			rm.setMsgInfo("试样组下没有试样条数");
			rm.setState("500");
			rm.setErrorInfo(e.getMessage());
		}
		return rm;
	}
	
	/**
	 * 保存
	 * @param sum
	 * @return
	 */
	@SuppressWarnings("deprecation")
	public ResultModel doAddWeb(CommonPage<ComBaseSample> sum) {
		ResultModel rm =new ResultModel();
		List<ComBaseSample> sample =sum.getObjectList();
		try {
			for (ComBaseSample sam : sample) {
				//ID为空则新增
				if (sam.getSmp_index()==null||"".equals(sam.getSmp_index())) {
					//取样索引号: S+两位年/月/日+3位流水号,示例：S171114001；
					if ("1".equals(sam.getSmp_type())) {	
						String id =this.getMapper(ComBaseSampleMapper.class).doFindL(sam.getPhy_code_m());
						id=sam.getPhy_code_m()+id;
						sam.setSmp_index(id);
					}else {
						//A+7位流水号
						String id =this.getMapper(ComBaseSampleMapper.class).doFindLs();
						sam.setSmp_index(id);
					}
					//当前时间为创建时间
					SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					Date time =null;
					time= sdf.parse(sdf.format(new Date()));
					sam.setCreate_time(new Timestamp(time.getTime()));
					String username=(String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
					sam.setCreate_name(username);
					this.getMapper(ComBaseSampleMapper.class).insert(sam);
					//写入取样码与产品名称关系表（COM_BASE_SAMPLE_R_PRODUCT）
					String prod_name=sam.getProd_name();
					String prod_code=sam.getProd_code();
					if (prod_name!=null&&!"".equals(prod_name)) {
						String prod_names[]= prod_name.split(",");
						String prod_codes[]= prod_code.split(",");
						for (int i = 0; i < prod_codes.length; i++) {
							ComBaseSampleRProduct product =new ComBaseSampleRProduct();
							if (sam.getSmp_index()!=null) {
								product.setSmp_index(sam.getSmp_index());
							}
							if (sam.getProd_code()!=null) {
								product.setProd_code(prod_codes[i]);
							}if (sam.getProd_name()!=null) {
								product.setProd_name(prod_names[i]);
							}
							product.setValidflag("1");
							this.getMapper(ComBaseSampleRProductMapper.class).insert(product);
						}
					}
					//写入取样码与钢级/牌号对应关系表（COM_BASE_SAMPLE_R_STEEL
					String steel_name=sam.getSteel_name();
					String steel_code=sam.getSteel_code();
					if (steel_name!=null&&!"".equals(steel_name)) {
						String steel_names[]= steel_name.split(",");
						String steel_codes[]= steel_code.split(",");
						for (int i = 0; i < steel_codes.length; i++) {
							ComBaseSampleRSteel steel =new ComBaseSampleRSteel();
							if (sam.getSmp_index()!=null) {
								steel.setSmp_index(sam.getSmp_index());
							}
							if (sam.getSteel_code()!=null) {
								steel.setSteel_code(steel_codes[i]);
							}
							if (sam.getSteel_name()!=null) {
								steel.setSteel_name(steel_names[i]);
							}
							if (sam.getCreate_name()!=null) {
								steel.setCreate_name(sam.getCreate_name());
							}
							steel.setCreate_time(new Date());
							steel.setValidflag("1");
							this.getMapper(ComBaseSampleRSteelMapper.class).insert(steel);
						}
					}
					//写入取样码与标准号对应关系表（COM_BASE_SAMPLE_R_STD）；
					String std_code=sam.getStd_code();
					String std_name=sam.getStd_name();
					if (std_name!=null&&!"".equals(std_name)) {
						String std_codes[]= std_code.split(",");
						String std_names[]= std_name.split(",");
						for (int i = 0; i < std_names.length; i++) {
							ComBaseSampleRStd rst =new ComBaseSampleRStd();
							if (sam.getSmp_index()!=null) {
								rst.setSmp_index(sam.getSmp_index());
							}
							if (sam.getStd_code()!=null) {
								rst.setStd_code(std_codes[i]);
							}
							if (sam.getStd_name()!=null) {
								rst.setStd_name(std_names[i]);
							}
							if (sam.getCreate_name()!=null) {
								rst.setCreate_name(sam.getCreate_name());
							}
							rst.setCreate_time(new Date());
							rst.setValidflag("1");
							this.getMapper(ComBaseSampleRStdMapper.class).insert(rst);
					}
					}
					rm.setState("200");
				}else {
					//不为空则修改
					//当前时间为修改时间
					SimpleDateFormat sdf=new SimpleDateFormat();
					Date time = sdf.parse(sdf.format(new Date()));
					sam.setUpdate_time(new Timestamp(time.getTime()));
					String username=(String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
					sam.setUpdate_name(username);
					this.getMapper(ComBaseSampleMapper.class).update(sam);
					//写入取样码与产品名称关系表（COM_BASE_SAMPLE_R_PRODUCT）
					String prod_name=sam.getProd_name();
					String prod_code=sam.getProd_code();
					if (prod_name!=null&&!"".equals(prod_name)) {
						String prod_names[]= prod_name.split(",");
						String prod_codes[]= prod_code.split(",");
						this.getMapper(ComBaseSampleRProductMapper.class).DeleteBySampIndex(sam.getSmp_index());
						for (int i = 0; i < prod_codes.length; i++) {
							ComBaseSampleRProduct product =new ComBaseSampleRProduct();
							if (sam.getSmp_index()!=null) {
								product.setSmp_index(sam.getSmp_index());
							}
							if (sam.getProd_code()!=null) {
								product.setProd_code(prod_codes[i]);
							}if (sam.getProd_name()!=null) {
								product.setProd_name(prod_names[i]);
							}
							product.setValidflag("1");
							this.getMapper(ComBaseSampleRProductMapper.class).insert(product);
						}
					}else{
						this.getMapper(ComBaseSampleRProductMapper.class).DeleteBySampIndex(sam.getSmp_index());
					}
					//写入取样码与钢级/牌号对应关系表（COM_BASE_SAMPLE_R_STEEL
					String steel_name=sam.getSteel_name();
					String steel_code=sam.getSteel_code();
					if (steel_name!=null&&!"".equals(steel_name)) {
						String steel_names[]= steel_name.split(",");
						String steel_codes[]= steel_code.split(",");
						this.getMapper(ComBaseSampleRSteelMapper.class).DeleteBySampIndex(sam.getSmp_index());
						for (int i = 0; i < steel_codes.length; i++) {
							ComBaseSampleRSteel steel =new ComBaseSampleRSteel();
							if (sam.getSmp_index()!=null) {
								steel.setSmp_index(sam.getSmp_index());
							}
							if (sam.getSteel_code()!=null) {
								steel.setSteel_code(steel_codes[i]);
							}
							if (sam.getSteel_name()!=null) {
								steel.setSteel_name(steel_names[i]);
							}
							if (sam.getCreate_name()!=null) {
								steel.setCreate_name(sam.getCreate_name());
							}
							steel.setCreate_time(new Date());
							steel.setValidflag("1");
							this.getMapper(ComBaseSampleRSteelMapper.class).insert(steel);
						}
					}else{
						this.getMapper(ComBaseSampleRSteelMapper.class).DeleteBySampIndex(sam.getSmp_index());
					}
					//写入取样码与标准号对应关系表（COM_BASE_SAMPLE_R_STD）；
					String std_code=sam.getStd_code();
					String std_name=sam.getStd_name();
					if (std_name!=null&&!"".equals(std_name)) {
						String std_codes[]= std_code.split(",");
						String std_names[]= std_name.split(",");
						this.getMapper(ComBaseSampleRStdMapper.class).DeleteBySampIndex(sam.getSmp_index());
						for (int i = 0; i < std_names.length; i++) {
							ComBaseSampleRStd rst =new ComBaseSampleRStd();
							if (sam.getSmp_index()!=null) {
								rst.setSmp_index(sam.getSmp_index());
							}
							if (sam.getStd_code()!=null) {
								rst.setStd_code(std_codes[i]);
							}
							if (sam.getStd_name()!=null) {
								rst.setStd_name(std_names[i]);
							}
							if (sam.getCreate_name()!=null) {
								rst.setCreate_name(sam.getCreate_name());
							}
							rst.setCreate_time(new Date());
							rst.setValidflag("1");
							this.getMapper(ComBaseSampleRStdMapper.class).insert(rst);
						}
					}else{
						this.getMapper(ComBaseSampleRStdMapper.class).DeleteBySampIndex(sam.getSmp_index());
					}
					rm.setState("200");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			// TODO: handle exception
			rm.setMsgInfo("保存失败");
			rm.setErrorInfo(e.getMessage());
			rm.setState("500");
		}
		return rm;
	}

	/**
	 * 作废处理
	 * @return
	 */
	public ResultModel doUpdatezf(CommonPage<ComBaseSample> sum) {
		ResultModel rm =new ResultModel();
		List<ComBaseSample> samples =sum.getObjectList();
		try {
			for (ComBaseSample sample : samples) {
				//当前时间为删除时间
				SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				Date time =null;
				time= sdf.parse(sdf.format(new Date()));
				String username=(String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
				sample =this.getMapper(ComBaseSampleMapper.class).findById(sample.getSmp_index());
				if(sample.getValidflag().equals("1")) {
					sample.setValidflag("0");
					sample.setDelete_name(username);
					sample.setDelete_time(new Timestamp(time.getTime()));
					this.getMapper(ComBaseSampleMapper.class).update(sample);
					rm.setState("200");
				}else {
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			// TODO: handle exception
			rm.setState("500");
			rm.setMsgInfo("作废失败");
			rm.setErrorInfo(e.getMessage());
		}
		return rm;
	}
	
	/**
	 * 恢复数据
	 * @param sum
	 * @return
	 */
	public ResultModel doUpdatehf(CommonPage<ComBaseSample> sum) {
		ResultModel rm =new ResultModel();
		List<ComBaseSample> samples =sum.getObjectList();
		try {
			for (ComBaseSample sample : samples) {
				sample =this.getMapper(ComBaseSampleMapper.class).findById(sample.getSmp_index());
				String sId=sample.getSmp_index();
				if(sample.getValidflag().equals("0")) {
					this.getMapper(ComBaseSampleMapper.class).doUpdatehuif(sId);
					rm.setState("200");
				}else {
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			// TODO: handle exception
			rm.setState("500");
			rm.setMsgInfo("恢复失败");
			rm.setErrorInfo(e.getMessage());
		}
		return rm;
	}
	
	
//	public ResultModel doSelectZlsj(String cic,String PRODUCT,String steel,String std) {
//		ResultModel rm =new ResultModel();
//		try {
//			
//			List<ComBaseSample> sam = this.getMapper(ComBaseSampleMapper.class).doSelectZlsj(cic,PRODUCT,steel,std);
//			rm.setData(sam);
//			rm.setState("200");
//		} catch (Exception e) {
//			// TODO: handle exception
//			rm.setMsgInfo("未查到数据");
//			rm.setState("500");
//		}
//		return rm;
//	}
	
	 /* 验证限制条件
	 * @param singMaxA
	 * @param MaxA
	 * @param singMinA
	 * @param MinA
	 * @param singMaxB
	 * @param MaxB
	 * @param singMinB
	 * @param MinB
	 * @return
	 */
	public boolean JudgmentRange(String singMaxA,String MaxA,String singMinA,String MinA,String singMaxB,String MaxB,String singMinB,String MinB)
	{
		
		if(Double.valueOf(MaxA)<Double.valueOf(MaxB))
		{
			return false;
		}
		if(Double.valueOf(MaxA)==Double.valueOf(MaxB))
		{
			if(singMaxA.equals("=")&&!singMaxB.equals("="))
			{
				return false;
			}
			
			if(singMaxA.equals("<")&&!singMaxB.equals("<"))
			{
				return false;
			}
		}
		
		if(Double.valueOf(MinA)>Double.valueOf(MinB))
		{
			return false;
		}
		if(Double.valueOf(MinA)==Double.valueOf(MinB))
		{
			if(singMinA.equals("=")&&!singMinB.equals("="))
			{
				return false;
			}
			
			if(singMinA.equals(">")&&!singMinB.equals(">"))
			{
				return false;
			}
			
		}
		return true;
	}
	
}
