package com.cim.idm.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cim.idm.exception.GlobalException;
import com.cim.idm.framework.IDMFrameServiceProxy;
import com.cim.idm.model.MaterialPacking;
import com.cim.idm.model.MaterialshipRequest;
import com.cim.idm.service.Impl.TransferInServiceImpl;
import com.cim.idm.utils.AjaxResult;
import com.cim.idm.utils.CommonUtils;
import io.swagger.annotations.Api;
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.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;


@Api("调拨入接口")
@RestController
@RequestMapping("/transferIn")
@EnableAutoConfiguration
public class TransferInController {
	
	@Autowired
	private TransferInServiceImpl transferInServiceImpl;
	
	CommonUtils untils=new CommonUtils();
	/**
	 * 获取调拨退待操作单号集合
	 * @param in
	 * @return
	 */
	@RequestMapping(value = "/BindBarCodeToTransferIn", method = RequestMethod.POST)
	public AjaxResult BindBarCodeToTransferIn(@RequestBody JSONObject in ){

		MaterialPacking materialPacking = JSON.toJavaObject(in, MaterialPacking.class);
		String locationName = materialPacking.getLocationName();
		String charge = materialPacking.getCharge();
		String materialPackingName = materialPacking.getMaterialPackingName();
		String materialSpecName = materialPacking.getMaterialSpecName();
		String shipRequestName = materialPacking.getShipRequestName();
		String shipRequestDetailName = materialPacking.getShipRequestDetailName();
		String user = materialPacking.getUser();
		String erpLocation = materialPacking.getErpLocation();
		String materialQty=materialPacking.getMaterialQuantity();
		String erpFactory = materialPacking.getErpFactory();
		if ("101".equals(erpFactory) || "102".equals(erpFactory)) {
			//恒温恒湿管控
			if(!(untils.JudgeMentERPLocationAndMaterialSpec(erpLocation,materialSpecName)))
			{
				throw new GlobalException("物料为:"+materialSpecName+" 仓库为:"+erpLocation+" ,不符合恒温恒湿管理");
			}
		}
		//判断条码是否存在且状态是出库
		String sql = "SELECT * FROM MATERIALPACKING M WHERE M.CHARGE = :CHARGE "
				+ "AND M.MATERIALSPECNAME = :MATERIALSPECNAME  AND M.STOCKSTATE = 'StockOut' AND (M.SHIPREQUESTNAME <> :SHIPREQUESTNAME OR M.SHIPREQUESTNAME IS NULL )";
		
		Map<String, Object> bindMap = new HashMap<String, Object>();
		bindMap.put("MATERIALSPECNAME",materialSpecName); 
		bindMap.put("CHARGE",charge ); 
		bindMap.put("SHIPREQUESTNAME",shipRequestName ); 
		List<Map<String,Object>> list = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, bindMap);

		if(Objects.isNull(list) || list.isEmpty()) {
			throw new GlobalException("未找到对应的条码出库记录！");
		}
		if(list.size() > 1) {
			throw new GlobalException("批次找到不唯一记录,请联系IT处理！");
		}
		
		//查找该单据该物料下的单据明细+需求数量+绑定数量
		String ShipDetailSql = "SELECT  SHIPREQUESTDETAILNAME ,REQUESTQUANTITY,ASSIGNEDQUANTITY  FROM MATERIALSHIPREQUESTDETAIL  m WHERE SHIPREQUESTNAME =:SHIPREQUESTNAME AND MATERIALSPECNAME =:MATERIALSPECNAME";
		Map<String, Object> ShipDetailMap = new HashMap<String, Object>();
		ShipDetailMap.put("SHIPREQUESTNAME",shipRequestName); 
		ShipDetailMap.put("MATERIALSPECNAME",materialSpecName ); 
		List<Map<String,Object>>  ShipDetaillist = IDMFrameServiceProxy.getSqlTemplate().queryForList(ShipDetailSql, ShipDetailMap);
		if(Objects.isNull(ShipDetaillist) || ShipDetaillist.isEmpty()) {
			throw new GlobalException("未找到对应的调拨入库明细！");
		}
		shipRequestDetailName=(String) ShipDetaillist.get(0).get("SHIPREQUESTDETAILNAME");
		for(int i=0;i<ShipDetaillist.size();i++)
		{
			String shipNo=(String) ShipDetaillist.get(i).get("SHIPREQUESTDETAILNAME");
			BigDecimal requestQtyBigDecimal = (BigDecimal) ShipDetaillist.get(i).get("REQUESTQUANTITY");  
			BigDecimal assQtyBigDecimal = (BigDecimal) ShipDetaillist.get(i).get("ASSIGNEDQUANTITY");  
			float requestQtyFloat = requestQtyBigDecimal.floatValue();  
			float assQtyFloat = assQtyBigDecimal.floatValue();  
			if(requestQtyFloat>=assQtyFloat+Float.parseFloat(materialQty))
			{
				shipRequestDetailName=shipNo;
				break;
			}
		}
		
