package com.cim.idm.service.Impl;

import com.cim.idm.framework.IDMFrameServiceProxy;
import com.cim.idm.framework.data.EventInfo;
import com.cim.idm.model.StorageSpec;
import com.cim.idm.service.ERPLocationMoveNoInvoiceService;
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 org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("ERPLocationMoveNoInvoice")
public class ERPLocationMoveNoInvoiceServiceImpl implements ERPLocationMoveNoInvoiceService {

	private EventInfo makeEventInfo;


	@Autowired
	private ChargeSplitServiceImpl ChargeSplitServiceImpl;

	@Autowired
	private ToSAPServiceImpl toSAPService;

	/**
	 * 调拨入库绑定条码
	 * @throws Exception 
	 */
	@Transactional
	public boolean CommitMove(List<StorageSpec> list, String user, String timesString, String opCode) throws Exception {
		
		List<MaterialPacking> all = new ArrayList<MaterialPacking> ();
		
		EventInfoUtil eventInfoUtil = new EventInfoUtil();
		String aimErpFactory = "";
		String aimErpLocation = "";
		String aimLOcationName = "";
		String erpFactory = "";
		String erpLocation = "";
		String locationName = "";
		List<MaterialPackingKey> arrayList = new ArrayList<MaterialPackingKey> ();
		for ( StorageSpec storageSpec : list) {
			String condition="WHERE MATERIALPACKINGNAME=? ";
			String[] bindSet={storageSpec.getMaterialPackingName()};
			List<MaterialPacking> MaterialPackingList = MaterialPackingServiceProxy.getMaterialPackingService().select(condition, bindSet);
			all.addAll(MaterialPackingList);
			//解析条码,根据远条码信息更新目标条码数量和库存状态
			makeEventInfo = eventInfoUtil.makeEventInfo("BarCodeToTransferIn", storageSpec.getUser(), "BarCodeToTransferIn", "", "");
//			String sql = "select * from STORAGESPEC WHERE STORAGENAME = :STORAGENAME " ;
//			Map<String, Object> hashMap2 = new HashMap<String,Object> ();
//			hashMap2.put("STORAGENAME", storageSpec.getAIMLOCATIONNAME()) ;
//			List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, hashMap2);
//			if (queryForList == null || queryForList.size() < 1) {
//				throw new GlobalException(storageSpec.getStorageName() + "库位不存在！");
//			}
			aimErpFactory =  storageSpec.getAIMERPFACTORY();
			aimErpLocation = storageSpec.getAIMERPLOCATION();
			aimLOcationName = storageSpec.getAIMLOCATIONNAME();
			erpFactory = storageSpec.getErpFactory();
			erpLocation = storageSpec.getErpLocation();
			locationName = storageSpec.getLOCATIONNAME();
			MaterialPackingKey materialPackingKey = new MaterialPackingKey("SDK",storageSpec.getMaterialPackingName());
			arrayList.add(materialPackingKey);
		}

		String billCode = toSAPService.NoSourceChangeLocation(arrayList,aimErpFactory, aimErpLocation, aimLOcationName, user);
		List<MaterialPackingKey> mpKeyList = new ArrayList<MaterialPackingKey> ();
		SetEventInfo setEventInfo = new SetEventInfo();
		for (MaterialPacking materialPacking : all) {
			MaterialPackingKey key = materialPacking.getKey();
			mpKeyList.add(key);
//			MaterialPackingServiceProxy.getMaterialPackingService().setEvent(materialPacking.getKey(), makeEventInfo, setEventInfo);
		}
		Map<String, Object> hashMap = new HashMap<String,Object> ();
		hashMap.put("erpLocation", aimErpLocation == null  ? "" : aimErpLocation);
		hashMap.put("erpFactory",  aimErpFactory == null  ? "" : aimErpFactory);
		hashMap.put("locationName", aimLOcationName == null  ? "" : aimLOcationName);
		hashMap.put("lastEventUser", user);
		hashMap.put("unDoID", billCode);
		setEventInfo.setUserColumns(hashMap);	
		MaterialPackingServiceProxy.getMaterialPackingService().setEvent(mpKeyList, makeEventInfo, setEventInfo);
		SaveUnDoInfo( billCode,timesString);
		return true;
	}
	
	/**
	 * 调拨入库绑定条码
	 * @throws Exception 
	 */
	@Transactional
	public boolean CommitMove1(List< StorageSpec> list,String user,String timesString,String opCode) throws Exception {
		
		
		List<MaterialPacking> all = new ArrayList<MaterialPacking> ();
		
		EventInfoUtil eventInfoUtil = new EventInfoUtil();
		String aimErpFactory = "";
		String aimErpLocation = "";
		String aimLOcationName = "";
		String erpFactory = "";
		String erpLocation = "";
		String locationName = "";
		List<MaterialPackingKey> arrayList = new ArrayList<MaterialPackingKey> ();
		
//		String locationNameCr = "";
		// 新增判断是否是现场仓
		String sqlW = "SELECT be.DESCRIPTION FROM BS_ERPLOCATION be WHERE be.ERPLOCATIONNAME = :ERPLOCATIONNAME";
		Map<String, Object> hashMap2 = new HashMap<String,Object> ();
		hashMap2.put("ERPLOCATIONNAME", list.get(0).getAIMERPLOCATION());
		List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sqlW, hashMap2);
		String locationNameCr = queryForList.get(0).get("DESCRIPTION").toString();
		
