package com.icomsys.main_vm.biz.test.controller;

import aj.org.objectweb.asm.TypeReference;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.google.gson.*;
import com.icomsys.main_vm.biz.advice.excep.CustomBadRequestException;
import com.icomsys.main_vm.biz.advice.excep.CustomNotFoundException;
import com.icomsys.main_vm.biz.common.common.service.LogVO;
import com.icomsys.main_vm.biz.common.common.service.RestTemplateService;
import com.icomsys.main_vm.biz.common.common.service.SequenceService;
import com.icomsys.main_vm.biz.common.login.res.OprmngCodeRes;
import com.icomsys.main_vm.biz.common.login.res.ServiceGroupRes;
import com.icomsys.main_vm.biz.common.login.res.UserVo;
import com.icomsys.main_vm.biz.common.system.service.SystemServiceGroupService;
import com.icomsys.main_vm.biz.common.system.vo.*;
import com.icomsys.main_vm.biz.test.controller.testvo.APINodeVo;
import com.icomsys.main_vm.common.code.EnumToMap;
import com.icomsys.main_vm.common.code.MenuVo;
import com.icomsys.main_vm.common.code.enumresource.MenuResource;
import com.icomsys.main_vm.common.code.enumresource.PolicyResource;
import com.icomsys.main_vm.common.code.enumresource.RoleResource;
import com.icomsys.main_vm.db.jpa.entity.conversation.TbProjectSetting;
import com.icomsys.main_vm.db.jpa.entity.monitoring.*;
import com.icomsys.main_vm.db.jpa.repo.monitoring.*;
import com.icomsys.main_vm.db.jpa.repo.system.*;
import com.icomsys.main_vm.db.mybatis.alias.MonitoringScenarioBreakVO;
import com.icomsys.main_vm.db.mybatis.mapper.TestMapper;
import com.querydsl.core.QueryResults;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.formula.functions.T;
import org.apache.poi.ss.usermodel.*;
import org.json.JSONObject;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.UriComponentsBuilder;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.net.URI;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
@Slf4j
@RequiredArgsConstructor
public class TestRestService {

    private final TbBotCommonCodeRepo tbBotCommonCodeRepo;
    private final TbBotUserRepo tbBotUserRepo;
    private final TbCustPolicyRepo tbCustPolicyRepo;
    private final TbIcsCustInfoRepo tbIcsCustInfoRepo;
    private final TbIcsOprMngInfoRepo tbIcsOprMngInfoRepo;
    private final TbServiceAuthGroupRepo tbServiceAuthGroupRepo;
    private final TbServiceGrouopRepo tbServiceGrouopRepo;
    private final TbServiceGroupPolicyRepo tbServiceGroupPolicyRepo;
    private final TbUserAuthGroupRepo tbUserAuthGroupRepo;
    private final TbUserCustRepo tbUserCustRepo;
    private final SequenceService sequenceService;
    private final PasswordEncoder passwordEncoder;
    private final SystemServiceGroupService systemServiceGroupService;
    private final HttpServletResponse httpServletResponse;
    private final ModelMapper modelMapper;

