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.service.bean.StngBean;
import cokr.xit.fims.cmmn.xls.FormatMaker;
import cokr.xit.fims.cmmn.xls.StyleMaker;
import cokr.xit.fims.crdn.CrdnQuery;
import cokr.xit.fims.crdn.dao.CrdnInfoMapper;
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/crdn02 로 접근할 수 있다.
 * @author leebj
 */
@Controller
@RequestMapping(name="단속 자료 검사", value=Crdn02Controller.CLASS_URL)
public class Crdn02Controller extends ApplicationController {

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

	public class METHOD_URL {
		public static final String
		crackdownDataInspectionMain = "/010/main.do",
		getInspectionDataList = "/020/list.do",
		getOverTimeInfo = "/050/info.do",
		updateOverTimeInfo = "/050/update.do"
		;
	}

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

	/** 단속 자료 검사 메인화면을 연다.
	 * @return fims/crdn/crdn02010-main
	 */
	@RequestMapping(name="단속 자료 검사 메인", value=METHOD_URL.crackdownDataInspectionMain)
	public ModelAndView crackdownDataInspectionMain() {
		Map<String, List<CommonCode>> commonCodes = getCodesOf("FIM002", "FIM003", "FIM010", "FIM026","FIM054");

		ModelAndView mav = new ModelAndView("fims/crdn/crdn02010-main")
			.addObject("pageName", "crdn02010")
			.addObject("FIM002List", commonCodes.get("FIM002"))
			.addObject("FIM003List", commonCodes.get("FIM003"))
			.addObject("FIM010List", commonCodes.get("FIM010"))
			.addObject("FIM054List", commonCodes.get("FIM054"))
			.addObject("TaskListForSgg", stngBean.filterTaskSectionCodeForSgg(commonCodes.get("FIM054")));
		return addCodes(commonCodes, mav, "FIM002", "FIM003", "FIM010", "FIM026");
	}

	/**검사자료 목록을 조회한다.<br />
	 * {@link CrdnService#getCrackdownList(CrdnQuery)} 참고
	 * @param query 검사자료 목록 조회 조건
	 * @return jsonView
	 */
	@Task
	@RequestMapping(name="검사자료 목록 조회", value=METHOD_URL.getInspectionDataList)
	public ModelAndView getInspectionDataList(CrdnQuery query) {
		switch(query.getInspectionDataType()) {
			case "photo" -> query.setGridType("photo");
			case "sameVehicleMain" -> query.setGridType("sameVehicleMain");
			case "sameVehicleSub" -> query.setGridType("sameVehicleSub");
		}
		setFetchSize(query)
			.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("단속일시", FormatMaker.yyyy_mm_dd_hh_mm_ss(format, "CRDN_YMD_TM").style(dateDT));
			valueMap.put("자료출처", format.of("CRDN_INPT_SE_NM").style(center));
			valueMap.put("차량번호", format.of("VHRNO"));
			valueMap.put("처리상태", format.of("CRDN_STTS_NM").style(center));
			valueMap.put("단속장소", format.of("CRDN_PLC"));
			valueMap.put("사진매수", format.of("ATCH_FILE_CNT").style(center));
			valueMap.put("위반건수", format.of("CRDN_CNT").style(center));
			valueMap.put("단속건수", format.of("CRDN_CNT").style(center));
			valueMap.put("검사결과", format.of("INSP_RSLT"));
			valueMap.put("처리방법", format.of("PRCS_MTHD").style(center));
			valueMap.put("위반동", format.of("CRDN_STDG_NM").style(center));
			valueMap.put("단속동", format.of("CRDN_STDG_NM").style(center));
			valueMap.put("원금액", format.of("FFNLG_CRDN_AMT").style(numeric));
			valueMap.put("감경금액", format.of("ADVNTCE_AMT").style(numeric));
			valueMap.put("금액", format.of("FFNLG_CRDN_AMT").style(numeric));
			valueMap.put("단속조", format.of("TEAM_NM").style(center));
			valueMap.put("성명", format.of("RTPYR_NM"));
			valueMap.put("주민번호", format.of("RTPYR_NO").style(center));
			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),"");
	}

	/**2시간 초과처리 팝업을 호출한다.<br />
	 * @param crdnId 단속 ID
	 * @return crdn02050-info
	 */
	@Task("PVS")
	@RequestMapping(name="2시간 초과 처리 화면 호출", value=METHOD_URL.getOverTimeInfo)
	public ModelAndView getOverTimeInfo(String savedCallbackFuncName, String crdnId) {
		DataObject crdnInfo = crdnInfoMapper.selectCrdnInfo(crdnId);

		return new ModelAndView("fims/crdn/crdn02050-info")
			.addObject("pageName","crdn02050")
			.addObject("crdnInfo", toJson(crdnInfo))
			.addObject("savedCallbackFuncName", savedCallbackFuncName);
	}

	/**단속자료의 2시간 초과여부를 변경하고, 금액을 수정한다. <br />
	 * @param chgAmtSe 금액 변경 구분, crdnId 단속 ID
	 * @return jsonView
	 * <pre><code> {
	 *     "saved": 수정되었으면 true, 그렇지 않으면 false
	 * }</code></pre>
	 */
	@Task("PVS")
	@RequestMapping(name="2시간 초과 정보 수정", value=METHOD_URL.updateOverTimeInfo)
	public ModelAndView updateOverTimeInfo(String chgAmtSe, String crdnId) {
		String rtnMsg = crdnService.updateOverTimeInfo(chgAmtSe, crdnId);
		return new ModelAndView("jsonView")
			.addObject("saved", rtnMsg.contains("[S]"));
	}
}