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.framework.util.time.TimeStampUtil;
import com.cim.idm.model.CheckMark;
import com.cim.idm.model.CheckPlan;
import com.cim.idm.service.Impl.ReturnStockIntoServiceImpl;
import com.cim.idm.service.impl.ToSAPServiceImpl;
import com.cim.idm.utils.AjaxResult;
import com.cim.idm.utils.EventInfoUtil;
import com.cim.idm.wmspackage.materialpacking.MaterialPackingServiceProxy;
import com.cim.idm.wmspackage.materialpacking.management.data.MaterialPackingKey;
import com.cim.idm.wmspackage.materialpacking.management.info.SetEventInfo;
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.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 盘点 标记
 * @author 
 *
 */
@RestController
@EnableAutoConfiguration
@RequestMapping("/api/checkmark")
public class CheckMarkController {
	@Autowired
	private ToSAPServiceImpl toSAPServiceImpl;
	@RequestMapping(value = "/createMark", method = RequestMethod.POST)
	public AjaxResult createMark(@RequestBody JSONObject in ) throws Exception{

		CheckMark javaObject = JSON.toJavaObject(in, CheckMark.class);
		String checkplanname = javaObject.getCHECKPLANNAME();
		String materialpackingname = javaObject.getMATERIALPACKINGNAME();
		String sitename = javaObject.getSITENAME();
		String checkplatate = javaObject.getCHECKPLATATE();
		String sql = "UPDATE CHECKPLAN c SET CHECKPLATATE = :CHECKPLATATE WHERE CHECKPLANNAME = :CHECKPLANNAME AND SITENAME = :SITENAME AND MATERIALPACKINGNAME = :MATERIALPACKINGNAME";
		Map<String, Object> bindMap = new HashMap<String, Object>();
		bindMap.put("SITENAME",sitename); 
		bindMap.put("MATERIALPACKINGNAME",materialpackingname); 
		bindMap.put("CHECKPLANNAME",checkplanname); 
		bindMap.put("CHECKPLATATE",checkplatate); 
		int update = IDMFrameServiceProxy.getSqlTemplate().update(sql, bindMap);
		System.out.println("****"+update);
		String sqlString = "UPDATE CHECKRECORD SET CHECKPLATATE = :CHECKPLATATE WHERE CHECKPLANNAME = :CHECKPLANNAME AND SITENAME = :SITENAME AND MATERIALPACKINGNAME = :MATERIALPACKINGNAME";
		int update2 = IDMFrameServiceProxy.getSqlTemplate().update(sqlString, bindMap);
		System.out.println("****"+update2);
		return AjaxResult.me().setResultObj(update);
	}
	
//	@RequestMapping(value = "/deleteMark", method = RequestMethod.POST)
//	public AjaxResult deleteMark(@RequestBody JSONObject in ) throws Exception{
//
//		CheckMark javaObject = JSON.toJavaObject(in, CheckMark.class);
//		String checkplanname = javaObject.getCHECKPLANNAME();
//		String materialpackingname = javaObject.getMATERIALPACKINGNAME();
//		String sitename = javaObject.getSITENAME();
//		String sql = "UPDATE CHECKPLAN c SET CHECKPLATATE = '否' WHERE CHECKPLANNAME = :CHECKPLANNAME AND SITENAME = :SITENAME AND MATERIALPACKINGNAME = :MATERIALPACKINGNAME";
//		Map<String, Object> bindMap = new HashMap<String, Object>();
//		bindMap.put("SITENAME",sitename); 
//		bindMap.put("MATERIALPACKINGNAME",materialpackingname); 
//		bindMap.put("CHECKPLANNAME",checkplanname); 
//		int update = IDMFrameServiceProxy.getSqlTemplate().update(sql, bindMap);
//		System.out.println("****"+update);
//		String sqlString = "UPDATE CHECKRECORD SET CHECKPLATATE = '否' WHERE CHECKPLANNAME = :CHECKPLANNAME AND SITENAME = :SITENAME AND MATERIALPACKINGNAME = :MATERIALPACKINGNAME";
//		int update2 = IDMFrameServiceProxy.getSqlTemplate().update(sql, bindMap);
//		System.out.println("****"+update2);
//		return AjaxResult.me().setResultObj(update);
//	}
	
