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.model.MaterialPacking;
import com.cim.idm.model.MaterialshipRequest;
import com.cim.idm.model.SalePreOrderDto;
import com.cim.idm.model.StockOutDto;
import com.cim.idm.service.Impl.InvoiceServiceImpl;
import com.cim.idm.service.Impl.SaleOutServiceImpl;
import com.cim.idm.utils.AjaxResult;
import com.cim.idm.wmsextend.generic.errorHandler.CustomException;
import com.cim.idm.wmspackage.materialpacking.MaterialPackingServiceProxy;
import com.cim.idm.wmspackage.materialpacking.management.data.MaterialPackingKey;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.transaction.annotation.Transactional;
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.io.IOException;
import java.math.BigDecimal;
import java.util.*;

@Api("调拨入接口")
@RestController
@RequestMapping("/SaleOut")
@EnableAutoConfiguration
public class SaleOutController {
	
	@Autowired
	private SaleOutServiceImpl SaleOut;
	
	@RequestMapping(value = "/getBhCondition", method = RequestMethod.POST)
	public AjaxResult getBhCondition(@RequestBody JSONObject in ){

		MaterialshipRequest ship = JSON.toJavaObject(in, MaterialshipRequest.class);
		String barCode = ship.getBarCode();
		StringBuffer stringBuffer = new StringBuffer ();
		stringBuffer.append(" ");
		stringBuffer.append(" WITH AA AS (	 SELECT MATERIALSPECNAME,LISTAGG(CAREER_ASSISTANCE, ',')  ");
		stringBuffer.append(" WITHIN GROUP (ORDER BY MATERIALSPECNAME) CAREER_ASSISTANCE FROM "); 
		stringBuffer.append(" (SELECT DISTINCT MATERIALSPECNAME,CAREER_ASSISTANCE FROM MATERIALPACKING m  ");
		stringBuffer.append(" WHERE CAREER_ASSISTANCE IS NOT NULL) GROUP BY MATERIALSPECNAME ) ");
		stringBuffer.append(" SELECT  ");
		stringBuffer.append(" m.MATERIALSPECNAME,  ");
		stringBuffer.append(" m.SDK_ID,  ");
		stringBuffer.append(" m.PHASE,  ");
		stringBuffer.append(" AA.CAREER_ASSISTANCE,  ");
		stringBuffer.append(" ss.SPECNAME ");
		stringBuffer.append(" FROM  ");
		stringBuffer.append(" MATERIALPACKING m ");
		stringBuffer.append(" LEFT JOIN SDK_SPEC ss ON  ");
		stringBuffer.append(" m.SDK_ID = ss.SDK_ID LEFT JOIN AA ON m.MATERIALSPECNAME  = AA.MATERIALSPECNAME ");
		stringBuffer.append(" WHERE  ");
		stringBuffer.append(" MATERIALPACKINGNAME = :MATERIALPACKINGNAME ");
		//查询单据明细信息
		Map<String, Object> bindMap = new HashMap<String, Object>();
		bindMap.put("MATERIALPACKINGNAME",barCode); 
		List<Map<String,Object>> list = IDMFrameServiceProxy.getSqlTemplate().queryForList(stringBuffer.toString(), bindMap);
		if (list == null || list.size() < 1) {
			return AjaxResult.me().setSuccess(false).setMessage("标签不存在");
		}
		return AjaxResult.me().setSuccess(true).setResultObj(list);
	}
	
	//查询预备货信息
	@RequestMapping(value = "/getSalePreOrderInvoice", method = RequestMethod.POST)
	public AjaxResult getSalePreOrderInvoice(@RequestBody JSONObject in ){

		MaterialshipRequest ship = JSON.toJavaObject(in, MaterialshipRequest.class);
		String shipRequestType = ship.getShipRequestType();
		String shipRequestName = ship.getShipRequestName();
		String erpfactory = ship.getErpfactory();
		String materialSpecName = ship.getMaterialSpecName();
		String sdk_id = ship.getSdk_id();
		String phase = ship.getPhase();
		String user = ship.getUser();
		StringBuffer stringBuffer = new StringBuffer ();
		stringBuffer.append(" ");
		stringBuffer.append(" SELECT ");
		stringBuffer.append(" m2.MATERIALSPECNAME , ");
		stringBuffer.append(" m2.PHASE , ");
		stringBuffer.append(" m2.SDK_ID , ");
		stringBuffer.append(" m2.REQUESTQUANTITY, m2.ASSIGNEDQUANTITY,");
		stringBuffer.append(" m.SHIPREQUESTNAME , ");
		stringBuffer.append(" m2.SHIPREQUESTDETAILNAME , ");
		stringBuffer.append(" m.LASTEVENTUSER ,m2.ERPFACTORY, ");
		stringBuffer.append(" ss.SPECNAME  ");
		stringBuffer.append(" FROM ");
		stringBuffer.append(" MATERIALSHIPREQUESTDETAIL m2 ");
		stringBuffer.append(" LEFT JOIN MATERIALSHIPREQUEST m ON ");
		stringBuffer.append(" m2.SHIPREQUESTNAME = m.SHIPREQUESTNAME ");
		stringBuffer.append(" LEFT JOIN SDK_SPEC ss ON m2.SDK_ID = ss.SDK_ID  ");
		stringBuffer.append(" WHERE ");
		stringBuffer.append(" 1 = 1 ");
		stringBuffer.append(" AND m.SHIPREQUESTSTATE = 'Created' ");
		stringBuffer.append(" AND m2.ASSIGNEDQUANTITY <> 0 ");
		stringBuffer.append(" AND m.SHIPREQUESTTYPE = 'SaleOutPre' ");
		stringBuffer.append(" AND m2.ERPFACTORY = :ERPFACTORY ");
		stringBuffer.append(" AND m.LASTEVENTUSER = :USER ");
//		stringBuffer.append(" AND m.SHIPREQUESTNAME = :SHIPREQUESTNAME ");
		stringBuffer.append(" AND m2.MATERIALSPECNAME = :MATERIALSPECNAME ");
		stringBuffer.append(" AND ( :SDK_ID IS NULL OR m2.SDK_ID = :SDK_ID ) ");
		stringBuffer.append(" AND ( :PHASE IS NULL OR m2.PHASE = :PHASE ) ");
		//查询单据明细信息
		Map<String, Object> bindMap = new HashMap<String, Object>();
		bindMap.put("MATERIALSPECNAME",materialSpecName); 
		bindMap.put("ERPFACTORY",erpfactory ); 
//		bindMap.put("SHIPREQUESTNAME",shipRequestName ); 
		bindMap.put("USER",user ); 
		bindMap.put("SDK_ID",sdk_id ); 
		bindMap.put("PHASE",phase ); 
		List<Map<String,Object>> list = IDMFrameServiceProxy.getSqlTemplate().queryForList(stringBuffer.toString(), bindMap);
		
		return AjaxResult.me().setResultObj(list);
	}
	
