package com.icomsys.main_vm.biz.rcp.learningTest.service;


import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;
import com.icomsys.main_vm.biz.advice.excep.CustomNotFoundException;
import com.icomsys.main_vm.biz.advice.excep.CustomBadRequestException;
import com.icomsys.main_vm.biz.common.common.service.LogService;
import com.icomsys.main_vm.biz.common.login.res.UserVo;
import com.icomsys.main_vm.biz.common.system.vo.SystemCommoncodeReq;
import com.icomsys.main_vm.biz.common.system.vo.SystemCommoncodeRes;
import com.icomsys.main_vm.biz.rcp.conversation.nlp.wisenut.service.NlpWisenutService;
import com.icomsys.main_vm.biz.rcp.conversation.nlp.wisenut.vo.NlpSimulationResult;
import com.icomsys.main_vm.biz.rcp.learningTest.vo.LearningTestDummyApiVO;
import com.icomsys.main_vm.common.code.code.LongTextManagerColumnCode;
import com.icomsys.main_vm.common.code.code.LongTextManagerTableCode;
import com.icomsys.main_vm.common.util.HashUtil;
import com.icomsys.main_vm.db.jpa.entity.scenario.TbApiNode;
import com.icomsys.main_vm.db.jpa.entity.scenario.TbLongtextManager;
import com.icomsys.main_vm.db.jpa.entity.scenario.id.TbLongtextManagerId;
import com.icomsys.main_vm.db.jpa.repo.scenario.TbApiNodeRepo;
import com.icomsys.main_vm.db.jpa.repo.scenario.TbLongtextManagerRepo;
import com.icomsys.main_vm.db.jpa.repo.system.TbBotCommonCodeRepo;
import com.icomsys.main_vm.db.mybatis.alias.LoginVO;
import com.querydsl.core.QueryResults;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.annotation.Resource;
import java.security.NoSuchAlgorithmException;
import java.util.Map;

@Service
@Slf4j
@RequiredArgsConstructor
public class LearningTestSimulatorService {

    @Resource
    MappingJackson2JsonView ajaxMainView;
    @Resource(name = "nlpWisenutService")
    private NlpWisenutService nlpAPIService;
    private final LogService logService;
    private final TbBotCommonCodeRepo tbBotCommonCodeRepo;

    private final TbLongtextManagerRepo tbLongtextManagerRepo;
    private final TbApiNodeRepo tbApiNodeRepo;

//    public ModelAndView callSimulator(String oprMngCode, String callId, String token, String userTalk, String methodType) {
    public ModelAndView callSimulator(String oprMngCode, String callId, String token, String userTalk, String methodType, String dnis) {
        ModelAndView mv = new ModelAndView(ajaxMainView);
        NlpSimulationResult result = new NlpSimulationResult();
        try {
//            result = nlpAPIService.simulationApi(oprMngCode, callId, token, userTalk, methodType);
            result = nlpAPIService.simulationApi(oprMngCode, callId, token, userTalk, methodType, dnis);
        } catch(Exception e) {
            log.error("error", e);
            result.setReturnCode("-999");
            result.setReturnMsg("API 호출 오류");
        }
        mv.addObject("result", result);
        return mv;
    }


    public QueryResults<SystemCommoncodeRes> selectCustCallNum (LoginVO resultVO, Map<Object, String> eMap) {

        UserVo userVo = new UserVo();
        userVo.setRoleVal(resultVO.getAuthCode());
        SystemCommoncodeReq dto = new SystemCommoncodeReq();
        dto.setUserVo(userVo);
        dto.setServiceGroup(eMap.get("serviceGroup"));
        dto.setOprmngCode(resultVO.getSiteCode() + "_RCP_" + eMap.get("serviceGroup"));
        return tbBotCommonCodeRepo.SystemCommoncodeCallNumList(dto);

    }

    public LearningTestDummyApiVO selectDummyApi(Long apiSeq) throws CustomNotFoundException {

        TbApiNode apiNode = tbApiNodeRepo.findBySeqAndUseYn(apiSeq, "Y")
                .orElseThrow(() -> new CustomNotFoundException("API 시퀀스 번호가 잘못 되었습니다."));

        LearningTestDummyApiVO result = new LearningTestDummyApiVO();

        TbLongtextManager dummyApi = tbLongtextManagerRepo.findById(
                        new TbLongtextManagerId(apiNode.getSeq(),
                                LongTextManagerTableCode.TB_API_NODE.getCode(),
                                LongTextManagerColumnCode.DUMMY_TEST.getCode()))
                .orElseGet(() -> new TbLongtextManager(apiNode.getSeq(),
                        LongTextManagerTableCode.TB_API_NODE.getCode(),
                        LongTextManagerColumnCode.DUMMY_TEST.getCode(),
                        "",""));

        result.setApiSeq(apiNode.getSeq());
        result.setApiTitle(apiNode.getNodeName());
        result.setJsonContents(dummyApi.getTextContents());
        result.setChecksum(dummyApi.getChecksum());

        return result;
    }

    public int saveDummyApi(LearningTestDummyApiVO dto) throws CustomNotFoundException, CustomBadRequestException {
        String dummyChecksum;
        TbApiNode apiNode = tbApiNodeRepo.findBySeqAndUseYn(dto.getApiSeq(), "Y")
                .orElseThrow(() -> new CustomNotFoundException("API 시퀀스 번호가 잘못 되었습니다."));

        try {
            dummyChecksum = HashUtil.getStringToChecksum(dto.getJsonContents());
        } catch (NoSuchAlgorithmException e) {
            throw new CustomBadRequestException("Dummy API 데이터 해시값 생성에 실패하였습니다.");
        }

        try {
            JsonElement jsonElement = JsonParser.parseString(dto.getJsonContents());
        } catch (JsonSyntaxException e) {
            throw new CustomBadRequestException("Dummy API Json 문법에 오류가 있습니다.");
        }

        TbLongtextManager dummyApi = tbLongtextManagerRepo.findById(
                        new TbLongtextManagerId(apiNode.getSeq(),
                                LongTextManagerTableCode.TB_API_NODE.getCode(),
                                LongTextManagerColumnCode.DUMMY_TEST.getCode()))
                .orElseGet(() -> new TbLongtextManager(apiNode.getSeq(),
                        LongTextManagerTableCode.TB_API_NODE.getCode(),
                        LongTextManagerColumnCode.DUMMY_TEST.getCode(),
                        "",""));

        if (dummyChecksum.equals(dummyApi.getChecksum())) { // 변경된 값이 없음
            return 1;
        }

        dummyApi.setTextContents(dto.getJsonContents());
        dummyApi.setChecksum(dummyChecksum);

        tbLongtextManagerRepo.save(dummyApi);
        return 0;
    }
}