		for ( StorageSpec storageSpec : list) {
			
			aimErpFactory =  storageSpec.getAIMERPFACTORY();
			aimErpLocation = storageSpec.getAIMERPLOCATION();
			aimLOcationName = storageSpec.getAIMLOCATIONNAME();
			erpFactory = storageSpec.getErpFactory();
			erpLocation = storageSpec.getErpLocation();
			locationName = storageSpec.getLOCATIONNAME();
			
			String condition="WHERE MATERIALPACKINGNAME=? ";
//			String[] bindSet={storageSpec.getMaterialPackingName()};
			
			//新加的拆分标签，没有做拆分，getMATERIALQUANTITY2是空的，新拆分出的标签如果目的仓库是现场仓，后面要做标签出库处理
			String[] bindSet = null;
			if(storageSpec.getMATERIALQUANTITY2() != null && !storageSpec.getMATERIALQUANTITY2().isEmpty()) {
				
				boolean moveTransformOut = ChargeSplitServiceImpl.NoLYChargeSplit(storageSpec, user, locationNameCr);
				if (moveTransformOut != true) {
					throw new RuntimeException("标签拆分失败");
				}
				bindSet = new String[]{storageSpec.getMATERIALPACKINGNAME2()};
			}else {
				bindSet = new String[]{storageSpec.getMaterialPackingName()};
			}
			
			
			List<MaterialPacking> MaterialPackingList = MaterialPackingServiceProxy.getMaterialPackingService().select(condition, bindSet);
			all.addAll(MaterialPackingList);
			//解析条码,根据远条码信息更新目标条码数量和库存状态
			makeEventInfo = eventInfoUtil.makeEventInfo("BarCodeToTransferIn", storageSpec.getUser(), "BarCodeToTransferIn", "", "");
//			String sql = "select * from STORAGESPEC WHERE STORAGENAME = :STORAGENAME " ;
//			Map<String, Object> hashMap2 = new HashMap<String,Object> ();
//			hashMap2.put("STORAGENAME", storageSpec.getAIMLOCATIONNAME()) ;
//			List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, hashMap2);
//			if (queryForList == null || queryForList.size() < 1) {
//				throw new GlobalException(storageSpec.getStorageName() + "库位不存在！");
//			}
			
			
			//新增判断拆分，有拆分就取拆分的标签，无拆分取原来的标签
			if(storageSpec.getMATERIALQUANTITY2() != null && !storageSpec.getMATERIALQUANTITY2().isEmpty()) {
				MaterialPackingKey materialPackingKey = new MaterialPackingKey("SDK",storageSpec.getMATERIALPACKINGNAME2());
				arrayList.add(materialPackingKey);
			}else {
				MaterialPackingKey materialPackingKey = new MaterialPackingKey("SDK",storageSpec.getMaterialPackingName());
				arrayList.add(materialPackingKey);
			}
			
		}
		
		String billCode = toSAPService.NoSourceChangeLocation(arrayList,aimErpFactory,
				aimErpLocation, aimLOcationName, user );
		List<MaterialPackingKey> mpKeyList = new ArrayList<MaterialPackingKey> ();
		SetEventInfo setEventInfo = new SetEventInfo();
		for (MaterialPacking materialPacking : all) {
			MaterialPackingKey key = materialPacking.getKey();
			mpKeyList.add(key);
//			MaterialPackingServiceProxy.getMaterialPackingService().setEvent(materialPacking.getKey(), makeEventInfo, setEventInfo);
		}
		
		
		Map<String, Object> hashMap = new HashMap<String,Object> ();
		hashMap.put("erpLocation", aimErpLocation == null  ? "" : aimErpLocation);
		hashMap.put("erpFactory",  aimErpFactory == null  ? "" : aimErpFactory);
		hashMap.put("locationName", aimLOcationName == null  ? "" : aimLOcationName);
		hashMap.put("lastEventUser", user);
		hashMap.put("unDoID", billCode);
		setEventInfo.setUserColumns(hashMap);	
		MaterialPackingServiceProxy.getMaterialPackingService().setEvent(mpKeyList, makeEventInfo, setEventInfo);
		SaveUnDoInfo( billCode,timesString);
		return true;
	}


	/**
	 * 存储物料凭证
	 * @param undoid
	 * @param commitDate
	 */
	public void SaveUnDoInfo( String undoid,String commitDate) {

		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,:commitDate 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);
		bindMap_insert.put("commitDate",commitDate);
		IDMFrameServiceProxy.getSqlTemplate()
		.update(insertUnDOMaterialPackingInfo, bindMap_insert);

	}
}
