package com.icomsys.main_vm.biz.rcp.conversation.nlp.wisenut.service.impl;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.LongSerializationPolicy;
import com.icomsys.main_vm.biz.rcp.conversation.nlp.wisenut.service.NlpWisenutService;
import com.icomsys.main_vm.biz.rcp.conversation.nlp.wisenut.util.RestTemplateUtil;
import com.icomsys.main_vm.biz.rcp.conversation.nlp.wisenut.vo.InferenceAPIResponseDTO;
import com.icomsys.main_vm.biz.rcp.conversation.nlp.wisenut.vo.NlpWisenutResult;
import com.icomsys.main_vm.biz.rcp.conversation.nlp.wisenut.vo.NlpSimulationResult;
import com.icomsys.main_vm.db.mybatis.mapper.NlpWisenutApiMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

import static com.icomsys.main_vm.biz.rcp.conversation.nlp.wisenut.util.RestTemplateUtil.callNlpApi;

@Service("nlpWisenutService")
public class NlpWisenutServiceImpl  implements NlpWisenutService {

	private static final Logger LOGGER = LoggerFactory.getLogger(NlpWisenutServiceImpl.class);

	@Autowired
	NlpWisenutApiMapper nlpWisenutApiMapper;

	@Value("${spring.config.activate.on-profile}")
	private String serviceActive;

	@Value("${feign.url.nlp}")
	private String nlpApi;

	@Value("${feign.url.cinnamon}")
	private String cinnamonApi;

	// 필요시 DAO 추가
//	@Resource(name = "xxxDAO")
//	private XxxDAO xxxDAO;

	@Override
	public NlpWisenutResult projectSettingApi()   {
		Gson gson = new Gson();
		NlpWisenutResult nlpWisenutResult = new NlpWisenutResult();
		boolean result = true;
		long mappingId = 0;

		try {
			// 필요시 DB에서 data 가져오기

			// request param setting
			String path = nlpApi + "/path";
			String body = gson.toJson("");
			HttpMethod method = HttpMethod.POST;

			// api request
			String responseBody = RestTemplateUtil.callNlpApi(path, body, method);
			Map<String, Object> responseMap = new HashMap<String, Object>();
			responseMap = gson.fromJson(responseBody, responseMap.getClass());

			double id = (double) responseMap.get("id");
			mappingId = (long) id;
		} catch (Exception ex) {
			LOGGER.error(ex.getMessage());
			result = false;
		}

		nlpWisenutResult.setResult(result);
		nlpWisenutResult.setMappingId(mappingId);
		// api에서 여러 데이터를 한번에 처리해서 return 받는 id가 여러개인 경우
//		nlpWisenutResult.setMappingIds(List<String>);

		return nlpWisenutResult;
	}

	// 의도추론 테스트 API 연동
	@Override
	public InferenceAPIResponseDTO multiQueryApi(int projectId, String[] query)   {
		GsonBuilder gb = new GsonBuilder();
		gb.setLongSerializationPolicy(LongSerializationPolicy.STRING);
		Gson gson = gb.create();
		InferenceAPIResponseDTO responseDTO = new InferenceAPIResponseDTO();
		try {
			// request param setting
			String path = nlpApi + "/intent/multiQuery";
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("projectId", projectId);
			params.put("query", query);
			String body = gson.toJson(params);
			HttpMethod method = HttpMethod.POST;

			// api request
			String responseBody = RestTemplateUtil.callNlpApi(path, body, method);
			responseDTO = gson.fromJson(responseBody, InferenceAPIResponseDTO.class);
		} catch (Exception ex) {
			responseDTO.setReturnCode("-999");
			responseDTO.setReturnMsg("API 호출 오류");
			LOGGER.error(ex.getMessage());
		}
		return responseDTO;
	}

