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

import com.google.gson.Gson;
import com.icomsys.main_vm.biz.advice.excep.CustomBadRequestException;
import com.icomsys.main_vm.biz.advice.excep.CustomNoSuchFieldException;
import com.icomsys.main_vm.biz.advice.excep.CustomNotFoundException;
import com.icomsys.main_vm.biz.common.common.service.ExcelService;
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.common.common.service.SequenceService;
import com.icomsys.main_vm.biz.common.common.service.functionnode.FunctionVo;
import com.icomsys.main_vm.biz.common.common.service.functionnode.FunctionWsNashorn;
import com.icomsys.main_vm.biz.common.login.res.OprmngCodeRes;
import com.icomsys.main_vm.biz.common.login.service.LoginService;
import com.icomsys.main_vm.biz.common.system.vo.DslDataTableRes;
import com.icomsys.main_vm.biz.common.system.vo.SystemPolicyMenuRes;
import com.icomsys.main_vm.biz.common.system.vo.SystemServiceGroupViewVo;
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.enumresource.MenuResource;
import com.icomsys.main_vm.db.jpa.entity.conversation.TbProjectSetting;
import com.icomsys.main_vm.db.jpa.entity.system.TbIcsCustInfo;
import com.icomsys.main_vm.db.jpa.repo.scenario.TbApiNodeRepo;
import com.icomsys.main_vm.db.jpa.repo.system.*;
import com.icomsys.main_vm.db.mybatis.mapper.TestMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.script.ScriptException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;

@RequestMapping("/rest")
@RestController
@RequiredArgsConstructor
@Slf4j
public class TestRestController {

    private final TestRestService 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 LoginService loginService;
    private final TestMapper testMapper;
    private final HttpServletRequest request;
    private final LogService logService;
    private final ExcelService excelService;

    @GetMapping("/test1")
    public String test1() {
        log.info("test1 init");
        log.info("test1 = {}", new Gson().toJson(EnumToMap.urlToMap));
        return new Gson().toJson(EnumToMap.urlToMap);
    }


    /**
     * 메뉴바인딩
     *
     * @return
     */
    @GetMapping("/test5")
    public Object test5() {
        log.info("test5 init");
        return testRestService.authToMenuList(testRestService.initData(), 1000001);
    }


    /**
     * 전체매뉴 -> 고객사별메뉴권한,
     * 고객사별메뉴권한 -> 그룹별권한
     *
     * @return
     */
    @GetMapping("/test6")
    public Object test6() {
        log.info("test6 init");
        return testRestService.authToAuthList(testRestService.initData(), 1000001);
    }

    @GetMapping("/test7")
    public String test7() {
        //Table All Test
        log.info(" 1 -{}", tbBotCommonCodeRepo.findAll());
        log.info(" 2 -{}", tbBotUserRepo.findAll());
        log.info(" 3 -{}", tbCustPolicyRepo.findAll());
        log.info(" 4 -{}", tbIcsCustInfoRepo.findAll());
        log.info(" 5 -{}", tbIcsOprMngInfoRepo.findAll());
        log.info(" 6 -{}", tbServiceAuthGroupRepo.findAll());
        log.info(" 7 -{}", tbServiceGrouopRepo.findAll());
        log.info(" 8 -{}", tbServiceGroupPolicyRepo.findAll());
        log.info(" 9 -{}", tbUserAuthGroupRepo.findAll());
        log.info(" 10 -{}", tbUserCustRepo.findAll());

        return "test7";
    }

    @GetMapping("/test8")
    public String test8() {

//        log.info("1 - {}", sequenceService.ServiceAuthGroupSeqNext());
//        log.info("2 - {}", sequenceService.UserSeqNext());

        return "test8";
    }

    @GetMapping("/test10")
    public List<String> test10() {
        return testRestService.test10();
    }

    @GetMapping("/test11")
    public Object test11() {
        return testRestService.authToMenuList(testRestService.test10(), 1000001);
    }

    @GetMapping("/test12")
    public Object test12() {
        return loginService.selectMainMenuLeft(4L, "ourStore", "SYSTEMADMIN");
    }

