/***文档注释***********************************************
 * 作者               :                   龙文航
 * 创建日期      :                   2017.11.22
 * 描述               :                   仓库管理-原料库在制品库成品库管理-倒剁管理
 * 注意事项      :                   无
 * 遗留BUG :                   无
 * 修改日期      :                   
 * 修改人员      :                   
 * 修改内容      :                   
***********************************************************/
package market.Lms.Warehouse.impl;

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

import market.Com.vo.CommonPage;
import market.Com.vo.ResultModel;
import market.Lms.Warehouse.mapper.YdmProductButtresslistMapper;
import market.Lms.Warehouse.mapper.YdmProductDetailMapper;
import market.Lms.Warehouse.mapper.YdmProductStowlistMapper;
import market.Lms.Warehouse.service.YdmProductStowlistService;
import market.Lms.Warehouse.vo.YdmProductButtresslist;
import market.Lms.Warehouse.vo.YdmProductDetail;
import market.Lms.Warehouse.vo.YdmProductStowlist;
import market.Mes.Opr.mapper.MesOprLogMapper;
import market.Mes.Opr.vo.MesOprLog;

import org.springframework.transaction.annotation.Transactional;

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;

@SuppressWarnings("rawtypes")
@RemoteService(path="YdmProductStowlistService")
public class YdmProductStowlistServiceImpl extends BaseServiceImpl<YdmProductStowlist,Object> implements YdmProductStowlistService {
	/**
	 * 倒剁管理-倒剁查询  无汇总，暂不使用
	 * memo1-4放厚宽的范围
	 * */
	public ResultModel doQueryWeb(CommonPage<YdmProductStowlist> cp) {
		ResultModel rm=new ResultModel();
		int pageIndex=cp.getPageIndex();
		int pageSize=cp.getPageSize();
		PageModel<YdmProductStowlist> pm = new PageModel<YdmProductStowlist>(pageIndex,pageSize);
		try {
			YdmProductStowlist yp=cp.getObject();
			String sWhere="1=1";
			if(cp.getStartTime()!=null&&cp.getStartTime()!="") {
				String starttime=cp.getStartTime();
				sWhere=" and STOWDATE>=to_date(concat("+starttime+",' 00:00:00'),'yyyy-MM-dd HH24:MI:SS') ";
			}
			if(cp.getEndTime()!=null&&cp.getEndTime()!="") {
				String endtime=cp.getEndTime();
				sWhere=" and STOWDATE<=to_date(concat("+endtime+",' 00:00:00'),'yyyy-MM-dd HH24:MI:SS') ";
			}
			if(cp.getObject().getCoilno()!=null&&cp.getObject().getCoilno()!="") {
				String coilno=cp.getObject().getCoilno();
				sWhere=" and COILNO like '%"+coilno+"%'";
			}
			if(cp.getObject().getJudgesteelcode()!=null&&cp.getObject().getJudgesteelcode()!="") {
				String judgesteelcodeString=cp.getObject().getJudgesteelcode();
				sWhere=" and JUDGESTEELCODE like '%"+judgesteelcodeString+"%'";
			}
			if(cp.getMemo1()!=null&&cp.getMemo1()!="") {
				double hmin=Double.valueOf(cp.getMemo1()).doubleValue();
				sWhere=" and THICK>="+hmin;
			}
			if(cp.getMemo2()!=null&&cp.getMemo2()!="") {
				double hmax=Double.valueOf(cp.getMemo2()).doubleValue();
				sWhere=" and THICK<="+hmax;
			}
			if(cp.getMemo3()!=null&&cp.getMemo3()!="") {
				double wmin=Double.valueOf(cp.getMemo3()).doubleValue();
				sWhere=" and WIDTH>="+wmin;
			}
			if(cp.getMemo4()!=null&&cp.getMemo4()!="") {
				double wmax=Double.valueOf(cp.getMemo4()).doubleValue();
				sWhere=" and WIDTH<="+wmax;
			}
			pm.setRows(this.getMapper(YdmProductStowlistMapper.class).findWithCondition(yp, sWhere, "STOWBILLNO", (pageIndex-1)*pageSize, pageSize));
			pm.setTotal(this.getMapper(YdmProductStowlistMapper.class).countWithCondition(yp,sWhere));
			rm.setState("200");
			rm.setData(pm);
		}
		catch(Exception ex)
		{
			rm.setState("500");
			rm.setMsgInfo("服务端异常，查询失败!");
			ex.printStackTrace();
		}
		return rm;
	}
	
