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

import com.google.gson.Gson;
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.system.vo.DslDataTableRes;
import com.icomsys.main_vm.biz.rcp.monitoring.req.ConsultingListVoReq;
import com.icomsys.main_vm.biz.rcp.monitoring.service.MonitoringConsultingService;
import com.icomsys.main_vm.biz.rcp.monitoring.vo.ConsultingVO;
import com.icomsys.main_vm.biz.rcp.monitoring.vo.RecordDownloadVO;
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.TbSynonymMaster;
import com.icomsys.main_vm.db.mybatis.alias.MonitoringConsultingVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@Slf4j
@RequiredArgsConstructor
@RequestMapping("/admin/rcp/statistics/monitoring")
public class MonitoringConsultingController {

    private final MonitoringConsultingService monitoringConsultingService;
    private final ExcelService excelService;
    private final LogService logService;

    private final HttpServletRequest httpServletRequest;

    @GetMapping("/consulting/manage.do")
    public String ConsultingView(Model model){
        Cookie[] cookies = httpServletRequest.getCookies(); // 모든 쿠키 가져오기
        if(cookies != null){
            for (Cookie c : cookies) {
                String name = c.getName(); // 쿠키 이름 가져오기
                String value = c.getValue(); // 쿠키 값 가져오기
                log.info("###Cookie_Name : " + name);
                log.info("###Cookie_Value : " + value);
            }
        }

        return "/adm/rcp/monitoring/consulting";
    }

