package cokr.xit.fims.cvlc.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;

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

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import cokr.xit.base.code.CommonCode;
import cokr.xit.base.file.FileInfo;
import cokr.xit.base.file.FileInfo.Relation;
import cokr.xit.base.file.web.FileInfoFactory;
import cokr.xit.base.web.ApplicationController;
import cokr.xit.fims.crdn.Crdn;
import cokr.xit.fims.crdn.CrdnQuery;
import cokr.xit.fims.crdn.dao.GlobalStngMapper;
import cokr.xit.fims.crdn.service.CrdnService;
import cokr.xit.fims.cvlc.CrdnCvlcpt;
import cokr.xit.fims.cvlc.service.CrdnCvlcptService;
import cokr.xit.foundation.UserInfo;
import cokr.xit.foundation.data.DataObject;

/**민원접수자료 서비스 웹 컨트롤러.<br />
 * {웹 컨텍스트}/cvlc/cvlc01 로 접근할 수 있다.
 * @author leebj
 */
public class Cvlc01Controller extends ApplicationController {

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

	public class METHOD_URL {
		public static final String
		civilComplaintReceiptDataMain = "/010/main.do",
		getCivilComplaintReceiptDataList = "/010/list.do",
		removeCivilComplaint = "/010/remove.do",
		getCivilComplaintReceiptInitialDataInfo = "/020/info.do",
		saveCivilComplaintProcessSection = "/020/update.do",
		copyCivilComplaintInfo = "/020/create.do",
		sendBackCivilComplaintInfo = "/020/remove.do",
		getCivilComplaintOriginalInfo = "/050/info.do",
		makeFileFromHwpFormat = "/050/makeFileFromHwpFormat.do"
		;
	}

	@Resource(name="globalStngMapper")
	protected GlobalStngMapper globalStngMapper;

	@Resource(name="crdnService")
	private CrdnService crdnService;

	@Resource(name="crdnCvlcptService")
	private CrdnCvlcptService crdnCvlcptService;

	/** 민원 접수 자료 메인화면을 연다.
	 * @return fims/cvlc/cvlc01010-main
	 */
	public ModelAndView civilComplaintReceiptDataMain() {
		ModelAndView mav = new ModelAndView();
		mav.setViewName("fims/cvlc/cvlc01010-main");
		mav.addObject("pageName", "cvlc01010-main");

		Map<String, List<CommonCode>> commonCodes = getCodesOf("FIM026","FIM054");
		mav.addObject("FIM054List", commonCodes.get("FIM054"));
		addCodes(commonCodes, mav, "FIM026");

		mav.addObject("currentUserName", UserInfo.current().getName());
		return mav;
	}

	/**민원접수자료 목록을 조회한다.<br />
	 * {@link CrdnService#getCrackdownList(CrdnQuery)} 참고
	 * @param query 민원접수자료 목록 조회 조건
	 * @return jsonView
	 */
	public ModelAndView getCivilComplaintReceiptDataList(CrdnQuery query) {
		query.setGridType("receiptData");
		setFetchSize(query);
		return setCollectionInfo(new ModelAndView("jsonView"), crdnCvlcptService.getCivilComplaintList(query),"");
	}

	/**지정한 민원자료를 제거한다.
	 * @param crdnId 단속대장 아이디
	 * @return jsonView
	 * <pre><code> {
	 *     "affected": 저장된 정보수
	 *     "saved": 저장되었으면 true, 그렇지 않으면 false
	 * }</code></pre>
	 */
	public ModelAndView removeCivilComplaint(String[] IDs) {

		boolean saved = crdnService.remove(IDs);

		return new ModelAndView("jsonView")
			.addObject("saved", saved);
	}

