package com.cim.idm.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cim.idm.framework.IDMFrameServiceProxy;
import com.cim.idm.framework.data.EventInfo;
import com.cim.idm.model.po.MaterialReceiveRequest;
import com.cim.idm.model.MaterialreceiveActDto;
import com.cim.idm.model.dto.TrackOutBoDto;
import com.cim.idm.mwmsextend.materialpacking.service.MaterialPackingServiceImpl;
import com.cim.idm.service.IDeliveryService;
import com.cim.idm.service.impl.QMSServiceImpl;
import com.cim.idm.service.impl.ToSAPServiceImpl;
import com.cim.idm.utils.AjaxResult;
import com.cim.idm.utils.EventInfoUtil;
import com.cim.idm.wmsextend.generic.errorHandler.CustomException;
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.RemoveInfo;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.*;

import com.cim.idm.service.Impl.SDKMaterialPackingServiceImpl;

import javax.annotation.Resource;

@RestController
@RequestMapping("/MaterialReceiveAct")
@EnableAutoConfiguration
public class MaterialReceiveActController {

	@Resource
	private IDeliveryService deliveryService;

	private static Log log = LogFactory.getLog(MaterialReceiveActController.class);
	private EventInfo makeEventInfo;

	private MaterialPackingServiceImpl MaterialPackingServiceImpl = new MaterialPackingServiceImpl ();

	@Autowired
	private ToSAPServiceImpl toSAPServiceImpl;

	@Autowired
	private SDKMaterialPackingServiceImpl SDKMaterialPackingServiceImpl;


	private QMSServiceImpl qMSServiceImpl = new QMSServiceImpl();

	@RequestMapping(value = "/dessiginBoxByAct", method = RequestMethod.POST)
	public AjaxResult dessiginBoxByAct(@RequestBody JSONObject in ) throws Exception{

		MaterialReceiveRequest materialReceiveRequest = JSON.toJavaObject(in, MaterialReceiveRequest.class);
		String user = materialReceiveRequest.getUser();
		makeEventInfo = new EventInfoUtil().makeEventInfo("dessiginBoxByAct", user, "dessiginBoxByAct");
		List<MaterialPacking> boxList = materialReceiveRequest.getBoxList();
		for (MaterialPacking materialPacking : boxList) {
			String materialQuantity = materialPacking.getMaterialQuantity() + "";
			String siteName = "SDK";
			String materialPackingName = materialPacking.getMaterialPackingName();
			String receiveRequestName = materialPacking.getReceiveRequestName();
			String receiveRequestDetailName = materialPacking.getReceiveRequestDetailName();
			Timestamp makeDate2 = materialPacking.getMakeDate();
			Date makeDate = materialPacking.getMakeDate();
			String receiveActNo2 = materialPacking.getReceiveActNo();
			ModifyRequestQtyInfo(makeEventInfo, siteName, receiveRequestName,
					receiveRequestDetailName, materialQuantity, makeDate2,
					receiveActNo2, materialQuantity,materialPackingName);
		}
		return AjaxResult.me().setResultObj(null);

	}