    @RequestMapping(value = "/consulting/list.do", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public DslDataTableRes<HashMap> consultingList(@RequestBody MonitoringConsultingVO vo) {
        vo.setLimit(vo.getPage() * vo.getPageSize());
        vo.setOffset(vo.getPageSize() * 10);

        List<HashMap> result = monitoringConsultingService.consultingList(vo);
        log.info("dataVo -> {}", new Gson().toJson(vo));

        //        int resultCnt = monitoringConsultingService.selectConsultingListCnt(vo);
        return new DslDataTableRes<HashMap>(result, Long.valueOf(vo.getPage() * vo.getPageSize() + result.size()), Long.valueOf(vo.getPageSize()), Long.valueOf(vo.getPage() * vo.getPageSize()));
    }

    @RequestMapping(value = "/consulting/recordCallList.do", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public List<HashMap> selectRecordCallList(@RequestBody MonitoringConsultingVO vo) {
        List<HashMap> result = monitoringConsultingService.selectRecordCallList(vo);

        return result;
    }

    @RequestMapping(value = "/consulting/sceneSelectList.do", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public List<HashMap> sceneSelectList(@RequestBody MonitoringConsultingVO vo) {
        List<HashMap> result = monitoringConsultingService.selectScenarioSeqAndName(vo);

        return result;
    }

    @RequestMapping(value = "/consulting/commonCodeSelectList.do", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public List<HashMap> commonCodeSelectList(@RequestBody MonitoringConsultingVO vo) {
        List<HashMap> result = monitoringConsultingService.selectCommonCodeAndDesc(vo);

        return result;
    }

    @RequestMapping(value = "/consulting/userCallCnt.do", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public int selectUserCallCnt(@RequestBody MonitoringConsultingVO vo) {
        return monitoringConsultingService.selectUserCallCnt(vo);
    }

    @RequestMapping(value = "/consulting/play.do", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String playRecordFile(@RequestBody RecordDownloadVO vo) {
        logService.LogSave(LogVO.builder()
                                .menuAuth(MenuResource.valueOf(vo.getMenuVal()))
                                .actionCode(String.valueOf((ActionResource.listen)))
                                .serviceGroup(vo.getOprMngCode())
                                .remark("녹취 듣기")
                                .build());

        return monitoringConsultingService.playRecordFileFromS3(vo.getFileName());
    }

    @ResponseBody
    @Transactional
    @PostMapping("/consulting/downloadRecordFile.do")
    public void downloadRecordFile(HttpServletRequest request, HttpServletResponse response, @ModelAttribute RecordDownloadVO vo) throws IOException {

        String recordFile = monitoringConsultingService.playRecordFileFromS3(vo.getFileName());
        //        String recordFile = "https://ccrma.stanford.edu/~jos/mp3/harpsi-cs.mp3";

        String resultFileName = recordFile.substring(recordFile.lastIndexOf('/') + 1);
        String filePath = recordFile.substring(0, recordFile.lastIndexOf('/') + 1);

        URL url;
        InputStream in = null;
        OutputStream out = null;

        try {
            String header = request.getHeader("User-Agent");
            if (!header.contains("MSIE") && !header.contains("Trident")) {
                resultFileName = new String(resultFileName.getBytes("UTF-8"), "iso-8859-1");
                response.setHeader("Content-Disposition", "attachment; filename=\"" + resultFileName + "\"");
            } else {
                resultFileName = URLEncoder.encode(recordFile, "UTF-8").replaceAll("\\+", "%20");
                response.setHeader("Content-Disposition", "attachment; filename=" + resultFileName + ";");
            }

            response.setHeader("Pragma", "no-cache;");
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Transfer-Encoding", "binary");
            out = response.getOutputStream();
            String fileUrl = filePath + resultFileName;
            url = new URL(fileUrl);
            in = url.openStream();

            while(true) {
                int data = in.read();
                if (data == -1) {
                    in.close();
                    out.close();
                    break;
                }

                out.write(data);
            }

            logService.LogSave(LogVO.builder()
                                    .menuAuth(MenuResource.valueOf(vo.getMenuVal()))
                                    .actionCode(String.valueOf((ActionResource.download)))
                                    .serviceGroup(vo.getOprMngCode())
                                    .remark("녹취 파일 다운로드")
                                    .build());
        } catch (Exception var13) {
            log.info("@@@@@@@@@@@@@@@ERROR@@@@@@@@@@@@@@@");
            response.setStatus(500);
        } finally {
            log.info("###########finally###########");
            if (in != null) {
                in.close();
            }

            if (out != null) {
                out.close();
            }
        }
    }

    @RequestMapping(value = "/consulting/chklistcnt.do", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public int chkListCnt(@RequestBody MonitoringConsultingVO vo) {
        return monitoringConsultingService.selectConsultingListCnt(vo);
    }

    @ResponseBody
    @Transactional
    @PostMapping("/consulting/exceldownload.do")
    public void downloadExcel(HttpServletResponse response, @ModelAttribute ConsultingListVoReq req) throws IOException {

        SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd/HH:mm:ss");

        String nowTime = sdf.format(System.currentTimeMillis());

        req.getMonitoringConsultingVO().setPage(-1);

        List<HashMap> result = monitoringConsultingService.consultingList(req.getMonitoringConsultingVO());

        List<ConsultingVO> consultingVOList = new ArrayList<>();

        if (result.size() > 0) {
            for (Map e : result) {
                ConsultingVO vo = new ConsultingVO();
                vo.setSeq(String.valueOf(new DecimalFormat("#").format(e.get("rownum"))));
                vo.setOprMngCodeName(String.valueOf(e.get("oprMngCodeName")));
                vo.setScenario(String.valueOf(e.get("scenarioName")));
                vo.setCallTime(String.valueOf(e.get("callTime")));
                vo.setCallInitDate(String.valueOf(e.get("callInitDate")));
                vo.setCallEndName(String.valueOf(e.get("callEndName")));
                vo.setTelNo(String.valueOf(e.get("telNo")));
                vo.setDnisNo(String.valueOf(e.get("dnisNo")));
                vo.setUserTalkCnt(String.valueOf(e.get("userTalkCnt")));
                vo.setBotTalkCnt(String.valueOf(e.get("botTalkCnt")));

                consultingVOList.add(vo);
            }
        } else {
            ConsultingVO vo = new ConsultingVO();
            vo.setSeq("");
            vo.setOprMngCodeName("");
            vo.setScenario("");
            vo.setCallTime("");
            vo.setCallInitDate("");
            vo.setCallEndName("");
            vo.setTelNo("");
            vo.setDnisNo("");
            vo.setUserTalkCnt("");
            vo.setBotTalkCnt("");

            consultingVOList.add(vo);
        }

        monitoringConsultingService.ExcelDownload("응대이력" + nowTime, consultingVOList, req.getTitleList());
        //        excelService.ExcelDownload("상담이력" + nowTime, consultingVOList, req.getTitleList());

        logService.LogSave(LogVO.builder()
                                .menuAuth(MenuResource.valueOf(req.getMenuVal()))
                                .actionCode(String.valueOf((ActionResource.download)))
                                .serviceGroup(req.getOprMngCode())
                                .remark("엑셀 다운로드")
                                .build());
    }

}