		boolean bindBarCodeToTransferIn = transferInServiceImpl.BindBarCodeToTransferIn(materialPackingName, charge, materialSpecName, user, shipRequestName, shipRequestDetailName,locationName);
		if (!bindBarCodeToTransferIn) {
			throw new GlobalException("绑定失败！");
		}
		return AjaxResult.me().setResultObj(list);

	}
	
	/**
	 * 2根据条码获取调拨入库操作单号集合2
	 * @param in
	 * @return
	 */
	@RequestMapping(value = "/BindBarCodeToTransfer", method = RequestMethod.POST)
	public AjaxResult BindBarCodeToTransfer(@RequestBody JSONObject in ){

		MaterialPacking materialPacking = JSON.toJavaObject(in, MaterialPacking.class);
		String locationName = materialPacking.getLocationName();
		String charge = materialPacking.getCharge();
		String materialPackingName = materialPacking.getMaterialPackingName();
		String materialSpecName = materialPacking.getMaterialSpecName();
//		String shipRequestName = materialPacking.getShipRequestName();
//		String shipRequestDetailName = materialPacking.getShipRequestDetailName();
		String user = materialPacking.getUser();
		String erpLocation = materialPacking.getErpLocation();
		String erpFactory = materialPacking.getErpFactory();
		String materialQty=materialPacking.getMaterialQuantity();
		//恒温恒湿管控
		if ("101".equals(erpFactory) || "102".equals(erpFactory)) {
			if(!(untils.JudgeMentERPLocationAndMaterialSpec(erpLocation,materialSpecName)))
			{
				throw new GlobalException("物料为:"+materialSpecName+" 仓库为:"+erpLocation+" ,不符合恒温恒湿管理");
			}
		}
		
		// 根据箱找到箱对应单据
//		String shipQuestSql = "SELECT M.SHIPREQUESTNAME FROM MATERIALPACKING M WHERE M.STOCKSTATE = 'StockOut' AND M.MATERIALPACKINGNAME = :MATERIALPACKINGNAME AND M.CHARGE = :CHARGE AND M.MATERIALSPECNAME = :MATERIALSPECNAME";
//		String shipQuestSql = "SELECT * FROM MATERIALPACKING M WHERE M.STOCKSTATE = 'StockOut' AND M.MATERIALPACKINGNAME = :MATERIALPACKINGNAME AND M.CHARGE = :CHARGE AND M.MATERIALSPECNAME = :MATERIALSPECNAME";

		String shipQuestSql = "SELECT * FROM MATERIALPACKING M WHERE M.STOCKSTATE != 'Created' AND M.MATERIALPACKINGNAME = :MATERIALPACKINGNAME AND M.CHARGE = :CHARGE AND M.MATERIALSPECNAME = :MATERIALSPECNAME";		
		Map<String, Object> bindMap = new HashMap<String, Object>();
		bindMap.put("CHARGE",charge); 
		bindMap.put("MATERIALPACKINGNAME",materialPackingName); 
		bindMap.put("MATERIALSPECNAME",materialSpecName); 
		
		List<Map<String,Object>> list = IDMFrameServiceProxy.getSqlTemplate().queryForList(shipQuestSql, bindMap);
		
		if((Objects.isNull(list) || list.isEmpty())) {
			throw new GlobalException("未找到对应的条码出库记录！");
		}
		
		if(list.size() > 1) {
			throw new GlobalException("批次找到不唯一记录,请联系IT处理！");
		}
		
		if("Stocked".equals(list.get(0).get("STOCKSTATE"))) {
			throw new GlobalException("条码已入库，不能重复扫描！");
		}
		
		// 良品与不良品与仓校验
		String packingGrade = list.get(0).get("OQARESULT") == null ? "" : list.get(0).get("OQARESULT").toString();
		Boolean judgeMtaerialStateWithERPLocation = untils.JudgeMtaerialStateWithERPLocation(erpLocation, packingGrade);
		if (!judgeMtaerialStateWithERPLocation) {
			throw new GlobalException("仓库类型和物料品质等级不一致");
		}
		
//		BigDecimal qty = (BigDecimal) list.get(0).get("MATERIALQUANTITY");
		
		// 根据单据找是否存在对应的出货单
		String orderSql2 = "SELECT DISTINCT MD.SHIPREQUESTNAME,MD.SHIPREQUESTDETAILNAME,MD.REQUESTQUANTITY,MD.ASSIGNEDQUANTITY, MD.ERPRECEIVEFACTORY FROM MATERIALSHIPREQUESTDETAIL "
				+ "MD LEFT JOIN MATERIALSHIPREQUEST MT ON MT.SHIPREQUESTNAME = MD.SHIPREQUESTNAME "
				+ "WHERE MD.SOURCENO = :SHIPREQUESTNAME AND MT.SHIPREQUESTTYPE = '4E' AND (:SDK_ID IS NULL OR MD.SDK_ID  = :SDK_ID) "
				+ "AND MD.MATERIALSPECNAME = :MATERIALSPECNAME AND  (:PHASE IS NULL OR MD.PHASE = :PHASE)";
		
		String orderSql = "SELECT DISTINCT MD.SHIPREQUESTNAME,MD.SHIPREQUESTDETAILNAME,MD.REQUESTQUANTITY,MD.ASSIGNEDQUANTITY, MT.ERPRECEIVEFACTORY FROM MATERIALSHIPREQUESTDETAIL "
				+ "MD LEFT JOIN MATERIALSHIPREQUEST MT ON MT.SHIPREQUESTNAME = MD.SHIPREQUESTNAME "
				+ "WHERE MD.SHIPREQUESTNAME = :SHIPREQUESTNAME AND MT.SHIPREQUESTTYPE = '4Y' AND NVL(MD.SDK_ID,'~')  = NVL(:SDK_ID,'~') "
				+ "AND MD.MATERIALSPECNAME = :MATERIALSPECNAME AND NVL(MD.PHASE,'~') = NVL(:PHASE,'~')";
		Map<String, Object> orderMap = new HashMap<String, Object>();
		orderMap.put("SHIPREQUESTNAME",list.get(0).get("SHIPREQUESTNAME")); 
		orderMap.put("SDK_ID",list.get(0).get("SDK_ID")); 
		orderMap.put("PHASE",list.get(0).get("PHASE")); 
		orderMap.put("MATERIALSPECNAME",materialSpecName); 
		List<Map<String,Object>> orderList = IDMFrameServiceProxy.getSqlTemplate().queryForList(orderSql, orderMap);
		
		if(orderList.size() > 0) {
			String ERPRECEIVEFACTORY = (String) orderList.get(0).get("ERPRECEIVEFACTORY");
			if(Objects.isNull(ERPRECEIVEFACTORY) || !ERPRECEIVEFACTORY.equals(erpFactory) ) {
				throw new GlobalException("接收组织不一致或不存在!");
			}
		} else {
			throw new GlobalException("未找到条码对应的单据!");
		}
		
		List<Map<String,Object>> orderList2 = IDMFrameServiceProxy.getSqlTemplate().queryForList(orderSql2, orderMap);
		
		list.get(0).put("receiveRequestName", orderList2.get(0).get("SHIPREQUESTNAME"));
		list.get(0).put("receiveRequestDetailName", orderList2.get(0).get("SHIPREQUESTDETAILNAME"));
//		//查找该单据该物料下的单据明细+需求数量+绑定数量
//		String ShipDetailSql = "SELECT  SHIPREQUESTDETAILNAME ,REQUESTQUANTITY,ASSIGNEDQUANTITY  FROM MATERIALSHIPREQUESTDETAIL  m WHERE SHIPREQUESTNAME =:SHIPREQUESTNAME AND MATERIALSPECNAME =:MATERIALSPECNAME";
//		Map<String, Object> ShipDetailMap = new HashMap<String, Object>();
//		ShipDetailMap.put("SHIPREQUESTNAME",shipRequestName); 
//		ShipDetailMap.put("MATERIALSPECNAME",materialSpecName ); 
//		List<Map<String,Object>>  ShipDetaillist = IDMFrameServiceProxy.getSqlTemplate().queryForList(ShipDetailSql, ShipDetailMap);
//		if(Objects.isNull(ShipDetaillist) || ShipDetaillist.isEmpty()) {
//			throw new GlobalException("未找到对应的调拨入库明细！");
//		}
		String shipRequestDetailName=(String) orderList.get(0).get("SHIPREQUESTDETAILNAME");
		String shipRequestName = (String) orderList.get(0).get("SHIPREQUESTNAME");
		for(int i=0;i<orderList.size();i++)
		{
			String shipNo=(String) orderList.get(i).get("SHIPREQUESTDETAILNAME");
			BigDecimal requestQtyBigDecimal = (BigDecimal) orderList.get(i).get("REQUESTQUANTITY");  
			BigDecimal assQtyBigDecimal = (BigDecimal) orderList.get(i).get("ASSIGNEDQUANTITY");  
			float requestQtyFloat = requestQtyBigDecimal.floatValue();  
			float assQtyFloat = assQtyBigDecimal.floatValue();  
			if(requestQtyFloat>=assQtyFloat+Float.parseFloat(materialQty))
			{
				shipRequestDetailName=shipNo;
				break;
			}
		}
		
//		boolean bindBarCodeToTransferIn = transferInServiceImpl.BindBarCodeToTransfer(materialPackingName, charge, materialSpecName, user, shipRequestName, shipRequestDetailName,locationName, erpLocation, erpFactory);
//		if (!bindBarCodeToTransferIn) {
//			throw new GlobalException("绑定失败！");
//		}
		return AjaxResult.me().setResultObj(list);
		
	}
	

	/**
	 * 获取调拨退待操作单号集合
	 * @param in
	 * @return
	 * @throws Exception 
	 */