	/**
	 *
	 * @param eventInfo
	 * @param siteName
	 * @param receiveRequestName
	 * @param receiveRequestDetailName
	 * @param receiveQuantity
	 * @param
	 * @param makeDate
	 * @param receiveActNO
	 * @param actDetailQuantity
	 * @throws Exception
	 */
	public static void ModifyRequestQtyInfo(EventInfo eventInfo,String siteName,
											String receiveRequestName,String receiveRequestDetailName,String receiveQuantity,
											Timestamp makeDate,String receiveActNO,String actDetailQuantity,String materialPackingName) throws Exception
	{
		try
		{
			Map<String, Object> hashMap = new HashMap<String,Object> ();
			//判断标签是否存在
			String sql = "SELECT * FROM MATERIALPACKING T WHERE T.SITENAME = :SITENAME AND T.MATERIALPACKINGNAME = :MATERIALPACKINGNAME";
			hashMap.put("SITENAME", siteName);
			hashMap.put("MATERIALPACKINGNAME", materialPackingName);
			List<Map<String, Object>> queryForList2 = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, hashMap);
			if (queryForList2 == null || queryForList2.size() < 1) {
				return;
			}
			//修改行项目数量信息
			String sql1 = "UPDATE MATERIALRECEIVEREQUESTDETAIL T SET T.RECEIVEDQUANTITY = T.RECEIVEDQUANTITY - :QTY "
					+ "WHERE T.RECEIVEREQUESTNAME = :RECEIVEREQUESTNAME AND T.RECEIVEREQUESTDETAILNAME = :RECEIVEREQUESTDETAILNAME";

			String sql2 = "UPDATE MATERIALRECEIVEACTDETAIL T SET T.RECEIVEQUANTITY = T.RECEIVEQUANTITY  - :QTY "
					+ "WHERE T.RECEIVEREQUESTNAME = :RECEIVEREQUESTNAME AND T.RECEIVEREQUESTDETAILNAME = :RECEIVEREQUESTDETAILNAME AND T.RECEIVEACTNO  = :RECEIVEACTNO";

			String sql3 = "SELECT T.RECEIVEQUANTITY FROM MATERIALRECEIVEACTDETAIL T WHERE T.RECEIVEREQUESTNAME = :RECEIVEREQUESTNAME "
					+ "AND T.RECEIVEREQUESTDETAILNAME = :RECEIVEREQUESTDETAILNAME AND T.RECEIVEACTNO  = :RECEIVEACTNO";
			String sql4 = "DELETE MATERIALRECEIVEACTDETAIL T WHERE T.RECEIVEREQUESTNAME = :RECEIVEREQUESTNAME "
					+ "AND T.RECEIVEREQUESTDETAILNAME = :RECEIVEREQUESTDETAILNAME AND T.RECEIVEACTNO  = :RECEIVEACTNO";
			hashMap.put("QTY", actDetailQuantity);
			hashMap.put("RECEIVEREQUESTNAME", receiveRequestName);
			hashMap.put("RECEIVEREQUESTDETAILNAME", receiveRequestDetailName);
			hashMap.put("RECEIVEACTNO", receiveActNO);
			IDMFrameServiceProxy.getSqlTemplate().update(sql1, hashMap);
			IDMFrameServiceProxy.getSqlTemplate().update(sql2, hashMap);
			List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql3, hashMap);
			if (queryForList != null && queryForList.get(0).get("RECEIVEQUANTITY").toString().equals("0")) {
				IDMFrameServiceProxy.getSqlTemplate().update(sql4, hashMap);
			}
			MaterialPackingServiceProxy.getMaterialPackingService().delete(new MaterialPackingKey(siteName, materialPackingName));
		}
		catch(Exception e)
		{
			throw e;
		}

	}

	/**
	 * 创建Box
	 * @param in
	 * @return
	 * @throws CustomException
	 * @throws Exception
	 */
	@RequestMapping(value = "/TrackOutBox", method = RequestMethod.POST)
	public AjaxResult TrackOutBox(@RequestBody JSONObject in )  {
		TrackOutBoDto boxs = JSON.toJavaObject(in, TrackOutBoDto.class);
		MaterialreceiveActDto box = boxs.getMaterialreceiveAct();
		String user = boxs.getUser();
		String areaName = box.getAreaName();
		String boxFlag = box.getBoxFlag();
		String boxQuantity = box.getMATERIALQUANTITY();//标签个数
		String charge = box.getCharge();
		String erpFactory = box.getErpFactory();
		String erpLocation = box.getErpLocation();
		String everyBoxQuantity = box.getMATERIALCREATEQUANTITY();//标签数量
		String expirationDay = box.getExpirationDay();
		String fqty = (box.getFqty() == null || "NaN" .equals(box.getFqty())) ? "0" : box.getFqty().toString();
		String funit = box.getFunit();
		String iqcflag = box.getIQCFLAG();
		String is_BATCH = box.getIS_BATCH();
		String locationName = box.getLocationName() == null ? "" : box.getLocationName();
		String makeDate = box.getMakeDate();
		String materialSpecName = box.getMaterialSpecName();
		String materialUnit = box.getMaterialUnit();
		String npFlag = box.getNPFlag();
		String phase = box.getPhase() ==null ? "" :  box.getPhase();
		String reasonCode = box.getReasonCode();
		String reasonCodeType = box.getReasonCodeType();
		String receiveActNo = box.getReceiveActNo();
		String receiveQty = box.getRECEIVEDQUANTITY2();//实收数量
		String receiveRequestDetailName = box.getReceiveRequestDetailName();
		// 单据
		String receiveRequestName = boxs.getReceiveRequestName();
		// 判断是否是倒库单据
		/*MaterialReceiveRequest byKey = deliveryService.getByKey(boxs.getSiteName(), boxs.getReceiveRequestName());
		if (byKey.getReceiveRequestType().equals(ReceiveTypeEnums.DK.getCode())) {
			// 检索该到库订单下该物料的采购订单的 name
			List<MaterialReceiveRequest> collect = deliveryService.getReceiveByDelivery(boxs.getSiteName(), boxs.getReceiveRequestName())
					.stream().filter(item -> item.getMaterialSpecName().equals(materialSpecName)).collect(Collectors.toList());
			// 检查剩余数量
			// @TODO
		}*/
		String remark = box.getRemark();
		String sdkid = box.getSdkid() == null ? "" : box.getSdkid();
		String shipRequestDetailName = box.getShipRequestDetailName();
		String shipRequestName = box.getShipRequestName();
		String siteName = box.getSiteName();
		String specName = box.getSpecName() == null ? "":box.getSpecName();
		String supplierCharge = box.getSupplierCharge();
		String supplierName = box.getSUPPLIERNO();
		String truegg = box.getTruegg();
		String salesperson = box.getSALESPERSON();
		String business_UNIT = box.getBUSINESS_UNIT();
		String career_ASSISTANCE = box.getCAREER_ASSISTANCE();
		makeEventInfo = new EventInfoUtil().makeEventInfo("TrackOutBox", user, "TrackOutBox");

		//判断数量卡控是否正确
		BigDecimal fboxQuantity = new BigDecimal(boxQuantity);//标签个数
		BigDecimal feveryBoxQuantity = new BigDecimal(everyBoxQuantity);//标签数量
		BigDecimal freceiveQty = new BigDecimal(receiveQty);//实收数量
		BigDecimal zero = BigDecimal.ZERO;
		if (fboxQuantity.compareTo(zero) <= 0) {
			return AjaxResult.me().setSuccess(false).setMessage("标签个数不能小于0");
		}
		if (feveryBoxQuantity.compareTo(zero) <= 0) {
			return AjaxResult.me().setSuccess(false).setMessage("标签数量不能小于0");
		}
		if (freceiveQty.compareTo(zero) <= 0) {
			return AjaxResult.me().setSuccess(false).setMessage("接收数量不能小于0");
		}
		String timeKey = null;
		try {
			//生产标签
			timeKey = MaterialPackingServiceImpl.Packing(makeEventInfo, siteName, areaName, receiveQty, boxQuantity,
					everyBoxQuantity, "Y", receiveRequestName, receiveRequestDetailName, materialSpecName,
					receiveActNo, makeDate, shipRequestName, shipRequestDetailName, reasonCodeType, reasonCode,
					erpLocation, erpFactory, charge, supplierName, npFlag, expirationDay, supplierCharge, sdkid,
					locationName, phase, specName, materialUnit, is_BATCH, iqcflag, funit, fqty, remark, truegg,
					salesperson,career_ASSISTANCE,business_UNIT);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return AjaxResult.me().setSuccess(false).setMessage(e.toString());
		}
		//更新订单数量
		//1.查询符合条件的Box
		String sql2 = " SELECT * FROM MATERIALPACKING m WHERE RECEIVEREQUESTNAME = :RECEIVEREQUESTNAME"
				+ " AND MATERIALSPECNAME = :MATERIALSPECNAME AND (:PHASE IS NULL OR PHASE = :PHASE) "
				+ "AND (:SDK_ID IS NULL OR SDK_ID = :SDK_ID) AND STOCKSTATE = 'Created' AND LASTEVENTTIMEKEY = :LASTEVENTTIMEKEY";
		Map<String, Object> hashMap = new HashMap<String,Object> ();
		hashMap.put("MATERIALSPECNAME", materialSpecName);
		hashMap.put("RECEIVEREQUESTNAME", receiveRequestName);
		hashMap.put("PHASE", phase);
		hashMap.put("SDK_ID", sdkid);
		hashMap.put("LASTEVENTTIMEKEY", timeKey);
		List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql2, hashMap);
		for (Map<String, Object> map : queryForList) {
			String materialPackingName = map.get("MATERIALPACKINGNAME").toString();  //标签
			String materialQuantity = map.get("MATERIALQUANTITY").toString();  //数量
			BigDecimal mathMaterialQuantity = new BigDecimal(materialQuantity);
			String invoiceSql = "SELECT\r\n" +
					"	M.REQUESTQUANTITY - M.RECEIVEDQUANTITY QTY,\r\n" +
					"	M.RECEIVEREQUESTNAME,\r\n" +
					"	M.RECEIVEREQUESTDETAILNAME \r\n" +
					"FROM\r\n" +
					"	MATERIALRECEIVEREQUESTDETAIL M\r\n" +
					"	LEFT JOIN MATERIALSPEC c ON c.MATERIALSPECNAME = M.MATERIALSPECNAME\r\n" +
					"WHERE\r\n" +
					"	M.RECEIVEREQUESTNAME = :RECEIVEREQUESTNAME\r\n" +
					"	AND M.MATERIALSPECNAME = :MATERIALSPECNAME\r\n" +
					"	AND (:PHASE IS NULL\r\n" +
					"		OR c.PHASE = :PHASE)\r\n" +
					"	AND (:SDK_ID IS NULL\r\n" +
					"		OR SDK_ID = :SDK_ID)\r\n" +
					"	AND M.REQUESTQUANTITY - M.RECEIVEDQUANTITY > 0";
			List<Map<String, Object>> queryForList2 = IDMFrameServiceProxy.getSqlTemplate().queryForList(invoiceSql, hashMap);
			for (Map<String, Object> map2 : queryForList2) {
				String insertSql = "INSERT INTO MATERIALPACKINGSUB T (T.MATERIALPACKINGNAME,T.RECEIVEREQUESTNAME,T.RECEIVEREQUESTDETAILNAME,T.QTY) "
						+ "VALUES (:MATERIALPACKINGNAME, :RECEIVEREQUESTNAME,:RECEIVEREQUESTDETAILNAME,:QTY)";
				String updateSql = "UPDATE MATERIALRECEIVEREQUESTDETAIL T SET T.RECEIVEDQUANTITY = T.RECEIVEDQUANTITY  + :QTY "
						+ "WHERE T.RECEIVEREQUESTNAME = :RECEIVEREQUESTNAME AND T.RECEIVEREQUESTDETAILNAME  = :RECEIVEREQUESTDETAILNAME";
				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", receiveRequestName2);
				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);
					IDMFrameServiceProxy.getSqlTemplate().update(insertSql, hashMap2);
					IDMFrameServiceProxy.getSqlTemplate().update(updateSql, hashMap2);
					break;
				} else if (mathMaterialQuantity.compareTo(mathQty) == 1) {//条码数量大于剩余数量
					hashMap2.put("QTY", qty);
					mathMaterialQuantity = mathMaterialQuantity.subtract(mathQty);
					IDMFrameServiceProxy.getSqlTemplate().update(insertSql, hashMap2);
					IDMFrameServiceProxy.getSqlTemplate().update(updateSql, hashMap2);
					System.out.println("a is greater than b");
					continue;
				} else {//条码数量小于订单剩余数量
					System.out.println("a is less than b");
					hashMap2.put("QTY", mathMaterialQuantity);
					IDMFrameServiceProxy.getSqlTemplate().update(insertSql, hashMap2);
					IDMFrameServiceProxy.getSqlTemplate().update(updateSql, hashMap2);
					break;
				}
			}

		}
		//2.查询符合条件的订单明细

