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

import com.google.gson.Gson;
import com.icomsys.main_vm.biz.common.common.service.LogService;
import com.icomsys.main_vm.biz.common.common.service.LogVO;
import com.icomsys.main_vm.biz.rcp.conversation.nlp.wisenut.service.NlpWisenutProjectService;
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.vo.ProjectSettingVO;
import com.icomsys.main_vm.biz.rcp.conversation.vo.SelectSimilarityCriteriaVO;
import com.icomsys.main_vm.common.code.enumresource.ActionResource;
import com.icomsys.main_vm.common.code.enumresource.MenuResource;
import com.icomsys.main_vm.db.jpa.repo.conversation.TbProjectSettingRepo;
import com.icomsys.main_vm.db.mybatis.alias.LoginVO;
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 javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
@Slf4j
public class NlpSettingService {

    @Resource(name = "nlpWisenutService")
    private NlpWisenutService nlpAPIService;

    private final LogService logService;
    private final HttpServletRequest request;
    private final HttpServletResponse response;
    private final MappingJackson2JsonView ajaxMainView;
    private final TbProjectSettingRepo tbProjectSettingRepo;
    private final NlpWisenutProjectService nlpWisenutProjectService;

    public ModelAndView similarityCriteria(Map<String, String> dataMap) {
        log.info("similarityCriteria param - {}", new Gson().toJson(dataMap));
        ModelAndView mv = new ModelAndView(ajaxMainView);
        String oprMngCode = dataMap.get("custCode") + "_RCP_" + dataMap.get("serviceGroup") == null ? null : dataMap.get("custCode") + "_RCP_" + dataMap.get("serviceGroup");
        List<SelectSimilarityCriteriaVO> nList = tbProjectSettingRepo.selectSimilarityCriteria(oprMngCode);

        mv.addObject("nMap", nList);

        return mv;
    }

    public ModelAndView updateUser(Map<String, String> dataMap) {
        LoginVO resultVO = (LoginVO) request.getSession().getAttribute("LoginVO");

        ProjectSettingVO vo = new ProjectSettingVO();

        String similarityCriteria = dataMap.get("similarityCriteria") == null ? null : dataMap.get("similarityCriteria");
        String classCriteria = dataMap.get("classCriteria") == null ? null : dataMap.get("classCriteria");
        String classResultCriteria = dataMap.get("classResultCriteria") == null ? null : dataMap.get("classResultCriteria");
        String fallbackMsg = dataMap.get("fallbackMsg") == null ? null : dataMap.get("fallbackMsg");
        String greetingMsg = dataMap.get("greetingMsg") == null ? null : dataMap.get("greetingMsg");
        String oprMngCode = dataMap.get("custCode") + "_RCP_" + dataMap.get("serviceCode") == null ? null : dataMap.get("custCode") + "_RCP_" + dataMap.get("serviceCode");
        String updateId = resultVO.getUserId();

        vo.setOprMngCode(oprMngCode);
        vo.setSimilarityCriteria(Double.parseDouble(similarityCriteria));;
        vo.setClassCriteria(Double.parseDouble(classCriteria));
        vo.setClassResultCriteria(Double.parseDouble(classResultCriteria));
        vo.setFallbackMsg(fallbackMsg);
        vo.setGreetingMsg(greetingMsg);
        vo.setUpdateId(updateId);
        vo.setUpdateDate(LocalDateTime.now());

//        tbProjectSettingRepo.updateServiceInfo(vo);
//
//        HashMap<String, String> map = new HashMap<>();
//        map.put("resultCode", "success.common.update");
//        map.put("resultMsg", "정상적으로 저장되었습니다.");
//
//        ModelAndView mv = new ModelAndView(ajaxMainView);
//        mv.addObject("nMap", map);
//
//        return mv;
        ModelAndView mv = new ModelAndView(ajaxMainView);
        HashMap eMap = new HashMap();
        eMap.putAll(dataMap);
        eMap.put("oprMngCode",oprMngCode);

        NlpWisenutResult nlpWisenutResult = nlpWisenutProjectService.projectUpdateApi(eMap);
        HashMap<String, String> map = new HashMap<>();

        if (nlpWisenutResult.getResult()) {
            tbProjectSettingRepo.updateServiceInfo(vo);

            map.put("resultCode", "success.common.update");
            map.put("resultMsg", "정상적으로 저장되었습니다.");
        } else {
            log.error(nlpWisenutResult.getReturnCode() + " : " + nlpWisenutResult.getReturnMsg());
            map.put("resultCode", "fail.common.update");
            map.put("resultMsg", "실패하였습니다.");
        }
        mv.addObject("nMap", map);
        return mv;
    }

    public ModelAndView trainingStart(String oprMngCode) {
        ModelAndView mv = new ModelAndView(ajaxMainView);
        NlpWisenutResult nlpWisenutResult = new NlpWisenutResult();
        try {
            nlpWisenutResult = nlpAPIService.trainingStartApi(oprMngCode);
            this.workLogSave(MenuResource.rcpoprmanagenlpSettingmanage, ActionResource.learn, oprMngCode.split("_")[2]);
            if (nlpWisenutResult.getResult()) {

            } else {
                log.error(nlpWisenutResult.getReturnCode() + " : " + nlpWisenutResult.getReturnMsg());
            }

        } catch(Exception e) {
            log.error("error", e);
            nlpWisenutResult.setReturnCode("-999");
            nlpWisenutResult.setReturnMsg("API 호출 오류");
        }
        mv.addObject("result", nlpWisenutResult);
        return mv;
    }

    public ModelAndView trainingApply(String oprMngCode) {
        ModelAndView mv = new ModelAndView(ajaxMainView);
        NlpWisenutResult nlpWisenutResult = new NlpWisenutResult();
        try {
            nlpWisenutResult = nlpAPIService.trainingApplyApi(oprMngCode);
            this.workLogSave(MenuResource.rcpoprmanagenlpSettingmanage, ActionResource.reflect, oprMngCode.split("_")[2]);
            if (nlpWisenutResult.getResult()) {

            } else {
                log.error(nlpWisenutResult.getReturnCode() + " : " + nlpWisenutResult.getReturnMsg());
            }
        } catch(Exception e) {
            log.error("error", e);
            nlpWisenutResult.setReturnCode("-999");
            nlpWisenutResult.setReturnMsg("API 호출 오류");
        }
        mv.addObject("result", nlpWisenutResult);
        return mv;
    }

    public void workLogSave(MenuResource menuAuth, ActionResource actionCode, String serviceCode) {
        logService.LogSave(LogVO.builder()
                .menuAuth(menuAuth)
                .actionCode(String.valueOf((actionCode)))
                .serviceGroup(serviceCode)
                .build());
    }
}
