package com.cim.idm.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cim.idm.data.ErpMessageLog;
import com.cim.idm.framework.IDMFrameServiceProxy;
import com.cim.idm.framework.util.time.TimeStampUtil;
import com.cim.idm.service.QMSService;
import com.cim.idm.util.MessageLogUtil;
import com.cim.idm.util.NCHttpUtil;
import com.cim.idm.util.QMSHttpUtil;
import com.cim.idm.wmsextend.generic.errorHandler.CustomException;
import com.cim.idm.wmsextend.generic.util.ConvertUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * QMS接口实现类
 * @author ZXYGY17
 *
 */
@Service
public class QMSServiceImpl implements QMSService{
	
	@Autowired
	QMSHttpUtil qmsHttpUtil;

	private static String  baseUrl = "http://192.168.1.72:9913";
	
	/**
	 * 质检信息发送QMS
	 * @throws CustomException 
	 */
	@Override
	public String PreIQCInfoSend(String receiveActNo, String siteName,String opCode, String erpFactory) throws CustomException {
//		if (1 == 1) return "";
		//根据入库单获取要发送QMS入库的信息
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT\r\n" +
				"		 T.SITENAME , BE.DESCRIPTION ERPLOCATIONDESC,T.LOCATIONNAME, \r\n" +
				"		 T.RECEIVEREQUESTNAME deliveryNumber, \r\n" +
				"		 TO_CHAR(T.RECEIVETIME ,'YYYY-MM-DD' ) deliveryDate, \r\n" +
				"		 T.RECEIVEREQUESTNAME , \r\n" +
				"		 M3.MATERIALSPECNAME materialCode, \r\n" +
				"		 M3.DESC_CN materialName, \r\n" +
				"		 M3.MATERIALGROUP materialGroup, \r\n" +
				"		 COUNT(DISTINCT T.CHARGE ) batchQuantity, \r\n" +
				"		 T.UNIT quantityUnit, \r\n" +
				"		 S.SUPPLIERNO SUPPLIERCODE, \r\n" +
				"		 S.SUPPLIERNAME SUPPLIERNAME, \r\n" +
				"		 SUBSTR(T.TRUEGG , 1, INSTR(T.TRUEGG , '*') - 1) BATCHNUMBER,\r\n" +
				"						 LISTAGG(DISTINCT T.CHARGE , ';')  WITHIN GROUP (ORDER BY T.CHARGE) AS LOTS \r\n" +
				"FROM\r\n" +
				"	MATERIALPACKINGSUB TT\r\n" +
				"LEFT JOIN MATERIALPACKING T ON\r\n" +
				"	TT.MATERIALPACKINGNAME = T.MATERIALPACKINGNAME\r\n" +
				"LEFT JOIN MATERIALRECEIVEREQUESTDETAIL M\r\n" +
				"						 ON\r\n" +
				"	TT.RECEIVEREQUESTNAME = M.RECEIVEREQUESTNAME\r\n" +
				"	AND TT.RECEIVEREQUESTDETAILNAME = M.RECEIVEREQUESTDETAILNAME\r\n" +
				"LEFT JOIN MATERIALRECEIVEREQUEST M2\r\n" +
				"						  ON\r\n" +
				"	TT.RECEIVEREQUESTNAME = M2.RECEIVEREQUESTNAME\r\n" +
				"LEFT JOIN SUPPLIER S ON\r\n" +
				"	S.SUPPLIERNO = T.SUPPLIERNAME \r\n" +
				"LEFT JOIN SDK_SPEC SS ON\r\n" +
				"	SS.SDK_ID = T.SDK_ID\r\n" +
				"	LEFT JOIN MATERIALSPEC m3 ON T.MATERIALSPECNAME = m3.MATERIALSPECNAME LEFT JOIN  BS_ERPLOCATION BE ON M.ERPLOCATION = BE.ERPLOCATIONNAME  \r\n" +
				"WHERE\r\n" +
				"	T.RECEIVEREQUESTNAME = :RECEIVEREQUESTNAME\r\n" +
				"	AND T.SITENAME = :SITENAME\r\n" +
				"	AND T.STOCKSTATE = 'Created' \r\n" +
				"	AND m3.IQCFLAG = 'Y'\r\n" +
				"	GROUP BY  T.SITENAME , BE.DESCRIPTION,\r\n" +
				"		 T.RECEIVEREQUESTNAME , \r\n" +
				"		 TO_CHAR(T.RECEIVETIME ,'YYYY-MM-DD' )  ,\r\n" +
				"		 M3.MATERIALSPECNAME , \r\n" +
				"		 M3.DESC_CN , \r\n" +
				"		 M3.MATERIALGROUP , \r\n" +
				"		 T.UNIT , \r\n" +
				"		 S.SUPPLIERNO , \r\n" +
				"		 S.SUPPLIERNAME , \r\n" +
				"		 SUBSTR(T.TRUEGG , 1, INSTR(T.TRUEGG , '*') - 1)  ,T.LOCATIONNAME");
		Map<String, Object> hashMap = new HashMap<String, Object> ();
		hashMap.put("RECEIVEREQUESTNAME", receiveActNo);
		hashMap.put("SITENAME", siteName);
		List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql.toString(), hashMap);
		if (queryForList == null || queryForList.size() < 1) {
			return "";
		}
		String makePreIQCInfoSendJson = MakePreIQCInfoSendJson(queryForList,opCode,receiveActNo, erpFactory);
		String httpPost = NCHttpUtil.httpPost(baseUrl + "/iqc/select/number", makePreIQCInfoSendJson);
		org.json.JSONObject jsonObject = new org.json.JSONObject(httpPost);
		String code = jsonObject.getString("code");
		if (!"00000".equals(code)) {

		}