    public List<String> initData() {
        List<String> authList = Arrays.asList(
                "rootRead",
                "rcpconversationintentRead",
                "rcpconversationintentmanageRead",
                "rcpconversationscenariomanageRead",
                "rcpconversationsynonymmanageRead",
                "rcpconversationdictionarymanageRead",
                "rcpconversationsystemEntitymanageRead",
                "rcpconversationapiNodemanageRead",
                "rcpconversationcmmNodemanageRead",
                "rcpconversationnlpSettingmanageRead",
                "rcplearningTestsimulatorRead",
                "rcplearningTestsimulatormanageRead",
                "rcpstatisticsRead",
                "rcpstatisticsuseRead",
                "rcpstatisticsuserecordmanageRead",
                "rcpstatisticsstatisticsRead",
                "rcpstatisticsstatisticsuesmanageRead",
                "rcpstatisticsstatisticsresponsemanageRead",
                "rcpstatisticsstatisticsintentmanageRead",
                "rcpstatisticsstatisticsscenariomanageRead",
                "rcpstatisticsmonitoringRead",
                "rcpstatisticsmonitoringcallmanageRead",
                "rcpstatisticsmonitoringaienginemanageRead",
                "rcpstatisticsmonitoringconsultingmanageRead",
                "rcpstatisticsmonitoringconversationMarkmanageRead",
                "rcpoprmanageRead",
                "rcpoprmanagegreetingmanageRead",
                "rcpoprmanagebothistorymanageRead",
                "rcpoprmanagepreviewmanageRead",
                "rcpoprmanagetranscriptmanageRead",
                "commonsystemRead",
                "commonsystemauthMenumanageRead",
                "commonsystemcustmanageRead",
                "commonsystemserviceGroupmanageRead",
                "commonsystemusermanageRead",
                "commonsystemgroupAuthmanageRead",
                "commonsystemoprmmgcodemanageRead",
                "rcpconversationintentmanageFull",
                "rcpconversationscenariomanageFull",
                "rcpconversationscenariomanageRelease",
                "rcpconversationsynonymmanageFull",
                "rcpconversationdictionarymanageFull",
                "rcpconversationsystemEntitymanageFull",
                "rcpconversationapiNodemanageFull",
                "rcpconversationcmmNodemanageFull",
                "rcpconversationnlpSettingmanageFull",
                "rcplearningTestsimulatormanageFull",
                "rcpstatisticsuserecordmanageFull",
                "rcpstatisticsstatisticsuesmanageFull",
                "rcpstatisticsstatisticsresponsemanageFull",
                "rcpstatisticsstatisticsintentmanageFull",
                "rcpstatisticsstatisticsscenariomanageFull",
                "rcpstatisticsmonitoringcallmanageFull",
                "rcpstatisticsmonitoringaienginemanageFull",
                "rcpstatisticsmonitoringconsultingmanageFull",
                "rcpstatisticsmonitoringconversationMarkmanageFull",
                "rcpoprmanagegreetingmanageFull",
                "rcpoprmanagebothistorymanageFull",
                "rcpoprmanagepreviewmanageFull",
                "rcpoprmanagetranscriptmanageFull",
                "commonsystemauthMenumanageFull",
                "commonsystemcustmanageFull",
                "commonsystemserviceGroupmanageFull",
                "commonsystemusermanageFull",
                "commonsystemgroupAuthmanageFull",
                "commonsystemoprmmgcodemanageFull",
                "privacymasking"
        );
        return authList;
    }

    public List<MenuResource> authToMenu(List<String> authList) {
        return authList.stream().map(e -> PolicyResource.valueOf(e).getMenu())
                .collect(Collectors.toList());
    }

    private static final String space = "   ";

    public List<MenuVo> authToAuthList(List<String> authList, int roleValSeq) {
        return authList.stream().map(e -> {
//                            log.info(e);
                            if (PolicyResource.valueOf(e).getMenu() != MenuResource.root && PolicyResource.valueOf(e).getRoleValSeq() < roleValSeq) {
//                                log.info(PolicyResource.valueOf(e).getMenu().getMenuName());
                                return MenuVo.builder()
                                        .seq(PolicyResource.valueOf(e).getMenu().getMenuSeq())
                                        .seqUpper(PolicyResource.valueOf(e).getMenu().getMenuSeqUpper())
                                        .menuName(EnumToMap.spaceMap.get(PolicyResource.valueOf(e).getMenu().getLevel()) + PolicyResource.valueOf(e).getPolicyName())
                                        .authName(PolicyResource.valueOf(e).getName())
                                        .level(PolicyResource.valueOf(e).getMenu().getLevel())
                                        .url(PolicyResource.valueOf(e).getMenu().getMenuUrl())
                                        .build();
                            } else {
                                log.info(PolicyResource.valueOf(e).getPolicyName());
                                return MenuVo.builder().seq(PolicyResource.rootRead.getMenu().getMenuSeq())
                                        .seqUpper(PolicyResource.rootRead.getMenu().getMenuSeqUpper())
                                        .menuName(PolicyResource.valueOf(e).getPolicyName())
                                        .authName(e)
                                        .level(PolicyResource.rootRead.getMenu().getLevel())
                                        .url(PolicyResource.rootRead.getMenu().getMenuUrl())
                                        .build();
                            }
                        }
                )
                .sorted(Comparator.comparing(MenuVo::getSeq))
                .distinct()
                .collect(Collectors.toList())
                ;
    }


