package cokr.xit.fims.cvlc.web;

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

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

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.Comment;
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.file.service.FileQuery;
import cokr.xit.base.file.service.bean.FileBean;
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.Crdn;
import cokr.xit.fims.crdn.CrdnQuery;
import cokr.xit.fims.crdn.service.CrdnService;
import cokr.xit.fims.cvlc.CrdnCvlcpt;
import cokr.xit.fims.cvlc.service.CrdnCvlcptService;
import cokr.xit.fims.task.Task;
import cokr.xit.foundation.data.DataObject;

/**민원답변대상자료 서비스 웹 컨트롤러.<br />
 * {웹 컨텍스트}/cvlc/cvlc02 로 접근할 수 있다.
 * @author leebj
 */
@Controller
@RequestMapping(name="민원답변대상자료 관리 업무", value=Cvlc02Controller.CLASS_URL)
public class Cvlc02Controller extends ApplicationController {

	public static final String CLASS_URL = "/cvlc/cvlc02";

	public class METHOD_URL {
		public static final String
		civilComplaintAnswerTargetDataMain = "/010/main.do",
		selectCivilComplaintAnswerTargetDataList = "/030/list.do",
		updateAnswerTargetProcessStatus = "/030/update.do",
		executeDisabledTagInfoInquire = "/040/update.do",
		answerPreviewInfo = "/060/info.do",
		updateAnswerContent = "/060/update.do"
		;
	}

	@Resource(name="crdnService")
	private CrdnService crdnService;
	@Resource(name="crdnCvlcptService")
	private CrdnCvlcptService crdnCvlcptService;
	@Resource(name="userMapper")
	protected UserMapper userMapper;
	@Resource(name = "stngBean")
	private StngBean stngBean;
	@Resource(name = "fileBean")
	private FileBean fileBean;

	/** 민원 답변 대상 자료 메인화면을 연다.
	 * @return fims/cvlc/cvlc02010-main
	 */
	@RequestMapping(name="민원 답변 대상 자료 메인", value=METHOD_URL.civilComplaintAnswerTargetDataMain)
	public ModelAndView civilComplaintAnswerTargetDataMain() {
		Map<String, List<CommonCode>> commonCodes = getCodesOf("FIM017","FIM022", "FIM026", "FIM054");

		ModelAndView mav = new ModelAndView("fims/cvlc/cvlc02010-main")
			.addObject("pageName", "cvlc02010")
			.addObject("FIM017List", commonCodes.get("FIM017"))
			.addObject("FIM054List", commonCodes.get("FIM054"))
			.addObject("TaskListForSgg", stngBean.filterTaskSectionCodeForSgg(commonCodes.get("FIM054")));
		return addCodes(commonCodes, mav, "FIM022", "FIM026");
	}