//		return AjaxResult.me().setResultObj(null);box
		return AjaxResult.me().setResultObj(in);
	}


	@RequestMapping(value = "/DeleteTrackOutBox", method = RequestMethod.POST)
	public AjaxResult DeleteTrackOutBox(@RequestBody JSONObject in ) throws Exception{
		TrackOutBoDto boxs = JSON.toJavaObject(in, TrackOutBoDto.class);
		MaterialreceiveActDto box = boxs.getMaterialreceiveAct();
		String user = boxs.getUser();
		String materialSpecName = box.getMaterialSpecName();
		String receiveRequestName = box.getReceiveRequestName();
		String sdkid = box.getSdkid();
		String phase = box.getPhase();
		String siteName = box.getSiteName();
		makeEventInfo = new EventInfoUtil().makeEventInfo("DeleteTrackOutBox", user, "DeleteTrackOutBox");
		String sql = " SELECT * FROM MATERIALPACKING m WHERE RECEIVEREQUESTNAME = :RECEIVEREQUESTNAME"
				+ " AND MATERIALSPECNAME = :MATERIALSPECNAME AND (:PHASE IS NULL OR PHASE = :PHASE) AND (:SDK_ID IS NULL OR SDK_ID = :SDK_ID) AND STOCKSTATE = 'Created'";
		Map<String, Object> hashMap = new HashMap<String,Object> ();
		hashMap.put("MATERIALSPECNAME", materialSpecName);
		hashMap.put("RECEIVEREQUESTNAME", receiveRequestName);
		hashMap.put("PHASE", phase);
		hashMap.put("SDK_ID", sdkid);
		List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, hashMap);
		for (Map<String, Object> map : queryForList) {
			String materialPackingName = map.get("MATERIALPACKINGNAME").toString();
			MaterialPackingKey materialPackingKey = new MaterialPackingKey(siteName, materialPackingName);
			RemoveInfo removeInfo = new RemoveInfo();
			MaterialPackingServiceProxy.getMaterialPackingService().remove(materialPackingKey,makeEventInfo,removeInfo);
			//找到条码明细表的数据，先更新订单在删除条码明细
			String selectSql = "SELECT * FROM MATERIALPACKINGSUB m WHERE m.MATERIALPACKINGNAME = :MATERIALPACKINGNAME";
			hashMap.put("MATERIALPACKINGNAME", materialPackingName);
			List<Map<String, Object>> queryForList2 = IDMFrameServiceProxy.getSqlTemplate().queryForList(selectSql, hashMap);
			for (Map<String, Object> map2 : queryForList2) {
				String qty = map2.get("QTY").toString();
				String receiveRequestName2 = map2.get("RECEIVEREQUESTNAME").toString();
				String receiveRequestDetailName2 = map2.get("RECEIVEREQUESTDETAILNAME").toString();
				hashMap.put("RECEIVEREQUESTNAME", receiveRequestName2);
				hashMap.put("RECEIVEREQUESTDETAILNAME", receiveRequestDetailName2);
				hashMap.put("QTY", qty);
				String updateSql = "UPDATE MATERIALRECEIVEREQUESTDETAIL T SET T.RECEIVEDQUANTITY = T.RECEIVEDQUANTITY  - :QTY "
						+ "WHERE T.RECEIVEREQUESTNAME = :RECEIVEREQUESTNAME AND T.RECEIVEREQUESTDETAILNAME  = :RECEIVEREQUESTDETAILNAME";
				IDMFrameServiceProxy.getSqlTemplate().update(updateSql, hashMap);

				String deleteSql = "DELETE FROM MATERIALPACKINGSUB m WHERE m.MATERIALPACKINGNAME = :MATERIALPACKINGNAME AND RECEIVEREQUESTNAME = :RECEIVEREQUESTNAME";
				IDMFrameServiceProxy.getSqlTemplate().update(deleteSql, hashMap);
			}
		}
		//更新订单数量
		return AjaxResult.me().setResultObj(null);
	}


	@RequestMapping(value = "/DeleteTrackOutThisBox", method = RequestMethod.POST)
	public AjaxResult DeleteTrackOutThisBox(@RequestBody JSONObject in ) throws Exception{
		TrackOutBoDto boxs = JSON.toJavaObject(in, TrackOutBoDto.class);
		MaterialreceiveActDto box = boxs.getMaterialreceiveAct();
		String user = boxs.getUser();
		String materialSpecName = box.getMaterialSpecName();
		String materialPackingName2 = box.getMaterialPackingName();
		String siteName = "SDK";
		makeEventInfo = new EventInfoUtil().makeEventInfo("DeleteTrackOutBox", user, "DeleteTrackOutBox");
		Map<String, Object> hashMap = new HashMap<String,Object> ();
		hashMap.put("MATERIALSPECNAME", materialSpecName);
		MaterialPackingKey materialPackingKey = new MaterialPackingKey(siteName, materialPackingName2);
		RemoveInfo removeInfo = new RemoveInfo();
		MaterialPackingServiceProxy.getMaterialPackingService().remove(materialPackingKey,makeEventInfo,removeInfo);
		//找到条码明细表的数据，先更新订单在删除条码明细
		String selectSql = "SELECT * FROM MATERIALPACKINGSUB m WHERE m.MATERIALPACKINGNAME = :MATERIALPACKINGNAME";
		hashMap.put("MATERIALPACKINGNAME", materialPackingName2);
		List<Map<String, Object>> queryForList2 = IDMFrameServiceProxy.getSqlTemplate().queryForList(selectSql, hashMap);
		for (Map<String, Object> map2 : queryForList2) {
			String qty = map2.get("QTY").toString();
			String receiveRequestName2 = map2.get("RECEIVEREQUESTNAME").toString();
			String receiveRequestDetailName2 = map2.get("RECEIVEREQUESTDETAILNAME").toString();
			hashMap.put("RECEIVEREQUESTNAME", receiveRequestName2);
			hashMap.put("RECEIVEREQUESTDETAILNAME", receiveRequestDetailName2);
			hashMap.put("QTY", qty);
			String updateSql = "UPDATE MATERIALRECEIVEREQUESTDETAIL T SET T.RECEIVEDQUANTITY = T.RECEIVEDQUANTITY  - :QTY "
					+ "WHERE T.RECEIVEREQUESTNAME = :RECEIVEREQUESTNAME AND T.RECEIVEREQUESTDETAILNAME  = :RECEIVEREQUESTDETAILNAME";
			IDMFrameServiceProxy.getSqlTemplate().update(updateSql, hashMap);

			String deleteSql = "DELETE FROM MATERIALPACKINGSUB m WHERE m.MATERIALPACKINGNAME = :MATERIALPACKINGNAME";
			IDMFrameServiceProxy.getSqlTemplate().update(deleteSql, hashMap);
		}
		//更新订单数量
		return AjaxResult.me().setResultObj(null);
	}

	//	删除销售入库
	@RequestMapping(value = "/DeleteSaleReturn", method = RequestMethod.POST)
	public AjaxResult DeleteSaleReturn(@RequestBody JSONObject in ) throws Exception{
		TrackOutBoDto boxs = JSON.toJavaObject(in, TrackOutBoDto.class);
		MaterialreceiveActDto box = boxs.getMaterialreceiveAct();
		String user = boxs.getUser();
		String materialSpecName = box.getMaterialSpecName();
		String materialPackingName2 = box.getMaterialPackingName();
		String siteName = "SDK";
		makeEventInfo = new EventInfoUtil().makeEventInfo("ProductSaleReturn", user, "ProductSaleReturn");
		Map<String, Object> hashMap = new HashMap<String,Object> ();
		hashMap.put("MATERIALSPECNAME", materialSpecName);
//		MaterialPackingKey materialPackingKey = new MaterialPackingKey(siteName, materialPackingName2);
//		RemoveInfo removeInfo = new RemoveInfo();
//		MaterialPackingServiceProxy.getMaterialPackingService().remove(materialPackingKey,makeEventInfo,removeInfo);
		//找到条码明细表的数据，先更新订单在删除条码明细
		String selectSql = "SELECT * FROM MATERIALPACKINGSUB m WHERE m.MATERIALPACKINGNAME = :MATERIALPACKINGNAME";
		hashMap.put("MATERIALPACKINGNAME", materialPackingName2);
		List<Map<String, Object>> queryForList2 = IDMFrameServiceProxy.getSqlTemplate().queryForList(selectSql, hashMap);
		for (Map<String, Object> map2 : queryForList2) {
			String qty = map2.get("QTY").toString();
			String receiveRequestName2 = map2.get("RECEIVEREQUESTNAME").toString();
			String receiveRequestDetailName2 = map2.get("RECEIVEREQUESTDETAILNAME").toString();
			hashMap.put("RECEIVEREQUESTNAME", receiveRequestName2);
			hashMap.put("RECEIVEREQUESTDETAILNAME", receiveRequestDetailName2);
			hashMap.put("QTY", qty);
			String updateSql = "UPDATE MATERIALRECEIVEREQUESTDETAIL T SET T.RECEIVEDQUANTITY = T.RECEIVEDQUANTITY  - :QTY "
					+ "WHERE T.RECEIVEREQUESTNAME = :RECEIVEREQUESTNAME AND T.RECEIVEREQUESTDETAILNAME  = :RECEIVEREQUESTDETAILNAME";
			IDMFrameServiceProxy.getSqlTemplate().update(updateSql, hashMap);

			String deleteSql = "DELETE FROM MATERIALPACKINGSUB m WHERE m.MATERIALPACKINGNAME = :MATERIALPACKINGNAME";
			IDMFrameServiceProxy.getSqlTemplate().update(deleteSql, hashMap);
		}

		com.cim.idm.wmspackage.materialpacking.management.info.SetEventInfo setEventInfo1 = new com.cim.idm.wmspackage.materialpacking.management.info.SetEventInfo();
		EventInfo eventInfo = EventInfoUtil.makeEventInfo("ProductSaleReturn", user, "ProductSaleReturn");
		HashMap<String,Object> hashMap2 = new HashMap<String,Object >();

		hashMap2.put("receiveRequestName","");
		hashMap2.put("stockState", "StockOut");

		setEventInfo1.setUserColumns(hashMap2);
		MaterialPackingKey materialPackingKey2 = new MaterialPackingKey(siteName,materialPackingName2);
		MaterialPacking setEvent = MaterialPackingServiceProxy.getMaterialPackingService().setEvent(materialPackingKey2, eventInfo, setEventInfo1);

		return AjaxResult.me().setResultObj(null);
	}

	/*
	 * 解绑销售入库
	 * lz
	 */
	@RequestMapping(value = "/DeleteProductSaleReturn", method = RequestMethod.POST)
	public AjaxResult DeleteProductSaleReturn(@RequestBody JSONObject in ) throws Exception{
		TrackOutBoDto boxs = JSON.toJavaObject(in, TrackOutBoDto.class);
		MaterialreceiveActDto box = boxs.getMaterialreceiveAct();
		String user = boxs.getUser();
		String materialSpecName = box.getMaterialSpecName();
		String materialPackingName2 = box.getMaterialPackingName();
		String siteName = "SDK";
		String receiveRequestName = box.getReceiveRequestName();
		String phase = box.getPhase();
		String sdkid = box.getSdkid();
		String materialquantity = box.getMATERIALQUANTITY();
		String selectSql = "SELECT	M.REQUESTQUANTITY - M.RECEIVEDQUANTITY QTY,	M.RECEIVEREQUESTNAME,M.RECEIVEREQUESTDETAILNAME \r\n" +
				"FROM	MATERIALRECEIVEREQUESTDETAIL M\r\n" +
				"WHERE	M.MATERIALSPECNAME = :MATERIALSPECNAME\r\n" +
				"	AND (:PHASE IS NULL	OR PHASE = :PHASE)\r\n" +
				"	AND (:SDK_ID IS NULL OR SDK_ID = :SDK_ID)\r\n" +
//				"	AND M.REQUESTQUANTITY - M.RECEIVEDQUANTITY > 0" +
				"	AND RECEIVEREQUESTNAME = :RECEIVEREQUESTNAME";
		Map<String,Object> map = new HashMap<String ,Object >();
		map.put("MATERIALSPECNAME", materialSpecName);
		map.put("PHASE", phase);
		map.put("SDK_ID", sdkid);
		map.put("RECEIVEREQUESTNAME", receiveRequestName);
		List<Map<String,Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(selectSql, map);
		BigDecimal mathMaterialQuantity = new BigDecimal(materialquantity);
		int i = 0;
		for (Map<String, Object> map2 : queryForList) {
			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 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", materialPackingName2);
			hashMap2.put("RECEIVEREQUESTNAME", receiveRequestName2);
			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);
				IDMFrameServiceProxy.getSqlTemplate().update(insertSql, hashMap2);
				IDMFrameServiceProxy.getSqlTemplate().update(updateSql, hashMap2);
				i++;
				break;
			} else if (mathMaterialQuantity.compareTo(mathQty) == 1) {//条码数量大于剩余数量
				if(i >= queryForList.size()-1) {
					hashMap2.put("QTY", mathMaterialQuantity.toString());
					mathMaterialQuantity = mathMaterialQuantity.subtract(mathQty);
					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);
					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());
				IDMFrameServiceProxy.getSqlTemplate().update(insertSql, hashMap2);
				IDMFrameServiceProxy.getSqlTemplate().update(updateSql, hashMap2);
				i++;
				break;
			}
		}
		com.cim.idm.wmspackage.materialpacking.management.info.SetEventInfo setEventInfo1 = new com.cim.idm.wmspackage.materialpacking.management.info.SetEventInfo();
		EventInfo eventInfo = EventInfoUtil.makeEventInfo("ProductSaleReturn", user, "ProductSaleReturn");
		HashMap<String,Object> hashMap = new HashMap<String,Object >();

		hashMap.put("receiveRequestName","");
		hashMap.put("stockState", "StockOut");

		setEventInfo1.setUserColumns(hashMap);
		MaterialPackingKey materialPackingKey2 = new MaterialPackingKey(siteName,materialPackingName2);
		MaterialPacking setEvent = MaterialPackingServiceProxy.getMaterialPackingService().setEvent(materialPackingKey2, eventInfo, setEventInfo1);

		//更新订单数量
		return AjaxResult.me().setResultObj(null);
	}


	@RequestMapping(value = "/commitToERP", method = RequestMethod.POST)
	public AjaxResult commitToERP(@RequestBody JSONObject in ) {
		TrackOutBoDto trackOutBoDto = JSON.toJavaObject(in, TrackOutBoDto.class);
		String user = trackOutBoDto.getUser();
		String opCode = trackOutBoDto.getOpCode();
		String commitDate = trackOutBoDto.getCommitDate();
		String name = trackOutBoDto.getReceiveRequestName();
		String site = trackOutBoDto.getSiteName();
		// 采购单
		List<MaterialReceiveRequest> requests = new ArrayList<>();
		// @TODO 判定单据类型
		/*MaterialReceiveRequest byKey = deliveryService.getByKey(site, name);
		if (byKey.getReceiveRequestType().equals(ReceiveTypeEnums.DK.getCode())) {
			// 到货单
			requests = deliveryService.getReceiveByDelivery(site, name);
		} else {
			requests.add(byKey);
		}*/
		// 采购单处理
		for (MaterialReceiveRequest request : requests) {
			String receiveRequestName = request.getReceiveRequestName();
			String siteName = request.getSiteName();
			String erpFactory = request.getSTOCKORGNO();
			try {
				//调用QMS
				qMSServiceImpl.PreIQCInfoSend(receiveRequestName, "SDK",opCode, erpFactory);
			} catch (CustomException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return AjaxResult.me().setSuccess(false).setMessage(e.toString());
			}

			String undoid;
			try {
				undoid = SendERPStockIn(receiveRequestName, siteName, user, opCode,commitDate,opCode);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return AjaxResult.me().setSuccess(false).setMessage(e.toString());
			}//发送过账
			makeEventInfo = new EventInfoUtil().makeEventInfo("NormalStockInForSDK", user, "NormalStockInForSDK");
			//更新入库凭证
			SDKMaterialPackingServiceImpl.updateUndoIdByReceive(receiveRequestName, undoid, makeEventInfo);
			//更新库存状态
			SDKMaterialPackingServiceImpl.SaveUnDoInfo( undoid,commitDate);
			SDKMaterialPackingServiceImpl.updateStockState( makeEventInfo, undoid,opCode);
		}
		return AjaxResult.me().setResultObj(null);
	}


	public String SendERPStockIn(String receiveRequestName, String siteName, String eventUser,String reActo,String commitDate,String opCode) throws Exception {
		//判断单据类型调用不同的NC接口
		String sql = "SELECT m.RECEIVEREQUESTTYPE,m.RECEIVEREQUESTDETAILTYPE FROM MATERIALRECEIVEREQUEST m WHERE m.RECEIVEREQUESTNAME = :RECEIVEREQUESTNAME";
		Map<String, Object> hashMap = new HashMap<String,Object> ();
		hashMap.put("RECEIVEREQUESTNAME", receiveRequestName);
		List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, hashMap);
		String billCode = "";
		if (queryForList != null && queryForList.size() > 0) {
			String type = queryForList.get(0).get("RECEIVEREQUESTTYPE").toString();
//			String receiverequestdetailtype = queryForList.get(0).get("RECEIVEREQUESTDETAILTYPE").toString();
			switch (type) {
				case "Z001" : //采购入库
				case "Z002" : //研发采购订单
				case "Z003" : //非生产物资采购订单
				case "Z004" : //固定资产、在建工程采购订单
					Map<String,Object> args = new HashMap<>();
					billCode = toSAPServiceImpl.PurStockIn(receiveRequestName, siteName, eventUser,
							args/* ,overReceiveControls */);
					break;
				case "Z005" : //服务费用采购订单
				case "Z006" : //股份 - 泗洪STO
				case "Z007" : //股份泗洪-分子公司STO
					break;
				case "Z008" : //物资退货采购订单
				default :
					break;
			}
		} else {
			throw new CustomException("找不到单据" + receiveRequestName);
		}
		return billCode;
	}

}