    public List<MenuVo> authToMenuList(List<String> authList, int roleValSeq) {
        return authList.stream().map(e -> {
                            log.info(e);
                            if (PolicyResource.valueOf(e).getMenu() != MenuResource.root && PolicyResource.valueOf(e).getRoleValSeq() < roleValSeq) {
                                log.info(PolicyResource.valueOf(e).getMenu().getMenuName());
                                return MenuVo.builder()
                                        .seq(PolicyResource.valueOf(e).getMenu().getMenuSeq())
                                        .seqUpper(PolicyResource.valueOf(e).getMenu().getMenuSeqUpper())
                                        .menuName(EnumToMap.spaceMap.get(PolicyResource.valueOf(e).getMenu().getLevel()) + PolicyResource.valueOf(e).getMenu().getMenuName())
                                        .authName("")
                                        .level(PolicyResource.valueOf(e).getMenu().getLevel())
                                        .url(PolicyResource.valueOf(e).getMenu().getMenuUrl())
                                        .build();
                            }
                            return MenuVo.builder().seq(PolicyResource.rootRead.getMenu().getMenuSeq())
                                    .seqUpper(PolicyResource.rootRead.getMenu().getMenuSeqUpper())
                                    .menuName(EnumToMap.spaceMap.get(PolicyResource.rootRead.getMenu().getLevel()) + PolicyResource.rootRead.getMenu().getMenuName())
                                    .authName("")
                                    .level(PolicyResource.rootRead.getMenu().getLevel())
                                    .url(PolicyResource.rootRead.getMenu().getMenuUrl())
                                    .build();
                        }
                )
                .sorted(Comparator.comparing(MenuVo::getSeq))
                .distinct()
                .collect(Collectors.toList())
                ;
    }

    public List<String> test10() {
        return tbUserAuthGroupRepo.userPolicyListSelect(4L, "ourStore");
    }

    public List<ServiceGroupRes> getServiceGroup() {
        List<ServiceGroupRes> result = tbServiceGrouopRepo.findByServiceGroupInAndServiceGroupUpper(tbUserCustRepo.findByUserSeq(4L)
                        .stream().map(e -> e.getServiceGroup()).collect(Collectors.toList()), "ourStore")
                .stream().map(f -> new ServiceGroupRes().toServiceGrouopRes(f)).collect(Collectors.toList());
        log.info("getServiceGroup - {}", new Gson().toJson(result));
        return result;
    }

    public QueryResults<SystemIcsCustInfoRes> pagingtest() {
        return tbIcsCustInfoRepo.SelectCustInfo(SystemIcsCustInfoReq.builder().page(0).size(10).build());
    }

    public List<OprmngCodeRes> test16() {
        List<OprmngCodeRes> result = tbServiceGrouopRepo.getMainOprmngCode(UserVo.builder()
                .userSeq(4L)
                .roleVal(RoleResource.USERADMIN.getName())
                .build());
        log.info("result - {}", new Gson().toJson(result));
        return result;
    }

    public DslDataTableRes<SystemPolicyMenuRes> test17() {
        SystemPolicyMenuReq dto = new SystemPolicyMenuReq();
        dto.setPage(0);
        dto.setSize(10);
        dto.setUserVo(UserVo.builder().userSeq(4L).lastUseServiceGroup("ourStore").roleVal(RoleResource.USERADMIN.getName()).build());
        QueryResults<SystemPolicyMenuRes> result = tbCustPolicyRepo.PolicyMenuListQueryResult(dto);

        DslDataTableRes dslRes = new DslDataTableRes(result, result.getResults().stream().map(e ->
                SystemPolicyMenuRes.builder()
                        .custCode(e.getCustCode())
                        .custName(e.getCustName())
                        .serviceGroup(e.getServiceGroup())
                        .serviceGroupName(e.getServiceGroupName())
                        .policyVal(e.getPolicyVal())
                        .policyName(PolicyResource.valueOf(e.getPolicyVal()).getPolicyName())
                        .menuName(PolicyResource.valueOf(e.getPolicyVal()).getMenu().getMenuName())
                        .build()
        ).collect(Collectors.toList()));
        return dslRes;
    }

