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

import com.google.gson.Gson;
import com.icomsys.main_vm.biz.advice.excep.CustomNotFoundException;
import com.icomsys.main_vm.biz.advice.excep.CustomRuntimeException;
import com.icomsys.main_vm.biz.common.common.service.ExcelService;
import com.icomsys.main_vm.biz.rcp.conversation.dto.IntentRequestDTO;
import com.icomsys.main_vm.biz.rcp.conversation.service.IntentManageService;
import com.icomsys.main_vm.biz.rcp.conversation.vo.SelectIntentListVo;
import com.icomsys.main_vm.biz.rcp.conversation.vo.intent.ExcelIntentListVo;
import com.icomsys.main_vm.biz.rcp.conversation.vo.intent.IntentSearchVo;
import com.icomsys.main_vm.biz.rcp.conversation.vo.synonym.SelectSynonymListVo;
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.system.TbIntentMasterRepo;
import com.icomsys.main_vm.db.mybatis.alias.LoginVO;
import com.querydsl.core.QueryResults;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@Slf4j
@RequiredArgsConstructor
@RequestMapping("/admin/rcp/conversation")
public class ConversationIntentController {

    private final TbIntentMasterRepo tbIntentMasterRepo;
    @Resource
    MappingJackson2JsonView ajaxMainView;
    //private final HttpServletRequest request;

    private final IntentManageService intentManageService;

    private final ExcelService excelService;

    @GetMapping("/intent/manage.do")
    public String ScenarioView(){
    return "/adm/rcp/conversation/intent";
    }

    @RequestMapping(value = "/intent/search.do", method = RequestMethod.POST)
    @ResponseBody
    public ModelAndView searchIntent(IntentSearchVo dto) throws CustomNotFoundException {
        return intentManageService.searchIntent(dto);
    }

    /**
     * @Name serviceNameList
     * @Description 인텐트관리 카테고리 목록 조회
     * @Author 문다운
     * v	 * @CreateDate 2022. 5. 26.
     */
    @RequestMapping(value = "/intent/category.do", method = RequestMethod.GET)
    @ResponseBody
    public ModelAndView searchIntentCategoryList(@RequestParam Map<String, String> dataMap) throws CustomNotFoundException {
        return intentManageService.searchIntentCategoryList(dataMap);
    }

    /**
     * @Name serviceNameList
     * @Description 인텐트 예문 목록 조회
     * @Author 문다운
     * @CreateDate 2022. 5. 26.
     */
    @RequestMapping(value = "/intent/examples.do", method = RequestMethod.GET)
    @ResponseBody
    public ModelAndView selectIntentExampleList(HttpServletRequest request, @RequestParam Map<String, String> dataMap) {
        return intentManageService.selectIntentExampleList(dataMap);
    }

    /**
     * @Name serviceNameList
     * @Description 인텐트 예문 목록 조회
     * @Author 문다운
     * @CreateDate 2022. 5. 26.
     */
    @RequestMapping(value = "/intent/check.do", method = RequestMethod.GET)
    @ResponseBody
    public ModelAndView selectIntentCnt(HttpServletRequest request, @RequestParam Map<String, String> dataMap) {
        log.debug("selectIntentCnt init ");
        ModelAndView mv = new ModelAndView(ajaxMainView);
        HashMap eMap = new HashMap();
        eMap.putAll(dataMap);
        int cnt = intentManageService.selectIntentCnt(eMap);
        mv.addObject("result", (cnt > 0 ? false : true));
        return mv;
    }

    /**
     * @Name serviceNameList
     * @Description 인텐트 수정
     * @Author 문다운
     * @CreateDate 2022. 5. 26.
     */
    @RequestMapping(value = "/intent/update.do", method = RequestMethod.POST)
    @ResponseBody
    @Transactional
    public ModelAndView updateIntent(@RequestBody IntentRequestDTO dto) {
        return intentManageService.updateIntent(dto);
    }

    /**
     * @Name serviceNameList
     * @Description 인텐트 등록
     * @Author 문다운
     * @CreateDate 2022. 6. 03.
     */
    @RequestMapping(value = "/intent/insert.do", method = RequestMethod.POST)
    @ResponseBody
    public ModelAndView insertIntent(HttpServletRequest request, @RequestBody IntentRequestDTO dto) {
        ModelAndView mv = new ModelAndView(ajaxMainView);
        boolean result = true;
        String message = "저장되었습니다.";
        String seq = "";
        try {
            LoginVO resultVO = (LoginVO) request.getSession().getAttribute("LoginVO");
            dto.setRegistId(resultVO.getUserId());
            dto.setUpdateId(resultVO.getUserId());

            HashMap paramMap = dto.toMap();
            intentManageService.insertIntentMaster(paramMap);    // 2022.06.28 마스터만 먼저 등록
            seq = (String) paramMap.get("seq");                // 2022.06.28 추가

        } catch (DuplicateKeyException e) {
            result = false;
            message = e.getMessage();
        } catch (Exception e) {
            result = false;
            message = "처리도중 오류가 발생했습니다.";
            log.error("error", e);
        }
        mv.addObject("result", result);
        mv.addObject("message", message);
        mv.addObject("seq", seq); // 2022.06.28 추가
        return mv;
    }

