package cokr.xit.fims.chongno;

import java.io.InputStream;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import cokr.xit.base.file.FileInfo;
import cokr.xit.base.file.service.bean.FileBean;
import cokr.xit.fims.base.FimsUser;
import cokr.xit.fims.cmmn.FimsPrintOption;
import cokr.xit.fims.crdn.Crdn;
import cokr.xit.fims.crdn.service.CrdnService;
import cokr.xit.fims.sndb.SndbQuery;
import cokr.xit.fims.sndb.service.SndngDtlService;
import cokr.xit.fims.sprt.SprtQuery;
import cokr.xit.fims.sprt.dao.IntegrationSearchMapper;
import cokr.xit.fims.sprt.service.bean.MediaBean;
import cokr.xit.foundation.data.DataFormat;
import cokr.xit.foundation.data.DataObject;
import cokr.xit.foundation.web.AbstractController;

@Controller
@RequestMapping("/preview")
public class JasperController extends AbstractController {
    @Resource(name="crdnService")
	private CrdnService crdnService;
    /**발송 상세 서비스*/
    @Resource(name="sndngDtlService")
    private SndngDtlService sndngDtlService;
    @Resource(name="integrationSearchMapper")
    private IntegrationSearchMapper integrationSearchMapper;
    @Resource(name="fileBean")
    private FileBean fileBean;
    @Resource(name="mediaBean")
    private MediaBean mediaBean;

    @RequestMapping(name="계도장 미리보기", value="/warning.do")
    public ModelAndView previewWarning(SndbQuery req) {
    	List<DataObject> crdnList = getCrdnList(req);
    	crdnList.forEach(row -> {
    		row.set("CRDN_YMD_TM", DataFormat.yyyy_mm_dd(row.get("CRDN_YMD")) + " " + DataFormat.hh_mm_ss(row.get("CRDN_TM")));
    	});
    	List<String> crdnIdList = crdnList.stream().map(row -> row.string("CRDN_ID")).toList();
    	List<Crdn> crdns = crdnService.getCrackdowns(crdnIdList);
    	List<Crdn> upds = crdns.stream()
    	.filter(crdn -> {
    		return true;
    	})
    	.toList();
		String[] crdnIds = crdnIdList.toArray(new String[crdnList.size()]);
        Map<String, List<FileInfo>> crdnFiles = fileBean.getFilesOf(Crdn.INF_TYPE, crdnIds).stream()
        	.collect(Collectors.groupingBy(row -> row.getInfoKey()));
        List<InputStream> inputStreams = crdnList.stream()
            	.flatMap(crdn -> {
            		crdn.set("CRDN_YMD_TM", DataFormat.yyyy_mm_dd(crdn.get("CRDN_YMD")) + " " + DataFormat.hh_mm_ss(crdn.get("CRDN_TM")));

    	        	List<FileInfo> files = crdnFiles.get(crdn.string("CRDN_ID"));
    	        	List<InputStream> inputs = isEmpty(files) ? Collections.emptyList() :
    	        		files.stream()
    	        			 .map(FileInfo::getInputStream)
    	        			 .toList();

    	        	for (int i = 0; i < Math.min(4, inputs.size()); ++i) {
    					crdn.set("VLTN_IMG" + i, inputs.get(i));
    	        	}
    	        	return inputs.stream();
    	        })
    	        .toList();

        String today = dateFormats.format("yyyyMMdd", System.currentTimeMillis());
        FimsUser user = (FimsUser)currentUser().getUser();
        DataObject params = new DataObject()
        	.set("thisYear", today.substring(0, 4))
        	.set("thisMonth", today.substring(4, 6))
        	.set("thisDay", today.substring(6))
        	.set("managerName", user.getName())
        	.set("managerPhoneNo", user.getPhoneNo())
        	.set("managerEmail", user.getEmailAddress());

        return new ModelAndView("jasperView")
        	.addObject("jasper", "warning.jasper")
        	.addObject("params", params)
        	.addObject("dataMap", crdnList)
        	.addObject("filename", "warning.pdf")
        	.addObject("closables", inputStreams);
    }

