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.CrdnQuery;
import cokr.xit.fims.crdn.ExmptnVhcl;
import cokr.xit.fims.crdn.service.CrdnStngService;
import cokr.xit.fims.task.Task;
import cokr.xit.foundation.data.DataObject;

/**면제차량 관리 서비스 웹 컨트롤러.<br />
 * {웹 컨텍스트}/crdn/crdn08 로 접근할 수 있다.
 * @author leebj
 */
@Controller
@RequestMapping(name="면제차량 관리", value=Crdn08Controller.CLASS_URL)
public class Crdn08Controller extends ApplicationController {

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

	public class METHOD_URL {
		public static final String
		  exemptionVehicleManagementMain = "/010/main.do"
		, getExemptionVehicleList = "/010/list.do"
		, removeExemptionVehicleInfo = "/010/remove.do"
		, getExemptionVehicleInfo = "/020/info.do"
		, createExemptionVehicleInfo = "/020/create.do"
		, updateExemptionVehicleInfo = "/020/update.do"
		, getExemptionVehicleHistoryList = "/030/list.do"
		;
	}

	@Resource(name="crdnStngService")
	private CrdnStngService crdnStngService;

	@Resource(name="userMapper")
	private UserMapper userMapper;

	/** 면제차량 관리 메인화면을 연다.
	 * @return fims/crdn/crdn08010-main
	 */
	@RequestMapping(name="면제차량 관리", value=METHOD_URL.exemptionVehicleManagementMain)
	public ModelAndView exemptionVehicleManagementMain() {
		Map<String, List<CommonCode>> commonCodes = getCodesOf("NTR034");

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

	/**면제차량 목록을 조회한다.<br />
	 * {@link CrdnStngService#getExemptionVehicleList(CrdnQuery)} 참고
	 * @param query 면제차량 목록 조회 조건
	 * @return jsonView
	 */
	@Task("BPV")
	@RequestMapping(name="면제차량 목록 조회", value=METHOD_URL.getExemptionVehicleList)
	public ModelAndView getExemptionVehicleList(CrdnQuery query) {
		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 dateYMD = format.yyyy_mm_dd();
			CellStyle dateDT = format.yyyy_mm_dd_hh_mm_ss();

			List<DataObject> list = crdnStngService.getExemptionVehicleList(query.setFetchSize(0));

			Map<String, Object> valueMap = new HashMap<String, Object>();
			valueMap.put("차량번호", format.of("VHRNO"));
			valueMap.put("사유", format.of("EXMPTN_RSN"));
			valueMap.put("공문번호", format.of("DOC_NO"));
			valueMap.put("소유주명", format.of("OWNR_NM"));
			valueMap.put("면제시작일", FormatMaker.yyyy_mm_dd(format, "EXMPTN_BGNG_YMD").style(dateYMD));
			valueMap.put("면제종료일", FormatMaker.yyyy_mm_dd(format, "EXMPTN_END_YMD").style(dateYMD));
			valueMap.put("입력자", format.of("RGTR_NM"));
			valueMap.put("입력일시", FormatMaker.yyyy_mm_dd_hh_mm_ss(format, "REG_DT").style(dateDT));
			valueMap.put("수정자", format.of("MDFR_NM"));
			valueMap.put("수정일시", FormatMaker.yyyy_mm_dd_hh_mm_ss(format, "MDFCN_DT").style(dateDT));
			valueMap.put("삭제자", format.of("DLTR_NM"));
			valueMap.put("삭제사유", format.of("DEL_RSN"));
			valueMap.put("삭제일시", FormatMaker.yyyy_mm_dd_hh_mm_ss(format, "DEL_DT").style(dateDT));
			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());
		}