	//查询发货单信息
	@RequestMapping(value = "/getSaleOrderInvoice", method = RequestMethod.POST)
	public AjaxResult getSaleOrderInvoice(@RequestBody JSONObject in ){

		MaterialshipRequest ship = JSON.toJavaObject(in, MaterialshipRequest.class);
		String shipRequestType = ship.getShipRequestType();
		String shipRequestName = ship.getShipRequestName();
		String erpfactory = ship.getErpfactory();
		String materialSpecName = ship.getMaterialSpecName();
		String sdk_id = ship.getSdk_id();
		String phase = ship.getPhase();
		String user = ship.getUser();
		StringBuffer stringBuffer = new StringBuffer ();
		stringBuffer.append(" ");
		stringBuffer.append(" SELECT ");
		stringBuffer.append(" m2.MATERIALSPECNAME , ");
		stringBuffer.append(" m2.PHASE , ");
		stringBuffer.append(" ss.SPECNAME , ");
		stringBuffer.append(" m2.ERPFACTORY , ");
		stringBuffer.append(" m2.SITENAME , ");
		stringBuffer.append(" m2.SHIPREQUESTNAME , ");
		stringBuffer.append(" m.LASTEVENTUSER, ");
		stringBuffer.append(" SUM(m2.REQUESTQUANTITY) REQUESTQUANTITY, ");
		stringBuffer.append(" SUM(m2.ASSIGNEDQUANTITY) ASSIGNEDQUANTITY ,m2.SDK_ID ,SUM(m2.REQUESTQUANTITY - m2.ASSIGNEDQUANTITY) MINUSQTY ");
		stringBuffer.append(" FROM ");
		stringBuffer.append(" MATERIALSHIPREQUESTDETAIL m2 ");
		stringBuffer.append(" LEFT JOIN MATERIALSHIPREQUEST m ON ");
		stringBuffer.append(" m2.SHIPREQUESTNAME = m.SHIPREQUESTNAME ");
		stringBuffer.append(" LEFT JOIN SDK_SPEC ss ON ");
		stringBuffer.append(" m2.SDK_ID = ss.SDK_ID ");
		stringBuffer.append(" LEFT JOIN MATERIALSPEC m3 ON ");
		stringBuffer.append(" m2.MATERIALSPECNAME = m3.MATERIALSPECNAME ");
		stringBuffer.append(" WHERE ");
		stringBuffer.append(" 1 = 1 ");
		stringBuffer.append(" AND m.SHIPREQUESTSTATE <> 'Completed' ");
		stringBuffer.append(" AND m.SHIPREQUESTTYPE = '4C' ");
		stringBuffer.append(" AND m.SHIPREQUESTNAME = :SHIPREQUESTNAME ");
		stringBuffer.append(" GROUP BY m2.MATERIALSPECNAME , ");
		stringBuffer.append(" m2.PHASE , ");
		stringBuffer.append(" ss.SPECNAME , ");
		stringBuffer.append(" m2.ERPFACTORY , ");
		stringBuffer.append(" m2.SITENAME , ");
		stringBuffer.append(" m2.SHIPREQUESTNAME , ");
		stringBuffer.append(" m.LASTEVENTUSER  ,m2.SDK_ID ");
		//查询单据明细信息
		Map<String, Object> bindMap = new HashMap<String, Object>();
		bindMap.put("MATERIALSPECNAME",materialSpecName); 
		bindMap.put("ERPFACTORY",erpfactory ); 
		bindMap.put("SHIPREQUESTNAME",shipRequestName ); 
		bindMap.put("USER",user ); 
		bindMap.put("SDK_ID",sdk_id ); 
		bindMap.put("PHASE",phase ); 
		List<Map<String,Object>> list = IDMFrameServiceProxy.getSqlTemplate().queryForList(stringBuffer.toString(), bindMap);
		return AjaxResult.me().setResultObj(list);
	}
	
	
	//查询发货单绑定批次信息
	@RequestMapping(value = "/getChargeBindBySale", method = RequestMethod.POST)
	public AjaxResult getChargeBindBySale(@RequestBody JSONObject in ){

		MaterialshipRequest ship = JSON.toJavaObject(in, MaterialshipRequest.class);
		String shipRequestType = ship.getShipRequestType();
		String shipRequestName = ship.getShipRequestName();
		String erpfactory = ship.getErpfactory();
		String materialSpecName = ship.getMaterialSpecName();
		String sdk_id = ship.getSdk_id();
		String phase = ship.getPhase();
		String user = ship.getUser();
		StringBuffer stringBuffer = new StringBuffer ();
		stringBuffer.append(" ");
		stringBuffer.append(" SELECT ");
		stringBuffer.append(" m.MATERIALSPECNAME , ");
		stringBuffer.append(" m.MATERIALPACKINGNAME , ");
		stringBuffer.append(" m.CHARGE , ");
		stringBuffer.append(" m.ERPFACTORY , ");
		stringBuffer.append(" m.MATERIALQUANTITY , ");
		stringBuffer.append(" m.MATERIALQUANTITY2 , ");
		stringBuffer.append(" m2.SHIPREQUESTNAME , ");
		stringBuffer.append(" m3.DESC_CN , ");
		stringBuffer.append(" ss.SPECNAME ,m.PHASE, ");
		stringBuffer.append(" be.DESCRIPTION ERPLOCATION, ");
		stringBuffer.append(" s.DESCRIPTION LOCATIONNAME ");
		stringBuffer.append(" FROM ");
		stringBuffer.append(" MATERIALPACKING m ");
		stringBuffer.append(" LEFT JOIN MATERIALSHIPREQUEST m2 ON ");
		stringBuffer.append(" m.SHIPREQUESTNAME = m2.SHIPREQUESTNAME ");
		stringBuffer.append(" LEFT JOIN MATERIALSPEC m3 ON ");
		stringBuffer.append(" m.MATERIALSPECNAME = m3.MATERIALSPECNAME ");
		stringBuffer.append(" LEFT JOIN SDK_SPEC ss ON ");
		stringBuffer.append(" ss.SDK_ID = m.SDK_ID ");
		stringBuffer.append(" LEFT JOIN BS_ERPLOCATION be ON ");
		stringBuffer.append(" m.ERPLOCATION = be.ERPLOCATIONNAME ");
		stringBuffer.append(" LEFT JOIN STORAGESPEC s ON ");
		stringBuffer.append(" s.ERPLOCATION = m.ERPLOCATION ");
		stringBuffer.append(" AND s.STORAGENAME = m.LOCATIONNAME ");
		stringBuffer.append(" WHERE m2.SHIPREQUESTTYPE = '4C' ");
		stringBuffer.append(" AND m.SHIPREQUESTNAME = :SHIPREQUESTNAME AND m.STOCKSTATE = 'Stocked' ");
		if (sdk_id != null && !"".equals(sdk_id)) {
			stringBuffer.append(" AND m.SDK_ID = :SDK_ID ");
		}
		if (phase != null && !"".equals(phase)) {
			stringBuffer.append(" AND m.PHASE = :PHASE ");
		}
		stringBuffer.append(" ORDER BY m.MATERIALSPECNAME, be.DESCRIPTION,s.DESCRIPTION");
		//查询单据明细信息
		Map<String, Object> bindMap = new HashMap<String, Object>();
		bindMap.put("MATERIALSPECNAME",materialSpecName); 
		bindMap.put("ERPFACTORY",erpfactory ); 
		bindMap.put("SHIPREQUESTNAME",shipRequestName ); 
		bindMap.put("USER",user ); 
		bindMap.put("SDK_ID",sdk_id ); 
		bindMap.put("PHASE",phase ); 
		List<Map<String,Object>> list = IDMFrameServiceProxy.getSqlTemplate().queryForList(stringBuffer.toString(), bindMap);
		return AjaxResult.me().setResultObj(list);
	}
	
