/***文档注释***********************************************
 * 作者               :                   龙文航
 * 创建日期      :                   2017.11.28
 * 描述               :                   仓库管理-盘库管理
 * 注意事项      :                   无
 * 遗留BUG :                   无
 * 修改日期      :                   
 * 修改人员      :                   
 * 修改内容      :                   
***********************************************************/
package market.Lms.Warehouse.impl;

import java.io.File;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Pattern;

import javassist.bytecode.SignatureAttribute.ObjectType;
import market.Api.Mes.impl.MesApiServiceImpl;
import market.Com.mapper.ComBaseSteelMapper;
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.YdmBaseButtressconfigMapper;
import market.Lms.Warehouse.mapper.YdmProductButtresslistMapper;
import market.Lms.Warehouse.mapper.YdmProductDetailMapper;
import market.Lms.Warehouse.mapper.YdmProductInlistMapper;
import market.Lms.Warehouse.mapper.YdmProductOutlistMapper;
import market.Lms.Warehouse.mapper.YdmProductStockMapper;
import market.Lms.Warehouse.service.YdmProductInlistService;
import market.Lms.Warehouse.service.YdmProductStockService;
import market.Lms.Warehouse.vo.ComPageIfRawMtrCoilPfmc;
import market.Lms.Warehouse.vo.YdmBaseButtressconfig;
import market.Lms.Warehouse.vo.YdmProductButtresslist;
import market.Lms.Warehouse.vo.YdmProductDetail;
import market.Lms.Warehouse.vo.YdmProductInlist;
import market.Lms.Warehouse.vo.YdmProductOutlist;
import market.Lms.Warehouse.vo.YdmProductStock;
import market.Mes.MaterielTrack.vo.PrcMaterielProcess;
import market.Mes.Opr.mapper.MesOprLogMapper;
import market.Mes.Opr.vo.MesOprLog;
import market.Pms.Util.ImportUtil;
import market.Slm.FundManagement.service.SlmFundFirstDetailService;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
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;

@RemoteService(path="YdmProductStockService")
public class YdmProductStockServiceImpl extends BaseServiceImpl<YdmProductStock,Object> implements YdmProductStockService {
	