    public List<SystemPolicyMenuRes> test18(int page, int size, String codeText1, String codeText2, String codeText3, String service) {
        SystemPolicyMenuReq dto = new SystemPolicyMenuReq();
        dto.setSize(size);
        dto.setPage(page);
        dto.setCodeText1(codeText1);
        dto.setCodeText2(codeText2);
        dto.setCodeText3(codeText3);
        dto.setServiceGroup(service);
        dto.setUserVo(UserVo.builder().userSeq(4L).lastUseServiceGroup("ourStore").roleVal(RoleResource.USERADMIN.getName()).build());
        log.info("dto - {}", new Gson().toJson(dto));
        List<SystemPolicyMenuRes> result = tbCustPolicyRepo.PolicyMenuListQueryList(dto)
                .stream().map(e ->
                        SystemPolicyMenuRes.builder()
                                .custCode(e.getCustCode())
                                .custName(e.getCustName())
                                .serviceGroup(e.getServiceGroup())
                                .serviceGroupName(e.getServiceGroupName())
                                .policyVal(e.getPolicyVal())
                                .policyName(PolicyResource.valueOf(e.getPolicyVal()).getPolicyName())
                                .menuName(PolicyResource.valueOf(e.getPolicyVal()).getMenu().getMenuName())
                                .menuSeq(PolicyResource.valueOf(e.getPolicyVal()).getMenu().getMenuSeq())
                                .build()
                )
                .filter(h -> {
                    if (dto.getServiceGroup() != null && !dto.getServiceGroup().equals("")) {
                        if (h.getServiceGroup().equals(dto.getServiceGroup())) {
                            return true;
                        } else {
                            return false;
                        }
                    }
                    return true;
                })
                .filter(f -> {
                    if (dto.getCodeText1() != null && !dto.getCodeText1().equals("")
                    ) {
                        if (f.getPolicyVal().toUpperCase().contains(dto.getCodeText1().trim().toUpperCase())) {
                            return true;
                        } else {
                            return false;
                        }
                    }
                    if (dto.getCodeText2() != null && !dto.getCodeText2().equals("")
                    ) {
                        if (f.getPolicyName().toUpperCase().contains(dto.getCodeText2().trim().toUpperCase())) {
                            return true;
                        } else {
                            return false;
                        }
                    }
                    if (dto.getCodeText3() != null && !dto.getCodeText3().equals("")
                    ) {
                        if (f.getMenuName().toUpperCase().contains(dto.getCodeText3().trim().toUpperCase())) {
                            return true;
                        } else {
                            return false;
                        }
                    }

                    return true;
                })
                .sorted(Comparator.comparing(SystemPolicyMenuRes::getMenuSeq))
                .skip(dto.getSize() * dto.getPage()).limit(dto.getSize())
                .collect(Collectors.toList());

        log.info("result size - {}", Long.parseLong(String.valueOf(result.size())));
        log.info("getSize - {}", Long.parseLong(String.valueOf(dto.getSize())));
        log.info("getoffset - {}", Long.parseLong(String.valueOf(dto.getSize() * dto.getPage())));
        log.info("dslresult - {}", new Gson().toJson(new DslDataTableRes<SystemPolicyMenuRes>(result.stream().map(e ->
                        SystemPolicyMenuRes.builder()
                                .custCode(e.getCustCode())
                                .custName(e.getCustName())
                                .serviceGroup(e.getServiceGroup())
                                .serviceGroupName(e.getServiceGroupName())
                                .policyVal(e.getPolicyVal())
                                .policyName(PolicyResource.valueOf(e.getPolicyVal()).getPolicyName())
                                .menuName(PolicyResource.valueOf(e.getPolicyVal()).getMenu().getMenuName())
                                .menuSeq(PolicyResource.valueOf(e.getPolicyVal()).getMenu().getMenuSeq())
                                .build()
                )
                .filter(h -> {
                    if (dto.getServiceGroup() != null && !dto.getServiceGroup().equals("") && !dto.getServiceGroup().equals("ALL")) {
                        if (h.getServiceGroup().equals(dto.getServiceGroup())) {
                            return true;
                        } else {
                            return false;
                        }
                    }
                    return true;
                })
                .filter(f -> {
                    if (dto.getCodeText1() != null && !dto.getCodeText1().equals("")
                    ) {
                        if (f.getPolicyVal().toUpperCase().contains(dto.getCodeText1().trim().toUpperCase())) {
                            return true;
                        } else {
                            return false;
                        }
                    }
                    if (dto.getCodeText2() != null && !dto.getCodeText2().equals("")
                    ) {
                        if (f.getPolicyName().toUpperCase().contains(dto.getCodeText2().trim().toUpperCase())) {
                            return true;
                        } else {
                            return false;
                        }
                    }
                    if (dto.getCodeText3() != null && !dto.getCodeText3().equals("")
                    ) {
                        if (f.getMenuName().toUpperCase().contains(dto.getCodeText3().trim().toUpperCase())) {
                            return true;
                        } else {
                            return false;
                        }
                    }
                    return true;
                })
                .sorted(Comparator.comparing(SystemPolicyMenuRes::getMenuSeq))
                .skip(dto.getSize() * dto.getPage()).limit(dto.getSize())
                .collect(Collectors.toList())
                , Long.parseLong(String.valueOf(result.size()))
                , Long.parseLong(String.valueOf(dto.getSize()))
                , Long.parseLong(String.valueOf(dto.getSize() * dto.getPage())))));
        return result;
    }