	/**민원답변대상자료 목록을 조회한다.<br />
	 * {@link CrdnService#getCrackdownList(CrdnQuery)} 참고
	 * @param query 민원답변대상자료 목록 조회 조건
	 * @return jsonView
	 */
	@Task
	@RequestMapping(name="민원답변대상자료 목록", value=METHOD_URL.selectCivilComplaintAnswerTargetDataList)
	public ModelAndView selectCivilComplaintAnswerTargetDataList(CrdnQuery query) {
		setFetchSize(query.setGridType("answerTargetData"));
		query.setSggCd(currentUser().getOrgID());

		if("xls".equals(query.getDownload())) {
			List<CellDef> cellDefs = fromJson(query.getCellDefs(), CellDef.listType());
			if(ifEmpty(query.getIncludePhoto(), () -> "").equals("Y")) {
				cellDefs.add((new CellDef()).setLabel("사진1").setWidth(18).setField("CRDN_PHOTO_PATH1"));
				cellDefs.add((new CellDef()).setLabel("사진2").setWidth(18).setField("CRDN_PHOTO_PATH2"));
			}

			XLSWriter xlsx = new XLSWriter().worksheet(0);
			Format format = new Format(xlsx);
			Comment comment = new Comment(xlsx);

			CellStyle center = format.cellStyle(Style.CENTER);
			CellStyle left = format.cellStyle(Style.LEFT);
			CellStyle dateYMD = format.yyyy_mm_dd();
			CellStyle dateDT = format.yyyy_mm_dd_hh_mm_ss();

			Map<String, Object> valueMap = new HashMap<String, Object>();
			valueMap.put("접수번호", center);
			valueMap.put("목록번호", center);
			valueMap.put("신고자", center);
			valueMap.put("담당자", center);
			valueMap.put("담당자전화번호", center);
			valueMap.put("접수일자", FormatMaker.yyyy_mm_dd(format,"CVLCPT_RCPT_YMD").style(dateYMD));
			valueMap.put("처리기한", FormatMaker.yyyy_mm_dd_hh_mm_ss(format,"CVLCPT_PRCS_PRNMNT_DT").style(dateDT));
			valueMap.put("위반일시", FormatMaker.yyyy_mm_dd_hh_mm_ss(format,"CRDN_YMD_TM").style(dateDT));
			valueMap.put("위반내용", center);
			valueMap.put("차량번호", left);
			valueMap.put("서손/계고사유", center);
			valueMap.put("특기사항", left);
			if(ifEmpty(query.getIncludePhoto(), () -> "").equals("Y")) {
				valueMap.put("사진1", FormatMaker.photoCellForApproval(format, comment, "CRDN_PHOTO_PATH1"));
				valueMap.put("사진2", FormatMaker.photoCellForApproval(format, comment, "CRDN_PHOTO_PATH2"));
			}
			CellDef.setValues(cellDefs, valueMap);

			List<DataObject> list = crdnCvlcptService.getCivilComplaintList(query.setFetchSize(0));
			if(ifEmpty(query.getIncludePhoto(), () -> "").equals("Y")) {
				for(DataObject crdn : list) {
					String crdnId = crdn.string("CRDN_ID");
					FileQuery fileQuery = new FileQuery();
					fileQuery.setInfoType(Crdn.INF_TYPE);
					fileQuery.setInfoKeys(crdnId);
					List<DataObject> fileInfoList = fileBean.getFileList(fileQuery);

					if(fileInfoList != null && fileInfoList.size() > 0) {
						for(int j=0; (j < fileInfoList.size()) && (j < 2); j++) {
							crdn.set("CRDN_PHOTO_PATH"+(j+1), fileInfoList.get(j).string("FILE_PATH"));
						}
					}
				}
			}

			xlsx.cell(0, 0).value("민원답변대상자료 목록").value(center).merge(0, cellDefs.size()-1);
			xlsx.cell(3, 0).rowValues(CellDef.header(cellDefs, () -> StyleMaker.headerStyle(xlsx)));
			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"), crdnCvlcptService.getCivilComplaintList(query),"");
	}

	/** 민원답변내용 미리보기 화면을 연다.
	 * @return
	 */
	@Task
	@RequestMapping(name="민원답변내용 미리보기", value=METHOD_URL.answerPreviewInfo)
	public ModelAndView answerPreviewInfo(HttpServletRequest hReq, CrdnQuery query) {
		query
			.setCurrentUserAcnt(currentUser().getAccount())
			.setTaskSeCd(hReq.getParameter("taskSeCd"))
//			.setTaskSeCd(hReq.getServletPath().split("/")[1])
			.setSggCd(currentUser().getOrgID());
		DataObject cvlcptInfo = crdnCvlcptService.getAnswerPreview(query);

		boolean json = jsonResponse();
		return new ModelAndView(json ? "jsonView" : "fims/cvlc/cvlc02060-info")
			.addObject("pageName", "cvlc02060")
			.addObject("taskSeCd", query.getTaskSeCd())
			.addObject("cvlcptInfo", json ? cvlcptInfo : toJson(cvlcptInfo));
	}

	/**지정한 민원 자료의 답변 내용을 저장한다.
	 * @param crdnCvlcpt 단속민원 정보
	 * @return jsonView
	 * <pre><code> {
	 *     "affected": 저장된 정보수
	 *     "saved": 저장되었으면 true, 그렇지 않으면 false
	 * }</code></pre>
	 */
	@Task
	@RequestMapping(name="답변 내용 저장", value=METHOD_URL.updateAnswerContent)
	public ModelAndView updateAnswerContent(CrdnCvlcpt crdnCvlcpt) {
		String rtnMsg = crdnCvlcptService.updateAnswerContent(crdnCvlcpt);
		return new ModelAndView("jsonView")
			.addObject("saved", rtnMsg.contains("[S]"));
	}

	/**민원 답변 대상 자료의 처리 상태를 변경한다.
	 * @param crdnCvlcpt 단속민원 정보
	 * @return jsonView
	 * <pre><code> {
	 *     "affected": 저장된 정보수
	 *     "saved": 저장되었으면 true, 그렇지 않으면 false
	 * }</code></pre>
	 */
	@Task
	@RequestMapping(name="답변 대상 처리상태 변경", value=METHOD_URL.updateAnswerTargetProcessStatus)
	public ModelAndView updateAnswerTargetProcessStatus(String processType, String... crdnIds) {
		String currentSggCd = currentUser().getOrgID();
		String currentUserAcnt = currentUser().getAccount();
		String rtnMsg = crdnCvlcptService.updateAnswerTargetProcessStatus(processType, currentSggCd, currentUserAcnt, crdnIds);

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

	/**지정한 단속자료에 대해 표지정보조회 실행 후 장애인차량이 아닌 건은 서손 처리한다.
	 * @param crdnIds 단속ID 목록
	 * @return jsonView
	 * <pre><code> {
	 *     "affected": 저장된 정보수
	 *     "saved": 저장되었으면 true, 그렇지 않으면 false
	 * }</code></pre>
	 */
	@Task("DPV")
	@RequestMapping(name="표지 정보 조회 실행", value=METHOD_URL.executeDisabledTagInfoInquire)
	public ModelAndView executeDisabledTagInfoInquire(String... crdnIds) {
		String rtnMsg = crdnCvlcptService.executeDisabledTagInfoInquire(crdnIds);
		return new ModelAndView("jsonView")
			.addObject("saved", rtnMsg.contains("[S]"));
	}
}