	/** 盘库管理 盘库查询
	 * SQL实现
	 * 条件+汇总+分页
	 * */
	public ResultModel doQueryWebBySQL(CommonPage<YdmProductStock> cp) {
		ResultModel rm=new ResultModel();
		int pageSize=cp.getPageSize();
		int pageIndex=cp.getPageIndex();
		PageModel<YdmProductStock> pm = new PageModel<YdmProductStock>(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(YdmProductStockMapper.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()));
			pm.setTotal(this.getMapper(YdmProductStockMapper.class).doQueryWebBySQLCount
					(cp.getStartTime(), cp.getEndTime(), cp.getObject().getCoilno(), cp.getObject().getSteelcode(),hmin,hmax,wmin,wmax,cp.getObject().getStorageattr()));
			rm.setData(pm);
			rm.setState("200");
		}
		catch(Exception ex) {
			rm.setState("500");
			rm.setMsgInfo("查询失败!");
			ex.printStackTrace();
		}
		return rm;
	}
	
	/**
	 * 冷轧回退
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	public ResultModel doLZReturn(CommonPage<YdmProductDetail> 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);
		try {			
			if (cp.getObject()==null) {
				throw new Exception("请传入参数");
			}
			//判断是否输入卷号
			if(cp.getObject().getCoilno()==null||"".equals(cp.getObject().getCoilno())){
				throw new Exception("请输入卷号!");
			}
			YdmProductDetail YPD = new YdmProductDetail();
			YPD.setStorageattr("500205");
			YPD.setState("0");
			YPD.setCoilno(cp.getObject().getCoilno());
			List<YdmProductDetail> list = this.getMapper(YdmProductDetailMapper.class).find(YPD, 0, 0);
			if (list==null || list.size()<=0) {
				throw new Exception("当前物料信息不存在");
			}
			String coilno = list.get(0).getCoilno();
			//1.物料备份
			CommonPage<YdmProductDetail> cpList = new CommonPage<YdmProductDetail>();
			cpList.setObjectList(list);
			this.getBean(YdmProductDetailBfServiceImpl.class).doAddDetailBf(cpList);
			//2.删除物料库存信息
			this.getMapper(YdmProductDetailMapper.class).doDelete(coilno, null);
			//3.删除物料入库信息
			this.getMapper(YdmProductInlistMapper.class).doDeleteByCoilnoStorage(coilno,"500205");
			//4.删除物料的历史记录
			this.getMapper(YdmProductOutlistMapper.class).doDeleteYpdHistory(coilno, "500205", null);
			
			MesOprLog mol = new MesOprLog("物流管理", "贸易外库盘库管理", "冷轧回退", username, opr_time, coilno, null, null, null, "原料卷号："+list.get(0).getMaterailcoilno());
			this.getMapper(MesOprLogMapper.class).insert(mol);
			rm.setState("200");
			rm.setMsgInfo("冷轧回退成功");
		}
		catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo("冷轧回退失败!");
		}
		return rm;
	}
	
	/**
	 * 物料出库
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	public ResultModel doOutBS(CommonPage<YdmProductDetail> cp) throws Exception {
		ResultModel rm=new ResultModel("200", "出库成功"); 
		List<YdmProductDetail> ypdL = cp.getObjectList();
		for (YdmProductDetail ypd : ypdL) {
			rm = this.handleOutBS(ypd);
			if ("500".equals(rm.getState())) {
				break;
			}
		}
		return rm;
	}
	
	/**
	 * 物料出库
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	public ResultModel handleOutBS(YdmProductDetail cp) throws Exception {
		ResultModel rm=new ResultModel(); 
		Date now = new Date();
		String userId = (String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(now); //操作时间
		String username=(String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		try {			
			if (cp==null) {
				throw new Exception("请传入参数");
			}
			//判断是否输入卷号
			if(cp.getCoilno()==null||"".equals(cp.getCoilno())){
				throw new Exception("请输入卷号!");
			}
			YdmProductDetail YPD = new YdmProductDetail();
			YPD.setStorageattr(cp.getStorageattr());//"500203"
			YPD.setState("0");
			YPD.setCoilno(cp.getCoilno());
			List<YdmProductDetail> list = this.getMapper(YdmProductDetailMapper.class).find(YPD, 0, 0);
			if (list==null || list.size()<=0) {
				throw new Exception("当前物料信息不存在");
			}
			YdmProductDetail ypd = list.get(0);			
			//2.新增出库数据
			YdmProductOutlist ypo=new YdmProductOutlist();
			ypo.setCreater(username);
			ypo.setCreatedate(now);
			ypo.setOutbillno(this.getBean(YdmProductOutlistServiceImpl.class).createOUTBILLNO());
			ypo.setOuttype("500512");//物料出库
			ypo.setOutdate(now);
			ypo.setOutoperator(username);
			ypo.setCoilno(ypd.getCoilno());
			ypo.setCoiltype(ypd.getCoiltype());
			ypo.setMaterailtype(ypd.getMaterailtype());
			ypo.setSource(ypd.getSource());
			ypo.setMaterailsupplier(ypd.getMaterailsupplier());
			ypo.setIsbox(ypd.getIsbox());
			ypo.setBoxno(ypd.getBoxno());
			ypo.setDrawingno(ypd.getDrawingno());
			ypo.setBatchno(ypd.getBatchno());
			ypo.setHeatno(ypd.getBatchno());
			ypo.setSmpno(ypd.getSmpno());
			ypo.setManagementno(ypd.getManagementno());
			ypo.setStorageattr(ypd.getStorageattr());
			ypo.setProd_code(ypd.getProd_code());
			ypo.setProd_name(ypd.getProd_name());
			ypo.setStd_code(ypd.getStd_code());
			ypo.setStd_name(ypd.getStd_name());
			ypo.setUse_code(ypd.getUse_code());
			ypo.setUse_name(ypd.getUse_name());
			ypo.setPline_name(ypd.getPline_name());
			ypo.setPostid(ypd.getPostid());
			ypo.setThick(ypd.getThick());
			ypo.setWidth(ypd.getWidth());
			ypo.setLength(ypd.getLength());
			ypo.setDiameter_inn(ypd.getDiameter_inn());
			ypo.setDiameter_out(ypd.getDiameter_out());
			ypo.setQuantity(ypd.getQuantity());
			ypo.setTheoryweight(ypd.getTheoryweight());
			ypo.setCoreweight(ypd.getCoreweight());
			ypo.setGrossweight(ypd.getGrossweight());
			ypo.setPackweight(ypd.getPackweight());
			ypo.setFactweight(ypd.getFactweight());
			ypo.setCustomer_nm(ypd.getCustomer_nm());
			ypo.setCustomer_no(ypd.getCustomer_no());
			ypo.setReceiv_no(ypd.getReceiv_no());
			ypo.setReceiv_nm(ypd.getReceiv_nm());
			ypo.setOrderno(ypd.getOrderno());
			ypo.setProdorderno(ypd.getProdorderno());
			ypo.setSteelcode(ypd.getSteelcode());
			ypo.setJudgesteelcode(ypd.getJudgesteelcode());
			ypo.setPacking_group(ypd.getPacking_group());
			ypo.setChemresult(ypd.getChemresult());
			ypo.setSizeresult(ypd.getSizeresult());
			ypo.setSurfaceresult(ypd.getSurfaceresult());
			ypo.setWeightresult(ypd.getWeightresult());
			ypo.setJudgeresult(ypd.getJudgeresult());
			ypo.setPhysresult(ypd.getPhysresult());
			ypo.setSpyresult(ypd.getSpyresult());
			ypo.setProducedate(ypd.getProducedate());
			ypo.setProduceorder(ypd.getProduceorder());
			ypo.setProduceteam(ypd.getProduceteam());
			ypo.setIndate(ypd.getIndate());
			ypo.setInorder(ypd.getInorder());
			ypo.setInteam(ypd.getInteam());
			ypo.setButtressno(ypd.getButtressno());				 
			if(ypd.getLocality()!=null){					
				ypo.setLocality(Long.valueOf(ypd.getLocality()));
			}
			
			// 加入物料属性：20230725刘侣
			ypo.setObj_attr_out(ypd.getObject_attr());
			// end
			
			ypo.setMemo("物料出库操作");
			this.getMapper(YdmProductOutlistMapper.class).insert(ypo);
			//清除垛位信息
			this.getMapper(YdmProductButtresslistMapper.class).doDelete(ypd.getCoilno(), ypd.getBoxno());			
			//1.库存信息状态为出库5
			YdmProductDetail newYdm = new YdmProductDetail();
			newYdm.setCoilno(ypd.getCoilno());
			newYdm.setState("5");
			this.getMapper(YdmProductDetailMapper.class).update(newYdm);
			
			// 现在不外卖废副品，去掉废副品物料跟踪：20241227刘侣
			// 增加物料进程数据：20240218 刘侣
			// 3、入库物料进程：
			// 调用生产计划接口进行物料跟踪
//			PrcMaterielProcess pmp = new PrcMaterielProcess();
//			pmp.setObject_no(ypd.getCoilno());
//			pmp.setPrc_code("5BYS10");
//			pmp.setCreate_time(now);
//			pmp.setRemark("盘库出库" + cp.getStorageattr());
//			pmp.setCreate_man_name(username);
//			PrcMaterielProcess pmp1 = new PrcMaterielProcess();
//			pmp1.setObject_no(ypd.getCoilno());
//			pmp1.setPrc_code("5BYA05");
//			pmp1.setCreate_time(now);
//			pmp1.setRemark("" + opr_time);
//			pmp1.setCreate_man_name(username);
//			int tmp1 = this.getBean(MesApiServiceImpl.class).INSERT_OBJ_PROCESS(pmp1);
//			int tmp = this.getBean(MesApiServiceImpl.class).INSERT_OBJ_PROCESS(pmp);
//			if (tmp1 == -1) {
//				throw new Exception("物料跟踪失败");
//			}
//			if (tmp == -1) {
//				throw new Exception("物料跟踪失败");
//			}
			// end
			
			// 盘库出库时，如果是非头尾边丝卷的话，需要增加判废异动点的发送：
			
			
			// 判断：只有非头尾边丝才可以发：
			String lastChar = ypd.getCoilno().substring(ypd.getCoilno().length()-1);
			if ("B".equals(lastChar) || "H".equals(lastChar)) {
				// 头尾不需要发送异动点：
			} else {
				// 记录判废成本异动点：20250407刘侣
				ComBaseCbYdd cd = new ComBaseCbYdd();
				cd.setCoilStus("1"); // 综判前算半成品，综判入库后算成品
				cd.setInstDisp("01");
				cd.setDataTypeIdx("O");
				// 当前产线：
				String currentMachine = ypd.getCoilno().contains("S") ? "YTSX" : ypd.getCoilno().contains("L") ? "YTZZ" : ypd.getCoilno().contains("P") ? "YTPZ" : ypd.getCoilno().contains("T") ? "YTTH" : ypd.getCoilno().contains("K") ? "YTHJ" : ypd.getCoilno().contains("F") ? "YTZJ" : "YT1";
				cd.setLocNo(currentMachine); // 填当前产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
				cd.setInvQtyUnit("块");
				cd.setInvWidth(ypd.getWidth() != null ? String.valueOf(ypd.getWidth()) : "0");
				cd.setCreateId(userId);
				cd.setActivityId("69A");
				cd.setInvLength(ypd.getLength() != null ? String.valueOf(ypd.getLength()) : "0");
				cd.setManageip(currentMachine); // 填当前产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
				cd.setProdName(ypd.getProd_name());
				cd.setInvThick(ypd.getThick() != null ? String.valueOf(ypd.getThick()) : "0");
				
				String prevcoil = this.getBean(YdmProductInlistService.class).doQueryTl(ypd.getCoilno());
				// 上道产线：
				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(ypd.getOrderno());
				cd.setCrntMill(currentMachine); // 填当前产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
				cd.setBeTransUnit("t");
				cd.setExecJobFunc("N");
				ComBaseSteel cbs = this.getMapper(ComBaseSteelMapper.class).findById(ypd.getSteelcode());
				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(ypd.getFactweight() != null ? ypd.getFactweight() / 1000 : ypd.getFactweight());
				cd.setProdTypeNo("CTR");
				cd.setAppId("优特钢产出卷综判");
				cd.setInvId(ypd.getCoilno());
				cd.setInvQty("1");
				cd.setSrcFac("1");
				cd.setGrade("40740801".equals(ypd.getJudgeresult()) ? "1" : "1"); // 正品　1　协议　3　次品　5
				cd.setProdClassNo("H");
				
				String currentMName = ypd.getCoilno().contains("S") ? "酸洗" : ypd.getCoilno().contains("L") ? "冷轧" : ypd.getCoilno().contains("P") ? "平整" : ypd.getCoilno().contains("T") ? "退火" : ypd.getCoilno().contains("K") ? "横剪" : ypd.getCoilno().contains("F") ? "分条" : "原料";
				
				// setSrcFac根据卷的物料属性去判断：
				cd.setSrcFac("507101".equals(ypd.getObject_attr()) ? "1" : "3");
				
				
//				if ("40740804".equals(ypd.getJudgeresult())) {
					cd.setActivityId("11AZ");
					cd.setCoilStus("0"); 
//				}
				cd.setAppId("优特" + currentMName + "综判");
				cd.setProdTypeNo(ypd.getCoilno().length() > 8 ? "CTR" : ypd.getMaterailcoilno().startsWith("L") ? "CCR" : "HCR");
				cd.setCrntMill(currentMachine); // 填上道产线：优特酸选 YTSX,优特轧制YTZZ,优特平整YTPZ,优特退火YTTH,优特横剪YTHJ,优特纵剪YTZJ
				cd.setInvId(ypd.getCoilno().length() <= 8 ? ypd.getMaterailcoilno() : ypd.getCoilno());
				
				this.getBean(SlmFundFirstDetailService.class).doCbDataIns(cd, cd.getActivityId(), ypd.getMaterailcoilno());
				
			}
			
			//日志
			MesOprLog mol = new MesOprLog("物流管理", "盘库管理", "物料出库", username, opr_time, ypd.getCoilno(), null, null, null, "原料卷号："+ypd.getMaterailcoilno());
			this.getMapper(MesOprLogMapper.class).insert(mol);
			rm.setState("200");
			rm.setMsgInfo("物料出库成功");
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo("边丝出库失败!");
		}
	    return rm;
	}
	
	/**
	 * 外购入库导入
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("deprecation")
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doImportOutInList() throws Exception{
		synchronized (this) {
			ResultModel rm = new ResultModel();
			Workbook wb = null;
			URL url = this.getClass().getClassLoader().getResource("/");
	        // 替换路径中的空格
	        String filePath = url.getPath().replaceAll("%20", " ");
	        File file = new File(filePath);
	        //1.导入excel
	        try {
				List<FileItem> items = ImportUtil.getUpload(YdmProductStockServiceImpl.this,file,getRequest());		
				for (FileItem item : items) {
					// 若是文件域则读取文件流
					if (!item.isFormField()) {
						wb = ImportUtil.getWB(item, file.length());
					}
				}
				rm.setState("200");
				rm.setMsgInfo("导入成功！");
			} catch (FileUploadException e) {
				rm.setState("500");
				rm.setMsgInfo("导入失败！");
			}
	        
	        // 2.读取Excel数据
	        int numRow = 0;//最后的行数
	        Sheet sheet = null;
			try {
				//第一个表单
				sheet = wb.getSheetAt(0);
				//行数
				numRow = sheet.getLastRowNum();//最后的行数
			} catch (Exception e) {
				throw new Exception("Excel表格数据读取失败！" + e.getMessage());
			}
						
			try {
				if (numRow >= 1) {
					Date now = new Date();
					String opr_time = new SimpleDateFormat("yyyyMMddHHmmss").format(now); //操作时间
					String order = (String) this.getSession().getAttribute(HomeService.SESSION_WORK_ORD);
					String team = (String) this.getSession().getAttribute(HomeService.SESSION_WORK_GRP);
					String username = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
					String condition = "";	 //牌号处理									
					String condition2 = ""; //区域处理				 
					String condition3 = ""; //垛位处理
					
					String materailcoilno,materailtype,steel,thick,width,weight,diameter_inn;
					String areano,buttressno,locality,memo,materailsupplier,object_attr;
					//原料卷类型
					HashMap<String,String> map=new HashMap<>();
					map.put("酸洗卷", "1");
					map.put("酸轧卷", "2");
					map.put("连退卷", "3");
					map.put("重卷卷", "4");
					map.put("热卷", "5");
					 
					for (int i = 1; i <= numRow; i++) {
						Row row = sheet.getRow(i);
						row.getCell(0).setCellType(Cell.CELL_TYPE_STRING);//数字转文本
						row.getCell(2).setCellType(Cell.CELL_TYPE_STRING);
						row.getCell(3).setCellType(Cell.CELL_TYPE_STRING);
						row.getCell(4).setCellType(Cell.CELL_TYPE_STRING);
						row.getCell(5).setCellType(Cell.CELL_TYPE_STRING);
						row.getCell(6).setCellType(Cell.CELL_TYPE_STRING);
						row.getCell(7).setCellType(Cell.CELL_TYPE_STRING);
						row.getCell(9).setCellType(Cell.CELL_TYPE_STRING);
						
						//处理行数据
						materailcoilno = String.valueOf(row.getCell(0).getStringCellValue());//原料卷号						
						materailtype = ImportUtil.getCellValue(row.getCell(1));				//原料卷类型
						steel = String.valueOf(row.getCell(2).getStringCellValue());		//牌号						
						thick = String.valueOf(row.getCell(3).getStringCellValue());		//厚
						width = String.valueOf(row.getCell(4).getStringCellValue());		//宽
						weight = String.valueOf(row.getCell(5).getStringCellValue());		//重量						
						diameter_inn = String.valueOf(row.getCell(6).getStringCellValue());	//内径
						areano = ImportUtil.getCellValue(row.getCell(7));					//区域
						buttressno = ImportUtil.getCellValue(row.getCell(8));				//垛位
						locality = String.valueOf(row.getCell(9).getStringCellValue());		//位置
						memo = ImportUtil.getCellValue(row.getCell(10)); 					//备注
						materailsupplier = ImportUtil.getCellValue(row.getCell(11)); 		//供应商
						object_attr = ImportUtil.getCellValue(row.getCell(12)); 			//物料属性
						//原料卷类型处理
						materailtype = map.get(materailtype);						
						//牌号处理
						condition = " and validflag = '1' and steel_name = '"+steel.trim()+"'";
						List<ComBaseSteel> cbsList = this.getMapper(ComBaseSteelMapper.class).findWithCondition(null, condition, null, 0, 0);
						if (CollectionUtils.isNotEmpty(cbsList)) {
							for (ComBaseSteel cbs : cbsList) {
								steel = cbs.getSteel_code();
								continue;
							}
						}else {
							rm.setState("500");
							rm.setMsgInfo("未找到热轧卷号【"+materailcoilno+"】对应的牌号："+steel.trim());
							return rm;
						}
						//物料属性处理
						if ("优特钢带".equals(object_attr.trim())) {
							object_attr = "507101";
						}else if ("客户".equals(object_attr.trim())) {
							object_attr = "507102";
						}
						//区域处理
						condition2 = " and sortcode = '1001' and storagesort = 'B' and buttressname like '%"+areano.trim()+"%'";
						List<YdmBaseButtressconfig> ybList= this.getMapper(YdmBaseButtressconfigMapper.class).findWithCondition(null, condition2, null, 0, 0);
						if (CollectionUtils.isNotEmpty(ybList)) {
							for (YdmBaseButtressconfig yb : ybList) {
								areano = yb.getButtressno();
								continue;
							}
						}else {
							rm.setState("500");
							rm.setMsgInfo("未找到热轧卷号【"+materailcoilno+"】对应的区域："+areano);
							return rm;							
						}
						//垛位处理
						condition3 = " and sortcode = '"+areano+"' and storagesort = 'C' and buttressname like '%"+buttressno.trim()+"%'";
						List<YdmBaseButtressconfig> ybbList = this.getMapper(YdmBaseButtressconfigMapper.class).findWithCondition(null, condition3, null, 0, 0);
						if (CollectionUtils.isNotEmpty(ybbList)) {
							for (YdmBaseButtressconfig ybb : ybbList) {
								buttressno = ybb.getButtressno();
								continue;
							}
						}else {
							rm.setState("500");
							rm.setMsgInfo("未找到热轧卷号【"+materailcoilno+"】对应的垛位:"+buttressno);
							return rm;
						}
						
						ComPageIfRawMtrCoilPfmc<ObjectType> cp = new ComPageIfRawMtrCoilPfmc<>();
						YdmProductDetail ypd= new YdmProductDetail();
						ypd.setMaterailcoilno(materailcoilno);
						ypd.setThick(Double.parseDouble(thick));
						ypd.setAreano(areano);
						//ypd.setCoilno(coilno);
						ypd.setJudgesteelcode(steel);
						ypd.setSteelcode(steel);
						ypd.setWidth(Double.parseDouble(width));
						ypd.setButtressno(buttressno);
						ypd.setLocality(locality);
						ypd.setMaterailtype(materailtype);
						ypd.setFactweight(Double.parseDouble(weight));
						ypd.setTheoryweight(Double.parseDouble(weight));
						ypd.setDiameter_out(1750d);
						ypd.setDiameter_inn(Double.parseDouble(diameter_inn));
						ypd.setInorder(order);
						ypd.setInteam(team);
						ypd.setIndate(now);
						ypd.setMaterailsupplier(materailsupplier);
						ypd.setMemo(memo);
						ypd.setObject_attr(object_attr);
						ypd.setStorageattr("500201");
						
						cp.setObject(ypd);
						ResultModel rm1 = this.getBean(IfRawMtrCoilPfmcServiceImpl.class).doConfirmOuts(cp);
						if (!"200".equals(rm1.getState())) {
							return rm1;
						}
						MesOprLog mol = new MesOprLog("物流管理", "外购入库管理", "导入", username , opr_time, ypd.getCoilno(), null, null, null, "原料卷号："+ypd.getMaterailcoilno());
						this.getMapper(MesOprLogMapper.class).insert(mol);
					}						
				}
			} catch (Exception e) {
				throw new Exception("外购入库失败！" + e.getMessage());
			}
			return rm; 
		} 	
	}
	
	/**
	 * 牌号调整
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doChangeSteel(CommonPage<YdmProductDetail> 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);
		
		try {
			List<YdmProductDetail> ypdList = cp.getObjectList();
			if (ypdList==null || ypdList.size()<=0) {
				throw new Exception("请传入参数");
			}
			String  judgesteelcode = cp.getMemo1();
			if (judgesteelcode==null || "".equals(judgesteelcode)) {
				throw new Exception("牌号不能为null");
			}
			for (YdmProductDetail ypd : ypdList) {
				//1.调整库存表的牌号
				YdmProductDetail newYpd = new YdmProductDetail();
				newYpd.setCoilno(ypd.getCoilno());
				newYpd.setJudgesteelcode(judgesteelcode);
				newYpd.setSteelcode(judgesteelcode);
				newYpd.setMemo("牌号调整");
				this.getMapper(YdmProductDetailMapper.class).update(newYpd);
				//2.调整入库表的牌号
				YdmProductInlist YPI = new YdmProductInlist();
				YPI.setCoilno(ypd.getCoilno());
				List<YdmProductInlist> ypiList = this.getMapper(YdmProductInlistMapper.class).find(YPI, 0, 0);
				if (ypiList!=null && ypiList.size()>0) {
					for (YdmProductInlist ypi : ypiList) {
						YdmProductInlist newYpi = new YdmProductInlist();
						newYpi.setInbillno(ypi.getInbillno());
						newYpi.setCoilno(ypd.getCoilno());
						newYpi.setJudgesteelcode(judgesteelcode);
						newYpi.setSteelcode(judgesteelcode);
						newYpi.setMemo("牌号调整");
						this.getMapper(YdmProductInlistMapper.class).update(newYpi);
					}
				}
				//3.调整出库表的牌号
				YdmProductOutlist YPO = new YdmProductOutlist();
				YPO.setCoilno(ypd.getCoilno());
				List<YdmProductOutlist> ypoList = this.getMapper(YdmProductOutlistMapper.class).find(YPO, 0, 0);
				if (ypoList!=null && ypoList.size()>0) {
					for (YdmProductOutlist ypo : ypoList) {
						YdmProductOutlist newYpo = new YdmProductOutlist();
						newYpo.setOutbillno(ypo.getOutbillno());
						newYpo.setCoilno(ypd.getCoilno());
						newYpo.setJudgesteelcode(judgesteelcode);
						newYpo.setSteelcode(judgesteelcode);
						newYpo.setMemo("牌号调整");
						this.getMapper(YdmProductOutlistMapper.class).update(newYpo);
					}
				}
				//4.调整库存历史表的牌号
				this.getMapper(YdmProductStockMapper.class).doChangeYpdHistorySteel(ypd.getCoilno(),judgesteelcode);
				
				MesOprLog mol = new MesOprLog("物流管理", "盘库管理", "牌号调整", username, opr_time, ypd.getCoilno(), null, null, null, "牌号进行了调整");
				this.getMapper(MesOprLogMapper.class).insert(mol);
			}
		}
		catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo("牌号调整失败!");
		}
		rm.setState("200");
		rm.setMsgInfo("牌号调整成功");
		return rm;
	}
	
	/**
	 * 调整包装状态
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doChangeIsPackage(CommonPage<YdmProductDetail> 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);
				
		try {
			List<YdmProductDetail> ypdList = cp.getObjectList();
			if (ypdList==null || ypdList.size()<=0) {
				throw new Exception("请传入参数");
			}
			String  is_package = cp.getMemo1();
			if (is_package==null || "".equals(is_package)) {
				throw new Exception("包装状态不能为空");
			}
			for (YdmProductDetail ypd : ypdList) {
				//调整包装状态
				YdmProductDetail newYpd = new YdmProductDetail();
				newYpd.setCoilno(ypd.getCoilno());
				newYpd.setIs_package(is_package);
				this.getMapper(YdmProductDetailMapper.class).update(newYpd);
				
				MesOprLog mol = new MesOprLog("物流管理", "盘库管理", "包装调整", username, opr_time, ypd.getCoilno(), null, null, null, "原料卷号："+ypd.getMaterailcoilno());
				this.getMapper(MesOprLogMapper.class).insert(mol);
			}
		} catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo("包装状态调整失败!");
		}
		rm.setState("200");
		rm.setMsgInfo("包装状态调整成功");
		return rm;
	}
	
	/**
	 * 废钢入库
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doInsertYpdByFg(CommonPage<YdmProductDetail> 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 work_grp=(String) this.getSession().getAttribute(HomeService.SESSION_WORK_GRP);
		String work_ord=(String) this.getSession().getAttribute(HomeService.SESSION_WORK_ORD);
		YdmProductDetail ypd=cp.getObject();
		try {   
			//判断是否输入卷号
			if(ypd.getCoilno()==null || "".equals(ypd.getCoilno())){
				throw new Exception("请输入卷号!");
			}
			//判断当前卷号是否重复
			YdmProductDetail isOk=this.getMapper(YdmProductDetailMapper.class).doFind(ypd.getCoilno(),ypd.getBoxno());
			if(isOk!=null){
				rm.setState("500");
				rm.setMsgInfo("已存在卷号重复的库存信息!");
				return rm;
			}			
			//判断位置是否被占用
			YdmProductButtresslist ypb=new YdmProductButtresslist();
			ypb.setButtressno(ypd.getButtressno());
			if (ypd.getLocality()!=null && !"".equals(ypd.getLocality())) {
				ypb.setLocality(Integer.parseInt(ypd.getLocality()));
			}			
			ypb.setAreano(ypd.getAreano());
			List<YdmProductButtresslist> lt=this.getMapper(YdmProductButtresslistMapper.class).find(ypb, 0, 0);
			if(lt!=null&&lt.size()>0){
				//throw new Exception("该目标区域货位位置已被占用!");
			}
			//1、插入库存信息					
			if (ypd.getIndate()==null||"".equals(ypd.getIndate())) {
				ypd.setIndate(now);
			}
			ypd.setTheoryweight(ypd.getFactweight());//理重==实重
			ypd.setCreater(username);
			ypd.setCreatedate(now);
			ypd.setMaterailcoilno(ypd.getCoilno());
			ypd.setInorder(work_ord);
			ypd.setInteam(work_grp);
			ypd.setSource("1");
			ypd.setProducedate(now);//生产时间
			ypd.setProduceorder(work_ord);
			ypd.setProduceteam(work_grp);
			ypd.setJudgeresult("40740803");//综判结果
			ypd.setObject_attr("507101");//优特钢带
			this.getMapper(YdmProductDetailMapper.class).insert(ypd);
			
			//2、插入入库信息
			YdmProductInlist ypi = new YdmProductInlist();
			BeanUtils.copyProperties(ypi, ypd);
			ypi.setInbillno(this.getBean(YdmProductInlistServiceImpl.class).createINBILLNO());
			ypi.setIntype("500412");//废钢入库
			ypi.setCreater(username);
			ypi.setCreatedate(now);						
			ypi.setIndate(now);
			ypi.setInorder(work_ord);
			ypi.setInteam(work_grp);
			ypi.setCoilno(ypd.getCoilno());						
			ypi.setMaterailtype(ypd.getMaterailtype());
			//ypi.setStorageattr("500209");//酸洗成品库
			ypi.setStorageattr(ypd.getStorageattr());
			ypi.setThick(ypd.getThick());
			ypi.setWidth(ypd.getWidth());
			ypi.setTheoryweight(ypd.getTheoryweight());
			ypi.setFactweight(ypd.getFactweight());
			ypi.setSteelcode(ypd.getSteelcode());
			ypi.setJudgesteelcode(ypd.getJudgesteelcode());					
			ypi.setProducedate(ypd.getProducedate());
			ypi.setProduceorder(ypd.getProduceorder());
			ypi.setProduceteam(ypd.getProduceteam());
			ypi.setOperator(username);
			ypi.setLocality("1");
			if (ypd.getLocality() != null && ypd.getLocality() != "")
				ypi.setPosition(ypd.getLocality());
			ypi.setMemo("废钢入库:"+ypd.getMemo());
			ypi.setButtressno(ypd.getButtressno());
			ypi.setMachine_code(ypd.getMachine_code());
			ypi.setMachine_name(ypd.getMachine_name());
			ypi.setJudgeresult(ypd.getJudgeresult());//综合判定结果
			ypi.setSurfaceresult(ypd.getSurfaceresult());//表面判定结果
			
			// 加入物料属性：20230725刘侣
			ypi.setObj_attr_in(ypd.getObject_attr());
			// end
			
			this.getMapper(YdmProductInlistMapper.class).insert(ypi);
			
			//3、插入垛位信息
			YdmProductButtresslist ypb1=new YdmProductButtresslist();
			ypb1.setCreater(username);
			ypb1.setCreatedate(now);
			ypb1.setLayer(1);  //层高1
			if(ypd.getLocality()!=null&&ypd.getLocality()!="")
				ypb1.setLocality(Integer.valueOf(ypd.getLocality()).intValue());
			ypb1.setButtressno(ypd.getButtressno());
			ypb1.setStorageattr(ypd.getStorageattr());
			ypb1.setAreano(ypd.getAreano());
			ypb1.setAreano(ypd.getAreano());
			ypb1.setCoilno(ypd.getCoilno());
			ypb1.setBoxno(ypd.getBoxno());
			this.getMapper(YdmProductButtresslistMapper.class).doInsert(ypb1);
			
			//4、调用生产计划模块物料跟踪接口 
			PrcMaterielProcess pmp = new PrcMaterielProcess();
			Date date =new  Date();
			pmp.setObject_no(ypd.getCoilno());
			pmp.setPrc_code("5BYA01");
			pmp.setCreate_time(date);
			pmp.setRemark("废钢入库");
			pmp.setCreate_man_name(username);
			int tmp= this.getBean(MesApiServiceImpl.class).INSERT_OBJ_PROCESS(pmp);
			if(tmp==-1){
				throw new Exception("物料跟踪失败");
			}
				    
			MesOprLog mol = new MesOprLog("物流管理", "废钢入库管理", "入库确认", username, opr_time, ypd.getCoilno(), null, null, null, "原料卷号："+ypd.getMaterailcoilno());
			this.getMapper(MesOprLogMapper.class).insert(mol);
		}
		catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo("废钢入库失败!");
			ex.printStackTrace();
			throw ex;
		}
		rm.setState("200");			
		return rm;
	}
	
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doDeleteYpdByFg(CommonPage<YdmProductDetail> 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);
		List<YdmProductDetail> ypdList = cp.getObjectList();
		try {   
			for (YdmProductDetail ypd : ypdList) {				
				//1、删除库存信息					
				this.getMapper(YdmProductDetailMapper.class).delete(ypd.getCoilno());			
				//2、删除入库信息
				this.getMapper(YdmProductInlistMapper.class).doDeleteByCoilnoStorage(ypd.getCoilno(), "500210");				
				//3、删除垛位信息
				this.getMapper(YdmProductButtresslistMapper.class).doDelete(ypd.getCoilno(), null);		
			    //4、日志
				MesOprLog mol = new MesOprLog("物流管理", "废钢入库管理", "撤销入库", username, opr_time, ypd.getCoilno(), null, null, null, "原料卷号："+ypd.getMaterailcoilno());
				this.getMapper(MesOprLogMapper.class).insert(mol);				
			}
		}
		catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo("撤销入库失败!");
			ex.printStackTrace();
			throw ex;
		}
		rm.setState("200");			
		return rm;
	}
	
	
}
