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.po.MaterialReceiveRequest;
import com.cim.idm.response.BaseResponse;
import com.cim.idm.response.RespGenerator;
import com.cim.idm.utils.AjaxResult;
import com.cim.idm.utils.CommonUtils;
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.HashMap;
import java.util.List;
import java.util.Map;
import com.cim.idm.service.Impl.ProductIntoServiceImpl;

/**
 * 成品入库控制器
 * @author ZXYGY17
 *
 */
@RestController
@RequestMapping("/FGStockIn")
@EnableAutoConfiguration
public class FGStockInController {

	@Autowired
	private ProductIntoServiceImpl ProductIntoServiceImpl;

	CommonUtils untils=new CommonUtils();


	/**
	 * 获取成品待入库信息
	 * @param in
	 * @return
	 */
	@RequestMapping(value = "/getBarCode", method = RequestMethod.POST)
	public AjaxResult getBarCode(@RequestBody JSONObject in ){

		MaterialPacking materialPacking = JSON.toJavaObject(in, MaterialPacking.class);
		String materialPackingName = materialPacking.getMaterialPackingName();
		String erpFactory = materialPacking.getErpFactory();
		String erpLocation = materialPacking.getErpLocation();
		String locationName = materialPacking.getLocationName();
		String materialSpecName = materialPacking.getMaterialSpecName();
		//判断条码是否存在且状态是在库,且仓库只能为线边仓（MDC_FLAG = 'Y'）
		String sql = "SELECT\n" +
				"\tM.STOCKSTATE,\n" +
				"\tM.RECEIVEACTNO\n" +
				"FROM\n" +
				"\tMATERIALPACKING M\n" +
				"LEFT JOIN BS_ERPLOCATION be ON\n" +
				"\tM.ERPLOCATION = be.ERPLOCATIONNAME\n" +
				"WHERE\n" +
				"\tbe.MDC_FLAG = 'Y'\n" +
				"\tAND M.MATERIALPACKINGNAME = :MATERIALPACKINGNAME";

		Map<String, Object> bindMap = new HashMap<String, Object>();
		bindMap.put("MATERIALPACKINGNAME",materialPackingName); 
		bindMap.put("ERPFACTORY",erpFactory); 
		bindMap.put("ERPLOCATION",erpLocation); 
		bindMap.put("LOCATIONNAME",locationName); 
		List<Map<String,Object>> list = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql, bindMap);
		if(list.size() > 1) {
			return AjaxResult.me().setSuccess(false).setMessage("条码不止一个,请联系IT处理！");
		}
		if (list.size() == 1) {
			for (Map<String, Object> map : list) {
				if (!"Created".equals(map.get("STOCKSTATE").toString())) {
					return AjaxResult.me().setSuccess(false).setMessage("条码已入库,请联系IT处理！");
				}
			}
		}
		String sql2 = "SELECT\r\n" +
				"	BMS.LOTNAME MATERIALPACKINGNAME,\r\n" + 
				"	BMS.PRODUCTSPECNAME MATERIALSPECNAME,\r\n" +
				"	BMS.PHASE ,BMS.SDK_ID,\r\n" + 
				"	SS.SPECNAME ,\r\n" + 
				"	m.DESC_CN ,\r\n" + 
				"	BMS.QTY MATERIALQUANTITY ,\r\n" + 
				"	BMS.REQUESTNAME RECEIVEREQUESTNAME ,\r\n" + 
				"	BMS.CHARGE,BMS.PACKINGGRADE, :ERPFACTORY ERPFACTORY, :ERPLOCATION ERPLOCATION, :LOCATIONNAME LOCATIONNAME,BMS.MAKEDATE \r\n" + 
				"FROM\r\n" + 
				"	BS_MES_SHIPPED BMS LEFT JOIN MATERIALSPEC m ON m.MATERIALSPECNAME = BMS.PRODUCTSPECNAME \r\n" + 
				"	LEFT JOIN SDK_SPEC SS ON SS.SDK_ID = BMS.SDK_ID \r\n" + 
				"WHERE\r\n" + 
				"	BMS.LOTNAME = :MATERIALPACKINGNAME\r\n" + 
				"	AND (BMS.RECEIVE_FLAG IS NULL\r\n" + 
				"		OR BMS.RECEIVE_FLAG <> 'Y')";
		List<Map<String,Object>> list2 = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql2, bindMap);
		if(list2.size()  < 1) {
			return AjaxResult.me().setSuccess(false).setMessage("未同步标签信息或者标签发生变更无法入库,请联系IT处理！");
		}
		
//		if (list2.get(0).get("MAKEDATE") == null) {
//			return AjaxResult.me().setSuccess(false).setMessage("生产日期为空,请联系IT处理！");
//		}

//		if ("101".equals(erpFactory) || "102".equals(erpFactory)) {

			// 良品与不良品与仓校验
			String packingGrade = list2.get(0).get("PACKINGGRADE") == null ? "" : list2.get(0).get("PACKINGGRADE").toString();
			Boolean judgeMtaerialStateWithERPLocation = untils.JudgeMtaerialStateWithERPLocation(erpLocation, packingGrade);
			if (!judgeMtaerialStateWithERPLocation) {
				throw new GlobalException("仓库类型和物料品质等级不一致");
			}

