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

import com.google.gson.Gson;
import com.google.gson.JsonObject;
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.vo.SystemEntityRes;
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.entity.conversation.TbEntityMaster;
import com.icomsys.main_vm.db.jpa.repo.scenario.TbEntityMasterRepo;
import com.icomsys.main_vm.db.mybatis.alias.LoginVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

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

@Service
@RequiredArgsConstructor
@Slf4j
public class ConversationSystemEntityService {
    private final TbEntityMasterRepo tbEntityMasterRepo;
    private final LogService logService;
    @Resource
    MappingJackson2JsonView ajaxMainView;

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

    @Transactional(readOnly = true)
    public List<SystemEntityRes> SystemEntityList() {

        return tbEntityMasterRepo.findAll().stream().map(e->
                SystemEntityRes.builder().entityName(e.getEntityName()).build()
        ).collect(Collectors.toList());
    }

    public ModelAndView synchronizeEntityList(HttpServletRequest request) {
        ModelAndView mv = new ModelAndView(ajaxMainView);

        LoginVO resultVO = (LoginVO) request.getSession().getAttribute("LoginVO");
        String userId = resultVO.getUserId();

        Gson gson = new Gson();
        List<String> list = null;
        List<HashMap> returnList = new ArrayList<HashMap>();
        try {
            String path = nlpApi + "/system/entityList";
            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("projectId", "0");

            String body = gson.toJson(jsonObject);
            HttpMethod method = HttpMethod.POST;

            // api request
            String responseBody = callNlpApi(path, body, method);
            responseBody = responseBody.replaceAll("\"", "\\\"");
            HashMap eMap = new HashMap();
            eMap = gson.fromJson(responseBody, eMap.getClass());
            Map<String, Object> map = (Map<String, Object>) eMap.get("data");
            list = (List<String>) map.get("systemEntityNameList");
            log.info("list", list);
            if (list.size() > 0) {
                if (!this.updateEntityList(list, userId)) {
                    mv.addObject("result", false);
                    mv.addObject("message", "데이터오류로 실패하였습니다.");
                    mv.addObject("list", this.SystemEntityList());
                    return mv;
                }
            }
            mv.addObject("result", true);
            mv.addObject("message", "동기화하였습니다.");
        } catch (Exception ex) {
            log.error(ex.getMessage());
            mv.addObject("result",false);
            mv.addObject("message","연동오류로 실패하였습니다.");
            mv.addObject("list", this.SystemEntityList());
            return mv;
        }

        mv.addObject("list", this.SystemEntityList());
        return mv;
    }

    public boolean updateEntityList(List<String> list, String userId) {

        try {
            tbEntityMasterRepo.truncateEntityMaster();
            for (String entity : list) {
                TbEntityMaster save = TbEntityMaster.builder()
                        .entityName(entity)
                        .registDate(LocalDateTime.now())
                        .registId(userId)
                        .build();
                tbEntityMasterRepo.save(save);
            }
        } catch (Exception e) {
            return false;
        }
        return true;
    }
}
