package cokr.xit.fims.crdn.web;

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

import javax.annotation.Resource;

import org.apache.poi.ss.usermodel.CellStyle;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import cokr.xit.base.code.CommonCode;
import cokr.xit.base.docs.xls.CellDef;
import cokr.xit.base.docs.xls.Format;
import cokr.xit.base.docs.xls.Style;
import cokr.xit.base.docs.xls.XLSWriter;
import cokr.xit.base.user.dao.UserMapper;
import cokr.xit.base.web.ApplicationController;
import cokr.xit.fims.cmmn.xls.FormatMaker;
import cokr.xit.fims.cmmn.xls.StyleMaker;
import cokr.xit.fims.crdn.Crdn;
import cokr.xit.fims.crdn.CrdnQuery;
import cokr.xit.fims.crdn.service.CrdnService;
import cokr.xit.fims.crdn.service.CrdnStngService;
import cokr.xit.fims.task.Task;
import cokr.xit.foundation.data.DataObject;

/**표지정보확인 서비스 웹 컨트롤러.<br />
 * {웹 컨텍스트}/crdn/crdn03 로 접근할 수 있다.
 * @author leebj
 */
@Controller
@RequestMapping(name="표지정보 미확인 자료 조회", value=Crdn03Controller.CLASS_URL)
public class Crdn03Controller extends ApplicationController {

	public static final String CLASS_URL = "/crdn/crdn03";

	public class METHOD_URL {
		public static final String
		tagInformationUndefinedDataMain = "/010/main.do",
		getTagInformationUndefinedDataList = "/030/list.do",
		updateTagInfo = "/030/update.do"
		;
	}

	@Resource(name="crdnService")
	private CrdnService crdnService;
	@Resource(name="crdnStngService")
	private CrdnStngService crdnStngService;
	@Resource(name="userMapper")
	protected UserMapper userMapper;

	/** 표지정보 미확인 자료 메인화면을 연다.
	 * @return fims/crdn/crdn03010-main
	 */
	@RequestMapping(name="표지정보 미확인 자료 메인", value=METHOD_URL.tagInformationUndefinedDataMain)
	public ModelAndView tagInformationUndefinedDataMain() {
		Map<String, List<CommonCode>> commonCodes = getCodesOf("FIM003", "FIM010");

		ModelAndView mav = new ModelAndView("fims/crdn/crdn03010-main").addObject("pageName","crdn03010");
		return addCodes(commonCodes, mav, "FIM003", "FIM010");
	}

	/**표지정보미확인자료 목록을 조회한다.<br />
	 * {@link CrdnService#getCrackdownList(CrdnQuery)} 참고
	 * @param req 표지정보미확인자료 목록 조회 조건
	 * @return jsonView
	 */
	@Task("DPV")
	@RequestMapping(name="표지정보미확인자료 목록", value=METHOD_URL.getTagInformationUndefinedDataList)
	public ModelAndView getTagInformationUndefinedDataList(CrdnQuery query) {
		setFetchSize(
			query
				.setGridType("tagInformationUndefinedData")
				.setSggCd(currentUser().getOrgID())
		);


		if("xls".equals(query.getDownload())) {
			List<CellDef> cellDefs = fromJson(query.getCellDefs(), CellDef.listType());

			XLSWriter xlsx = new XLSWriter().worksheet(0);
			Format format = new Format(xlsx);
			CellStyle center = format.cellStyle(Style.CENTER);
			CellStyle numeric = format.n_nn0();
			CellStyle dateDT = format.yyyy_mm_dd_hh_mm_ss();

			List<DataObject> list = crdnService.getCrackdownList(query.setFetchSize(0));

			Map<String, Object> valueMap = new HashMap<String, Object>();
			valueMap.put("자료출처", format.of("CRDN_INPT_SE_NM").style(center));
			valueMap.put("위반일시", FormatMaker.yyyy_mm_dd_hh_mm_ss(format, "CRDN_YMD_TM").style(dateDT));
			valueMap.put("차량번호", format.of("VHRNO"));
			valueMap.put("법정동", format.of("CRDN_STDG_NM").style(center));
			valueMap.put("잔액", format.of("BLNC").style(numeric));
			valueMap.put("사진건수", format.of("ATCH_FILE_CNT").style(center));
			valueMap.put("발행번호", format.of(format.of("CRDN_SN")));
			CellDef.setValues(cellDefs, valueMap);

			xlsx.cell(0, 0).value("표지정보미확인자료 목록").value(center).merge(0, cellDefs.size()-1)
				.cell(3, 0).rowValues(CellDef.header(cellDefs, () -> StyleMaker.headerStyle(xlsx)))
				.cell(4, 0).values(list, CellDef.values(cellDefs.stream().map(i -> {if(i.getValue() instanceof Format) {i.setField(null);}; return i;}).toList()));

			return new ModelAndView("downloadView").addObject("download", xlsx.getDownloadable().setFilename("표지정보미확인자료 목록.xlsx"))
					.addObject("downloadData", list).addObject("dataNames", cellDefs.stream().map(CellDef::getLabel).toList());
		}

		return setPagingInfo(new ModelAndView("jsonView"), crdnService.getCrackdownList(query),"");
	}

	/**표지정보 미확인 자료를 수정한다.
	 * @param crdn 단속 대장 정보
	 * @return jsonView
	 * <pre><code> {
	 *     "saved": 수정되었으면 true, 그렇지 않으면 false
	 * }</code></pre>
	 */
	@Task("DPV")
	@RequestMapping(name="표지정보 미확인 자료 수정", value=METHOD_URL.updateTagInfo)
	public ModelAndView updateTagInfo(Crdn crdn) {
		String rtnMsg = crdnService.updateTagInfo(crdn);
		return new ModelAndView("jsonView")
			.addObject("saved", rtnMsg.contains("[S]"));
	}
}