	//重写拣配功能.zd.2024.9.10
	@Transactional
	@RequestMapping(value = "/AssignShipRequest", method = RequestMethod.POST)
	public AjaxResult assignShipRequest(@RequestBody JSONObject in ) throws Exception {
		MaterialPacking materialPacking = JSON.toJavaObject(in, MaterialPacking.class);
		String materialPackingName = materialPacking.getMaterialPackingName();
		String[] mpList=materialPackingName.split(";");
		String user = materialPacking.getUser();
		String siteName = "SDK";
		String shipRequestName=materialPacking.getShipRequestName();
		String materialSpecName=materialPacking.getMaterialSpecName();
		String phase=materialPacking.getPhase();
		String sdk_id=materialPacking.getSdk_id();
		List<String> boxList=new ArrayList<>();
		for(int i=0;i<mpList.length;i++) 
		{
			if(StringUtils.isNotEmpty(mpList[i])) 
			{
				boxList.add(mpList[i]);
			}
		}
		
		InvoiceServiceImpl invoiceServiceImpl =new InvoiceServiceImpl();
		
		String sql=" 	SELECT * FROM (\r\n" + 
				"					SELECT sum(m.MATERIALQUANTITY)ALLQTY,min(m.MATERIALQUANTITY)MINQTY FROM MATERIALPACKING m \r\n" + 
				"					WHERE m.SITENAME = :SITENAME \r\n" + 
				"					AND m.MATERIALPACKINGNAME IN (:BOXLIST))\r\n" + 
				"					LEFT JOIN (SELECT (sum(m2.REQUESTQUANTITY)-sum(m2.ASSIGNEDQUANTITY))MINUSQTY FROM MATERIALSHIPREQUESTDETAIL m2 \r\n" + 
				"					WHERE m2.SHIPREQUESTNAME=:SHIPREQUESTNAME\r\n" + 
				"					AND m2.MATERIALSPECNAME=:MATERIALSPECNAME\r\n" + 
				"					AND (:PHASE IS NULL OR m2.PHASE=:PHASE)\r\n" + 
				"					AND ( :SDK_ID IS NULL OR  m2.SDK_ID=:SDK_ID) \r\n" + 
				"					) ON 1=1\r\n" + 
				"					LEFT JOIN (SELECT m3.SHIPREQUESTTYPE FROM MATERIALSHIPREQUEST m3 WHERE m3.SHIPREQUESTNAME=:SHIPREQUESTNAME)\r\n" + 
				"					ON 1=1 ";
		
		Map<String,Object> bp=new HashMap<>();
		bp.put("SITENAME", siteName);
		bp.put("BOXLIST", boxList);
		bp.put("SHIPREQUESTNAME", shipRequestName);
		bp.put("MATERIALSPECNAME", materialSpecName);
		bp.put("PHASE", phase);
		bp.put("SDK_ID", sdk_id);
		List<Map<String,Object>> sr=IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, bp);
		String MINUSQTY=sr.get(0).get("MINUSQTY")==null?"0":sr.get(0).get("MINUSQTY").toString();
		String ALLQTY=sr.get(0).get("ALLQTY")==null?"0":sr.get(0).get("ALLQTY").toString();
		String MINQTY=sr.get(0).get("MINQTY")==null?"0":sr.get(0).get("MINQTY").toString();
		String shipRequestType=sr.get(0).get("SHIPREQUESTTYPE")==null?"":sr.get(0).get("SHIPREQUESTTYPE").toString();
		String shipRequestDetailType=sr.get(0).get("SHIPREQUESTDETAILTYPE")==null?"":sr.get(0).get("SHIPREQUESTDETAILTYPE").toString();
		BigDecimal minusQty = new BigDecimal(MINUSQTY);//剩余需求数量
		BigDecimal allQty = new BigDecimal(ALLQTY);//Box总数量
		BigDecimal minQty = new BigDecimal(MINQTY);//最小Box数量
		BigDecimal Fzero = new BigDecimal(0);
		int dy0 = minusQty.compareTo(Fzero);
		
//		if ("4C".equals(shipRequestType)) {
//			if ((allQty.subtract(minusQty)).compareTo(Fzero)>0) {
//				//return AjaxResult.me().setSuccess(false).setMessage("销售不允许超发！");
//				throw new CustomException("销售不允许超发");
//			}
//		}
//		else 
//		{
//			if ((allQty.subtract(minusQty)).compareTo(minQty)>0) {
//				return AjaxResult.me().setSuccess(false).setMessage("只允许超发1个！");
//				//throw new CustomException("只允许超发1个");
//			}
//		}
		
//		销售订单不允许超发 但超发一只的时候可以挪到右侧，进行拆箱取数量保证不超发		
//		if ("4Y".equals(shipRequestType)) {//调拨单
//			if ( "4Y-Cxx-03".equals(shipRequestDetailType)) {
//				if ((allQty.subtract(minusQty)).compareTo(minQty)>0) {
//					return AjaxResult.me().setSuccess(false).setMessage("只允许超发1个！");
//					//throw new CustomException("只允许超发1个");
//				}
//			}
//		} else if ("BLSQ4K".equals(shipRequestType)) {//领料
//			if ((allQty.subtract(minusQty)).compareTo(minQty)>0) {
//				return AjaxResult.me().setSuccess(false).setMessage("只允许超发1个！");
//				//throw new CustomException("只允许超发1个");
//			}
//		} else if ("CKSQ4I".equals(shipRequestType)) { //其他出库
//			if ((allQty.subtract(minusQty)).compareTo(minQty)>0) {
//				return AjaxResult.me().setSuccess(false).setMessage("只允许超发1个！");
//				//throw new CustomException("只允许超发1个");
//			}
//		} else if ("OEM".equals(shipRequestType)) { //委外
//			if ((allQty.subtract(minusQty)).compareTo(minQty)>0) {
//				return AjaxResult.me().setSuccess(false).setMessage("只允许超发1个！");
//				//throw new CustomException("只允许超发1个");
//			}
//		} else if ("4C".equals(shipRequestType)) {
//			if ((allQty.subtract(minusQty)).compareTo(minQty)>0) {
//				return AjaxResult.me().setSuccess(false).setMessage("销售不允许超发！");
//				//throw new CustomException("只允许超发1个");
//			}
//		}else {
//			return AjaxResult.me().setSuccess(false).setMessage("单据类型不正确！");
//		}

		
		for(int i=0;i<boxList.size();i++) 
		{
			MaterialPackingKey materialPackingKey = new MaterialPackingKey(siteName,boxList.get(i));
			com.cim.idm.wmspackage.materialpacking.management.data.MaterialPacking selectByKey = MaterialPackingServiceProxy.getMaterialPackingService().selectByKey(materialPackingKey);

			try {
				invoiceServiceImpl.Reserve2(selectByKey, shipRequestName, materialSpecName,sdk_id, phase, "Assign", "SDK", user,"","N");
			} catch (Exception e) {
				
				return AjaxResult.me().setSuccess(false).setMessage(e.toString());
			}
		}
		