    // 예문 단건 등록으로 변경 2022.06.28 추가
    @RequestMapping(value = "/intent/insertExample.do", method = RequestMethod.POST)
    @ResponseBody
    public ModelAndView insertIntent_example(HttpServletRequest request, @RequestBody IntentRequestDTO dto) {
        ModelAndView mv = new ModelAndView(ajaxMainView);
        boolean result = true;
        String message = "저장되었습니다.";

        String seq = "";
        try {
            LoginVO resultVO = (LoginVO) request.getSession().getAttribute("LoginVO");
            dto.setRegistId(resultVO.getUserId());
            dto.setUpdateId(resultVO.getUserId());

            String saveType = dto.getSaveType();
            if("D".equals(saveType)) {
                intentManageService.deleteIntentExample_one(dto.toMap());  	// 예문 삭제
                message = "정상적으로 삭제되었습니다.";
            }else if("I".equals(saveType)) {

                HashMap paramMap = dto.toMap();
                intentManageService.insertIntentExample(paramMap);  		// 예문 등록
                seq = (String) paramMap.get("seq");
                mv.addObject("seq", seq);
            }

        } catch (DuplicateKeyException e) {
            result = false;
            message = e.getMessage();
        } catch (Exception e) {
            result = false;
            message = "처리도중 오류가 발생했습니다.";
            log.error("error", e);
        }
        mv.addObject("result", result);
        mv.addObject("message", message);
        return mv;
    }

    /**
     * @Name serviceNameList
     * @Description 인텐트 삭제
     * @Author 문다운
     * @CreateDate 2022. 5. 26.
     */
    @RequestMapping(value = "/intent/delete.do", method = RequestMethod.POST)
    @ResponseBody
    public ModelAndView deleteIntent(HttpServletRequest request, @RequestParam Map<String, String> dataMap) {
        ModelAndView mv = new ModelAndView(ajaxMainView);
        boolean result = true;
        String message = "삭제되었습니다.";
        try {
            if (StringUtils.isBlank(dataMap.get("seq"))) {
                result = false;
                message = "삭제할 인텐트를 선택해주세요.";
            } else {
                HashMap eMap = new HashMap();
                eMap.putAll(dataMap);

                LoginVO resultVO = (LoginVO) request.getSession().getAttribute("LoginVO");
                eMap.put("updateId", resultVO.getUserId());
                intentManageService.deleteIntent(eMap);
            }
        } catch (Exception e) {
            result = false;
            message = "저장도중 오류가 발생했습니다.";
            log.error("error", e);
        }
        mv.addObject("result", result);
        mv.addObject("message", message);
        return mv;
    }

    /**
     * @Name uploadExcel
     * @Description 엑셀 업로드
     * @author 문다운
     * @CreateDate 2022.06.04
     */
    @RequestMapping(value = "/intent/upload.do", method = RequestMethod.POST)
    public String uploadExcel(MultipartHttpServletRequest request, @RequestParam Map<String, String> dataMap, RedirectAttributes redirectAttr) {
        boolean result = true;
        String message = "정상적으로 저장되었습니다.";
        try {
            HashMap eMap = new HashMap();
            LoginVO resultVO = (LoginVO) request.getSession().getAttribute("LoginVO");
            eMap.putAll(dataMap);
            eMap.put("registId", resultVO.getUserId());
            eMap.put("updateId", resultVO.getUserId());
            message = intentManageService.insertIntentExcel(request, eMap);
            intentManageService.workLogSave(MenuResource.rcpconversationintentmanage, ActionResource.upload, dataMap.get("serviceGroup"), "엑셀 업로드");
        } catch (CustomRuntimeException e) {
            result = false;
            message = e.getMessage();
        } catch (DuplicateKeyException e) {
            result = false;
            message = e.getMessage();
        }
        catch (Exception e) {
            result = false;
            message = "처리도중 오류가 발생했습니다.";
            log.error("error upload excel", e);
        }
        redirectAttr.addFlashAttribute("result", result);
        redirectAttr.addFlashAttribute("message", message);
        return "redirect:/admin/rcp/conversation/intent/manage.do";
    }

    @RequestMapping(value = "/intent/download.do", method = RequestMethod.POST)
    @ResponseBody
    @Transactional
    public void downloadExcel(IntentSearchVo dto) throws IOException, CustomNotFoundException {
        log.info("excel intent");
        intentManageService.downloadExcel(dto);
    }

}

