package cokr.xit.fims.mngt.web;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import cokr.xit.base.user.SigunguQuery;
import cokr.xit.base.user.service.SigunguDepartmentService;
import cokr.xit.base.web.ApplicationController;
import cokr.xit.fims.base.FimsUser;
import cokr.xit.fims.mngt.Ntc;
import cokr.xit.fims.mngt.NtcQuery;
import cokr.xit.fims.mngt.service.NtcService;
import cokr.xit.foundation.data.DataObject;

/**공지사항 서비스 웹 컨트롤러.<br />
 * {웹 컨텍스트}/mngt/mngt01 로 접근할 수 있다.
 * @author leebj
 */
@Controller
@RequestMapping(name="공지사항 관리", value=Mngt01Controller.CLASS_URL)
public class Mngt01Controller extends ApplicationController {

	public static final String CLASS_URL = "/mngt/mngt01";

	public class METHOD_URL {
		public static final String
			ntcMain = "/010/main.do",
			getNtcList = "/010/list.do",
			getNtcInfo = "/020/info.do",
			create = "/020/create.do",
			update = "/020/update.do",
			remove = "/020/remove.do"
		;
	}

	@Resource(name="ntcService")
	private NtcService ntcService;
	@Resource(name="sigunguDepartmentService")
	private SigunguDepartmentService sggDeptService;

	/** 공지사항 메인화면을 연다.
	 * @return fims/mngt/mngt01010-main
	 */
	@RequestMapping(name="공지사항 메인", value=METHOD_URL.ntcMain)
	public ModelAndView ntcMain() {
		ModelAndView mav = new ModelAndView("fims/mngt/mngt01010-main")
			.addObject("pageName", "mngt01010");

		FimsUser currentUser = (FimsUser) currentUser().getUser();
		boolean publicOfficer = "01".equals(currentUser.getCntnSeCd());
		mav.addObject("isPublicOfficer", publicOfficer);

		List<DataObject> sggList = null;
		if(publicOfficer){
			sggList = sggDeptService.getSigunguList(new SigunguQuery());

			if(!currentUser.getOrgID().equals("ADMIN")) {
				String upSggCd = "";
				List<DataObject> curSggInfo = sggDeptService.getSigunguList(new SigunguQuery().setSggIDs(currentUser.getOrgID()));
				if(curSggInfo != null && !curSggInfo.isEmpty()) {
					upSggCd = curSggInfo.get(0).string("UP_SGG_CD");
				}
				final String UP_SGG_CD = upSggCd.equals("") ? "" : upSggCd;

				sggList = sggList.stream().filter((item) -> {
					if(item.string("SGG_CD").equals(currentUser.getOrgID())) {
						return true;
					}
					if(item.string("UP_SGG_CD").equals(currentUser.getOrgID())) {
						return true;
					}
					if(!UP_SGG_CD.equals("")) {
						if(item.string("SGG_CD").equals(UP_SGG_CD)) {
							return true;
						}
					}
					return false;
				}).toList();
			}
		}

		return mav.addObject("sggList", sggList);
	}

	/**공지사항 목록을 조회하여 반환한다.<br />
	 * {@link NtcService#getNtcList(NtcQuery)} 참고
	 * @param req 공지사항 조회 조건
	 * @return jsonView
	 * <pre><code> {
	 *     "ntcList": [공지사항 목록]
	 *     "ntcStart": 공지사항 목록 시작 인덱스
	 *     "ntcFetch": 한 번에 가져오는 공지사항 목록 수
	 *     "ntcTotal": 조회 결과 찾은 전체 공지사항 수
	 * }</code></pre>
	 */
	@RequestMapping(name="공지사항 목록 조회", value=METHOD_URL.getNtcList)
	public ModelAndView getNtcList(NtcQuery req) {
		setFetchSize(req);

		FimsUser currentUser = (FimsUser)currentUser().getUser();

		if(!"ADMIN".equals(currentUser.getOrgID())) {
			req.setUserSggCd(currentUser.getOrgID());
			req.setUserCntnSeCd(currentUser.getCntnSeCd());
		}

		List<DataObject> list = ntcService.getNtcList(req);

		return setPagingInfo(new ModelAndView("jsonView"), list, "");
	}