	@RequestMapping(value = "/checkmarkAudit", method = RequestMethod.POST)
	public AjaxResult checkmarkAudit(@RequestBody JSONObject in ) throws Exception{

		CheckPlan javaObject = JSON.toJavaObject(in, CheckPlan.class);
		String planDate = javaObject.getPlanDate(); //时间
		String checkPlanName = javaObject.getCheckPlanName();//测试名
		
		Map<String, Object> bindMap = new HashMap<String, Object>();
		bindMap.put("PLANDATE",planDate); 
		bindMap.put("CHECKPLANNAME",checkPlanName); 
		
		
		String sql = "UPDATE CHECKPLAN c SET CHECKPLANSTATE = 'Audit' WHERE PLANDATE  = :PLANDATE AND CHECKPLANNAME = :CHECKPLANNAME";
		
		int update = IDMFrameServiceProxy.getSqlTemplate().update(sql, bindMap);
		return AjaxResult.me().setResultObj(update);
	}
	
	//Approved
	@RequestMapping(value = "/Auditcheckmark", method = RequestMethod.POST)
	public AjaxResult Auditcheckmark(@RequestBody JSONObject in ) throws Exception{

		CheckPlan javaObject = JSON.toJavaObject(in, CheckPlan.class);
		String planDate = javaObject.getPlanDate(); //时间
		String checkPlanName = javaObject.getCheckPlanName();//测试名
		String user=javaObject.getUser();
		String commitDate=javaObject.getCommitDate();
		String opCode = javaObject.getOpCode();
		if(StringUtils.isEmpty(commitDate)) 
		{
			commitDate=TimeStampUtil.getCurrentTime("yyyy-MM-dd");
		}
		String billCode="";
		String siteName="SDK";
		EventInfoUtil eventInfoUtil=new EventInfoUtil();
		EventInfo makeEventInfo=new EventInfo();
		ReturnStockIntoServiceImpl rs=new ReturnStockIntoServiceImpl();
		
		Map<String, Object> bindMap = new HashMap<String, Object>();
		bindMap.put("PLANDATE",planDate); 
		bindMap.put("CHECKPLANNAME",checkPlanName); 
		
		//盘点计划有，实物没有。做其他出库.zd.2024.8.30
		// 获取盘亏的ERPLOCATION
		String sql_erp = " SELECT DISTINCT ERPLOCATION FROM (\r\n"
				+ " SELECT	c.ERPLOCATION,	(NVL(c2.MATERIALQUANTITY, 0) -c.MATERIALQUANTITY) AS DifferenceQuantity,\r\n"
				+ " c.CHECKPLATATE,c.CHECKPLANSTATE\r\n" + " FROM	CHECKPLAN c\r\n"
				+ " LEFT JOIN CHECKRECORD c2 ON	c.CHECKPLANNAME = c2.CHECKPLANNAME	AND c.ERPLOCATION = c2.ERPLOCATION	\r\n"
				+ " AND c.MATERIALPACKINGNAME = c2.MATERIALPACKINGNAME	AND c.SYSLOCATION = c2.ACTLOCATION\r\n"
				+ " WHERE  c.CHECKPLANNAME =:CHECKPLANNAME	AND c.PLANDATE = :PLANDATE )\r\n"
				+ " WHERE DifferenceQuantity<0 AND nvl(CHECKPLATATE,'是')='是' AND nvl(CHECKPLANSTATE,'N')<>'Approved' ";
		List<Map<String, Object>> sr_erp = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql_erp, bindMap);
		if (sr_erp.size() > 0) {
			for (int i = 0; i < sr_erp.size(); i++) {
				String erpLocation = sr_erp.get(i).get("ERPLOCATION").toString();
				bindMap.put("ERPLOCATION", erpLocation);
				//查找盘亏的批次
				String sql_pk = " SELECT a.*,ABS(DifferenceQuantity)NUM FROM (\r\n" + 
						" SELECT	c.MATERIALPACKINGNAME,c.MATERIALSPECNAME,c.ERPLOCATION,c.SYSLOCATION,m.ERPFACTORY,\r\n" + 
						" NVL( c.MATERIALQUANTITY,0) AS MATERIALQUANTITY,NVL(c2.MATERIALQUANTITY, 0) AS MATERIALACTQUANTITY,	\r\n" +
						"	(NVL(c2.MATERIALQUANTITY, 0) -c.MATERIALQUANTITY) AS DifferenceQuantity,c.CHECKPLATATE,c.CHECKPLANSTATE,\r\n" +
						"	m.CHARGE ,m.SDK_ID ,m.PHASE ,TO_CHAR(m.EXPIRINGDATE, 'YYYY-MM-DD HH24:MI:SS') expdate,\r\n" + 
						"	TO_CHAR(m.MAKEDATE, 'YYYY-MM-DD HH24:MI:SS') proddate,TO_CHAR(SYSDATE, 'YYYY-MM-DD HH24:MI:SS') indate\r\n" + 
						" FROM	CHECKPLAN c\r\n" + 
						" LEFT JOIN MATERIALPACKING m ON c.MATERIALPACKINGNAME=m.MATERIALPACKINGNAME \r\n" + 
						" LEFT JOIN CHECKRECORD c2 ON	c.CHECKPLANNAME = c2.CHECKPLANNAME	AND c.ERPLOCATION = c2.ERPLOCATION	\r\n" + 
						" AND c.MATERIALPACKINGNAME = c2.MATERIALPACKINGNAME	AND c.SYSLOCATION = c2.ACTLOCATION\r\n" + 
						" WHERE  c.CHECKPLANNAME =:CHECKPLANNAME	AND c.PLANDATE = :PLANDATE AND c.ERPLOCATION=:ERPLOCATION)A\r\n" + 
						" WHERE DifferenceQuantity<0 AND nvl(CHECKPLATATE,'是')='是' AND nvl(CHECKPLANSTATE,'N')<>'Approved' ";
				List<Map<String, Object>> sr_pk = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql_pk, bindMap);
				if(sr_pk.size()>0) 
				{
					//调用NC接口
					billCode=toSAPServiceImpl.qtcrNoInvoiceForCheckPlan(sr_pk, "qtc", user, commitDate,opCode);
					//更新盘点计划状态
					String sql = "UPDATE CHECKPLAN c SET CHECKPLANSTATE = 'Approved' WHERE PLANDATE  = :PLANDATE AND CHECKPLANNAME = :CHECKPLANNAME AND ERPLOCATION=:ERPLOCATION";				
					IDMFrameServiceProxy.getSqlTemplate().update(sql, bindMap);
					//更新批次状态
					List<MaterialPackingKey> mpkList=new ArrayList<>();
					for(int j=0;j<sr_pk.size();j++) 
					{
						MaterialPackingKey mpk=new MaterialPackingKey();
						mpk.setSiteName(siteName);
						mpk.setMaterialPackingName(sr_pk.get(j).get("MATERIALPACKINGNAME").toString());
						mpkList.add(mpk);
					}
					SetEventInfo setEventInfo=new SetEventInfo();
					Map<String,Object> userc=new HashMap<>();
					userc.put("unDoID", billCode);
					userc.put("stockState", "StockOut");
					setEventInfo.setUserColumns(userc);
					makeEventInfo = eventInfoUtil.makeEventInfo("StockOutForCheckPlan", user, "StockOutForCheckPlan");
					MaterialPackingServiceProxy.getMaterialPackingService().setEvent(mpkList, makeEventInfo, setEventInfo);
					
					//存储物料凭证
					rs.SaveUnDoInfo(billCode, commitDate);
				}
			}
		}
				
		//盘点计划没有，实物有。做其他入库.zd.2024.8.30
		// 获取盘盈的ERPLOCATION
		String sql_erp_py = " SELECT DISTINCT ERPLOCATION FROM (\r\n" + 
				"SELECT	c.ERPLOCATION ,	c.CHECKPLANSTATE,\r\n" + 
				"	(NVL(c.MATERIALQUANTITY, 0) -NVL(c2.MATERIALQUANTITY, 0)) AS DifferenceQuantity,c.CHECKPLATATE\r\n" +
				" FROM	CHECKRECORD c \r\n" + 
				" LEFT JOIN CHECKPLAN c2 ON	c.CHECKPLANNAME = c2.CHECKPLANNAME	AND c.ERPLOCATION = c2.ERPLOCATION	\r\n" + 
				" AND c.MATERIALPACKINGNAME = c2.MATERIALPACKINGNAME	AND c.ACTLOCATION = c2.SYSLOCATION \r\n" + 
				" WHERE c.CHECKPLANNAME =:CHECKPLANNAME	AND c.PLANDATE = :PLANDATE )\r\n" + 
				" WHERE DifferenceQuantity>0 AND nvl(CHECKPLATATE,'是')='是' AND nvl(CHECKPLANSTATE,'N')<>'Approved' ";
		List<Map<String, Object>> sr_erp_py = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql_erp_py, bindMap);
		if (sr_erp_py.size() > 0) {
			for (int i = 0; i < sr_erp_py.size(); i++) {
				String erpLocation = sr_erp_py.get(i).get("ERPLOCATION").toString();
				bindMap.put("ERPLOCATION", erpLocation);
				// 查找盘盈的批次
				String sql_py = " SELECT a.*,ABS(DifferenceQuantity)NUM FROM (\r\n" + 
						" SELECT	c.MATERIALPACKINGNAME,c.MATERIALSPECNAME,c.ERPLOCATION,c.ACTLOCATION SYSLOCATION,m.ERPFACTORY,\r\n" + 
						" NVL( c.MATERIALQUANTITY,0) AS MATERIALQUANTITY,NVL(c2.MATERIALQUANTITY, 0) AS MATERIALACTQUANTITY,	\r\n" +
						"	(NVL(c.MATERIALQUANTITY, 0) -NVL(c2.MATERIALQUANTITY, 0)) AS DifferenceQuantity,c.CHECKPLATATE,c.CHECKPLANSTATE,\r\n" +
						"	m.CHARGE ,m.SDK_ID ,m.PHASE ,TO_CHAR(m.EXPIRINGDATE, 'YYYY-MM-DD HH24:MI:SS') expdate,\r\n" + 
						"	TO_CHAR(m.MAKEDATE, 'YYYY-MM-DD HH24:MI:SS') proddate,TO_CHAR(SYSDATE, 'YYYY-MM-DD HH24:MI:SS') indate\r\n" + 
						"	FROM	CHECKRECORD c \r\n" + 
						" LEFT JOIN MATERIALPACKING m ON c.MATERIALPACKINGNAME=m.MATERIALPACKINGNAME\r\n" + 
						" LEFT JOIN CHECKPLAN c2 ON	c.CHECKPLANNAME = c2.CHECKPLANNAME	AND c.ERPLOCATION = c2.ERPLOCATION	\r\n" + 
						" AND c.MATERIALPACKINGNAME = c2.MATERIALPACKINGNAME	AND c.ACTLOCATION = c2.SYSLOCATION \r\n" + 
						" WHERE c.CHECKPLANNAME =:CHECKPLANNAME	AND c.PLANDATE = :PLANDATE AND c.ERPLOCATION =:ERPLOCATION)a\r\n" + 
						" WHERE DifferenceQuantity>0 AND nvl(CHECKPLATATE,'是')='是' AND nvl(CHECKPLANSTATE,'N')<>'Approved' ";
				List<Map<String, Object>> sr_pk = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql_py, bindMap);
				if (sr_pk.size() > 0) {
					// 调用NC接口
					billCode = toSAPServiceImpl.qtcrNoInvoiceForCheckPlan(sr_pk, "qtr", user, commitDate,opCode);
					// 更新盘点计划状态
					String sql = "UPDATE CHECKRECORD c SET CHECKPLANSTATE = 'Approved' WHERE PLANDATE  = :PLANDATE AND CHECKPLANNAME = :CHECKPLANNAME AND ERPLOCATION=:ERPLOCATION";
					IDMFrameServiceProxy.getSqlTemplate().update(sql, bindMap);
					// 更新批次状态
					List<MaterialPackingKey> mpkList = new ArrayList<>();
					for (int j = 0; j < sr_pk.size(); j++) {
						MaterialPackingKey mpk = new MaterialPackingKey();
						mpk.setSiteName(siteName);
						mpk.setMaterialPackingName(sr_pk.get(j).get("MATERIALPACKINGNAME").toString());
						mpkList.add(mpk);
						String sqlu=" UPDATE MATERIALPACKING m SET m.ERPLOCATION =:ERPLOCATION,m.LOCATIONNAME =:LOCATIONNAME\r\n" + 
								" WHERE m.SITENAME =:SITENAME AND m.MATERIALPACKINGNAME =:MATERIALPACKINGNAME ";
						Map<String,Object> bpu=new HashMap<>();
						bpu.put("ERPLOCATION", erpLocation);
						bpu.put("LOCATIONNAME", sr_pk.get(j).get("SYSLOCATION").toString());
						bpu.put("SITENAME", siteName);
						bpu.put("MATERIALPACKINGNAME", sr_pk.get(j).get("MATERIALPACKINGNAME").toString());
						IDMFrameServiceProxy.getSqlTemplate().update(sqlu, bpu);
					}
					SetEventInfo setEventInfo = new SetEventInfo();
					Map<String, Object> userc = new HashMap<>();
					userc.put("unDoID", billCode);
					userc.put("stockState", "Stocked");
					setEventInfo.setUserColumns(userc);
					makeEventInfo = eventInfoUtil.makeEventInfo("StockInForCheckPlan", user, "StockInForCheckPlan");
					MaterialPackingServiceProxy.getMaterialPackingService().setEvent(mpkList, makeEventInfo,
							setEventInfo);
					
					//存储物料凭证
					rs.SaveUnDoInfo(billCode, commitDate);
				}
			}
		}		
		
		return AjaxResult.me().setResultObj(null);
	}
}