    public Map<String, String> jstreeParentConvertToPolicy() {
        Map<String, String> pMaps = new HashMap<>();
        log.info("jstreeParentConvertToPolicy");
        PolicyResource.ALL.stream().forEach(e -> {

//            정책이 메뉴를 가지고있음.
//            메뉴 어퍼가있음
//            메뉴어퍼에 해당하는 메뉴를 찾음
//            그메뉴를 가지고있는 오쓰를찾음
            Long seqq = e.getMenu().getMenuSeqUpper();
            log.info(e.getName());
            if (seqq == 0L || seqq == 1L) {
                log.info("#");
                pMaps.put(e.getName(), "#");
            } else {
                log.info("seq - {}", seqq);
                pMaps.put(e.getName(), EnumToMap.MenuSeqToPolicyMap.get(seqq));
            }
        });
        log.info("돌아아라라 - {}", new Gson().toJson(EnumToMap.MenuSeqToPolicyMap));
        log.info("돌아아라라 - {}", new Gson().toJson(EnumToMap.PolicyToParentMap));
        return pMaps;
    }

    public List<SystemServiceGroupViewVo> test20() {

        List<SystemServiceGroupViewVo> test20 = tbServiceGrouopRepo.getServiceGroupView("ourStore");
        for (SystemServiceGroupViewVo e : test20) {
            log.info("eee -{}", new Gson().toJson(e));
            e.setPolicyVal(tbCustPolicyRepo.findByServiceGroup(e.getServiceGroup()).stream()
                    .map(f -> f.getPolicyVal()).collect(Collectors.toList()));
        }
        return test20;
    }

    public void test22() {

        if (!tbUserAuthGroupRepo.existsByServiceGroupAndUserSeqAndAuthGroupSeqNot("DAISO", 4L, 12L)) {
            log.info("seq4");
        }
        ;


    }


    public void test25Service() {
        tbIcsCustInfoRepo.findAll();
    }

//    public List<TestVoUser> test21() {
//        return tbBotUserRepo.testConCat();
//    }


    public void ExcelService(String fileName, List<?> data) throws IOException {
        List<String> title = new ArrayList<>();
        for (Field e : data.get(0).getClass().getDeclaredFields()) {
            title.add(e.getName());
        }
        ExcelService(fileName, data, title);
    }

    public void ExcelService(String fileName, List<?> data, List<String> title) throws IOException {
        Workbook wb = new HSSFWorkbook();
        Sheet sheet = wb.createSheet("new sheet");
        CreationHelper createHelper = wb.getCreationHelper();
        Row row = sheet.createRow(0);
        CellStyle cellStyle1 = wb.createCellStyle();
        cellStyle1.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        applyCellStyle(cellStyle1);
        CellStyle cellStyle2 = wb.createCellStyle();
        cellStyle2.setFillForegroundColor(IndexedColors.WHITE.getIndex());
        applyCellStyle(cellStyle2);
        AtomicInteger ai = new AtomicInteger();
        List<String> keySet = new ArrayList<>();
        for (String e : title) {
            Cell c = row.createCell(ai.getAndIncrement());
            c.setCellValue(e);
            c.setCellStyle(cellStyle1);
        }
        sheet.autoSizeColumn(0);
        for (Field e : data.get(0).getClass().getDeclaredFields()) {
            keySet.add(e.getName());
        }
        row.setHeight((short) 400);
        AtomicInteger ai1 = new AtomicInteger();
        for (Object e : data) {
            Row row1 = sheet.createRow(ai1.incrementAndGet());
            AtomicInteger ai2 = new AtomicInteger();
            JSONObject obj = new JSONObject(e);
            for (String f : keySet) {
                int rowNum = ai2.getAndIncrement();
                if (obj.names().toList().contains(f)) {
                    Cell c = row1.createCell(rowNum);
                    c.setCellValue(createHelper.createRichTextString(obj.get(f).toString()));
                    c.setCellStyle(cellStyle2);
                } else {
                    Cell c = row1.createCell(rowNum);
                    c.setCellValue(createHelper.createRichTextString(""));
                    c.setCellStyle(cellStyle2);
                }
                sheet.autoSizeColumn(rowNum);
                row1.setHeight((short) 400);
            }
        }
        try (OutputStream fileOut = new FileOutputStream("base.xls")) {
            wb.write(fileOut);
            httpServletResponse.setContentType("application/vnd.ms-excel; charset=EUC-KR");
            httpServletResponse.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls; charset=EUC-KR");
            wb.write(httpServletResponse.getOutputStream());
        }
    }