    private List<DataObject> getCrdnList(SndbQuery req) {
    	String[] crdnIds = req.getCrdnIds();
    	if (isEmpty(crdnIds)) {
	        List<DataObject> trgtDtls = sndngDtlService.getSndngTrgtDtlIds(req);
	        crdnIds = trgtDtls.stream()
	        	.map(row -> row.string("CRDN_ID"))
	        	.toList()
	        	.toArray(new String[trgtDtls.size()]);
    	}

    	return integrationSearchMapper.selectIntegrationDataList(new SprtQuery().setCrdnIds(crdnIds));
    }

    @RequestMapping(name="사전통지서 미리보기", value="/prenotice.do")
    public ModelAndView previewPrenotice(SndbQuery req, FimsPrintOption printOption) {
    	List<DataObject> crdnList = getCrdnList(req);
    	String[] crdnIds = crdnList.stream().map(row -> row.string("CRDN_ID")).toList().toArray(new String[crdnList.size()]);
        Map<String, List<FileInfo>> crdnFiles = fileBean.getFilesOf(Crdn.INF_TYPE, crdnIds).stream()
        	.collect(Collectors.groupingBy(row -> row.getInfoKey()));

        String today = dateFormats.format("yyyyMMdd", System.currentTimeMillis()),
         	   year = today.substring(0, 4),
         	   month = today.substring(4, 6),
         	   day = today.substring(6);
        FimsUser user = (FimsUser)currentUser().getUser();
        String userName = user.getName(),
        	   userPhoneNo = user.getPhoneNo(),
        	   userEmail = user.getEmailAddress();
        List<InputStream> inputStreams = crdnList.stream()
        	.flatMap(crdn -> {
        		crdn.set("CRDN_YMD_TM", DataFormat.yyyy_mm_dd(crdn.get("CRDN_YMD")) + " " + DataFormat.hh_mm_ss(crdn.get("CRDN_TM")))
        			.set("ADVNTCE_DUDT_YMD", DataFormat.yyyy_mm_dd(crdn.get("ADVNTCE_DUDT_YMD")))
        			.set("issueYear", year).set("issueMonth", month).set("issueDay", day)
        			.set("managerName", userName).set("managerPhoneNo", userPhoneNo).set("managerEmail", userEmail)
	        	   ;

	        	List<FileInfo> files = crdnFiles.get(crdn.string("CRDN_ID"));
	        	List<InputStream> inputs = isEmpty(files) ? Collections.emptyList() :
	        		files.stream()
	        			 .map(FileInfo::getInputStream)
	        			 .toList();

	        	for (int i = 0; i < Math.min(4, inputs.size()); ++i) {
					crdn.set("VLTN_IMG" + i, inputs.get(i));
	        	}
	        	return inputs.stream();
	        })
	        .toList();

        String jasper = switch (printOption.getPaperSeCd()) {
        case "01" -> "/prenotice-a4.jasper";
        case "02" -> "/prenotice-letter.jasper";
        default -> throw new IllegalArgumentException("paperSeCd: " + printOption.getPaperSeCd());
        };
        return new ModelAndView("jasperView")
        	.addObject("jasper", jasper)
        	.addObject("dataMap", crdnList)
        	.addObject("filename", "prenotice.pdf")
        	.addObject("closables", inputStreams);
    }

    @RequestMapping(name="고지서 미리보기", value="/notice.do")
    public ModelAndView previewNotice(SndbQuery req, FimsPrintOption printOption) {
    	List<DataObject> crdnList = getCrdnList(req);

        String today = dateFormats.format("yyyyMMdd", System.currentTimeMillis());
        FimsUser user = (FimsUser)currentUser().getUser();
        DataObject params = new DataObject()
        	.set("thisYear", today.substring(0, 4))
        	.set("thisMonth", today.substring(4, 6))
        	.set("thisDay", today.substring(6))
        	.set("managerName", user.getName())
        	.set("managerPhoneNo", user.getPhoneNo())
        	.set("managerEmail", user.getEmailAddress());

        String jasper = switch (printOption.getPaperSeCd()) {
        case "01" -> "/notice-a4.jasper";
        case "02" -> "/notice-letter.jasper";
        default -> throw new IllegalArgumentException("paperSeCd: " + printOption.getPaperSeCd());
        };
        return new ModelAndView("jasperView")
        	.addObject("jasper", jasper)
        	.addObject("params", params)
        	.addObject("dataMap", crdnList)
        	.addObject("filename", "prenotice.pdf");
    }
}