	/**공지사항 상세 내용을 조회하여 반환한다.<br />
	 * {@link NtcService#getNtcInfo(NtcQuery)} 참고
	 * @param ntcId 공지사항 ID
	 * @return jsonView
	 */
	@RequestMapping(name="공지사항 상세 조회", value=METHOD_URL.getNtcInfo)
	public ModelAndView getNtcInfo(String ntcId, String cntnSeCd) {
		boolean json = jsonResponse();
		ModelAndView mav = new ModelAndView(json ? "jsonView" : "fims/mngt/mngt01020-info")
			.addObject("pageName", "mngt01020");

		DataObject info = !isEmpty(ntcId) ? ntcService.getNtcInfo(ntcId) : null;
		mav.addObject("ntcInfo", json ? info : toJson(info));

		FimsUser currentUser = (FimsUser) currentUser().getUser();
		boolean publicOfficer = "01".equals(currentUser.getCntnSeCd());
		mav.addObject("isPublicOfficer", publicOfficer);

		List<DataObject> allSggList = sggDeptService.getSigunguList(new SigunguQuery());
		mav.addObject("allSggList", allSggList);

		List<DataObject> selectableSggList = null;
		if(publicOfficer) {
			selectableSggList = sggDeptService.getSigunguList(new SigunguQuery());
			if(!currentUser.getOrgID().equals("ADMIN")) {
				String upSggCd = "";
				List<DataObject> curSggInfo = sggDeptService.getSigunguList(new SigunguQuery().setSggIDs(currentUser.getOrgID()));
				if(curSggInfo != null && !curSggInfo.isEmpty()) {
					upSggCd = curSggInfo.get(0).string("UP_SGG_CD");
				}
				mav.addObject("upSggCd", upSggCd);
				final String UP_SGG_CD = upSggCd.equals("") ? "" : upSggCd;

				selectableSggList = selectableSggList.stream().filter((item) -> {
					if(item.string("SGG_CD").equals(currentUser.getOrgID())) {
						return true;
					}
					if(item.string("UP_SGG_CD").equals(currentUser.getOrgID())) {
						return true;
					}
					if(!UP_SGG_CD.equals("")) {
						if(item.string("SGG_CD").equals(UP_SGG_CD)) {
							return true;
						}
					}
					return false;
				}).toList();
			}
		}
		return mav
			.addObject("selectableSggList", toJson(selectableSggList))
			.addObject("cntnSeCd", cntnSeCd);
	}

	/**공지사항를 등록한다.
	 * @param ntc 공지사항 정보
	 * @return jsonView
	 * <pre><code> {
	 *     "saved": 등록되었으면 true, 그렇지 않으면 false
	 * }</code></pre>
	 */
	@RequestMapping(name="공지사항 등록", value=METHOD_URL.create)
	public ModelAndView create(Ntc ntc) {
		String rtnMsg = ntcService.create(ntc);

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

	/**공지사항 정보를 수정한다.
	 * @param ntc 공지사항 정보
	 * @return jsonView
	 * <pre><code> {
	 *     "saved": 수정되었으면 true, 그렇지 않으면 false
	 * }</code></pre>
	 */
	@RequestMapping(name="공지사항 수정", value=METHOD_URL.update)
	public ModelAndView update(Ntc ntc) {
		String rtnMsg = ntcService.update(ntc);

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

	/**지정한 공지사항를 제거한다.
	 * @param ntcIDs 공지사항 아이디
	 * @return jsonView
	 * <pre><code> {
	 *     "affected": 저장된 정보수
	 *     "saved": 저장되었으면 true, 그렇지 않으면 false
	 * }</code></pre>
	 */
	@RequestMapping(name="공지사항 삭제", value=METHOD_URL.remove)
	public ModelAndView remove(Ntc ntc) {
		String rtnMsg = ntcService.remove(ntc);

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