	/** 민원내역 원본 보기 팝업 화면을 연다.
	 * @return fims/cvlc/cvlc01050-info
	 */
	public ModelAndView getCivilComplaintOriginalInfo(HttpServletRequest hReq, CrdnQuery query) {

		boolean json = jsonResponse();

		ModelAndView mav = new ModelAndView(json ? "jsonView" : "fims/cvlc/cvlc01050-info");
		mav.addObject("pageName", "cvlc01050-info");
		String urlTaskSeCd = hReq.getServletPath().split("/")[1];
		mav.addObject("taskSeCd", urlTaskSeCd);

		Map<String, List<CommonCode>> commonCodes = getCodesOf("FIM039");
		mav.addObject("FIM039List", commonCodes.get("FIM039"));

		DataObject info = crdnCvlcptService.getCivilComplaintOriginalInfo(query);

		mav.addObject("cvlcptInfo", json ? info : toJson(info));
		return mav;
	}

	/** 민원내역 원본을 한글 파일로 작성한다.
	 * @return hwp파일
	 */
	public ModelAndView makeFileFromHwpFormat(CrdnQuery query) {

		Map<String,String> result = crdnCvlcptService.makeFileFromHwpFormat(query);
		ModelAndView mav = new ModelAndView("jsonView");
		mav.addAllObjects(result);
		return mav;
	}

	/**민원접수 초기자료 상세조회 팝업 화면을 연다.<br />
	 * @return fims/cvlc/cvlc01020-info
	 */
	public ModelAndView getCivilComplaintReceiptInitialDataInfo(HttpServletRequest hReq, CrdnQuery query) {
		boolean json = jsonResponse();
		String pageName = "cvlc01020-info";

		ModelAndView mav = new ModelAndView(json ? "jsonView" : "fims/cvlc/"+pageName);
		mav.addObject("pageName", pageName);

		String urlTaskSeCd = hReq.getServletPath().split("/")[1];
		mav.addObject("taskSeCd", urlTaskSeCd);

		DataObject info = crdnCvlcptService.getCivilComplaintReceiptInitialDataInfo(query);

		mav.addObject("crdnInfo", json ? info : toJson(info));

		mav.addObject("openerPageName", hReq.getParameter("openerPageName"));

		mav.addObject("stdgNmList", globalStngMapper.selectStdgNmListForCurrentUser());

		String vltnByTask = "";
		switch(urlTaskSeCd) {
			case "PVS" -> { vltnByTask = "WEB002"; }
			case "BPV" -> { vltnByTask = "FIM005"; }
			case "DPV" -> { vltnByTask = "FIM006"; }
			case "ECA" -> { vltnByTask = "FIM061"; }
		}
		Map<String, List<CommonCode>> commonCodes = getCodesOf("FIM011","FIM053","LVS005",vltnByTask);
		mav.addObject("FIM011List", commonCodes.get("FIM011"));
		mav.addObject("FIM053List", commonCodes.get("FIM053"));
		mav.addObject("LVS005List", commonCodes.get("LVS005"));
		mav.addObject("VLTNList", commonCodes.get(vltnByTask));

		switch(urlTaskSeCd) {
			case "PVS" -> {
				commonCodes = getCodesOf("FIM002","FIM007","FIM009");
				mav.addObject("FIM002List", commonCodes.get("FIM002"));
				mav.addObject("FIM007List", commonCodes.get("FIM007"));
				mav.addObject("FIM009List", commonCodes.get("FIM009"));
			}
			case "BPV" -> {
				commonCodes = getCodesOf("FIM002","FIM009");
				mav.addObject("FIM002List", commonCodes.get("FIM002"));
				mav.addObject("FIM009List", commonCodes.get("FIM009"));
			}
			case "DPV" -> {
				commonCodes = getCodesOf("FIM034");
				mav.addObject("FIM034List", commonCodes.get("FIM034"));
			}
			case "ECA" -> { }
		}

		return mav;
	}