    private void applyCellStyle(CellStyle cellStyle) {
        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        cellStyle.setBorderLeft(BorderStyle.THIN);
        cellStyle.setBorderTop(BorderStyle.THIN);
        cellStyle.setBorderRight(BorderStyle.THIN);
        cellStyle.setBorderBottom(BorderStyle.THIN);
    }


    public ResponseEntity exceldataTest() throws IOException, IllegalAccessException {

//        ExcelService(tbBotCommonCodeRepo.findAll()
//                .stream().map(e -> SystemCommoncodeRes.builder()
//                        .oprMngCode(e.getOprMngCode())
//                        .codeType(e.getCodeType())
//                        .minorCode(e.getMinorCode())
//                        .majorCode(e.getMajorCode())
//                        .description(e.getDescription())
//                        .attribute1(e.getAttribute1())
//                        .attribute2(e.getAttribute2())
//                        .attribute3(e.getAttribute3())
//                        .build()).collect(Collectors.toList()));

        List<String> asd = new ArrayList<>();
        for (int i = 0; i < 15; i++) {
            asd.add(i + "번");
        }
        asd.add("시나리오그룹");
        asd.add("공통코드생성일");
        ExcelService("다운로드테스트", tbIcsCustInfoRepo.findAll());
        return ResponseEntity.ok().build();
    }

    public void test27(MultipartFile dto) throws IOException {
        Workbook wb = new HSSFWorkbook(dto.getInputStream());
        Sheet a = wb.getSheetAt(0);

        for (int i = 0; i < a.getLastRowNum() + 1; i++) {
            log.info("data - {}", a.getLastRowNum());
            int celSize = a.getRow(i).getLastCellNum();
            for (int j = 0; j < celSize; j++) {
                log.info("data cel - {}", a.getRow(i).getCell(j));
            }
        }


        log.info(a.getSheetName());
    }


    private final TestMapper testMapper;

    public List<FailNodeVO> test28() {
        List<MonitoringScenarioBreakVO> result = testMapper.MonitoringScenarioBreak("2023-02-06", "2023-02-07");
        List<FailNodeVO> convert = new ArrayList<>();
        Map<Long, Integer> scenarioSeqMap = new HashMap<>();
        int totCnt = result.size();
        int faCnt = 0;
        int suCnt = 0;

        for (MonitoringScenarioBreakVO e : result) {
            if (scenarioSeqMap.containsKey(e.getScenarioSeq())) {
                int cnt = scenarioSeqMap.get(e.getScenarioSeq());
                log.info("cnt - {}", cnt);
                scenarioSeqMap.put(e.getScenarioSeq(), cnt += 1);
            } else {
                scenarioSeqMap.put(e.getScenarioSeq(), 1);
            }
            log.info(e.getScenarioResultCode());
            if (e.getScenarioResultCode().equals("S")) {
                suCnt += 1;
            }
            if (e.getScenarioResultCode().equals("F")) {
                faCnt += 1;
            }
        }

        for (MonitoringScenarioBreakVO e : result) {
            convert.add(FailNodeVO.builder()
                    .oprMngCode(e.getOprMngCode())
                    .scenarioSeq(e.getScenarioSeq())
                    .scenarioName(e.getScenarioName())
                    .totCnt(totCnt)
                    .useCnt(scenarioSeqMap.get(e.getScenarioSeq()))
                    .succCnt(suCnt)
                    .failCnt(faCnt)
                    .build());
        }

        return convert;
    }


    private final RestTemplateService restTemplateService;