	/**
	 * 倒垛查询
	 * SQL实现
	 * memo1-memo4传厚/宽的范围 memo5剁位号 
	 * 条件+汇总+分页
	 * */
	public ResultModel doQueryWebBySQL(CommonPage<YdmProductStowlist> cp) {
		ResultModel rm=new ResultModel();
		int pageSize=cp.getPageSize();
		int pageIndex=cp.getPageIndex();
		PageModel<YdmProductStowlist> pm = new PageModel<YdmProductStowlist>(pageIndex,pageSize);
		try {
			String regex = "^(\\d+\\.?\\d*)$";	
			boolean isMatch = true;
			Object hmin="",hmax="",wmin="",wmax="";
			if (cp.getMemo1() != null && cp.getMemo1() != "") {
				isMatch = Pattern.matches(regex, cp.getMemo1().trim());
				if (!isMatch) {
					rm.setState("500");
					rm.setMsgInfo("请输入正确的厚度和宽度!");
					return rm;
				}
				hmin = Double.valueOf(cp.getMemo1()).doubleValue();
			}
			if (cp.getMemo2() != null && cp.getMemo2() != "") {
				isMatch = Pattern.matches(regex, cp.getMemo2().trim());
				if (!isMatch) {
					rm.setState("500");
					rm.setMsgInfo("请输入正确的厚度和宽度!");
					return rm;
				}
				hmax = Double.valueOf(cp.getMemo2()).doubleValue();
			}
			if (cp.getMemo3() != null && cp.getMemo3() != "") {
				isMatch = Pattern.matches(regex, cp.getMemo3().trim());
				if (!isMatch) {
					rm.setState("500");
					rm.setMsgInfo("请输入正确的厚度和宽度!");
					return rm;
				}
				wmin = Double.valueOf(cp.getMemo3()).doubleValue();
			}
			if (cp.getMemo4() != null && cp.getMemo4() != "") {
				isMatch = Pattern.matches(regex, cp.getMemo4().trim());
				if (!isMatch) {
					rm.setState("500");
					rm.setMsgInfo("请输入正确的厚度和宽度!");
					return rm;
				}
				wmax = Double.valueOf(cp.getMemo4()).doubleValue();
			}
			pm.setRows(this.getMapper(YdmProductStowlistMapper.class).doQueryWebBySQL
					((pageIndex-1)*pageSize, (pageIndex-1)*pageSize+pageSize, cp.getStartTime(), cp.getEndTime(), cp.getObject().getCoilno(), cp.getObject().getSteelcode(),hmin,hmax,wmin,wmax,cp.getObject().getStorageattr(),cp.getMemo5(),cp.getObject().getMaterailcoilno()));
			pm.setTotal(this.getMapper(YdmProductStowlistMapper.class).doQueryWebBySQLCount
					(cp.getStartTime(), cp.getEndTime(), cp.getObject().getCoilno(), cp.getObject().getSteelcode(),hmin,hmax,wmin,wmax,cp.getObject().getStorageattr(),cp.getMemo5()));
			rm.setData(pm);
			rm.setState("200");
		}
		catch(Exception ex) {
			rm.setState("500");
			rm.setMsgInfo("查询失败!");
			ex.printStackTrace();
		}
		return rm;
	}
	
	/**
	 * 生成主键
	 * @return
	 * @throws Exception 
	 */
	private String createSTOWBILLNO() throws Exception {
		try {
			String stowbillno="";
			List<HashMap> list = this.getMapper(YdmProductStowlistMapper.class).getNo("ST"+(new SimpleDateFormat("yyyyMMdd").format(new Date())));
			stowbillno = (String) list.get(0).get("MAXNO");
			return stowbillno;
		} catch (Exception ex) {
			throw (ex);
		}
	}
	