//	@RequestMapping(value = "/CommitTransferInInvoice", method = RequestMethod.POST)
//	public AjaxResult CommitTransferInInvoice(@RequestBody JSONObject in ) throws Exception{
//
//		MaterialPacking materialPacking = JSON.toJavaObject(in, MaterialPacking.class);
//		String locationName = materialPacking.getLocationName();
//		String charge = materialPacking.getCharge();
//		String materialPackingName = materialPacking.getMaterialPackingName();
//		String materialSpecName = materialPacking.getMaterialSpecName();
//		String shipRequestName = materialPacking.getShipRequestName();
//		String shipRequestDetailName = materialPacking.getShipRequestDetailName();
//		String user = materialPacking.getUser();
//		boolean commitTransferInInvoice = transferInServiceImpl.CommitTransferInInvoice(shipRequestName, user);
//		if (!commitTransferInInvoice) {
//			throw new GlobalException("过账失败！");
//		}
//		return AjaxResult.me().setResultObj(null);
//
//	}
	
	/**
	 * 获取调拨退待操作单号集合
	 * @param in
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value = "/CommitTransferInInvoice", method = RequestMethod.POST)
	public AjaxResult CommitTransferInInvoice(@RequestBody JSONObject in ) throws Exception{

		MaterialshipRequest MaterialshipRequest = JSON.toJavaObject(in, MaterialshipRequest.class);
		String locationName = MaterialshipRequest.getLocationName();
		String erpLocation = MaterialshipRequest.getErplocation();
		String erpFactory = MaterialshipRequest.getErpfactory();
		String charge = MaterialshipRequest.getPhase();
		String materialPackingName = MaterialshipRequest.getMaterialPackingName();
		String materialSpecName = MaterialshipRequest.getMaterialSpecName();
		String shipRequestName = MaterialshipRequest.getShipRequestName();
		String shipRequestDetailName = MaterialshipRequest.getShipRequestDetailName();
		String oqaresultstate = MaterialshipRequest.getOQARESULTSTATE();
		List<MaterialPacking> boxList = MaterialshipRequest.getBoxList();
		String user = MaterialshipRequest.getUser();
		String commitDate = MaterialshipRequest.getCommitDate();
		String opcode = MaterialshipRequest.getOpcode();
		boolean commitTransferInInvoice = transferInServiceImpl.CommitTransfer(boxList, user, erpFactory, erpLocation, locationName,commitDate,opcode,oqaresultstate);
		if (!commitTransferInInvoice) {
			throw new GlobalException("过账失败！");
		}
		return AjaxResult.me().setResultObj(null);
	}
}