    public Map test31(String dbData) throws CustomBadRequestException, NoSuchMethodException {

        String sss = "";
        log.info("dbdata - -{}", dbData);
        Map<String, String> somethingMap = new HashMap<>();

        somethingMap.put("#{userMessage}", "예약 예약 예약");
        somethingMap.put("#{origintest1}", "test1");
        somethingMap.put("#{origintest2}", "test2");
        somethingMap.put("#{origintest3}", "test3");

        return restTemplateService.APINode(somethingMap, somethingMap, dbData);

    }


    public void test33(String s) throws CustomBadRequestException, NoSuchMethodException {
        Map<String, String> somethingMap = new HashMap<>();

        somethingMap.put("#{userMessage}", "예약 예약 예약");
        somethingMap.put("#{origintest1}", "test1");
        somethingMap.put("#{origintest2}", "test2");
        somethingMap.put("#{origintest3}", "test3");

        restTemplateService.APINode(somethingMap, somethingMap, s);
    }


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

    public Long test34() throws CustomNotFoundException {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        ResponseEntity callRes = restTemplateService
                .PostCall(UriComponentsBuilder.newInstance().uri(URI.create(wisepath + "/proj/insert")).build()
                        , headers
                        , new Gson().toJson(WisenutInsertReqVo.builder()
                                .oprMngCode("UPLUS_RCO_OURSTOREAI")
                                .serviceGroupDesc("UPLUS 우리가게 AI 최상위 서비스")
                                .build())
                );
        if (!callRes.getStatusCode().equals(HttpStatus.OK)) {
            throw new CustomNotFoundException("NLP 서버 연결에 실패하였습니다.");
        }
        log.info("nlp result = {}", callRes.getBody());
        WisenutInsertResVo callVo = new Gson().fromJson(callRes.getBody().toString(), WisenutInsertResVo.class);
        return callVo.getProjectId();
    }

    public List<TbProjectSetting> test35() throws CustomNotFoundException {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        List<TbProjectSetting> projectSettins = new ArrayList<>();

        List<WisenutInsertReqVo> setdata = new ArrayList<>();
        for (int i = 0; i < 2; i++) {
            setdata.add(WisenutInsertReqVo.builder()
                    .oprMngCode("OUR" + i)
                    .serviceGroupDesc("desc" + i)
                    .build());
        }

        for (WisenutInsertReqVo e : setdata) {
            ResponseEntity callRes = restTemplateService
                    .PostCall(UriComponentsBuilder.newInstance().uri(URI.create(wisepath + "/proj/insert"))
                            .build(), headers, new Gson().toJson(e));

            if (callRes.getStatusCode().equals(HttpStatus.OK)) {
                WisenutInsertResVo callVo = new Gson().fromJson(callRes.getBody().toString(), WisenutInsertResVo.class);
                projectSettins.add(TbProjectSetting.builder()
                        .ifMappingId(callVo.getProjectId())
                        .oprMngCode(e.getName())
                        .similarityCriteria(e.getSimThreshold())
                        .classCriteria(e.getConfidentThreshold())
                        .classResultCriteria(e.getConfidentThresholdGap())
                        .build());

            } else {
                throw new CustomNotFoundException("Wisenut 연결에 실패하였습니다.");
            }
        }

        log.info("projectSettins - {}", new Gson().toJson(projectSettins));
        return projectSettins;
    }

    private final TbCallInfoRepo tbCallInfoRepo;
    private final TbCallUserLogRepo tbCallUserLogRepo;
    private final TbScenarioBreakNodeRepo tbScenarioBreakNodeRepo;
    private final TbCallBotLogRepo tbCallBotLogRepo;
    private final TbCallBotRecRepo tbCallBotRecRepo;
    private final TbCallUserRecRepo tbCallUserRecRepo;