        return AjaxResult.me().setResultObj(null);
    }
	
	//重写取消拣配功能.zd.2024.9.10
	@Transactional
	@RequestMapping(value = "/DeAssignShipRequest", method = RequestMethod.POST)
	public AjaxResult deAssignShipRequest(@RequestBody JSONObject in) throws Exception {
		MaterialPacking materialPacking = JSON.toJavaObject(in, MaterialPacking.class);
		String materialPackingName = materialPacking.getMaterialPackingName();
		String[] mpList = materialPackingName.split(";");
		String user = materialPacking.getUser();
		String siteName = "SDK";
		String shipRequestName = materialPacking.getShipRequestName();
		String materialSpecName = materialPacking.getMaterialSpecName();
		List<String> boxList = new ArrayList<>();
		for (int i = 0; i < mpList.length; i++) {
			if (StringUtils.isNotEmpty(mpList[i])) {
				boxList.add(mpList[i]);
			}
		}

		InvoiceServiceImpl invoiceServiceImpl = new InvoiceServiceImpl();
		for (int i = 0; i < boxList.size(); i++) {
			MaterialPackingKey materialPackingKey = new MaterialPackingKey(siteName, boxList.get(i));
			com.cim.idm.wmspackage.materialpacking.management.data.MaterialPacking selectByKey = MaterialPackingServiceProxy
					.getMaterialPackingService().selectByKey(materialPackingKey);

			try {
				String sdk_ID = selectByKey.getSDK_ID();
				String phase = selectByKey.getPHASE();
				invoiceServiceImpl.Reserve2(selectByKey, shipRequestName, materialSpecName, sdk_ID, phase, "Dessign", "SDK",
						user, "", "N");
			} catch (Exception e) {

				return AjaxResult.me().setSuccess(false).setMessage(e.toString());
			}
		}

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

	//指定批次拣配功能.zd.2024.9.10
	@Transactional
	@RequestMapping(value = "/AssignShipRequestByCharge", method = RequestMethod.POST)
	public AjaxResult assignShipRequestByCharge(@RequestBody JSONObject in) throws Exception {
		MaterialPacking materialPacking = JSON.toJavaObject(in, MaterialPacking.class);
		String materialPackingName = materialPacking.getMaterialPackingName();
		String[] mpList = materialPackingName.split(";");
		String user = materialPacking.getUser();
		String siteName = "SDK";
		String shipRequestName = materialPacking.getShipRequestName();
		//String materialSpecName = materialPacking.getMaterialSpecName();
		List<String> boxList = new ArrayList<>();
		for (int i = 0; i < mpList.length; i++) {
			if (StringUtils.isNotEmpty(mpList[i])) {
				boxList.add(mpList[i]);
			}
		}
		InvoiceServiceImpl invoiceServiceImpl = new InvoiceServiceImpl();
		for(int i=0;i<boxList.size();i++) 
		{
			String sqlmp=" SELECT m.MATERIALPACKINGNAME,m.MATERIALSPECNAME,m.MATERIALQUANTITY FROM MATERIALPACKING m WHERE m.CHARGE =:CHARGE AND m.STOCKSTATE ='Stocked' AND m.MATERIALQUANTITY >0 ";
			Map<String,Object> bpmp=new HashMap<>();
			bpmp.put("CHARGE", boxList.get(i));
			List<Map<String,Object>> srmp=IDMFrameServiceProxy.getSqlTemplate().queryForList(sqlmp, bpmp);
			if(srmp.size()==0) 
			{
				return AjaxResult.me().setSuccess(false).setMessage("未查询到批次："+boxList.get(i));
			}
			String boxid=srmp.get(0).get("MATERIALPACKINGNAME").toString();
			String materialSpecName=srmp.get(0).get("MATERIALSPECNAME").toString();
			String materialQuantity=srmp.get(0).get("MATERIALQUANTITY").toString();
			MaterialPackingKey materialPackingKey = new MaterialPackingKey("SDK",boxid);
			com.cim.idm.wmspackage.materialpacking.management.data.MaterialPacking selectByKey = MaterialPackingServiceProxy.getMaterialPackingService().selectByKey(materialPackingKey);
			//查询单据类型
			String sql = "SELECT\r\n" + 
					"	m.SHIPREQUESTTYPE ,\r\n" + 
					"	m.SHIPREQUESTDETAILTYPE,\r\n" + 
					"	t.MATERIALSPECNAME ,\r\n" + 
					"	SUM(t.REQUESTQUANTITY - t.ASSIGNEDQUANTITY) MINUSQTY,t.SDK_ID,t.PHASE\r\n" + 
					"FROM\r\n" + 
					"	MATERIALSHIPREQUESTDETAIL t\r\n" + 
					"LEFT JOIN MATERIALSHIPREQUEST m ON\r\n" + 
					"	t.SHIPREQUESTNAME = m.SHIPREQUESTNAME\r\n" + 
					"WHERE\r\n" + 
					"	m.SHIPREQUESTNAME = :SHIPREQUESTNAME\r\n" + 
					"	AND t.MATERIALSPECNAME = :MATERIALSPECNAME\r\n" + 
					"	AND (:SDK_ID IS NULL\r\n" + 
					"		OR t.SDK_ID = :SDK_ID)\r\n" + 
					"	AND (:PHASE IS NULL\r\n" + 
					"		OR t.PHASE = :PHASE)\r\n" + 
					"		GROUP BY m.SHIPREQUESTTYPE ,\r\n" + 
					"	m.SHIPREQUESTDETAILTYPE,\r\n" + 
					"	t.MATERIALSPECNAME,t.SDK_ID,t.PHASE\r\n" + 
					"ORDER BY\r\n" + 
					"	t.MATERIALSPECNAME ,\r\n" + 
					"	t.SDK_ID,\r\n" + 
					"	t.PHASE";
			Map<String, Object> hashMap = new HashMap<String,Object> ();
			hashMap.put("SHIPREQUESTNAME", shipRequestName);
			hashMap.put("MATERIALSPECNAME", materialSpecName);
			hashMap.put("SDK_ID", "");
			hashMap.put("PHASE", "");
			List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, hashMap);
			if(Objects.isNull(queryForList) || queryForList.isEmpty()) {
				return AjaxResult.me().setSuccess(false).setMessage("未找到对应的数据："+shipRequestName+","+materialSpecName);
			}
			
			String judge = "SELECT\r\n" + 
					"	m.SDK_ID,MATERIALSPECNAME,\r\n" + 
					"	m.PHASE,\r\n" + 
					"	CASE WHEN MATERIALQUANTITY2 > 0 THEN MATERIALQUANTITY2    " + 
					"	 ELSE MATERIALQUANTITY   END    MATERIALQUANTITY2 , " + 
					"	m.SHIPREQUESTNAME,\r\n" + 
					"	m.STOCKSTATE,\r\n" + 
					"	m.PACKINGGRADE ,\r\n" + 
					"	CASE WHEN to_char(EXPIRINGDATE, 'yyyymmdd') >= to_char(SYSDATE, 'yyyymmdd') THEN 1\r\n" + 
					"	ELSE 0 END EXP, OQARESULTSTATE \r\n" + 
					"FROM\r\n" + 
					"	MATERIALPACKING m\r\n" + 
					"WHERE\r\n" + 
					"	m.MATERIALPACKINGNAME = :MATERIALPACKINGNAME";
			Map<String, Object> hashMap2 = new HashMap<String,Object> ();
			hashMap2.put("MATERIALPACKINGNAME", boxid);
			List<Map<String, Object>> queryForList2 = IDMFrameServiceProxy.getSqlTemplate().queryForList(judge, hashMap2);
			String materialQuantity2="";
			if (queryForList2 != null && queryForList2.size() > 0) {
				materialSpecName = queryForList2.get(0).get("MATERIALSPECNAME") == null ? "" : queryForList2.get(0).get("MATERIALSPECNAME").toString();
				//sdk_id = queryForList2.get(0).get("SDK_ID") == null ? "" : queryForList2.get(0).get("SDK_ID").toString();
				//phase = queryForList2.get(0).get("PHASE") == null ? "" : queryForList2.get(0).get("PHASE").toString();
				materialQuantity2 = queryForList2.get(0).get("MATERIALQUANTITY2") == null ? "" : queryForList2.get(0).get("MATERIALQUANTITY2").toString();
				String  invoice = queryForList2.get(0).get("SHIPREQUESTNAME") == null ? "" : queryForList2.get(0).get("SHIPREQUESTNAME").toString();
				String stockState = queryForList2.get(0).get("STOCKSTATE") == null ? "" : queryForList2.get(0).get("STOCKSTATE").toString();
				String packinggrade  = queryForList2.get(0).get("PACKINGGRADE") == null ? "" : queryForList2.get(0).get("PACKINGGRADE").toString();
				String exp  = queryForList2.get(0).get("EXP") == null ? "" : queryForList2.get(0).get("EXP").toString();
				String oqaresultstate  = queryForList2.get(0).get("OQARESULTSTATE") == null ? "" : queryForList2.get(0).get("OQARESULTSTATE").toString();
				if (!"Stocked".equals(stockState)) {
					return AjaxResult.me().setSuccess(false).setMessage("条码不在库！");
				}
				if (!"OK".equals(packinggrade)) {
					return AjaxResult.me().setSuccess(false).setMessage("批次不合格！");
				}
				if (!"1".equals(exp)) {
					return AjaxResult.me().setSuccess(false).setMessage("批次已过期！");
				}
				if (!"END".equals(oqaresultstate)) {
					return AjaxResult.me().setSuccess(false).setMessage("未完成质检！");
				}
//				if (!"".equals(invoice)) {
//					return AjaxResult.me().setSuccess(false).setMessage("条码已被" + invoice + "备货！");
//				}
			} else {
				return AjaxResult.me().setSuccess(false).setMessage("未找到对应的条码！");
			}
			String shipRequestType = queryForList.get(0).get("SHIPREQUESTTYPE").toString();
			String shipRequestDetailType = queryForList.get(0).get("SHIPREQUESTDETAILTYPE").toString();
			String minusQty = queryForList.get(0).get("MINUSQTY").toString();
			BigDecimal FmaterialQuantity = new BigDecimal(materialQuantity);
			BigDecimal FminusQty = new BigDecimal(minusQty);
			BigDecimal Fzero = new BigDecimal(0);
			//"SHIPREQUESTDETAILTYPE": "4Y-Cxx-03",//跨组织领料调拨单 
			//"BLSQ4K".equals(shipRequestType) || "4Y".equals(shipRequestType) || "CKSQ4I".equals(shipRequestType)
			int dy0 = FminusQty.compareTo(Fzero);
			
				if ("4Y".equals(shipRequestType)) {//调拨单
					if ( "4Y-Cxx-03".equals(shipRequestDetailType)) {
						if (dy0 < 0) {//只能超发一个
							return AjaxResult.me().setSuccess(false).setMessage("只能超发一个不能出库了！");
						}
					} 
				} else if ("BLSQ4K".equals(shipRequestType)) {//领料
					if (dy0 < 0) {//只能超发一个
						return AjaxResult.me().setSuccess(false).setMessage("只能超发一个不能出库了！");
					}
				} else if ("CKSQ4I".equals(shipRequestType)) { //其他出库
					if (dy0 < 0) {//只能超发一个
						return AjaxResult.me().setSuccess(false).setMessage("只能超发一个不能出库了！");
					}
				} else if ("4C".equals(shipRequestType)) {
					if (dy0 <= 0) {//只能超发一个
						return AjaxResult.me().setSuccess(false).setMessage("销售不允许超发！");
					}
				}else {
					return AjaxResult.me().setSuccess(false).setMessage("单据类型不正确！");
				}
				
				try {
					invoiceServiceImpl.Reserve2(selectByKey, shipRequestName, materialSpecName,"", "", "Assign", "SDK", user,materialQuantity2,"N");
				} catch (CustomException e) {
					e.printStackTrace();
					AjaxResult.me().setSuccess(false).setMessage(e.toString());
				}
		}
		
		return AjaxResult.me().setResultObj(null);
	}
	
	//修改发货数量功能.zd.2024.9.10
	@Transactional
	@RequestMapping(value = "/UpdateOutQty", method = RequestMethod.POST)
	public AjaxResult updateOutQty(@RequestBody JSONObject in)  {
		MaterialPacking materialPacking = JSON.toJavaObject(in, MaterialPacking.class);
		String materialPackingName = materialPacking.getMaterialPackingName();
		String user = materialPacking.getUser();
		String siteName = "SDK";
		String shipRequestName = materialPacking.getShipRequestName();
		String mqty2 = materialPacking.getMaterialQuantity2();
		String materialSpecName=materialPacking.getMaterialSpecName();
		String sdk_id = materialPacking.getSdk_id();
		String phase = materialPacking.getPhase();
		String sql="SELECT (m.MATERIALQUANTITY2 - :MQTY2) MQTY2,(m.MATERIALQUANTITY - :MQTY2)MQTY, SDK_ID,PHASE FROM MATERIALPACKING m \r\n" + 
				" WHERE m.SITENAME =:SITENAME\r\n" + 
				" AND m.MATERIALPACKINGNAME =:MATERIALPACKINGNAME";
		Map<String,Object> bp=new HashMap<>();
		bp.put("SITENAME", siteName);
		bp.put("MATERIALPACKINGNAME", materialPackingName);
		bp.put("MQTY2", mqty2);
		List<Map<String,Object>> sr=IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, bp);
		String minusQty="";
		if(sr.size()>0)
		{
			minusQty=sr.get(0).get("MQTY2").toString();
			sdk_id = sr.get(0).get("SDK_ID") == null ? "" : sr.get(0).get("SDK_ID").toString();
			phase = sr.get(0).get("PHASE") == null ? "" : sr.get(0).get("PHASE").toString();
			String mQty=sr.get(0).get("MQTY").toString();
			if(Double.parseDouble(mQty)<0) 
			{
				return AjaxResult.me().setSuccess(false).setMessage("发料数量不能超过批次总数量");
			}
		}
		else 
		{
			return AjaxResult.me().setSuccess(false).setMessage("未查询到条码");
		}
		

			
		try 
		{
			//更新materialpacking表字段materialQuantity2并留履历
			MaterialPackingKey mpk=new MaterialPackingKey(siteName, materialPackingName);
			com.cim.idm.wmspackage.materialpacking.management.info.SetEventInfo setEventInfo=new com.cim.idm.wmspackage.materialpacking.management.info.SetEventInfo();
			Map<String,Object> userc=new HashMap<>();
			userc.put("materialQuantity2", mqty2);
//			
////			set会精度缺失mqty2
//			setEventInfo.setUserColumns(userc);
//			EventInfo eventInfo=EventInfoUtil.makeEventInfo("UpdateOutQty", user, "UpdateOutQty");
//			MaterialPackingServiceProxy.getMaterialPackingService().setEvent(mpk, eventInfo, setEventInfo);
			

//			再用这个update更新
			Map<String,Object> LKbp=new HashMap<>();
			LKbp.put("SITENAME", siteName);
			LKbp.put("MATERIALPACKINGNAME", materialPackingName);
			LKbp.put("MATERIALQUANTITY2", mqty2);
			String sqlK = "UPDATE\r\n" + 
					"	MATERIALPACKING m\r\n" + 
					"SET\r\n" + 
					"	m.MATERIALQUANTITY2 = :MATERIALQUANTITY2\r\n" + 
					"WHERE\r\n" + 
					"	m.MATERIALPACKINGNAME = :MATERIALPACKINGNAME\r\n" + 
					"	AND m.SITENAME = :SITENAME ";
			
			IDMFrameServiceProxy.getSqlTemplate().update(sqlK, LKbp);
			//更新MaterialShipRequestDetail表ASSIGNEDQUANTITY
			String sqlu="UPDATE  MATERIALSHIPREQUESTDETAIL m SET m.ASSIGNEDQUANTITY=m.ASSIGNEDQUANTITY - :MQTY\r\n" + 
					" WHERE m.SHIPREQUESTNAME =:SHIPREQUESTNAME AND m.MATERIALSPECNAME =:MATERIALSPECNAME\r\n" + 
					" AND m.ASSIGNEDQUANTITY >0   AND (:SDK_ID IS NULL OR m.SDK_ID = :SDK_ID)  AND (:PHASE IS NULL OR m.PHASE = :PHASE)";
			Map<String,Object> bpu=new HashMap<>();
			bpu.put("MQTY", minusQty);
			bpu.put("SHIPREQUESTNAME", shipRequestName);
			bpu.put("MATERIALSPECNAME", materialSpecName);
			bpu.put("SDK_ID", sdk_id);
			bpu.put("PHASE", phase);
			IDMFrameServiceProxy.getSqlTemplate().update(sqlu, bpu);
			
		} catch (Exception e) 
		{
			return AjaxResult.me().setSuccess(false).setMessage(e.toString());
		}
		

		return AjaxResult.me().setResultObj(null);
	}
	@Transactional
	@RequestMapping(value = "/CompleteShipRequest", method = RequestMethod.POST)
	public AjaxResult completeShipRequest(@RequestBody JSONObject in ) throws Exception{
		StockOutDto ms = JSON.toJavaObject(in, StockOutDto.class);
		String shipRequestName = ms.getShipRequestName();
		String siteName = "SDK";
		String user = ms.getUser();
//		String erpfactory = ms.getErpfactory();
//		String erplocation = ms.getErplocation();
//		String locationName = ms.getLocationName();
//		String shipRequestType = ms.getShipRequestType();
		String commitDate = ms.getCommitDate();
		String opCode = ms.getOpCode();
		String reMark = ms.getReMark();
		List<com.cim.idm.wmspackage.materialpacking.management.data.MaterialPacking> boxList = new ArrayList<>();
		
		Map<String, Object> hashMap = new HashMap<String,Object> ();
		hashMap.put("SHIPREQUESTNAME", shipRequestName);
		
		String sqlGetBox="SELECT m.MATERIALPACKINGNAME,m.MATERIALQUANTITY,DECODE(NVL(m.MATERIALQUANTITY2,0), 0 ,m.MATERIALQUANTITY,m.MATERIALQUANTITY2) MATERIALQUANTITY2  FROM MATERIALPACKING m \r\n" + 
				" WHERE m.SHIPREQUESTNAME =:SHIPREQUESTNAME\r\n" + 
				" AND m.STOCKSTATE ='Stocked'\r\n" + 
				" AND m.MATERIALQUANTITY2 >0";
		List<Map<String, Object>> sr = IDMFrameServiceProxy.getSqlTemplate().queryForList(sqlGetBox, hashMap);
		if(sr.size()>0) 
		{
			for(int i=0;i<sr.size();i++) 
			{
				MaterialPackingKey mpk=new MaterialPackingKey(siteName, sr.get(i).get("MATERIALPACKINGNAME").toString());
				com.cim.idm.wmspackage.materialpacking.management.data.MaterialPacking mp = MaterialPackingServiceProxy.getMaterialPackingService().selectByKey(mpk);
				mp.setMaterialQuantity( Double.parseDouble(sr.get(i).get("MATERIALQUANTITY").toString()));
				mp.setMaterialQuantity2( Double.parseDouble(sr.get(i).get("MATERIALQUANTITY2").toString()));
				boxList.add(mp);
			}
		}
		else 
		{
			throw new CustomException("找不到出库单号" + shipRequestName);
		}
		String sendERPStockOut = null;
		String shipRequestType="";
		String sql = "SELECT m.SHIPREQUESTTYPE FROM MATERIALSHIPREQUEST m WHERE m.SHIPREQUESTNAME = :SHIPREQUESTNAME";
		
		List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, hashMap);
		if (queryForList != null && queryForList.size() > 0) {
			String type = queryForList.get(0).get("SHIPREQUESTTYPE").toString();
			shipRequestType = type;
		} else {
			return AjaxResult.me().setSuccess(false).setMessage("找不到出库单据" + shipRequestName);
		}
		InvoiceServiceImpl invoiceServiceImpl=new InvoiceServiceImpl();
		sendERPStockOut=invoiceServiceImpl.SendERPStockOut20240802(shipRequestName, siteName, user, boxList,commitDate,opCode);