	/**
	 * 倒垛管理-倒垛确认
	 * @throws Exception 
	 * */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doConfirm(CommonPage<YdmProductStowlist> 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);
		String order = (String) this.getSession().getAttribute(HomeService.SESSION_WORK_ORD);
		String team = (String) this.getSession().getAttribute(HomeService.SESSION_WORK_GRP);
		try {
			List<YdmProductStowlist> ypList=cp.getObjectList();
			for(YdmProductStowlist yp:ypList) {
				// 判断是不是在库，不是直接提示不在库，不允许倒剁：20220907刘侣；start
				YdmProductDetail ypd = this.getMapper(YdmProductDetailMapper.class).findById(yp.getCoilno());
				if (ypd != null) {
					if (!"0".equals(ypd.getState()) && !"2".equals(ypd.getState()) && !"7".equals(ypd.getState())) {
						rm.setState("500");
						rm.setMsgInfo("此卷还未入库，不允许倒剁");
						return rm;
					}
				} else {
					rm.setState("500");
					rm.setMsgInfo(yp.getCoilno() + "：此卷未交工。。。");
					return rm;
				}
				// end
				
				YdmProductButtresslist ypb=new YdmProductButtresslist();
				//1.删除原有的垛位信息
				List<YdmProductButtresslist> listbb = new ArrayList<YdmProductButtresslist>();
				if(yp.getCoilno()!=null && !"".equals(yp.getCoilno())){
					ypb.setCoilno(yp.getCoilno());
					listbb = this.getMapper(YdmProductButtresslistMapper.class).find(ypb, 0, 0);
					this.getMapper(YdmProductButtresslistMapper.class).doDelete(yp.getCoilno(), yp.getBoxno());
				}				
				//2.插入数据到垛位信息表
				ypb.setCoilno(yp.getCoilno());
				//垛位，位置，层数
				ypb.setButtressno(yp.getButtressno());
				if (yp.getLocality()==null||"".equals(yp.getLocality())) {
					throw new Exception("请传入位置");
				}
				ypb.setLocality(Integer.parseInt(yp.getLocality()));
				//设置层数(原料库和酸洗原料库默认层数为1)
				if (yp.getLayer()==null && ("500201".equals(yp.getStorageattr())||"500208".equals(yp.getStorageattr()))) {
					ypb.setLayer(1);
				}else {
					ypb.setLayer(Integer.parseInt(yp.getLayer()));					
				}
				//判断现有垛位上是否存在物料
				String condition = " and buttressno = '"+ypb.getButtressno()+"' and layer = '"+ypb.getLayer()+"' and locality = '"+ypb.getLocality()+"'";
				int count = this.getMapper(YdmProductButtresslistMapper.class).countWithCondition(null, condition);
				if (count > 0) {
					// 20220907 由return rm 换成throw exception：
					throw new Exception("目标垛位已经存在物料信息，无法倒垛");
//					rm.setState("500");
//					rm.setMsgInfo("目标垛位已经存在物料信息，无法倒垛");
//					return rm;
				}
				ypb.setStorageattr(yp.getStorageattr());
				ypb.setAreano(yp.getAreano());				
				ypb.setBoxno(yp.getBoxno());
				ypb.setCreater(username);
				ypb.setCreatedate(now);
				this.getMapper(YdmProductButtresslistMapper.class).doInsert(ypb);
				//3.插入数据到倒垛信息表
				if(listbb !=null&&listbb.size()>0) {
					if(listbb.get(0).getButtressno()!=null&&!"".equals(listbb.get(0).getButtressno()))
						yp.setOldbuttressno(listbb.get(0).getButtressno());
					if(!"".equals(listbb.get(0).getLayer()))
						yp.setOldlayer(String.valueOf(listbb.get(0).getLayer()).toString());
					if(!"".equals(listbb.get(0).getLocality()))
						yp.setOldlocality(String.valueOf(listbb.get(0).getLocality()).toString());
				}
				yp.setStowbillno(this.createSTOWBILLNO());
				yp.setCreater(username);
				yp.setCreatedate(now);
				yp.setStowdate(now);
				yp.setStowoperator(username);
				yp.setStoworder(order);
				yp.setStowteam(team);
				this.getMapper(YdmProductStowlistMapper.class).insert(yp);
				//日志
				MesOprLog mol = new MesOprLog("物流管理", "倒垛管理", "倒垛确认", username, opr_time, yp.getCoilno(), null, null, null, "原料卷号："+yp.getMaterailcoilno());
				this.getMapper(MesOprLogMapper.class).insert(mol);
				rm.setData(yp);
			}
			rm.setState("200");
		}
		catch(Exception ex) {
			rm.setState("500");
			rm.setMsgInfo("服务端异常，倒垛确认失败!");
			ex.printStackTrace();
			throw ex;
		}
		return rm;
	}
}