//		}
//		String wgbg  = "SELECT\r\n" +
//				"	LISTAGG(RECEIVEREQUESTNAME, ',') WITHIN GROUP (\r\n" +
//				"	ORDER BY RECEIVEREQUESTNAME) AS RECEIVEREQUESTNAME,\r\n" +
//				"	SUM(REQTY) AS REQTY,\r\n" +
//				"	SUM(QTY) AS QTY,\r\n" +
//				"	 SDK_ID ,\r\n" +
//				"	 MATERIALSPECNAME ,\r\n" +
//				"	 PHASE\r\n" +
//				"FROM\r\n" +
//				"	(\r\n" +
//				"	SELECT\r\n" +
//				"		M.RECEIVEREQUESTNAME,\r\n" +
//				"		SS.SPECNAME AS SDK_ID,\r\n" +
//				"		M.MATERIALSPECNAME,\r\n" +
//				"		M.PHASE,\r\n" +
//				"		M.REQUESTQUANTITY AS QTY,\r\n" +
//				"		(M.REQUESTQUANTITY - M.RECEIVEDQUANTITY) AS REQTY\r\n" +
//				"	FROM\r\n" +
//				"		BS_MES_SHIPPED BMS\r\n" +
//				"	LEFT JOIN MATERIALRECEIVEREQUESTDETAIL M ON\r\n" +
//				"		(BMS.REQUESTNAME = M.PRODUCTORDER\r\n" +
//				"			OR BMS.REQUESTNAME = M.PLANORDER)\r\n" +
//				"		AND BMS.PRODUCTSPECNAME = M.MATERIALSPECNAME\r\n" +
//				"		AND (NVL(BMS.SDK_ID, '~') = NVL(M.SDK_ID, '~'))\r\n" +
//				"		AND (NVL(BMS.PHASE, '~') = NVL(M.PHASE, '~'))\r\n" +
//				"	LEFT JOIN SDK_SPEC SS ON\r\n" +
//				"		BMS.SDK_ID = SS.SDK_ID\r\n" +
//				"	WHERE\r\n" +
//				"		BMS.LOTNAME = :MATERIALPACKINGNAME   \r\n" +
//				") SUBQUERY\r\n" +
//				"GROUP BY\r\n" +
//				"	SDK_ID ,\r\n" +
//				"	 MATERIALSPECNAME ,\r\n" +
//				"	 PHASE";
//		List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(wgbg, bindMap);
//		if (queryForList ==null || queryForList.size() < 1) {
//			return AjaxResult.me().setSuccess(false).setMessage( list2.get(0).get("RECEIVEREQUESTNAME") + " 无法匹配完工报告，确认完工报告已开立");
//		} else
//		{
//			String sysl = queryForList.get(0).get("REQTY") == null ? "0" : queryForList.get(0).get("REQTY").toString();
//			String djsl = queryForList.get(0).get("QTY") == null ? "0" : queryForList.get(0).get("QTY").toString();
//			if ("0".equals(sysl)) {
//				return AjaxResult.me().setSuccess(false).setMessage(list2.get(0).get("RECEIVEREQUESTNAME") + "的完工报告已为0,不能继续使用");
//			}
//			String djdh = queryForList.get(0).get("RECEIVEREQUESTNAME") == null ? "" : queryForList.get(0).get("RECEIVEREQUESTNAME").toString();
//			list2.get(0).put("REQTY", sysl);
//			list2.get(0).put("QTY", djsl);
//			list2.get(0).put("RECEIVEREQUESTNAME", djdh);
//		}
		
		return AjaxResult.me().setResultObj(list2);
	}


	
	
	/**
	 * 处理FGStockIn请求，用于物料接收
	 * 该方法接收一个JSONObject作为输入，解析并转换为MaterialReceiveRequest对象，然后调用服务方法进行处理
	 *
	 * @param in 包含物料接收信息的JSON对象
	 * @return 返回一个AjaxResult对象，表示操作结果
	 * @throws Exception 如果处理过程中发生异常
	 */
	@RequestMapping(value = "/FGStockIn", method = RequestMethod.POST)
	public BaseResponse<Object> fgStockIn(@RequestBody JSONObject in)   {
	    // 将输入的JSONObject转换为MaterialReceiveRequest对象
	    MaterialReceiveRequest sl = JSON.toJavaObject(in, MaterialReceiveRequest.class);

	    // 获取提交日期
	    String commitDate = sl.getCommitDate();
	    // 获取操作员代码
	    String opCode = sl.getOpCode();
	    // 获取物料包装列表
	    List<com.cim.idm.wmspackage.materialpacking.management.data.MaterialPacking> boxList = sl.getBoxList();
	    // 获取用户信息
	    String user = sl.getUser();

	    // 初始化接收请求实际编号为null
	    String ReceiveRequestActNo = null;

	    // 调用手动入库的方法入库Box
        try {
            ProductIntoServiceImpl.fgStockInByManul(boxList, user, ReceiveRequestActNo, commitDate, opCode);
        } catch (Exception e) {
            return RespGenerator.returnError(e.getMessage());
        }

        // 返回成功结果
	    return RespGenerator.returnOK(null);
	}

}
