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

import com.google.gson.Gson;
import com.icomsys.main_vm.biz.rcp.conversation.dto.IntentRequestDTO;
import com.icomsys.main_vm.biz.rcp.conversation.nlp.wisenut.service.NlpWisenutIntentService;
import com.icomsys.main_vm.biz.rcp.conversation.nlp.wisenut.service.NlpWisenutService;
import com.icomsys.main_vm.biz.rcp.conversation.nlp.wisenut.vo.NlpWisenutResult;
import com.icomsys.main_vm.biz.rcp.conversation.nlp.wisenut.vo.SentenceListVO;
import com.icomsys.main_vm.db.mybatis.mapper.NlpWisenutApiMapper;
import org.apache.commons.lang3.StringUtils;
import org.junit.Assert;
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.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

/**
 * @Name NlpWisenutIntentServiceImpl
 * @Description Intent API
 * @Author dongheejang
 * @CreateDate 2022. 06. 17.
 */

@Service("nlpWisenutIntentService")
public class NlpWisenutIntentServiceImpl implements NlpWisenutIntentService {

    @Autowired
    NlpWisenutApiMapper nlpWisenutApiMapper;

    @Autowired
    NlpWisenutService nlpWisenutService;

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

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

    @Value("${nlpapi}")
    private boolean nlp;

    /**
     * @Name intentInsertApi
     * @Description 인텐트 추가 API
     * @Author dongheejang
     * @CreateDate 2022. 06. 17.
     *
     * @param eMap
     * @return NlpWisenutResult
     *
     * @ChangeDescription
     */
    @Override
    public NlpWisenutResult intentInsertApi(HashMap eMap) {

        if (nlp) {
        Gson gson = new Gson();
        HashMap nMap = new HashMap();

        NlpWisenutResult nlpWisenutResult = new NlpWisenutResult();

        boolean result = true;
        long mappingId = 0;
        String returnMsg = "";
        String returnCode = "";

        try {
            long projectId = nlpWisenutApiMapper.selectProjectIdforOprMngCode(eMap); // projectId DB에서 가져오기

            nMap.put("projectId",projectId);
            nMap.put("name",eMap.get("intentName"));
            nMap.put("taskBody","");
            nMap.put("taskType","DirectAnswer"); // TOBE - taskType에 대한 정리 필요
            nMap.put("mainSentence","");


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

            // api request
            String responseBody = 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;
            } else {
                double id = (double) responseMap.get("intentId");
                mappingId = (long) id;
            }

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

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

        return nlpWisenutResult;
        } else {
            return nlpWisenutService.defaultResult();
        }
    }

    /**
     * @Name intentUpdateApi
     * @Description 인텐트 수정 API
     * @Author dongheejang
     * @CreateDate 2022. 06. 17.
     *
     * @param eMap
     * @return NlpWisenutResult
     *
     * @ChangeDescription
     */
    @Override
    public NlpWisenutResult intentUpdateApi(HashMap eMap)  {

        if (nlp) {
        Gson gson = new Gson();
        HashMap nMap = new HashMap();

        NlpWisenutResult nlpWisenutResult = new NlpWisenutResult();

        boolean result = true;
        String returnMsg = "";
        String returnCode = "";

        try {
            long projectId = nlpWisenutApiMapper.selectProjectIdforOprMngCode(eMap); // projectId DB에서 가져오기
            long intentId = nlpWisenutApiMapper.selectIntentId(eMap); // intentId DB에서 가져오기

            nMap.put("projectId",projectId);
            nMap.put("id",intentId);
            nMap.put("name",eMap.get("intentName"));
            nMap.put("taskType","DirectAnswer");
            nMap.put("mainSentence","");
            nMap.put("taskBody","");

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

            // api request
            String responseBody = 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) {
            returnMsg = ex.getMessage();
            result = false;
        }

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

        return nlpWisenutResult;
        } else {
            return nlpWisenutService.defaultResult();
        }
    }