//		sendERPStockOut="1";
		if (sendERPStockOut == null || "".equals(sendERPStockOut)) {
			return AjaxResult.me().setSuccess(false).setMessage("过账失败");
		}
		return AjaxResult.me().setResultObj(null);
	}
	
	//查询发货单绑定批次信息
	@RequestMapping(value = "/BindSalePreToSale", method = RequestMethod.POST)
	public AjaxResult BindSalePreToSale(@RequestBody JSONObject in ){
		
		SalePreOrderDto sp = JSON.toJavaObject(in, SalePreOrderDto.class);
		
		List<SalePreOrderDto> salePreList = sp.getSalePreList();
		
		String saleOrder = sp.getSaleOrder();//第三个表格单据
		String saleQty = sp.getSaleQty();//第三表格备货数量
		String saleMaterialSpecName = sp.getSaleMaterialSpecName();
		
		String saleSdk_id = sp.getSaleSdk_id();

		String salePhase = sp.getSalePhase();
		String user = sp.getUser();
		
		if (saleMaterialSpecName == null || "".equals(saleMaterialSpecName)) {
			return AjaxResult.me().setSuccess(false).setMessage("发货物料号不能为空");
		}
	
		if (saleOrder == null || "".equals(saleOrder)) {
			return AjaxResult.me().setSuccess(false).setMessage("发货单不能为空");
		}
		
		if (user == null || "".equals(user)) {
			return AjaxResult.me().setSuccess(false).setMessage("作业员不能为空");
		}
		
//		比较数量，saleQty是salePreQty的和
//		BigDecimal fsalePreQty = new BigDecimal(salePreQty);
//		BigDecimal fsaleQty = new BigDecimal(saleQty);
//		if (fsalePreQty.compareTo(fsaleQty) != 0) {
//			return AjaxResult.me().setSuccess(false).setMessage("数量不一致");
//		}
		BigDecimal sumPreQty = BigDecimal.ZERO;
		int listSize = salePreList.size();
		for (int i = 0; i < listSize; i++) {
			BigDecimal fsalePreQty = new BigDecimal(salePreList.get(i).getSalePreQty());
			sumPreQty = sumPreQty.add(fsalePreQty);
		}
		BigDecimal fsaleQty = new BigDecimal(saleQty);
		if (sumPreQty.compareTo(fsaleQty) != 0) {
			return AjaxResult.me().setSuccess(false).setMessage("数量不一致");
		}
		
		for(SalePreOrderDto pre : salePreList)
		{
			String salePreNo = pre.getSalePreNo();//第二个表格单据
//			String salePreQty = pre.getSalePreQty();//第二表格剩余数量
			String salePreSdk_id = pre.getSalePreSdk_id();
			String salePrePhase = pre.getSalePrePhase();
			String salePreMaterialSpecName = pre.getSalePreMaterialSpecName();
			
			if (!salePreMaterialSpecName.equals(saleMaterialSpecName)) {
				return AjaxResult.me().setSuccess(false).setMessage("物料号不一致");
			}
			
			if (salePrePhase != null && salePhase != null)  { //规格都不为空
				if (!salePrePhase.equals(salePhase)) {
					return AjaxResult.me().setSuccess(false).setMessage("物料阶段不一致");
				}
			} else if (salePrePhase == null && salePhase == null) {
				
			} else {
				return AjaxResult.me().setSuccess(false).setMessage("物料阶段不一致");
			}
			
			
			if (salePreSdk_id != null && saleSdk_id != null)  { //规格都不为空
				if (!salePreSdk_id.equals(saleSdk_id)) {
					return AjaxResult.me().setSuccess(false).setMessage("物料号规格不一致");
				}
			} else if (salePreSdk_id == null && saleSdk_id == null) {
				
			} else {
				return AjaxResult.me().setSuccess(false).setMessage("物料号规格不一致");
			}
					
			if (salePreMaterialSpecName == null || "".equals(salePreMaterialSpecName)) {
				return AjaxResult.me().setSuccess(false).setMessage("预备货物料号不能为空");
			}
			
			if (salePreNo == null || "".equals(salePreNo)) {
				return AjaxResult.me().setSuccess(false).setMessage("预备货单不能为空");
			}
			
			SaleOut.BindSalePreToSale(saleOrder, saleMaterialSpecName, salePreSdk_id, user, salePhase, salePreNo);
		
			String sql = "UPDATE MATERIALSHIPREQUEST SET SHIPREQUESTSTATE = 'Completed' WHERE SHIPREQUESTNAME = :SHIPREQUESTNAME ";
			Map<String, Object> hashMap = new HashMap<String,Object> ();
			hashMap.put("SHIPREQUESTNAME", salePreNo);
			IDMFrameServiceProxy.getSqlTemplate().update(sql, hashMap);
		}

		return AjaxResult.me().setSuccess(true).setMessage("备货成功");
	}

	/**
	 * pc备货出库添加是否可以不良品校验
	 * @param in
	 * @return
	 */
	@Transactional
	@RequestMapping(value = "/RejectsAndExpCheck", method = RequestMethod.POST)
	public AjaxResult RejectsAndExpCheck(@RequestBody JSONObject in ) throws CustomException {
		MaterialshipRequest materialShipRequest = JSON.toJavaObject(in, MaterialshipRequest.class);
		String shipRequestName2 = materialShipRequest.getShipRequestName();
		//根据单据类型判断生产订单类型，如果是领料单且单据类型是复卷和返工的不卡控批次质量状态
		String dTypeSql = "SELECT M.PRODUCTORDERTYPE,M.PRODUCTORDERNO FROM MATERIALSHIPREQUEST M WHERE M.SHIPREQUESTNAME = :SHIPREQUESTNAME";
		Map<String, Object> hashMap3 = new HashMap<String,Object> ();
		hashMap3.put("SHIPREQUESTNAME", shipRequestName2);
		String productOrderType = "";
		List<Map<String, Object>> queryForListW = new ArrayList<>();
		List<Map<String, Object>> queryForList3 = IDMFrameServiceProxy.getSqlTemplate().queryForList(dTypeSql, hashMap3);
		if (queryForList3 != null && queryForList3.size() > 0) {
			productOrderType = queryForList3.get(0).get("PRODUCTORDERTYPE") == null ? "" :queryForList3.get(0).get("PRODUCTORDERTYPE").toString();
		}

		// 查询工单维护表 是否有对应的生产订单
		String workSql = "SELECT w.WORKORDER FROM WORKORDER w WHERE w.WORKORDER =:WORKORDER";
		Map<String, Object> hashMapW = new HashMap<String,Object> ();
		hashMapW.put("WORKORDER", shipRequestName2);
		queryForListW = IDMFrameServiceProxy.getSqlTemplate().queryForList(workSql, hashMapW);

		String IsCheck = "N";  // 是否可以为不良和过期
		if (("55A2-02".equals(productOrderType) || "55A2-Cxx-08".equals(productOrderType)
				|| "4455-Cxx-10".equals(productOrderType) || "4455-Cxx-01".equals(productOrderType)
				|| "5X-Cxx-07".equals(productOrderType)) || (queryForListW != null && !queryForListW.isEmpty())) {//复卷，返工工单
			IsCheck = "Y";
		}
		return AjaxResult.me().setResultObj(IsCheck);
	}
	/**
	 * 销售出库
	 * @param in
	 * @return
	 */
	@RequestMapping(value = "/Commit4CToERP", method = RequestMethod.POST)
	public AjaxResult Commit4CToERP(@RequestBody JSONObject in ){

		MaterialshipRequest ship = JSON.toJavaObject(in, MaterialshipRequest.class);
		String shipRequestName = ship.getShipRequestName();
		String commitDate = ship.getCommitDate();
		String opcode = ship.getOpcode();
		List<MaterialPacking> boxList = ship.getBoxList();
		String user = ship.getUser();
		try {
			SaleOut.Commit4CToERP(shipRequestName, boxList, user,commitDate,opcode);
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.me().setSuccess(false).setMessage(e.toString());
		}
		return AjaxResult.me().setSuccess(true).setMessage("出库成功");
	}
	
	/**
	 * 销售解绑
	 * @param in
	 * @return
	 */
	@RequestMapping(value = "/DessignSaleCharge", method = RequestMethod.POST)
	public AjaxResult DessignSaleCharge(@RequestBody JSONObject in ){

		MaterialshipRequest ship = JSON.toJavaObject(in, MaterialshipRequest.class);
		String shipRequestName = ship.getShipRequestName();
		
		String pcSql = "UPDATE MATERIALPACKING T SET T.MATERIALQUANTITY2 = 0,T.SHIPREQUESTNAME = ''  WHERE T.SHIPREQUESTNAME = :SHIPREQUESTNAME";

		String subSql = "DELETE FROM MATERIALPACKINGSUB m WHERE m.RECEIVEREQUESTNAME  =  :SHIPREQUESTNAME";

		String dhSql = "UPDATE MATERIALSHIPREQUESTDETAIL T SET T.ASSIGNEDQUANTITY = 0 WHERE T.SHIPREQUESTNAME = :SHIPREQUESTNAME";
		Map<String, Object> hashMap = new HashMap<String,Object> ();
		hashMap.put("SHIPREQUESTNAME", shipRequestName);
		IDMFrameServiceProxy.getSqlTemplate().update(dhSql, hashMap);
		IDMFrameServiceProxy.getSqlTemplate().update(pcSql, hashMap);
		IDMFrameServiceProxy.getSqlTemplate().update(subSql, hashMap);
		return AjaxResult.me().setSuccess(true).setMessage("取消备货成功");
	}
	
	
	@RequestMapping(value = "/updateSalePreOrder", method = RequestMethod.POST)
	public AjaxResult updateSalePreOrder(@RequestBody JSONObject in ){

		MaterialshipRequest ship = JSON.toJavaObject(in, MaterialshipRequest.class);
		String shipRequestName = ship.getShipRequestName();
		String shipRequestDetailName = ship.getShipRequestDetailName();
		String materialPackingName = ship.getMaterialPackingName();
		String materialQuantity = ship.getMaterialQuantity();
		String materialQuantity2 = ship.getMaterialQuantity2();
		BigDecimal fmaterialQuantity = new BigDecimal(materialQuantity);
		BigDecimal fmaterialQuantity2 = new BigDecimal(materialQuantity2);
		String materialSpecName = ship.getMaterialSpecName();
		String sdk_id = ship.getSdk_id();
		String phase = ship.getPhase();
		String pcSql = "UPDATE MATERIALPACKING T SET T.MATERIALQUANTITY2 = :QTY  WHERE T.MATERIALPACKINGNAME = :MATERIALPACKINGNAME";

		//查询已过帐，待过账数量更新到已接受数量
		String dck = "SELECT  SUM(DECODE(m2.MATERIALQUANTITY2, 0, m2.MATERIALQUANTITY,m2.MATERIALQUANTITY2)) QTY FROM  MATERIALPACKING m2 WHERE m2.SHIPREQUESTNAME = :SHIPREQUESTNAME "
				+ "AND m2.MATERIALSPECNAME = :MATERIALSPECNAME AND (:SDK_ID IS NULL OR m2.SDK_ID = :SDK_ID) AND (:PHASE IS NULL OR m2.PHASE = :PHASE) AND STOCKSTATE = 'Stocked'";


		String ckls = "SELECT  NVL(SUM(m.QTY),0) QTY FROM MATERIALPACKINGSUBHISTORY m LEFT JOIN MATERIALPACKING m2 ON m.MATERIALPACKINGNAME = m2.MATERIALPACKINGNAME WHERE  m.RECEIVEREQUESTNAME = :SHIPREQUESTNAME "
				+ "AND m2.MATERIALSPECNAME = :MATERIALSPECNAME AND (:SDK_ID IS NULL OR m2.SDK_ID = :SDK_ID) AND (:PHASE IS NULL OR m2.PHASE = :PHASE)";


		String ck = "SELECT  NVL(SUM(m.QTY),0) QTY FROM MATERIALPACKINGSUB m LEFT JOIN MATERIALPACKING m2 ON m.MATERIALPACKINGNAME = m2.MATERIALPACKINGNAME WHERE  m.RECEIVEREQUESTNAME = :SHIPREQUESTNAME "
				+ "AND m2.MATERIALSPECNAME = :MATERIALSPECNAME AND (:SDK_ID IS NULL OR m2.SDK_ID = :SDK_ID) AND (:PHASE IS NULL OR m2.PHASE = :PHASE)";
		
		String dhSql =  " UPDATE\r\n" + 
				"	MATERIALSHIPREQUESTDETAIL m\r\n" + 
				"SET\r\n" + 
				"	m.ASSIGNEDQUANTITY =  :ASSIGNEDQUANTITY WHERE\r\n" + 
				"	m.SITENAME = :SITENAME\r\n" + 
				"	AND m.SHIPREQUESTNAME = :SHIPREQUESTNAME\r\n" + 
				"	AND m.MATERIALSPECNAME = :MATERIALSPECNAME\r\n" + 
				"	AND (:SDK_ID IS NULL\r\n" + 
				"		OR m.SDK_ID = :SDK_ID)\r\n" + 
				"	AND (:PHASE IS NULL\r\n" + 
				"		OR m.PHASE = :PHASE) \r\n" + 
				"	AND ROWNUM = 1 ";
		Map<String, Object> bindMap = new HashMap<String,Object> ();
		bindMap.put("QTY", materialQuantity2);
		bindMap.put("SITENAME", "SDK");
		bindMap.put("SHIPREQUESTNAME", shipRequestName);
		bindMap.put("MATERIALPACKINGNAME", materialPackingName);
		bindMap.put("MATERIALSPECNAME", materialSpecName);
		bindMap.put("SDK_ID", sdk_id);
		bindMap.put("PHASE", phase);
		IDMFrameServiceProxy.getSqlTemplate().update(pcSql, bindMap);
		BigDecimal ASSIGNEDQUANTITY = new BigDecimal(0);
		List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(dck, bindMap);
		if (queryForList != null && queryForList.size() > 0) {
			String string = queryForList.get(0).get("QTY").toString();
			BigDecimal bigDecimal = new  BigDecimal(string);
			ASSIGNEDQUANTITY = ASSIGNEDQUANTITY.add(bigDecimal);
		}
		List<Map<String, Object>> queryForList3 = IDMFrameServiceProxy.getSqlTemplate().queryForList(ckls, bindMap);
		if (queryForList3 != null && queryForList3.size() > 0) {
			String string = queryForList3.get(0).get("QTY").toString();
			ASSIGNEDQUANTITY = ASSIGNEDQUANTITY.add(new  BigDecimal(string));
		}
		List<Map<String, Object>> queryForList4 = IDMFrameServiceProxy.getSqlTemplate().queryForList(ck, bindMap);
		if (queryForList4 != null && queryForList4.size() > 0) {
			String string = queryForList4.get(0).get("QTY").toString();
			ASSIGNEDQUANTITY = ASSIGNEDQUANTITY.add(new  BigDecimal(string));
		}
		bindMap.put("ASSIGNEDQUANTITY", ASSIGNEDQUANTITY);
		IDMFrameServiceProxy.getSqlTemplate().update(dhSql, bindMap);
		return AjaxResult.me().setSuccess(true).setMessage("更新备货成功");
	}
}
