package com.cim.idm.service.Impl;

import com.cim.idm.exception.GlobalException;
import com.cim.idm.framework.IDMFrameServiceProxy;
import com.cim.idm.framework.data.EventInfo;
import com.cim.idm.service.SaleReturnService;
import com.cim.idm.service.impl.ToSAPServiceImpl;
import com.cim.idm.utils.EventInfoUtil;
import com.cim.idm.wmspackage.materialpacking.MaterialPackingServiceProxy;
import com.cim.idm.wmspackage.materialpacking.management.data.MaterialPacking;
import com.cim.idm.wmspackage.materialpacking.management.data.MaterialPackingKey;
import com.cim.idm.wmspackage.materialpacking.management.info.SetEventInfo;
import com.cim.idm.wmspackage.storage.StorageServiceProxy;
import com.cim.idm.wmspackage.storage.management.data.StorageSpec;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("SaleReturn")
public class SaleReturnServiceImpl implements SaleReturnService {

	private EventInfo makeEventInfo;

	@Autowired
	private ToSAPServiceImpl  toSAPServiceImpl;

	/**
	 * 调拨入库绑定条码
	 */
	@Transactional
	@Override
	public boolean BindBarCodeToSaleReturn(String materialPackingName,String charge,String materialspecName,String user,
			String shipRequestName,String shipRequestDetailName,String locationName) throws GlobalException {
		//解析条码,根据远条码信息更新目标条码数量和库存状态
		String condition="WHERE CHARGE=? AND MATERIALSPECNAME=? ";
		String[] bindSet={charge,materialspecName};
		List<MaterialPacking> MaterialPackingList = MaterialPackingServiceProxy.getMaterialPackingService().select(condition, bindSet);
		SetEventInfo setEventInfo = new SetEventInfo();
		EventInfoUtil eventInfoUtil = new EventInfoUtil();
		makeEventInfo = eventInfoUtil.makeEventInfo("BarCodeToSaleReturn", user, "BarCodeToSaleReturn");
		String sql = "select * from STORAGESPEC WHERE STORAGENAME = :STORAGENAME" ;
		Map<String, Object> hashMap2 = new HashMap<String,Object> ();
		hashMap2.put("STORAGENAME", locationName) ;
		List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, hashMap2);
		if (queryForList == null || queryForList.size() < 1) {
			throw new GlobalException(locationName + "库位不存在！");
		}
		//根据货位找到ERP库位和组织
		condition="WHERE STORAGENAME=? ";
		String[] indSet={locationName};
		List<StorageSpec> select = StorageServiceProxy.getStorageSpecService().select(condition, indSet);
		String erpFactory = "";
		String erpLocation = "";
		for (StorageSpec storageSpec : select) {
			erpLocation = storageSpec.getErpLocation();
			erpFactory = storageSpec.getErpFactory();
		}
		if ("".equals(erpLocation) || "".equals(erpFactory)) {
			throw new GlobalException(locationName + "库位不存在！");
		}
		String[] split = materialPackingName.split("\\|");
		for (MaterialPacking materialPacking : MaterialPackingList) {
			//更新批次，数量，库位状态
			Map<String, Object> hashMap = new HashMap<String,Object> ();
			hashMap.put("materialPackingName", materialPackingName);
			hashMap.put("materialQuantity", split[7]);
			hashMap.put("materialCreateQuantity", split[7]);
			hashMap.put("receiveRequestName", shipRequestName);
			hashMap.put("receiveRequestDetailName", shipRequestDetailName);
			hashMap.put("shipRequestName", shipRequestName);
			hashMap.put("shipRequestDetailName", shipRequestDetailName);
			hashMap.put("erpLocation", erpLocation);
			hashMap.put("erpFactory", erpFactory);
			hashMap.put("locationName", locationName);
			setEventInfo.setUserColumns(hashMap);
			MaterialPackingServiceProxy.getMaterialPackingService().setEvent(materialPacking.getKey(), makeEventInfo, setEventInfo);
			
			String sql2 = "UPDATE MATERIALSHIPREQUESTDETAIL T SET T.ASSIGNEDQUANTITY = T.ASSIGNEDQUANTITY + :materialQuantity "
					+ "WHERE T.SHIPREQUESTNAME = :shipRequestName AND T.SHIPREQUESTDETAILNAME  = :shipRequestDetailName ";
			IDMFrameServiceProxy.getSqlTemplate().update(sql2, hashMap);
			
		}
		return true;
	}
	
	/**
	 * 销售退库 lz
	 */
	@Transactional
	@Override  
	public boolean BindBarProductSaleReturn(String materialSpecName,String phase,List<Map<String, Object>> queryForList2,String materialQuantity,String materialPackingName,
			String user,String erpFactory,String erpLocation,String locationName,String receiveRequestName,String charge) throws GlobalException {
		
		BigDecimal mathMaterialQuantity = new BigDecimal(materialQuantity);
		int i = 0;
		for (Map<String, Object> map2 : queryForList2) {
			
			String sqlString = "SELECT * FROM MATERIALPACKINGSUB WHERE  MATERIALPACKINGNAME = :MATERIALPACKINGNAME\r\n"
					+ " AND RECEIVEREQUESTNAME = :RECEIVEREQUESTNAME AND RECEIVEREQUESTDETAILNAME = :RECEIVEREQUESTDETAILNAME";
			
			String insertSql = "UPDATE MATERIALPACKINGSUB T SET T.QTY = (T.QTY + :QTY)"
					+ "WHERE T.MATERIALPACKINGNAME = :MATERIALPACKINGNAME and T.RECEIVEREQUESTNAME = :RECEIVEREQUESTNAME and T.RECEIVEREQUESTDETAILNAME = :RECEIVEREQUESTDETAILNAME";
			String updateSql = "UPDATE MATERIALRECEIVEREQUESTDETAIL T SET T.RECEIVEDQUANTITY = (T.RECEIVEDQUANTITY  + :QTY) "
					+ "WHERE T.RECEIVEREQUESTNAME = :RECEIVEREQUESTNAME AND T.RECEIVEREQUESTDETAILNAME  = :RECEIVEREQUESTDETAILNAME";
			
			String insertSql1 = "INSERT INTO MATERIALPACKINGSUB T (T.MATERIALPACKINGNAME,T.RECEIVEREQUESTNAME,T.RECEIVEREQUESTDETAILNAME,T.QTY) "
					+ "VALUES (:MATERIALPACKINGNAME, :RECEIVEREQUESTNAME,:RECEIVEREQUESTDETAILNAME,:QTY)"; 
			String qty = map2.get("QTY").toString();
			BigDecimal mathQty = new BigDecimal(qty);
			String receiveRequestName2 = map2.get("RECEIVEREQUESTNAME").toString();
			String receiveRequestDetailName2 = map2.get("RECEIVEREQUESTDETAILNAME").toString();
			Map<String, Object> hashMap2 = new HashMap<String,Object> ();
			hashMap2.put("MATERIALPACKINGNAME", materialPackingName);
			hashMap2.put("RECEIVEREQUESTNAME", receiveRequestName);
			hashMap2.put("RECEIVEREQUESTDETAILNAME", receiveRequestDetailName2);
			if (mathMaterialQuantity.compareTo(mathQty) == 0) {//条码数量和剩余数量一致
				System.out.println("a equals b");
				BigDecimal a = new BigDecimal("10.5");
				BigDecimal b = new BigDecimal("5.5");
				int result = a.compareTo(b);
				hashMap2.put("QTY", mathMaterialQuantity);
				List<Map<String,Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sqlString, hashMap2);
				if(queryForList.size() == 0) {
					IDMFrameServiceProxy.getSqlTemplate().update(insertSql1, hashMap2);
				} else {
					IDMFrameServiceProxy.getSqlTemplate().update(insertSql, hashMap2);
				}
//				IDMFrameServiceProxy.getSqlTemplate().update(insertSql, hashMap2);
				IDMFrameServiceProxy.getSqlTemplate().update(updateSql, hashMap2);
				i++;
				break;
			} else if (mathMaterialQuantity.compareTo(mathQty) == 1) {//条码数量大于剩余数量
				if(i >= queryForList2.size()-1) {
					hashMap2.put("QTY", mathMaterialQuantity.toString());
					mathMaterialQuantity = mathMaterialQuantity.subtract(mathQty);
					List<Map<String,Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sqlString, hashMap2);
					if(queryForList.size() == 0) {
						IDMFrameServiceProxy.getSqlTemplate().update(insertSql1, hashMap2);
					} else {
						IDMFrameServiceProxy.getSqlTemplate().update(insertSql, hashMap2);
					}
//					IDMFrameServiceProxy.getSqlTemplate().update(insertSql, hashMap2);
					IDMFrameServiceProxy.getSqlTemplate().update(updateSql, hashMap2);
					System.out.println("a is greater than b");
					i++;
				} else {
					hashMap2.put("QTY", qty.toString());
					mathMaterialQuantity = mathMaterialQuantity.subtract(mathQty);
					List<Map<String,Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sqlString, hashMap2);
					if(queryForList.size() == 0) {
						IDMFrameServiceProxy.getSqlTemplate().update(insertSql1, hashMap2);
					} else {
						IDMFrameServiceProxy.getSqlTemplate().update(insertSql, hashMap2);
					}
//					IDMFrameServiceProxy.getSqlTemplate().update(insertSql, hashMap2);
					IDMFrameServiceProxy.getSqlTemplate().update(updateSql, hashMap2);
					System.out.println("a is greater than b");
					i++;
					continue;
				}
			} else {//条码数量小于订单剩余数量
				System.out.println("a is less than b");
				hashMap2.put("QTY", mathMaterialQuantity.toString());
				List<Map<String,Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sqlString, hashMap2);
				if(queryForList.size() == 0) {
					IDMFrameServiceProxy.getSqlTemplate().update(insertSql1, hashMap2);
				} else {
					IDMFrameServiceProxy.getSqlTemplate().update(insertSql, hashMap2);
				}
				IDMFrameServiceProxy.getSqlTemplate().update(updateSql, hashMap2);
				i++;
				break;
			}
		}
		String ckzt = "SELECT BE.TYPE VALUETYPE FROM BS_ERPLOCATION BE WHERE BE.ERPFACTORYNAME = :ERPFACTORYNAME AND BE.ERPLOCATIONNAME  = :ERPLOCATIONNAME ";
		Map<String,Object> dic = new HashMap<String,Object>();
		dic.put("ERPFACTORYNAME", erpFactory);
		dic.put("ERPLOCATIONNAME", locationName);
		List<Map<String, Object>> maps = IDMFrameServiceProxy.getSqlTemplate().queryForList(ckzt, dic);
		String oqa = "OK";
		if (maps != null && maps.size() > 0) {
			String temp = maps.get(0).get("VALUETYPE").toString();
			if ("2".equals(temp)) {
				oqa = "NG";
			}
		}
		EventInfoUtil eventInfoUtil = new EventInfoUtil();
		SetEventInfo setEventInfo = new SetEventInfo();
		EventInfo eventInfo = EventInfoUtil.makeEventInfo("ProductSaleReturn", user, "ProductSaleReturn");
		HashMap<String,Object> hashMap2 = new HashMap<String,Object >();
		hashMap2.put("erpFactory", erpFactory); 
		hashMap2.put("erpLocation", erpLocation);

		hashMap2.put("locationName", locationName);
		hashMap2.put("receiveRequestName",receiveRequestName);
		hashMap2.put("shipRequestName","");
		hashMap2.put("stockState", "Created"); 
		hashMap2.put("oqaResult", oqa);
		hashMap2.put("packingGrade", oqa);
		hashMap2.put("oqaResultState", "END");
		setEventInfo.setUserColumns(hashMap2);
		MaterialPackingKey materialPackingKey = new MaterialPackingKey("SDK",materialPackingName);
		MaterialPacking setEvent = MaterialPackingServiceProxy.getMaterialPackingService().setEvent(materialPackingKey, eventInfo, setEventInfo);
		return true;
	}
	
	
	
	@Override
	public boolean CommitSaleReturnInvoice(String shipRequestName,String user,String commitDate,String opcode) throws Exception {
		EventInfoUtil eventInfoUtil = new EventInfoUtil();
		makeEventInfo = eventInfoUtil.makeEventInfo("CommitSaleReturnInvoice", user, "CommitSaleReturnInvoice", "", "");
		SetEventInfo setEventInfo = new SetEventInfo();
		String billCode = toSAPServiceImpl.SaleReturn(shipRequestName, "SDK", user,commitDate,opcode);
		//判断是否获得物料凭证
		if (billCode == null || "".equals(billCode)) {
			throw new GlobalException("ERP过账失败！");
		}
		
		String condition1="WHERE SHIPREQUESTNAME=? AND STOCKSTATE='StockOut' ";
		String[] bindSet2 = {shipRequestName};
		List<MaterialPacking> MaterialPackingList = MaterialPackingServiceProxy.getMaterialPackingService().select(condition1, bindSet2);
		for (MaterialPacking materialPacking : MaterialPackingList) {
			//更新批次，数量，库位状态
			Map<String, Object> hashMap = new HashMap<String,Object> ();
			hashMap.put("stockState", "Stocked");
			hashMap.put("shipRequestName", "");
			hashMap.put("shipRequestDetailName", "");
			hashMap.put("unDoID", billCode);
			setEventInfo.setUserColumns(hashMap);
			MaterialPackingServiceProxy.getMaterialPackingService().setEvent(materialPacking.getKey(), makeEventInfo, setEventInfo);
		}
		SaveUnDoInfo( billCode);
		
		String sql3 = "UPDATE MATERIALSHIPREQUEST T SET T.SHIPREQUESTSTATE = 'Completed' WHERE T.SHIPREQUESTNAME = :SHIPREQUESTNAME";
		IDMFrameServiceProxy.getSqlTemplate().update(sql3, new HashMap<String,Object> () {{
			this.put("SHIPREQUESTNAME", shipRequestName);
		}});
		return true;
	}
	
	
	
	/**
	 * 接收ERP返回消息更新WMS凭证
	 * @param
	 */
	public void SaveUnDoInfo( String undoid) {

		String insertUnDOMaterialPackingInfo = "insert into BS_MATERIALPACKINGUNDOINFO (unDoID,preundoid,UNDODETAILNAME,undoidstate,UNDOIDDATE,"
				+ "SITENAME, MATERIALPACKINGNAME, MATERIALPACKINGTYPE, CONTENTMATERIALTYPE,"
				+ "MATERIALTYPE, MATERIALSPECNAME, SUPERMATERIALPACKINGNAME, PACKINGGRADE, SUBPACKINGQUANTITY, MATERIALCREATEQUANTITY,"
				+ "MATERIALQUANTITY, PACKINGSTATE, OLDPACKINGSTATE, STOCKSTATE, OLDSTOCKSTATE, HOLDSTATE, AREANAME, LOCATIONNAME,"
				+ "DURABLENAME, MATERIALPROCESSGROUPNAME, LASTEVENTNAME, LASTEVENTTIMEKEY, LASTEVENTTIME, LASTEVENTUSER,"
				+ "LASTEVENTCOMMENT, CREATETIME, CREATEUSER, RECEIVEREQUESTNAME, RECEIVEREQUESTDETAILNAME,"
				+ "MAKEDATE, RECEIVEACTNO, STOCKINTYPE, RECEIVETIME, RECEIVEUSER, SHIPREQUESTNAME, SHIPREQUESTDETAILNAME, SHIPTIME,"
				+ "SHIPUSER, REASONCODETYPE, OQARESULTSTATE, OQARESULT, ERPLOCATION, ERPFACTORY, REASONCODE, CHARGE, SUPPLIERNAME,ETCSTATE,ERPEVENTTIME,NPFLAG)"
				+ "select unDoID,'' as preundoid,UNDODETAILNAME,'Completed' as undoidstate,TO_CHAR(SYSDATE, 'YYYY-MM-DD HH24:MI:SS') AS UNDOIDDATE," //
				+ "SITENAME, MATERIALPACKINGNAME, MATERIALPACKINGTYPE, CONTENTMATERIALTYPE,"
				+ "MATERIALTYPE, MATERIALSPECNAME, SUPERMATERIALPACKINGNAME, PACKINGGRADE, SUBPACKINGQUANTITY, MATERIALCREATEQUANTITY,"
				+ "MATERIALQUANTITY, PACKINGSTATE, OLDPACKINGSTATE, STOCKSTATE, OLDSTOCKSTATE, HOLDSTATE, AREANAME, LOCATIONNAME,"
				+ "DURABLENAME, MATERIALPROCESSGROUPNAME, LASTEVENTNAME, LASTEVENTTIMEKEY, LASTEVENTTIME, LASTEVENTUSER,"
				+ "LASTEVENTCOMMENT, CREATETIME, CREATEUSER, RECEIVEREQUESTNAME, RECEIVEREQUESTDETAILNAME,"
				+ "MAKEDATE, RECEIVEACTNO, STOCKINTYPE, RECEIVETIME, RECEIVEUSER, SHIPREQUESTNAME, SHIPREQUESTDETAILNAME, SHIPTIME,"
				+ "SHIPUSER, REASONCODETYPE, OQARESULTSTATE, OQARESULT, ERPLOCATION, ERPFACTORY, REASONCODE, CHARGE, SUPPLIERNAME,ETCSTATE,ERPEVENTTIME,NPFLAG"
				+ " from MATERIALPACKING  "
				+ " where unDoID=:UNDOID";

		Map<String, Object> bindMap_insert = new HashMap<String, Object>();
		bindMap_insert.put("UNDOID", undoid);
		IDMFrameServiceProxy.getSqlTemplate()
				.update(insertUnDOMaterialPackingInfo, bindMap_insert);

	}





	
	
}
