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.framework.data.EventInfo;
import com.cim.idm.model.MaterialPacking;
import com.cim.idm.model.MoveInDto;
import com.cim.idm.service.Impl.InvoiceServiceImpl;
import com.cim.idm.utils.AjaxResult;
import com.cim.idm.utils.CommonUtils;
import com.cim.idm.wmspackage.materialpacking.MaterialPackingServiceProxy;
import com.cim.idm.wmspackage.materialpacking.management.data.MaterialPackingKey;
import com.cim.idm.wmspackage.materialpacking.management.info.MaterialPackingAssignShipRequestInfo;
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.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.*;

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


@Api("移库接口")
@RestController
@RequestMapping("/MoveIn")
@EnableAutoConfiguration
public class MoveInController {
	
	@Autowired
	private MoveInServiceImpl MoveInServiceImpl;
	
	CommonUtils untils=new CommonUtils();
	
	/**
	 * 获取调拨退待操作单号集合
	 * @param in
	 * @return
	 */
	@RequestMapping(value = "/BindBarCodeToMoveIn", method = RequestMethod.POST)
	public AjaxResult BindBarCodeToMoveIn(@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 materialQty=materialPacking.getMaterialQuantity();
		String erpLocation=materialPacking.getErpLocation();
		//恒温恒湿管控
		if(!(untils.JudgeMentERPLocationAndMaterialSpec(erpLocation,materialSpecName)))
		{
			throw new GlobalException("物料为:"+materialSpecName+" 仓库为:"+erpLocation+" ,不符合恒温恒湿管理");
		}
		//判断条码是否存在且状态是在库
		String sql = "SELECT * FROM MATERIALPACKING M WHERE M.CHARGE = :CHARGE AND M.MATERIALPACKINGNAME = :MATERIALPACKINGNAME"
				+ " AND M.MATERIALSPECNAME = :MATERIALSPECNAME  AND M.STOCKSTATE = 'Stocked' 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 ); 
		bindMap.put("MATERIALPACKINGNAME",materialPackingName ); 
		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 sql3 = "SELECT\r\n" + 
				"	M.*,\r\n" + 
				"	CASE\r\n" + 
				"		WHEN M.MATURATIONINTIME IS NOT NULL THEN SYSDATE - M.MATURATIONINTIME - m2.MATURATIONTIME\r\n" + 
				"		ELSE 1\r\n" + 
				"	END FLAG\r\n" + 
				"FROM\r\n" + 
				"	MATERIALPACKING M\r\n" + 
				"LEFT JOIN MATERIALSPEC m2 ON\r\n" + 
				"	M.MATERIALSPECNAME = m2.MATERIALSPECNAME\r\n" + 
				"WHERE\r\n" + 
				"	M.STOCKSTATE = 'Stocked'\r\n" + 
				"	AND M.MATERIALPACKINGNAME = :MATERIALPACKINGNAME ";

		Map<String, Object> bindMap3 = new HashMap<String, Object>();
		bindMap.put("MATERIALPACKINGNAME", materialPacking.getMaterialPackingName());
		List<Map<String,Object>> list3 = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql3, bindMap3);

		if(Objects.isNull(list3) || list3.isEmpty()) {
			throw new GlobalException("未找到对应的数据！");
		}
		
		if(!Objects.isNull(list3) && !list3.isEmpty()) {
			String string = list.get(0).get("FLAG").toString();
			float parseFloat = Float.parseFloat(string);
			float abs = Math.abs(parseFloat);
			if (parseFloat < 0) {
				throw new GlobalException("还差" + abs + "天才能熟化出库!");
			}
		}
		//查找该单据该物料下的单据明细+需求数量+绑定数量
				String ShipDetailSql = "SELECT  SHIPREQUESTDETAILNAME ,NVL(REQUESTQUANTITY ,0) REQUESTQUANTITY,NVL(ASSIGNEDQUANTITY ,0) 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("未找到对应的转库入库明细！");
				}
				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;
					}
				}
		if("".equals(shipRequestDetailName))
			throw new GlobalException("该单据下无该物料的明细或该明细剩余接收数量低于该标签数量");
		boolean bindBarCodeToMoveIn = MoveInServiceImpl.BindBarCodeToMoveIn(materialPackingName, charge, materialSpecName, user, shipRequestName, shipRequestDetailName,locationName);
		if (!bindBarCodeToMoveIn) {
			throw new GlobalException("绑定失败！");
		}
		return AjaxResult.me().setResultObj(list);

	}
	

	/**
	 * 获取调拨退待操作单号集合
	 * @param in
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value = "/CommitMoveInInvoice", method = RequestMethod.POST)
	public AjaxResult CommitMoveInInvoice(@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();
		String commitDate = materialPacking.getCommitDate();
		String opCode = materialPacking.getOpCode();
		boolean commitMoveInInvoice = MoveInServiceImpl.CommitMoveInInvoice(shipRequestName, user,commitDate,opCode);
		if (!commitMoveInInvoice) {
			throw new GlobalException("过账失败！");
		}
		return AjaxResult.me().setResultObj(null);

	}

	@RequestMapping(value = "/AllCommitMoveInInvoice", method = RequestMethod.POST)
	public AjaxResult AllCommitMoveInInvoice(@RequestBody JSONObject in ) throws Exception {
		MoveInDto materialPacking = JSON.toJavaObject(in, MoveInDto.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 commitDate = materialPacking.getCommitDate();
		String opCode = materialPacking.getOpCode();
		List<com.cim.idm.wmspackage.materialpacking.management.data.MaterialPacking> boxList = materialPacking.getBoxList();
		boolean bindBarCodeToMoveIn = MoveInServiceImpl.BindBarCodeToMoveIn2(boxList,materialPackingName, user, shipRequestName, shipRequestDetailName,locationName);
		if (!bindBarCodeToMoveIn) {
			throw new GlobalException("货位绑定到条码失败！");
		}
		boolean commitMoveInInvoice = MoveInServiceImpl.CommitMoveInInvoice(shipRequestName, user,commitDate,opCode);
		if (!commitMoveInInvoice) {
			throw new GlobalException("过账失败！");
		}
		return AjaxResult.me().setResultObj(null);

	}
	


}