		setFetchSize(query);
		return setPagingInfo(new ModelAndView("jsonView"), crdnStngService.getExemptionVehicleList(query),"");
	}

	/**면제차량 상세조회 팝업 화면을 연다.<br />
	 * @return fims/crdn/crdn08020-info
	 */
	@Task("BPV")
	@RequestMapping(name="면제차량 정보 조회", value=METHOD_URL.getExemptionVehicleInfo)
	public ModelAndView getExemptionVehicleInfo(String exmptnVhclId) {
		DataObject info = !isEmpty(exmptnVhclId) ? crdnStngService.getExemptionVehicleInfo(exmptnVhclId) : new DataObject();

		return new ModelAndView("fims/crdn/crdn08020-info")
			.addObject("pageName", "crdn08020")
			.addObject("exmptnVhclInfo", toJson(info));
	}

	/** 면제차량 정보를 등록한다.
	 * {@link CrdnStngService#createExemptionVehicleInfo(exmptnVhcl)} 참고
	 * @param exmptnVhcl 면제차량 정보
	 * @return jsonView
	 * <pre><code> {
	 *     "saved": 저장되었으면 true, 그렇지 않으면 false
	 * }</code></pre>
	 */
	@Task("BPV")
	@RequestMapping(name="면제차량 정보 등록", value=METHOD_URL.createExemptionVehicleInfo)
	public ModelAndView createExemptionVehicleInfo(ExmptnVhcl exmptnVhcl) {
		exmptnVhcl.setSggCd(currentUser().getOrgID());
		String rtnMsg = crdnStngService.createExemptionVehicleInfo(exmptnVhcl);

		return new ModelAndView("jsonView")
			.addObject("saved", rtnMsg.contains("[S]"));
	}

	/** 면제차량 정보를 수정한다.
	 * {@link CrdnStngService#updateExemptionVehicleInfo(exmptnVhcl)} 참고
	 * @param exmptnVhcl 면제차량 정보
	 * @return jsonView
	 * <pre><code> {
	 *     "saved": 저장되었으면 true, 그렇지 않으면 false
	 * }</code></pre>
	 */
	@Task("BPV")
	@RequestMapping(name="면제차량 정보 수정", value=METHOD_URL.updateExemptionVehicleInfo)
	public ModelAndView updateExemptionVehicleInfo(ExmptnVhcl exmptnVhcl) {
		exmptnVhcl.setSggCd(currentUser().getOrgID());
		String rtnMsg = crdnStngService.updateExemptionVehicleInfo(exmptnVhcl);
		return new ModelAndView("jsonView")
			.addObject("saved", rtnMsg.contains("[S]"));
	}

	/** 면제차량 정보를 삭제한다.
	 * {@link CrdnStngService#removeExemptionVehicleInfo(exmptnVhclId)} 참고
	 * @param exmptnVhcl 면제차량 정보
	 * @return jsonView
	 * <pre><code> {
	 *     "saved": 저장되었으면 true, 그렇지 않으면 false
	 * }</code></pre>
	 */
	@Task("BPV")
	@RequestMapping(name="면제차량 정보 삭제", value=METHOD_URL.removeExemptionVehicleInfo)
	public ModelAndView removeExemptionVehicleInfo(ExmptnVhcl exmptnVhcl) {
		String rtnMsg = crdnStngService.removeExemptionVehicleInfo(exmptnVhcl);
		return new ModelAndView("jsonView")
			.addObject("saved", rtnMsg.contains("[S]"));
	}

	/**면제차량 이력을 조회한다.<br />
	 * {@link CrdnStngService#getExemptionVehicleHistoryList(CrdnQuery)} 참고
	 * @param exmptnVhclId 면제차량 ID
	 * @return jsonView
	 */
	@Task("BPV")
	@RequestMapping(name="면제차량 이력 조회", value=METHOD_URL.getExemptionVehicleHistoryList)
	public ModelAndView getExemptionVehicleHistoryList(String exmptnVhclId) {
		List<DataObject> list = crdnStngService.getExemptionVehicleHistoryList(exmptnVhclId);

		ModelAndView mav = new ModelAndView("fims/crdn/crdn08030-info")
			.addObject("pageName", "crdn08030")
			.addObject("list", toJson(list));

		Map<String, List<CommonCode>> commonCodes = getCodesOf("NTR034");
		return addCodes(commonCodes, mav, "NTR034");
	}
}