    @GetMapping("/test13")
    public Object test13() {
        List<String> aa = new ArrayList<>();
        try {
            aa = testMapper.getUserPolicy(4L, "ourStore");
            ;
        } catch (Exception e) {
            log.info("log - {}", e.getMessage());
        }
        return aa;
    }


    @GetMapping("/test14")
    public Object test14() {
        return testRestService.getServiceGroup();
    }

    @GetMapping("/test15")
    public Object test15() {
        return testRestService.pagingtest();
    }

    @GetMapping("/test16")
    public List<OprmngCodeRes> test16() throws CustomNoSuchFieldException {
        log.info("getOPR INIT");
        return testRestService.test16();
    }

    @GetMapping("/test17")
    public DslDataTableRes<SystemPolicyMenuRes> test17() throws CustomNoSuchFieldException {
        log.info("getOPR INIT");
        return testRestService.test17();
    }


    @GetMapping("/test18")
    public List<SystemPolicyMenuRes> test18(
            @RequestParam(name = "page", required = false) int page,
            @RequestParam(name = "size", required = false) int size,
            @RequestParam(name = "codeText1", required = false) String codeText1,
            @RequestParam(name = "codeText2", required = false) String codeText2,
            @RequestParam(name = "codeText3", required = false) String codeText3,
            @RequestParam(name = "service", required = false) String service
    ) throws CustomNoSuchFieldException {
        log.info("TEST18");
        return testRestService.test18(page, size, codeText1, codeText2, codeText3, service);
    }

    @GetMapping("/test19")
    public Map<String, String> test19() {

        Map<String, String> pMap = testRestService.jstreeParentConvertToPolicy();
        log.info("test19 - {}", new Gson().toJson(pMap));
        return pMap;
    }

    @GetMapping("/test20")
    public List<SystemServiceGroupViewVo> test20() {
        return testRestService.test20();
    }

    private final TbApiNodeRepo tbApiNodeRepo;
//    @GetMapping("/test21")
//    public List<TestVoUser> test21(){
//        return testRestService.test21();
//    }

    @GetMapping("/test21")
    public String test21() throws IOException {
//        String path =  request.getSession().getServletContext().getRealPath("");

        String path = new ClassPathResource("/document/Ourstore_Ai_Manager_User_Manual_v1.0.pdf").getFile().getAbsolutePath();
        return path;
    }

    @GetMapping("/test22")
    public String test22() {
        testRestService.test22();
        return "a";
    }

    @GetMapping("/test23")
    public void test23() {
        log.info("reg를 넘김");

        logService.LogSave(LogVO.builder()
                .menuAuth(MenuResource.rcpconversation)
                .actionCode("testActionCode")
                .registDate(LocalDateTime.now())
                .build());

    }

    @GetMapping("/test24")
    public void test24() {
        log.info("reg를안 넘김");
        logService.LogSave(LogVO.builder()
                .menuAuth(MenuResource.rcpconversationsystemEntitymanage)
                .actionCode("testActionCode")
                .build());
    }


    @PostMapping("/test25")
    public void test25(@RequestParam("files") MultipartFile dto) throws IOException {
        log.info("test25 - {}", new Gson().toJson(dto.getOriginalFilename()));
        log.info("test25 - {}", new Gson().toJson(dto));
//        testRestService.test27(dto);
        List<TbIcsCustInfo> result = excelService.ExcelUploadConvert(dto, TbIcsCustInfo.class);

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

    }

    @GetMapping("/test26")
    public void test26() throws IOException {
//        excelService.ExcelDownload("asd", tbIcsCustInfoRepo.findAll());
        excelService.ExcelDownload("asd", tbIcsCustInfoRepo.findAll());
    }

    @GetMapping("/test27")
    public void test27() throws IOException {
//        testRestService.ExcelUploadConvert(TbIcsCustInfo.class);
    }

    @GetMapping("/test28")
    public List<FailNodeVO> test28() {

        return testRestService.test28();
    }

    @GetMapping("/test29")
    public void test29() throws IOException {
        excelService.ExcelDownload("asdqwe", tbIcsCustInfoRepo.findAll(), Arrays.asList("ㅁㄴㅇㅁㄴㅇ", "ㅁㄴㅇㄴㅁㅇ", "ㅁㄴㅇㅁㄴㅇ"));
    }