//		String msg = jsonObject.getString("msg");
		//JSONObject object = (JSONObject) jsonObject.get("data");
		Thread t = new Thread(new Runnable(){
			public void run(){
				// run方法具体重写
				UUID uuid = UUID.randomUUID();
				ErpMessageLog erplog = new ErpMessageLog();
				erplog.setEventUser("");
				erplog.setServerName("WmsToQMS");
				erplog.setEventName("PreIQCInfoSend");
				erplog.setId(uuid.toString());
				erplog.setInterfaceTime(ConvertUtil.getCurrTime("yyyy-MM-dd HH:mm:ss"));
				erplog.setMessageId(UUID.randomUUID().toString());
				erplog.setSendMsg(makePreIQCInfoSendJson);
				erplog.setReturnMsg2(httpPost.toString());
				erplog.setResultCode(code);
				MessageLogUtil.writeMessageLog(erplog);
			}});
		t.start();
		return code;

	}


	/**
	 * 组装IQC检验信息
	 *
	 * @param list
	 * @return
	 */
	public String MakePreIQCInfoSendJson (List<Map<String, Object>> list,String opCode, String receiveActNo, String erpFactory) {

		if (list == null || list.size() < 1) {
			return null;
		}
		JSONArray jsonArray = new JSONArray();
		for (int i = 0; i < list.size(); i++) {
			JSONObject jsonObject = new JSONObject(true);
//			       "deliveryNumber": "SDK20240511003",
//			         "supplierName": "BOE",
//			         "supplierCode": "0000102038",
//			         "materialName": "胶带",
//			         "materialCode": "2F08S4J4",
//			         "materialGroup": "A40001",
//			         "batchQuantity": 10,
//			         "quantityUnit": "1",
//			         "deliveryDate": "2024-1-1 12:2:2"
			jsonObject.put("opCode", opCode);
			jsonObject.put("deliveryNumber", opCode);
			jsonObject.put("warehouse", list.get(i).get("ERPLOCATIONDESC"));
			jsonObject.put("supplierName", list.get(i).get("SUPPLIERNAME"));
			jsonObject.put("supplierCode", list.get(i).get("SUPPLIERCODE"));
			jsonObject.put("materialName", list.get(i).get("MATERIALNAME"));
			jsonObject.put("materialCode", list.get(i).get("MATERIALCODE"));
			jsonObject.put("materialGroup", list.get(i).get("MATERIALGROUP"));
			jsonObject.put("batchQuantity", list.get(i).get("BATCHQUANTITY"));
			jsonObject.put("quantityUnit", list.get(i).get("QUANTITYUNIT"));
			jsonObject.put("deliveryDate", list.get(i).get("DELIVERYDATE"));
			jsonObject.put("specifications", list.get(i).get("BATCHNUMBER"));
			jsonObject.put("LOCATIONNAME", list.get(i).get("LOCATIONNAME"));
			jsonObject.put("inspector", "检验室(原材仓)");


			String factoryArea = "";
			if("103".equals(erpFactory)) {
				factoryArea = "tc";
			}else if("105".equals(erpFactory)) {
				factoryArea = "cq";
			}else if("106".equals(erpFactory)){
				factoryArea = "dg";
			}else {
				factoryArea = "sh";
			}
			// 入库单号和厂区
			jsonObject.put("transferOrderNumber", receiveActNo);
			jsonObject.put("factoryArea", factoryArea);

			String lots = list.get(i).get("LOTS") == null ? "" : list.get(i).get("LOTS").toString();
			String[] split = lots.split("\\;");
			JSONArray jsonArray2 = new JSONArray ();
			for (int j = 0; j < split.length; j++) {
				jsonArray2.add(split[j]);
			}
			jsonObject.put("lots", jsonArray2);
			jsonArray.add(jsonObject);
		}

		return jsonArray.toJSONString();

	}

	//通用的发送QMS消息。zd.2024.8.10
		public String QMSInfoSend(String receiveActNo, String siteName,String qmsType) throws CustomException {
			//qmsType 场景  0：IQC	1：出货检	2：销售退货	 3：过期复检
			//if (1 == 1) return "";
			// 将ArrayList转换为数组  
			//String[] lots = mpList.toArray(new String[0]); // 或者使用 new String[mpList.size()]
			//根据receiveActNo获取要发送QMS的信息
			String sql=" SELECT m.MATERIALSPECNAME,s.DESC_CN ,s.WIDTH ,s.MATERIALUNIT ,s.MATERIALGROUP ,max(m.ERPLOCATION)ERPLOCATION,  \r\n" + 
					"										 max(m.BUSINESS_UNIT)BUSINESS_UNIT,sum(m.MATERIALQUANTITY)QTY ,LISTAGG(m.CHARGE, ',') WITHIN GROUP (ORDER BY m.CHARGE)CHARGE  \r\n" + 
					"										 ,M.SUPPLIERNAME SUPPLIERCODE,(SELECT S.SUPPLIERNAME FROM SUPPLIER s WHERE S.SUPPLIERNO=M.SUPPLIERNAME)SUPPLIERNAME\r\n" + 
					"										 FROM MATERIALPACKING m ,MATERIALSPEC s ,BS_MATERIALFACTORY bm  \r\n" + 
					"										 WHERE m.RECEIVEACTNO =:RECEIVEACTNO  \r\n" + 
					"										 AND m.SITENAME =:SITENAME  \r\n" + 
					"										 AND m.MATERIALSPECNAME =s.MATERIALSPECNAME   \r\n" + 
					"										 AND m.MATERIALSPECNAME =bm.MATERIALSPECNAME \r\n" + 
					"										 AND m.ERPFACTORY=bm.ERPFACTORY \r\n" + 
					"										 AND nvl(bm.IQCFLAG,'N')='Y' \r\n" + 
					"										 GROUP BY m.MATERIALSPECNAME,s.DESC_CN ,s.WIDTH ,s.MATERIALUNIT ,s.MATERIALGROUP,M.SUPPLIERNAME";
			
			Map<String, Object> hashMap = new HashMap<String, Object> ();
			hashMap.put("RECEIVEACTNO", receiveActNo);
			hashMap.put("SITENAME", siteName);
			List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql.toString(), hashMap);
			String code="";
			if(queryForList.size()>0) 
			{
				String makeQMSSendJson = MakeQMSSendJson(queryForList, qmsType, receiveActNo);
				String httpPost = NCHttpUtil.httpPost(baseUrl + "/apitest/sdkqms/wms/generalQualityInspection", makeQMSSendJson);
				org.json.JSONObject jsonObject = new org.json.JSONObject(httpPost);
				code = jsonObject.getString("code");
	//			if (!"00000".equals(code)) {
	//				throw new CustomException("ACTSTATEERROR","","");
	//			}
	//			String msg = jsonObject.getString("msg");
				//JSONObject object = (JSONObject) jsonObject.get("data");
	
				// 写log
				ErpMessageLog erplog = new ErpMessageLog();
				erplog.setEventUser("");
				erplog.setServerName("WmsToQMS");
				erplog.setEventName("QMSInfoSend");
				erplog.setInterfaceTime(TimeStampUtil.getCurrentTime(TimeStampUtil.FORMAT_DEFAULT));
				erplog.setMessageId(UUID.randomUUID().toString());
				erplog.setSendMsg2(makeQMSSendJson);
				erplog.setReturnMsg2(httpPost.toString());
				erplog.setResultCode(code);
				MessageLogUtil.writeMessageLog(erplog);  
			}
			return code;
			
		}
		
		//组装发送QMS的json
		public String MakeQMSSendJson (List<Map<String, Object>> list,String qmsType,String receiveActNo) {
			
			if (list == null || list.size() < 1) {
				return null;
			}
//			{
//				"data": {
//					"inspectionScenario": "0",
//					"infoList": [
//						{
//			                "commonNumber":"1",
//			                "warehouse":"1",
//			                "deliveryDate":"2024-4-20",
//			                "shippingDate":"2024-4-20",
//							"materialCode": "code001",
//							"materialName": "testName",
//							"materialGroup": "物料组4",
//							"specification": "1",
//							"modelNumber": "1",
//							"stage": "1",
//							"classes": "1",
//							"shift": "1",
//							"quantity": "5",
//							"unit": "1",
//							"lot": ["lot4,lot5,lot6"],
//						},
//						{
//			                "commonNumber":"1",
//			                "warehouse":"1",
//			                "deliveryDate":"2024-4-20",
//			                "shippingDate":"2024-4-20",
//							"materialCode": "code001",
//							"materialName": "testName",
//							"materialGroup": "物料组4",
//							"specification": "1",
//							"modelNumber": "1",
//							"stage": "1",
//							"classes": "1",
//							"shift": "1",
//							"quantity": "5",
//							"unit": "1",
//							"lot": ["lot1,lot2,lot3"],
//						},
//					]
//				}
//			}
			
			JSONObject sendData = new JSONObject(true);
	        
	        JSONObject data = new JSONObject(true);
	        sendData.put("data", data);
	        JSONArray infoArray = new JSONArray();
	        
	        data.put("inspectionScenario", qmsType);
	        data.put("infoList", infoArray);
	        for (Map<String, Object> mm : list) 
	        {
	            JSONObject item = new JSONObject(true);
	            
	            item.put("commonNumber", receiveActNo);
	            item.put("warehouse", mm.get("ERPLOCATION"));
	            item.put("deliveryDate", TimeStampUtil.getCurrentTime("yyyy-MM-dd"));
	            item.put("shippingDate", TimeStampUtil.getCurrentTime("yyyy-MM-dd"));
	            item.put("materialCode", mm.get("MATERIALSPECNAME"));
	            item.put("materialName", mm.get("DESC_CN"));
	            item.put("materialGroup", mm.get("MATERIALGROUP"));
	            item.put("specification", mm.get("WIDTH"));
	            item.put("modelNumber", mm.get("MATERIALSPECNAME"));
	            //item.put("stage", mm.get("MATERIALSPECNAME"));
	            //item.put("classes", mm.get("MATERIALGROUP"));
	            item.put("businessUnit", mm.get("BUSINESS_UNIT"));
	            item.put("quantity", mm.get("QTY"));
	            item.put("unit", mm.get("MATERIALUNIT"));
	            item.put("lot", mm.get("CHARGE").toString().split(","));
	            item.put("supplierCode", mm.get("SUPPLIERCODE"));
	            item.put("supplierName", mm.get("SUPPLIERNAME"));
	            
	            infoArray.add(item);
	        }
	        
			return sendData.toJSONString();
			
		}

		//组装熟化库成品检发送QMS的json
			public String MakeSHQMSSendJson (List<Map<String, Object>> list,String qmsType,String receiveActNo) {
				
				if (list == null || list.size() < 1) {
					return null;
				}

//				{
//				    "data": {
//				        "source": "MES",
//				        "dispatchOrderNumber": "7-23-orderTest1",
//				        "workShop": "111",
//				        "productionLine": "222",
//				        "businessUnit": "涂布",
//				        "materialCode": "code001",
//				        "materialName": "testName",
//				        "materialGroup": "物料组4",
//				        "specification": "1",
//				        "modelNumber": "1",
//				        "stage": "1",
//				        "classes": "1",
//				        "shift": "1",
//				        "quantity": "5",
//				        "unit": "1",
//				        "machine": "1",
//				        "remark": "1",
//				        "motherRoll": "",
//				        "lot": [],
//				        "ifCured": "0"
//				    }
//				}
				JSONObject sendData = new JSONObject(true);
		        
		        JSONObject data = new JSONObject(true);
		        sendData.put("data", data);
		       
		        
		        data.put("source", qmsType);
		        data.put("dispatchOrderNumber", "");
		        data.put("workShop", qmsType);
		        data.put("productionLine", "");
		        data.put("businessUnit", qmsType);
		        data.put("materialCode", "");
		        data.put("materialName", qmsType);
		        data.put("materialGroup", "");
		        data.put("specification", qmsType);
		        data.put("modelNumber", "");
		        data.put("stage", qmsType);
		        data.put("classes", "");
		        data.put("shift", qmsType);
		        data.put("quantity", "");
		        data.put("unit", qmsType);
		        data.put("machine", "");
		        data.put("remark", qmsType);
		        data.put("motherRoll", "");
		        data.put("lot", qmsType);
		        data.put("ifCured", ""); 
		        
				return sendData.toJSONString();
				
			}


	public String TCDBIQCInfoSend( String opCode,String shiprequestName,String erpFactory) throws CustomException {
//		if (1 == 1) return "";
		//根据入库单获取要发送QMS入库的信息
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT T.SITENAME,\r\n" +
				"       BE.DESCRIPTION ERPLOCATIONDESC,\r\n" +
				"       T.LOCATIONNAME,\r\n" +
				"       TO_CHAR(T.RECEIVETIME, 'YYYY-MM-DD') deliveryDate,\r\n" +
				"       M3.MATERIALSPECNAME materialCode,\r\n" +
				"       M3.DESC_CN materialName,\r\n" +
				"       M3.MATERIALGROUP materialGroup,\r\n" +
				"       COUNT(DISTINCT T.CHARGE) batchQuantity,\r\n" +
				"       T.UNIT quantityUnit,\r\n" +
				"       S.SUPPLIERNO SUPPLIERCODE,\r\n" +
				"       S.SUPPLIERNAME SUPPLIERNAME,\r\n" +
				"       T.TRUEGG BATCHNUMBER,\r\n" +
				"       LISTAGG(DISTINCT T.CHARGE, ';') WITHIN GROUP(ORDER BY T.CHARGE) AS LOTS\r\n" +
				"  FROM MATERIALPACKING T\r\n" +
				"  LEFT JOIN SUPPLIER S\r\n" +
				"    ON S.SUPPLIERNO = T.SUPPLIERNAME\r\n" +
				"  LEFT JOIN SDK_SPEC SS\r\n" +
				"    ON SS.SDK_ID = T.SDK_ID\r\n" +
				"  LEFT JOIN MATERIALSPEC m3\r\n" +
				"    ON T.MATERIALSPECNAME = m3.MATERIALSPECNAME\r\n" +
				"  LEFT JOIN BS_ERPLOCATION BE\r\n" +
				"    ON T.ERPLOCATION = BE.ERPLOCATIONNAME\r\n" +
				"   AND T.ERPFACTORY = BE.ERPFACTORYNAME\r\n" +
				" WHERE T.MESSAGEID = :MESSAGEID\r\n" +
				"   AND T.OQARESULTSTATE <> 'END'\r\n" +
				" GROUP BY T.SITENAME,\r\n" +
				"          BE.DESCRIPTION,\r\n" +
				"          TO_CHAR(T.RECEIVETIME, 'YYYY-MM-DD'),\r\n" +
				"          M3.MATERIALSPECNAME,\r\n" +
				"          M3.DESC_CN,\r\n" +
				"          M3.MATERIALGROUP,\r\n" +
				"          T.UNIT,\r\n" +
				"          S.SUPPLIERNO,\r\n" +
				"          S.SUPPLIERNAME,\r\n" +
				"          T.TRUEGG,\r\n" +
				"          T.LOCATIONNAME");
		Map<String, Object> hashMap = new HashMap<String, Object> ();
		hashMap.put("MESSAGEID", opCode);
		List<Map<String, Object>> queryForList = IDMFrameServiceProxy.getSqlTemplate().queryForList(sql.toString(), hashMap);
		if (queryForList == null || queryForList.size() < 1) {
			return "";
		}
		String makePreIQCInfoSendJson = MakePreIQCInfoSendJson(queryForList,opCode, shiprequestName, erpFactory);
		String httpPost = NCHttpUtil.httpPost(baseUrl + "/iqc/select/number", makePreIQCInfoSendJson);
		org.json.JSONObject jsonObject = new org.json.JSONObject(httpPost);
		String code = jsonObject.getString("code");
		if (!"00000".equals(code)) {

		}
//		String msg = jsonObject.getString("msg");
		//JSONObject object = (JSONObject) jsonObject.get("data");
		Thread t = new Thread(new Runnable(){
			public void run(){
				// run方法具体重写
				UUID uuid = UUID.randomUUID();
				ErpMessageLog erplog = new ErpMessageLog();
				erplog.setEventUser("");
				erplog.setServerName("WmsToQMS");
				erplog.setEventName("PreIQCInfoSend");
				erplog.setId(uuid.toString());
				erplog.setInterfaceTime(ConvertUtil.getCurrTime("yyyy-MM-dd HH:mm:ss"));
				erplog.setMessageId(UUID.randomUUID().toString());
				erplog.setSendMsg(makePreIQCInfoSendJson);
				erplog.setReturnMsg2(httpPost.toString());
				erplog.setResultCode(code);
				MessageLogUtil.writeMessageLog(erplog);
			}});
		t.start();
		return code;

	}
	
}