    /**
     * @Name intentDeleteApi
     * @Description 인텐트 삭제 API
     * @Author dongheejang
     * @CreateDate 2022. 06. 17.
     *
     * @param eMap
     * @return NlpWisenutResult
     *
     * @ChangeDescription
     */
    @Override
    public NlpWisenutResult intentDeleteApi(HashMap eMap) {

        if (nlp) {
        Gson gson = new Gson();
        HashMap nMap = new HashMap();

        NlpWisenutResult nlpWisenutResult = new NlpWisenutResult();

        boolean result = true;
        String returnMsg = "";
        String returnCode = "";

        try {
            HashMap pmap = nlpWisenutApiMapper.selectIntentIdForDelete(eMap); // intentId DB에서 가져오기

            nMap.put("projectId",pmap.get("projectId"));
            nMap.put("id",pmap.get("intentId"));

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

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

            Map<String, Object> responseMap = new HashMap<String, Object>();
            responseMap = gson.fromJson(responseBody, responseMap.getClass());
            returnMsg = responseMap.get("returnMsg").toString();
            returnCode = responseMap.get("returnCode").toString();

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

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

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

        return nlpWisenutResult;
        } else {
            return nlpWisenutService.defaultResult();
        }
    }

    /**
     * @Name intentSentenceInsertApi
     * @Description 사용자 질의 추가 API
     * @Author dongheejang
     * @CreateDate 2022. 06. 17.
     *
     * @param eMap
     * @return NlpWisenutResult
     *
     * @ChangeDescription
     */
    @Override
    public NlpWisenutResult intentSentenceInsertApi(HashMap eMap) {

        if (nlp) {
        Gson gson = new Gson();
        HashMap nMap = new HashMap();

        NlpWisenutResult nlpWisenutResult = new NlpWisenutResult();

        boolean result = true;
        long mappingId = 0;
        String returnMsg = "";
        String returnCode = "";

        List<IntentRequestDTO> eList = (List<IntentRequestDTO>) eMap.get("exampleList");


        try {
            long projectId; // projectId DB에서 가져오기
            long intentId; // intentId DB에서 가져오기

            if (StringUtils.isEmpty((String)eMap.get("intentSeq"))) {
                HashMap pMap = nlpWisenutApiMapper.selectIntentIdForDelete(eMap);
                projectId = (long) pMap.get("projectId");
                intentId = (long) pMap.get("intentId");
            } else {
                projectId = nlpWisenutApiMapper.selectProjectIdforOprMngCode(eMap);
                intentId = nlpWisenutApiMapper.selectIntentId(eMap);
            }
            long soeId = 12345678; // soeID

            nMap.put("projectId",projectId);
            nMap.put("intentId",intentId);
            nMap.put("soeId",soeId);

            if (eList.size() > 0) {
                nMap.put("sentence",eList.get(0).getExampleText());
            }

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

            // api request
            String responseBody = 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;
            } else {
                double id = (double) responseMap.get("sentenceId");
                mappingId = (long) id;
            }

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

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

        return nlpWisenutResult;
        } else {
            return nlpWisenutService.defaultResult();
        }
    }

    /**
     * @Name intentSentenceUpdateApi
     * @Description 사용자 질의 수정 API
     * @Author dongheejang
     * @CreateDate 2022. 06. 17.
     *
     * @param eMap
     * @return NlpWisenutResult
     *
     * @ChangeDescription
     */
    @Override
    public NlpWisenutResult intentSentenceUpdateApi(HashMap eMap)  {

        if (nlp) {
        Gson gson = new Gson();
        HashMap nMap = new HashMap();

        NlpWisenutResult nlpWisenutResult = new NlpWisenutResult();

        boolean result = true;
        String returnMsg = "";
        String returnCode = "";

        try {
            long projectId = nlpWisenutApiMapper.selectProjectIdforOprMngCode(eMap); // projectId DB에서 가져오기
            long intentId = nlpWisenutApiMapper.selectIntentId(eMap); // intentId DB에서 가져오기
            long sentenceId = nlpWisenutApiMapper.selectIntentSentenctId(eMap); // sentectId DB에서 가져오기

            nMap.put("projectId",projectId);
            nMap.put("intentId",intentId);
            nMap.put("id",sentenceId);
            nMap.put("sentence",eMap.get("exampleList"));

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

            // api request
            String responseBody = 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) {
            returnMsg = ex.getMessage();
            result = false;
        }

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

        return nlpWisenutResult;
        } else {
            return nlpWisenutService.defaultResult();
        }
    }

    /**
     * @Name intentSentenceDeleteApi
     * @Description 사용자 질의 삭제 API
     * @Author dongheejang
     * @CreateDate 2022. 06. 17.
     *
     * @param eMap
     * @return NlpWisenutResult
     *
     * @ChangeDescription
     */
    @Override
    public NlpWisenutResult intentSentenceDeleteApi(HashMap eMap)  {

        if (nlp) {
        Gson gson = new Gson();
        HashMap nMap = new HashMap();

        NlpWisenutResult nlpWisenutResult = new NlpWisenutResult();

        boolean result = true;
        String returnMsg = "";
        String returnCode = "";

        try {
            HashMap pMap = nlpWisenutApiMapper.selectIntentSentenctIdforDelete(eMap); // projectId DB에서 가져오기 // sentectId DB에서 가져오기

            nMap.put("projectId",pMap.get("projectId"));
            nMap.put("id",pMap.get("sentenceId"));

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

            // api request
            String responseBody = 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) {
            returnMsg = ex.getMessage();
            result = false;
        }

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

        return nlpWisenutResult;
        } else {
            return nlpWisenutService.defaultResult();
        }
    }

    /**
     * @Name intentSentenceInsertAllApi
     * @Description 사용자 질의 다중 추가
     * @Author dongheejang
     * @CreateDate 2023. 04. 21.
     *
     * @param eMap
     * @return NlpWisenutResult
     *
     * @ChangeDescription
     */
    @Override
    public NlpWisenutResult intentSentenceInsertAllApi(HashMap eMap)  {

        if (nlp) {
            Gson gson = new Gson();
            HashMap nMap = new HashMap();

            NlpWisenutResult nlpWisenutResult = new NlpWisenutResult();

            boolean result = true;
            String returnMsg = "";
            String returnCode = "";
//            ArrayList<SentenceListVO> sentenceList = new ArrayList<SentenceListVO>();

            try {
                long projectId = nlpWisenutApiMapper.selectProjectIdforOprMngCode(eMap); // projectId DB에서 가져오기

                nMap.put("projectId",projectId);
                nMap.put("sentenceList",eMap.get("sentenceList"));

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

                // api request
                String responseBody = callNlpApi(path, body, method);
//                String responseBody = "{\"sentenceList\":[{\"intentId\": 114651124, \"soeId\": 12345678, \"sentence\": \"ACB\", \"intentName\": \"1\", \"sentenceId\" : 114651208,\"returnCode\":\"000\"}], \"returnCode\": \"000\", \"returnMsg\": \"Success\"}";
                Map<String, Object> responseMap = new HashMap<String, Object>();
                responseMap = gson.fromJson(responseBody, responseMap.getClass());
                returnCode = responseMap.get("returnCode").toString();
                returnMsg = responseMap.get("returnMsg").toString();

                List<Object> tempList = (List<Object>) responseMap.get("sentenceList");
                List<SentenceListVO> sentenceList = new ArrayList<>();

                for (Object object : tempList) {
                    Map<String, Object> tempMap = (Map<String, Object>) object;

                    SentenceListVO sentenceListVO = new SentenceListVO();
                    sentenceListVO.setSentence((String) tempMap.get("sentence"));
                    sentenceListVO.setIntentName((String) tempMap.get("intentName"));
                    sentenceListVO.setReturnCode((String) tempMap.get("returnCode"));
                    double iIdd = (double) tempMap.get("intentId");
                    long iIdl = (long) iIdd;
                    sentenceListVO.setIntentId(iIdl);
                    double sIdd = (double) tempMap.get("intentId");
                    long sIdl = (long) sIdd;
                    sentenceListVO.setSentenceId(sIdl);

                    sentenceList.add(sentenceListVO);
                }

                if (!sentenceList.isEmpty()) {
                    nlpWisenutResult.setSentenceList(sentenceList);
                }
                if (!returnCode.equals("000")) {
                    result = false;
                }
            } catch (Exception ex) {
                returnMsg = ex.getMessage();
                result = false;
            }

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

            return nlpWisenutResult;
        } else {
            return nlpWisenutService.defaultResult();
        }
    }
}