	// 시뮬레이터 API 호출
	@Override
	public NlpSimulationResult simulationApi(String oprMngCode, String callId, String token, String userTalk, String methodType, String dnis)   {
		Gson gson = new Gson();
		NlpSimulationResult nlpSimulationResult = new NlpSimulationResult();

//		String dnis = "";
//
//		if ("local".equals(serviceActive) || "dev".equals(serviceActive)) {
//			if (oprMngCode.equals("UPLUS_RCP_AISTORE")) {
//				// 요식업
//				dnis = "07075999946";
//			} else {
//				// 유통업
//				dnis = "07075999943";
//			}
//		} else if ("stg".equals(serviceActive)) {
//			if (oprMngCode.equals("UPLUS_RCP_AISTORE")) {
//				// 요식업
//				dnis = "07075999956";
//			} else {
//				// 유통업
//				dnis = "07075999955";
//			}
//		} else if ("pro".equals(serviceActive)) {
//			if (oprMngCode.equals("UPLUS_RCP_AISTORE")) {
//				// 요식업
//				dnis = "07040066981";
//			} else {
//				// 유통업
//				dnis = "07040066982";
//			}
//		}

		try {
			// request param setting
			Map<String, String> bodyMap = new HashMap<String, String>();
			bodyMap.put("talkText", userTalk);
			bodyMap.put("mentType", "CHAT");
			bodyMap.put("oprMngCode", oprMngCode);
			bodyMap.put("method", methodType);
			bodyMap.put("callId", callId);
			bodyMap.put("telNo", "01012341234");
			bodyMap.put("dnis", dnis);
			bodyMap.put("downtownNum ", dnis);
			bodyMap.put("token", token);
			bodyMap.put("transactionId", "0");
			bodyMap.put("sttRecordFilePath", "");
			bodyMap.put("ttsRecordFilePath", "");

			String path = cinnamonApi + "/platform/api/simulation";
			String body = gson.toJson(bodyMap);
			System.out.println(body);
			HttpMethod method = HttpMethod.POST;

			// api request
			String responseBody = RestTemplateUtil.callNlpApi(path, body, method);

			Map<String, Object> responseMap = new HashMap<String, Object>();
			responseMap = gson.fromJson(responseBody, responseMap.getClass());
			Map<String, Object> vbParam = (Map<String, Object>) responseMap.get("data");
			Map<String, String> paramMap = (Map<String, String>) vbParam.get("vbData");

			String returnCode = String.valueOf(Double.valueOf(String.valueOf(responseMap.get("resultCode"))).intValue());

			nlpSimulationResult.setToken(String.valueOf(responseMap.get("token")));
			nlpSimulationResult.setReturnCode(returnCode);
			nlpSimulationResult.setReturnMsg("성공");
			nlpSimulationResult.setBotTalk(responseMap.get("announceMents") == null ? "" : responseMap.get("announceMents").toString());
			nlpSimulationResult.setIntentId(vbParam.get("intentId") == null ? "" : vbParam.get("intentId").toString());
			nlpSimulationResult.setIntentName(vbParam.get("intentName") == null ? "" : vbParam.get("intentName").toString());
			nlpSimulationResult.setIntentScore(vbParam.get("score") == null ? "" : vbParam.get("score").toString() + " %");
			nlpSimulationResult.setParameter(paramMap);

		} catch (Exception ex) {
			LOGGER.error(ex.getMessage());
		}

		return nlpSimulationResult;
	}

	// 학습 시작 api
	@Override
	public NlpWisenutResult trainingStartApi(String oprMngCode)  {
		Gson gson = new Gson();
		HashMap nMap = new HashMap();

		NlpWisenutResult nlpWisenutResult = new NlpWisenutResult();
		boolean result = true;
		String returnMsg = "";
		String returnCode = "";

		HashMap eMap = new HashMap();

		try {
			eMap.put("serviceCode",oprMngCode);
			long projectId = nlpWisenutApiMapper.selectProjectId(eMap); // projectId DB에서 가져오기

			nMap.put("projectId", projectId);

			// request param setting
			String path = nlpApi + "/training/start";
			String body = gson.toJson(nMap);
			HttpMethod method = HttpMethod.POST;

			// api request
			String responseBody = RestTemplateUtil.callNlpApi(path, body, method);
			Map<String, Object> responseMap = new HashMap<String, Object>();
			responseMap = gson.fromJson(responseBody, responseMap.getClass());
			returnCode = responseMap.get("returnCode").toString();
			returnMsg = responseMap.get("returnMsg").toString();

			if (!returnCode.equals("000")) {
				result = false;
			}

		} catch (Exception ex) {
			LOGGER.error(ex.getMessage());
			result = false;
		}

		nlpWisenutResult.setResult(result);
		nlpWisenutResult.setReturnCode(returnCode);
		nlpWisenutResult.setReturnMsg(returnMsg);

		return nlpWisenutResult;
	}

	// 모델 반영 api
	@Override
	public NlpWisenutResult trainingApplyApi(String oprMngCode) {
		Gson gson = new Gson();
		HashMap nMap = new HashMap();

		NlpWisenutResult nlpWisenutResult = new NlpWisenutResult();
		boolean result = true;
		String returnMsg = "";
		String returnCode = "";

		HashMap eMap = new HashMap();

		try {
			eMap.put("serviceCode",oprMngCode);
			long projectId = nlpWisenutApiMapper.selectProjectId(eMap); // projectId DB에서 가져오기

			nMap.put("projectId", projectId);

			// request param setting
			String path = nlpApi + "/training/apply";
			String body = gson.toJson(nMap);
			HttpMethod method = HttpMethod.POST;

			// api request
			String responseBody = RestTemplateUtil.callNlpApi(path, body, method);
			Map<String, Object> responseMap = new HashMap<String, Object>();
			responseMap = gson.fromJson(responseBody, responseMap.getClass());
			returnCode = responseMap.get("returnCode").toString();
			returnMsg = responseMap.get("returnMsg").toString();

			if (!returnCode.equals("000")) {
				result = false;
			}

		} catch (Exception ex) {
			LOGGER.error(ex.getMessage());
			result = false;
		}

		nlpWisenutResult.setResult(result);
		nlpWisenutResult.setReturnCode(returnCode);
		nlpWisenutResult.setReturnMsg(returnMsg);

		return nlpWisenutResult;
	}

	@Override
	public NlpWisenutResult defaultResult()  {
		long id = 0;
		NlpWisenutResult nlpWisenutResult = new NlpWisenutResult();
		nlpWisenutResult.setResult(true);
		nlpWisenutResult.setMappingId(id);
		return nlpWisenutResult;
	}
}