package cokr.xit.fims.cmmn.hwp.format;

import java.awt.Rectangle;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.stream.IntStream;

import org.egovframe.rte.fdl.string.EgovStringUtil;

import cokr.xit.applib.HttpStatusCodeException;
import cokr.xit.applib.Print;
import cokr.xit.applib.hwp.OffcsCellFinder;
import cokr.xit.applib.hwp.format.HWPFormat;
import cokr.xit.fims.cmmn.FimsPrintOption;
import cokr.xit.foundation.Assert;
import cokr.xit.foundation.data.DataObject;
import kr.dogfoot.hwplib.object.bodytext.control.table.Cell;
import kr.dogfoot.hwplib.object.bodytext.paragraph.Paragraph;

public class SvbtcList extends HWPFormat {

	public SvbtcList(Print print, FimsPrintOption printOption, List<DataObject> dataObjectList) {
		super(print, printOption, dataObjectList);
		this.maxRunCount = 1;
		this.formatFilePath = "template/hwp/svbtcList.hwp";
		this.print.setFormatKorName("공시송달");
		this.print.setFormatName("svbtc");
	}

	@Override
	public List<String> getDownloadDataNames() {
		List<String> list = new ArrayList<>();
		list.add("수령인명");
		list.add("수령인주소");
		list.add("차량번호");
		list.add("위반일자");
		list.add("위반장소");
		list.add("반송일자");
		list.add("반송사유");
		return list;
	}


	@Override
	public void runAsWriter() {
		DataObject info = !Assert.isEmpty(data) ? data.get(0) : null;
		if (info == null) return;

		String offcsFilePath = EgovStringUtil.null2void(info.string("OFFCS_FILE_PATH"));
		if(!offcsFilePath.isEmpty()) {
			File offcsFile = new File(offcsFilePath);
			if(!offcsFile.exists()) {
				throw new HttpStatusCodeException(500, "HWP파일 생성 중 오류가 발생하였습니다.\n직인 파일을 찾을 수 없습니다.");
			}
			BiConsumer<Paragraph, Rectangle> bc = writer.image().add(offcsFilePath);

			Cell cell = OffcsCellFinder.find(writer);
			if(cell != null) {
				Paragraph para = cell.getParagraphList().getParagraph(0);
				int width = (int)cell.getListHeader().getWidth(),
					height = (int)cell.getListHeader().getHeight();
				bc.accept(para, new Rectangle(1, 1, width, height));
			}
		}

		writer.setValue("문서번호", info.string("INPUT_DOC_NO"));
		writer.setValue("제목", info.string("INPUT_TTL_NM"));
		writer.setValue("공고기간", info.string("INPUT_SVBTC_DATE"));
		writer.setValue("기관장", info.string("INST_LEADER"));
		writer.setValue("부서명", info.string("SGG_DEPT_NM"));
		writer.setValue("부서전화번호", "☎" + info.string("DEPT_TELNO"));


		List<DataObject> list = IntStream.rangeClosed(1, this.data.size()).boxed().map(i -> {
			DataObject one = data.get(i-1);
			return (DataObject) new DataObject()
			.set("성명", one.string("RCPN_NM_MASK"))
			.set("주소", one.string("WHOL_ADDR_MASK"))
			.set("차량번호", one.string("VHRNO_MASK"))
			.set("위반장소", one.string("CRDN_PLC"))
			.set("위반일자", one.string("CRDN_DT"))
			.set("반송일자", one.string("DLVR_YMD_MASK"))
			.set("반송사유", one.string("UNDLVR_RSN_NM"))
			;
		}).toList();
		writer.table(2, 2, 2).setValues(list);

	}
}