	/**지정한 민원 초기자료를 수정한다.
	 * @param hReq 수정 요청, crdnCvlcpt 민원 정보, crdn 단속 정보, 추가한 이미지 파일 newFileList, modifyFileList 편집한 이미지 파일
	 * @return jsonView
	 * <pre><code> {
	 *     "affected": 저장된 정보수
	 *     "saved": 저장되었으면 true, 그렇지 않으면 false
	 * }</code></pre>
	 */
	public ModelAndView saveCivilComplaintProcessSection(HttpServletRequest hReq, CrdnCvlcpt crdnCvlcpt, Crdn crdn, MultipartFile[] newFileList, MultipartFile[] modifyFileList) {

		String sggCd = globalStngMapper.selectSggCdForCurrentUser();
		crdn.setSggCd(sggCd);
		crdnCvlcpt.setSggCd(sggCd);

		boolean saved = false;

		String[] deleteFileKeyList = hReq.getParameterValues("deleteFileKeyList");
		String[] modifyFileKeyList = hReq.getParameterValues("modifyFileKeyList");

		List<FileInfo> newFileInfoList = new ArrayList<FileInfo>();
		if(newFileList != null || modifyFileList != null) {

			Relation relation = new Relation();
			relation.setInfoType(crdn.INF_TYPE);
			relation.setInfoKey(crdn.getCrdnId());

			if(newFileList != null) {
				newFileInfoList = new FileInfoFactory().makeFileInfos(relation, newFileList);
			}
			if(modifyFileList != null) {
				newFileInfoList.addAll(new FileInfoFactory().makeFileInfos(relation, modifyFileList));

				if(deleteFileKeyList == null) {
					deleteFileKeyList = modifyFileKeyList;
				} else {
					String[] arr1 = deleteFileKeyList;
					String[] arr2 = modifyFileKeyList;
			        String[] sumArr = Stream.of(arr1, arr2).flatMap(Stream::of).toArray(String[]::new);
			        deleteFileKeyList = (sumArr);
				}
			}
		}

		Map<String, Object> nonQueryRequest = new HashMap<String, Object>();
		nonQueryRequest.put("deleteFileKeyList", deleteFileKeyList);

		String acceptYn = hReq.getParameter("acceptYn");
		if(ifEmpty(acceptYn, () -> "").equals("Y")) {
			nonQueryRequest.put("acceptType", "accept");
		} else {
			if(crdn.getLevyExclSeCd().equals("2")) {
				nonQueryRequest.put("acceptType", "someAccept");
			} else if(crdn.getLevyExclSeCd().equals("1")) {
				nonQueryRequest.put("acceptType", "nonAccept");
			}
		}

		saved = crdnCvlcptService.updateCvlcptProcessSection(nonQueryRequest, crdnCvlcpt, crdn, newFileInfoList);


		return new ModelAndView("jsonView")
			.addObject("saved", saved);
	}

	/**지정한 민원 자료의 복사본을 생성한다.
	 * @param crdnId 단속대장 아이디
	 * @return jsonView
	 * <pre><code> {
	 *     "saved": 저장되었으면 true, 그렇지 않으면 false
	 * }</code></pre>
	 */
	public ModelAndView copyCivilComplaintInfo(String crdnId) {

		boolean saved = false;

		saved = crdnCvlcptService.copyCvlcptCrdnInfo(crdnId);

		return new ModelAndView("jsonView")
			.addObject("saved", saved);
	}

	/**지정한 민원 자료를 반송(회수) 처리한다.
	 * @param crdnId 단속 ID
	 * @return jsonView
	 * <pre><code> {
	 *     "saved": 저장되었으면 true, 그렇지 않으면 false
	 * }</code></pre>
	 */
	public ModelAndView sendBackCivilComplaintInfo(String crdnId) {

		boolean saved = false;

		saved = crdnCvlcptService.sendBackCivilComplaintInfo(crdnId);

		return new ModelAndView("jsonView")
			.addObject("saved", saved);
	}
}