    @PostMapping("/test30")
    public void test30(@RequestBody APINodeVo dto) {
        log.info("s - {}", new Gson().toJson(dto));


    }

    @GetMapping("/test31")
    public Map test31() throws CustomBadRequestException, NoSuchMethodException {
        String dbData = "{\"apiNodeName\":\"예약 날짜 확인\",\"urlType\":\"GET\",\"URL\":\"http://15.165.95.232:8080/platform/api/informal/numeral/Date\",\"header\":[{\"key\":\"Content-Type\",\"value\":\"application/json\",\"desc\":\"\"}],\"param\":[{\"key\":\"formatType\",\"value\":\"yyyy-MM-dd\",\"desc\":\"\"},{\"key\":\"talkText\",\"value\":\"#{userMessage}\",\"desc\":\"\"}],\"request\":[{\"value\":\"userMessage\",\"desc\":\"sample \\\"내일모레 예약하려고 합니다 \\\"\"}],\"response\":[{\"key\":\"responseCode\",\"value\":\"$.responseCode\",\"desc\":\"\"},{\"key\":\"processResult\",\"value\":\"$.resultData.processResult\",\"desc\":\"\"},{\"key\":\"findDate\",\"value\":\"$.resultData.findDate\",\"desc\":\"\"},{\"key\":\"weekOfTheDay\",\"value\":\"$.resultData.weekOfTheDay\",\"desc\":\"\"}],\"body\":\"\"}";

        return testRestService.test31(dbData);

    }

    @GetMapping("/test32")
    public void test32() throws ExecutionException, InterruptedException, TimeoutException, ScriptException {

        HashMap<String, String> calldata = new HashMap();
        calldata.put("abc", "1");
        Map resultMap = FunctionWsNashorn.builder(1000)
                .create(FunctionVo.builder()
                        .varList(Arrays.asList("시나리오변수1", "func변수1", "abc"))
                        .callData(calldata)
                        .initSctipt(" if (abc ==  \"1\") {\n  func변수1 = \"시나리오 변수 값이 1 입니다\";\n} else {\n func변수1 = \"시나리오 변수 값이 1이 아닙니다\";\n}\n")
                        .build())
                .build();

        log.info("result Map - - {}", new Gson().toJson(resultMap));
    }

    @GetMapping("/test33")
    public void test33() throws CustomBadRequestException, NoSuchMethodException {
        String s = "{\"apiNodeName\":\"ㅁㄴㅇㄻㄴㅇㄹ\",\"urlType\":\"POST\",\"URL\":\"http://192.168.219.106:8080/platform/api/call/list\",\"header\":[{\"key\":\"Content-Type\",\"value\":\"application/json\",\"desc\":\"\"}],\"param\":[],\"body\":\"{\\r\\n    \\\"downtownNum\\\": #{downtownNum},\\r\\n    \\\"startDate\\\": #{startDate},\\r\\n    \\\"endDate\\\": #{endDate}\\r\\n}\",\"request\":[{\"value\":\"downtownNum\",\"desc\":\"07075999946\"},{\"value\":\"startDate\",\"desc\":\"2021-08-03\"},{\"value\":\"endDate\",\"desc\":\"2023-08-03\"}],\"response\":[{\"key\":\"resultCode\",\"value\":\"$.resultCode\",\"desc\":\"\"},{\"key\":\"resultMessage\",\"value\":\"$.resultMessage\",\"desc\":\"\"},{\"key\":\"callListCnt\",\"value\":\"$.resultData.callListCnt\",\"desc\":\"\"},{\"key\":\"callList\",\"value\":\"$.resultData.callList\",\"desc\":\"\"}]}";
        log.info("s - {}", s);
        testRestService.test33(s);

    }

    @GetMapping("/test34")
    public Long test34() throws CustomNotFoundException {
        log.info("nlp mapping id controller");
        return testRestService.test34();
    }

    @GetMapping("/test35")
    public List<TbProjectSetting> test35() throws CustomNotFoundException {
        log.info("nlp mapping id controller5");
        return testRestService.test35();
    }

    @GetMapping("/test36")
    public Long test36() {
        log.info("test  36  ===");
       return testRestService.test36();
//        return "res";
    }

}