    public Long test36() {
        //5184000건
        //6개월
        Long sTime = System.currentTimeMillis();
        for (int i = 0; i < 180; i++) {
            //24시간
            for (int k = 0; k < 24; k++) {
                //60분
                List<TbCallInfo> callInfo = new ArrayList<>();
                List<TbCallBotLog> botLog = new ArrayList<>();
                List<TbCallBotRec> botRec = new ArrayList<>();
                List<TbCallUserLog> userLog = new ArrayList<>();
                List<TbCallUserRec> userRec = new ArrayList<>();
                List<TbScenarioBreakNode> breakNodes = new ArrayList<>();

                for (int l = 0; l < 60; l++) {
                    //1시간에20건
                    for (int n = 0; n < 20; n++) {
//                        String token = UUID.randomUUID().toString().substring(0, 43);
                        String token = UUID.randomUUID().toString() + l;
                        LocalDateTime insertTime = LocalDateTime.of(2023, 4, 21, 23, 59)
                                .minusDays(i)
                                .minusHours(k)
                                .minusMinutes(l + 5);
                        callInfo.add(TbCallInfo.builder()
                                .token(token)
                                .oprMngCode("UPLUS_RCP_AISTORE")
                                .inChannelType("VOICE")
                                .callId(token)
                                .telNo("01012341234")
                                .dnisNo("07012341234")
                                .callInitDate(insertTime.minusSeconds(n))
                                .callEndDate(insertTime.plusSeconds(300))
                                .callTime(10)
                                .callEndType("END")
                                .callEndConversion("END")
                                .callEndReason("SCENARIO")
                                .build());
                        int beaknode = n;
                        //봇로그 복녹음 유저로그 유저녹음 5개배수
                        //봇로그 복녹음 유저로그 유저녹음 5개배수
                        for (int m = 0; m < 5; m++) {
                            botLog.add(TbCallBotLog.builder()
                                    .token(token)
                                    .talkSeq(m + 1)
                                    .mentSpeechNo(1)
                                    .botText("text" + m)
                                    .itemName("")
                                    .rcpInfo("RCPINFO")
                                    .registDate(insertTime.minusSeconds(n))
                                    .build());
                            botRec.add(TbCallBotRec.builder()
                                    .token(token)
                                    .talkSeq(m + 1)
                                    .recFilePath(token + m)
                                    .registDate(insertTime.minusSeconds(n))
                                    .build());
                            userLog.add(TbCallUserLog.builder()
                                    .token(token)
                                    .talkSeq(m + 1)
                                    .oprMngCode("UPLUS_RCP_AISTORE")
                                    .userText("userText" + m + 1)
                                    .intentId((long) m)
                                    .intentName("")
                                    .score("")
                                    .intentResultCode("INTENT_SUCCESS")
                                    .ifMappingId((long) m)
                                    .ifReturnCode("000")
                                    .ifReturnMsg("INTENT_SUCCESS")
                                    .registDate(insertTime.minusSeconds(n))
                                    .scenarioSeq((long) m)
                                    .scenarioName("senarioname" + m)
                                    .build());
                            userRec.add(TbCallUserRec.builder()
                                    .token(token)
                                    .talkSeq(m + 1)
                                    .itemCode("")
                                    .recFilePath(token + m)
                                    .registDate(insertTime.minusSeconds(n))
                                    .build());
                            //브레이크노드 저장
                            //브레이크노드 20프로 이탈
                            if (beaknode % 5 == 0) {
                                breakNodes.add(TbScenarioBreakNode.builder()
                                        .token(token)
                                        .talkSeq(m)
                                        .oprMngCode("UPLUS_RCP_AISTORE")
                                        .scenatioSeq((long) (l + 1))
                                        .releaseSeq((long) m + 1)
                                        .scenarioName("names")
                                        .scenarioResultCode("S")
                                        .nodeCode("nc" + m + 1)
                                        .nodeName("nodeName" + m + 1)
                                        .nodeType("type")
                                        .registDate(insertTime.minusSeconds(n))
                                        .build());
                            }
                        }
                    }
                }
                tbCallInfoRepo.saveAllAndFlush(callInfo);
                tbCallBotLogRepo.saveAllAndFlush(botLog);
                tbCallBotRecRepo.saveAllAndFlush(botRec);
                tbCallUserLogRepo.saveAllAndFlush(userLog);
                tbCallUserRecRepo.saveAllAndFlush(userRec);
                tbScenarioBreakNodeRepo.saveAllAndFlush(breakNodes);
//                    log.info("chk callInfo - {}", new Gson().toJson(callInfo));
//                    log.info("chk botLog - {}", new Gson().toJson(botLog));
//                    log.info("chk userLog - {}", new Gson().toJson(userLog));
//                    log.info("chk break - {}", new Gson().toJson(breakNodes));
            }
        }
        Long eTime = System.currentTimeMillis();
        return eTime - sTime;
    }

    public String test37(){
     return "a";
    }

}
