package cokr.xit.fims.cmmn.service.bean;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import cokr.xit.fims.cmmn.ExtrStngQuery;
import cokr.xit.fims.cmmn.dao.ExtrStngMapper;
import cokr.xit.fims.cmmn.pdf.extraction.Extraction;
import cokr.xit.fims.cmmn.pdf.extraction.PDFExtractionUtil;
import cokr.xit.fims.cmmn.service.LinkService;
import cokr.xit.foundation.component.AbstractServiceBean;
import cokr.xit.foundation.data.DataObject;

@Service("linkService")
public class LinkServiceBean extends AbstractServiceBean implements LinkService {

	@Resource(name = "linkBean")
	private LinkBean linkBean;

	@Resource(name = "extrStngMapper")
	private ExtrStngMapper extrStngMapper;

	@Override
	public String insertElectronicNoticeSndng(String filePath, String sggCd, String taskSeCd, String tmplatId) {

        ExtrStngQuery extrStngQuery = new ExtrStngQuery();
        extrStngQuery.setSggCd(sggCd).setTaskSeCd(taskSeCd);
        extrStngQuery.setTmplatId(tmplatId);
        List<DataObject> extractStngs = extrStngMapper.selectExtrArtclStngList(extrStngQuery);

		List<Extraction> extractionInfos = PDFExtractionUtil.extract(filePath, extractStngs);


		for(int i=0; i < extractionInfos.size(); i++) {

			Map<String, String> extractedText = extractionInfos.get(i).getTextItem();
			List<String> crdnPhotoBase64 = extractionInfos.get(i).getBase64List();

			//마스터
    		DataObject masterInfo = new DataObject();
    		masterInfo.set("signguCode", sggCd);
    		masterInfo.set("ffnlgCode", taskSeCd);
    		masterInfo.set("tmplatId", tmplatId);
    		masterInfo.set("sndngCo", extractionInfos.size());
    		masterInfo.set("sndngDt", extractedText.get("sndngDt")); //발송일시
    		masterInfo.set("closDt", extractedText.get("closDt")); //마감일시
    		//디테일
    		DataObject detailInfo = new DataObject();
    		detailInfo.set("signguCode", sggCd);
    		detailInfo.set("ffnlgCode", taskSeCd);
    		detailInfo.set("vhcleNo", extractedText.get("vhcleNo"));
    		detailInfo.set("ihidnum", extractedText.get("ihidnum"));
    		detailInfo.set("moblphonNo", extractedText.get("moblphonNo"));
    		detailInfo.set("nm", extractedText.get("nm"));
    		detailInfo.set("adres", extractedText.get("adres"));
    		detailInfo.set("detailAdres", extractedText.get("detailAdres"));
    		detailInfo.set("zip", extractedText.get("zip"));

    		//템플릿메시지데이터
    		detailInfo.set("tmpltMsgData", "");

    		//모바일페이지
    		String jsonTemplate = extrStngMapper.selectExtrBscStng(extrStngQuery).string("MOBILE_PAGE_TMPLT");
    		String json = linkBean.makeJson(jsonTemplate, extractedText, crdnPhotoBase64);
    		detailInfo.set("mobilePageCn", json);

    		//
    		detailInfo.set("mainCode", "");
    		//
    		detailInfo.set("useInsttIdntfcId", "");

    		//테이블 인서트
    		linkBean.insertElectronicNoticeSndng(masterInfo, List.of(detailInfo));
		}

		return "[S]";
	}
}
