package cokr.xit.fims.cmmn.web;

import java.io.File;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import cokr.xit.base.code.CommonCode;
import cokr.xit.base.user.SigunguQuery;
import cokr.xit.base.user.dao.UserMapper;
import cokr.xit.base.user.service.bean.SigunguBean;
import cokr.xit.base.web.ApplicationController;
import cokr.xit.fims.base.FimsUser;
import cokr.xit.fims.cmmn.ExtrForm;
import cokr.xit.fims.cmmn.ExtrStngQuery;
import cokr.xit.fims.cmmn.OtptForm;
import cokr.xit.fims.cmmn.OtptStngQuery;
import cokr.xit.fims.cmmn.OutsourcingForm;
import cokr.xit.fims.cmmn.OutsourcingStngQuery;
import cokr.xit.fims.cmmn.service.StngService;
import cokr.xit.fims.cmmn.service.bean.ExtrStngBean;
import cokr.xit.fims.cmmn.service.bean.OtptStngBean;
import cokr.xit.fims.cmmn.service.bean.OutsourcingStngBean;
import cokr.xit.fims.cmmn.service.bean.StngBean;
import cokr.xit.foundation.data.DataObject;

/**설정 관리 서비스의 웹 컨트롤러
*
* <p>상세 설명:
*
* <pre>
* ============ 변경 이력 ============
* 2024-02-20	leebj 최초 작성
* ================================
* </pre>
*/
@Controller
@RequestMapping(name="설정관리", value=StngController.CLASS_URL)
public class StngController extends ApplicationController {
	public static final String CLASS_URL = "/stng/stng01";

	public class METHOD_URL {
		public static final String
		otptStngMain = "/010/main.do",
		getOtptStngInfo = "/010/info.do",
		saveOtptStngInfo = "/010/save.do",
		extrStngMain = "/020/main.do",
		getExtrStngInfo = "/020/info.do",
		saveExtrStngInfo = "/020/save.do",
		outsourcingStngMain = "/030/main.do",
		getOutsourcingStngInfo = "/030/info.do",
		saveOutsourcingStngInfo = "/030/save.do"
		;
	}

	@Resource(name = "stngService")
	private StngService stngService;

	@Resource(name = "stngBean")
	private StngBean stngBean;

	@Resource(name = "sigunguBean")
	private SigunguBean sigunguBean;

	@Resource(name = "otptStngBean")
	private OtptStngBean otptStngBean;

	@Resource(name = "outsourcingStngBean")
	private OutsourcingStngBean outsourcingStngBean;

	@Resource(name = "extrStngBean")
	private ExtrStngBean extrStngBean;

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


	/** 출력물 설정 메인 화면을 연다.
	 * @return 출력물 설정 메인 화면
	 */
	@RequestMapping(name="출력물 설정 메인 화면", value=METHOD_URL.otptStngMain)
	public ModelAndView otptStngMain() {
		ModelAndView mav = new ModelAndView("fims/stng01010-main");
		mav.addObject("pageName", "stng01010");

		Map<String, List<CommonCode>> commonCodes = getCodesOf("FIM054","FIM047","FIM078","FIM080");

		mav.addObject("FIM047List", commonCodes.get("FIM047"));
		mav.addObject("FIM054List", commonCodes.get("FIM054"));
		mav.addObject("TaskListForSgg", stngBean.filterTaskSectionCodeForSgg(commonCodes.get("FIM054")));
		mav.addObject("FIM078List", commonCodes.get("FIM078"));
		mav.addObject("FIM080List", commonCodes.get("FIM080"));
		addCodes(commonCodes, mav, "FIM047", "FIM054", "FIM078","FIM080");

		return mav;
	}

	/** 출력물 설정 정보를 불러온다.
	 * @return 출력물 설정 정보
	 */
	@RequestMapping(name="출력물 설정 정보 조회", value=METHOD_URL.getOtptStngInfo)
	public ModelAndView getOtptStngInfo(OtptStngQuery otptStngQuery) {

		ModelAndView mav = new ModelAndView("jsonView");

		//출력 설정 제목
		FimsUser currentUser = (FimsUser) currentUser().getUser();
		String sggCd = currentUser.getOrgID();
		DataObject sgg = sigunguBean.getSigunguList(new SigunguQuery().setSggIDs(sggCd)).get(0);
		String sggNm = sgg.string("SGG_NM");

		Map<String, List<CommonCode>> commonCodes = getCodesOf("FIM054","FIM047","FIM078");
		List<CommonCode> FIM047 = commonCodes.get("FIM047");
		List<CommonCode> FIM054 = commonCodes.get("FIM054");
		List<CommonCode> FIM078 = commonCodes.get("FIM078");

		String taskSeNm = FIM054.stream().
				filter(item -> item.getCode().equals(otptStngQuery.getTaskSeCd())).findFirst().get().getValue();

		String sndngSeNm = FIM047.stream().
				filter(item -> item.getCode().equals(otptStngQuery.getSndngSeCd())).findFirst().get().getValue();

		String otptPaperSeNm = FIM078.stream().
				filter(item -> item.getCode().equals(otptStngQuery.getPaperSeCd())).findFirst().get().getValue();

		String otptStngTitle = "["+sggNm+", "+taskSeNm+"]"+" "+sndngSeNm+" "+"("+otptPaperSeNm+")";
		mav.addObject("otptStngTitle", otptStngTitle);

		//출력물 기본 설정
		DataObject otptBscStng = new DataObject();
		otptBscStng = otptStngBean.getOtptBscStng(otptStngQuery);
		mav.addObject("otptGlobalStng", otptBscStng);

		//출력 요소별 설정
		Map<String,Object> otptArtclStngMap = otptStngBean.getOtptArtclStngMap(otptStngQuery);

		mav.addObject("otptArtclStngMap", otptArtclStngMap);

		return mav;
	}

	/** 출력물 설정 정보를 저장한다.
	 * @return 저장 여부
	 */
	@RequestMapping(name="출력물 설정 정보 저장", value=METHOD_URL.saveOtptStngInfo)
	public ModelAndView saveOtptStngInfo(OtptForm otptForm, MultipartFile backgroundFile) {
		ModelAndView mav = new ModelAndView("jsonView");
		boolean saved = false;

		if(backgroundFile != null && !backgroundFile.isEmpty() && backgroundFile.getSize() != 0) {
			FimsUser currentUser = (FimsUser) currentUser().getUser();
			String sggCd = currentUser.getOrgID();

			String bgPath = "files/attachment/etc/background/"+sggCd;

			String ext = FilenameUtils.getExtension(backgroundFile.getOriginalFilename());
			String fileName = otptForm.getTaskSeCd()+"-"+otptForm.getSndngSeCd()+"-"+otptForm.getPaperSeCd()+"."+ext;

			File workDir = new File(bgPath);
			workDir.mkdirs();
			try {
				String bgFullPath = bgPath + "/" + fileName;
				File newFile = new File(bgFullPath);
				if(newFile.exists()) {
					if(!newFile.delete()) {
						throw new RuntimeException("배경 이미지 업로드 중 오류가 발생하였습니다.");
					}
				}
				backgroundFile.transferTo(newFile);

				otptForm.setBcrnImgPath(bgFullPath);
				otptForm.setBcrnImgFileNm(backgroundFile.getOriginalFilename());
			} catch (Exception e) {
				throw new RuntimeException("배경 이미지 업로드 중 오류가 발생하였습니다.");
			}
		}

		saved = otptStngBean.saveOtptBscStng(otptForm);
		if(saved) {
			saved = otptStngBean.saveOtptArtclStng(otptForm);
		}

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


	/** PDF 자료 추출 설정 메인 화면을 연다.
	 * @return PDF 자료 추출 설정 메인 화면
	 */
	@RequestMapping(name="PDF 자료 추출 설정 메인 화면", value=METHOD_URL.extrStngMain)
	public ModelAndView extrStngMain() {
		ModelAndView mav = new ModelAndView("fims/stng01020-main");
		mav.addObject("pageName", "stng01020");

		Map<String, List<CommonCode>> commonCodes = getCodesOf("FIM054","FIM047","FIM078","FIM080","EIF001");

		mav.addObject("FIM047List", commonCodes.get("FIM047"));
		mav.addObject("FIM054List", commonCodes.get("FIM054"));
		mav.addObject("TaskListForSgg", stngBean.filterTaskSectionCodeForSgg(commonCodes.get("FIM054")));
		mav.addObject("FIM078List", commonCodes.get("FIM078"));
		mav.addObject("FIM080List", commonCodes.get("FIM080"));
		mav.addObject("TmplatList", commonCodes.get("EIF001"));
		addCodes(commonCodes, mav, "FIM047", "FIM054", "FIM078","FIM080");

		return mav;
	}

	/** PDF 자료 추출 설정 정보를 불러온다.
	 * @return PDF 자료 추출 설정 정보
	 */
	@RequestMapping(name="PDF 자료 추출 설정 정보 조회", value=METHOD_URL.getExtrStngInfo)
	public ModelAndView getExtrStngInfo(ExtrStngQuery extrStngQuery) {

		ModelAndView mav = new ModelAndView("jsonView");

		//설정 제목
		FimsUser currentUser = (FimsUser) currentUser().getUser();
		String sggCd = currentUser.getOrgID();
		DataObject sgg = sigunguBean.getSigunguList(new SigunguQuery().setSggIDs(sggCd)).get(0);
		String sggNm = sgg.string("SGG_NM");

		Map<String, List<CommonCode>> commonCodes = getCodesOf("FIM054","FIM047","FIM078");
		List<CommonCode> FIM054 = commonCodes.get("FIM054");


		String taskSeNm = FIM054.stream().
				filter(item -> item.getCode().equals(extrStngQuery.getTaskSeCd())).findFirst().get().getValue();

		String templateName = "";
		if(extrStngQuery.getTmplatId().equals("JU001")) {
			templateName = "사전통지서";
		} else if(extrStngQuery.getTmplatId().equals("JU002")){
			templateName = "본고지(수시분)";
		}

		String extrStngTitle = "["+sggNm+", "+taskSeNm+"]"+" "+templateName;
		mav.addObject("extrStngTitle", extrStngTitle);


		//추출 기본 설정
		DataObject extrBscStng = extrStngBean.getExtrBscStng(extrStngQuery);
		if(extrBscStng == null) {
			mav.addObject("EXTR_BSC_ID", "");
			mav.addObject("MOBILE_PAGE_TMPLT", "");
		} else {
			mav.addObject("EXTR_BSC_ID", extrBscStng.string("EXTR_BSC_ID"));
			mav.addObject("MOBILE_PAGE_TMPLT", extrBscStng.string("MOBILE_PAGE_TMPLT"));
		}

		//추출 요소별 설정
		Map<String,Object> extrArtclStngMap = extrStngBean.getExtrArtclStngMap(extrStngQuery);
		mav.addObject("extrArtclStngMap", extrArtclStngMap);

		return mav;
	}

	/** PDF 추출 설정 정보를 저장한다.
	 * @return 저장 여부
	 */
	@RequestMapping(name="PDF 자료 추출 설정 정보 저장", value=METHOD_URL.saveExtrStngInfo)
	public ModelAndView saveExtrStngInfo(ExtrForm extrForm) {
		ModelAndView mav = new ModelAndView("jsonView");
		boolean saved = false;

		saved = extrStngBean.saveExtrBscStng(extrForm);
		if(saved) {
			saved = extrStngBean.saveExtrArtclStng(extrForm);
		}

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

	/** 외주요청파일 서식 설정 메인 화면을 연다.
	 * @return 외주요청파일 서식 설정 메인 화면
	 */
	@RequestMapping(name="외주요청파일 서식 설정 메인 화면", value=METHOD_URL.outsourcingStngMain)
	public ModelAndView outsourcingStngMain() {
		ModelAndView mav = new ModelAndView("fims/stng01030-main");
		mav.addObject("pageName", "stng01030");

		Map<String, List<CommonCode>> commonCodes = getCodesOf("FIM054","FIM047","FIM078","FIM080");

		mav.addObject("FIM047List", commonCodes.get("FIM047"));
		mav.addObject("FIM054List", commonCodes.get("FIM054"));
		mav.addObject("TaskListForSgg", stngBean.filterTaskSectionCodeForSgg(commonCodes.get("FIM054")));
		mav.addObject("FIM078List", commonCodes.get("FIM078"));
		mav.addObject("FIM080List", commonCodes.get("FIM080"));
		addCodes(commonCodes, mav, "FIM047", "FIM054", "FIM078","FIM080");

		return mav;
	}


	/** 외주요청파일 서식 설정 정보를 불러온다.
	 * @return 외주요청파일 서식 설정 정보
	 */
	@RequestMapping(name="외주요청파일 서식 설정 정보 조회", value=METHOD_URL.getOutsourcingStngInfo)
	public ModelAndView getOutsourcingStngInfo(OutsourcingStngQuery outsourcingStngQuery) {

		ModelAndView mav = new ModelAndView("jsonView");

		//설정 제목
		FimsUser currentUser = (FimsUser) currentUser().getUser();
		String sggCd = currentUser.getOrgID();
		DataObject sgg = sigunguBean.getSigunguList(new SigunguQuery().setSggIDs(sggCd)).get(0);
		String sggNm = sgg.string("SGG_NM");

		Map<String, List<CommonCode>> commonCodes = getCodesOf("FIM054","FIM047","FIM078");
		List<CommonCode> FIM047 = commonCodes.get("FIM047");
		List<CommonCode> FIM054 = commonCodes.get("FIM054");

		String taskSeNm = FIM054.stream().
				filter(item -> item.getCode().equals(outsourcingStngQuery.getTaskSeCd())).findFirst().get().getValue();

		String sndngSeNm = FIM047.stream().
				filter(item -> item.getCode().equals(outsourcingStngQuery.getSndngSeCd())).findFirst().get().getValue();

		String outsourcingStngTitle = "["+sggNm+", "+taskSeNm+"]"+" "+sndngSeNm;
		mav.addObject("outsourcingStngTitle", outsourcingStngTitle);

		//기본 설정
		DataObject zipGlobalStng = new DataObject();
		//zipGlobalStng = outsourcingStngBean.getBscStng();
		zipGlobalStng.put("OUTSOURCING_BSC_ID","");
		mav.addObject("zipGlobalStng", zipGlobalStng);

		//요소별 설정
		Map<String,Object> zipArtclStngMap = outsourcingStngBean.getArtclStngMap(outsourcingStngQuery);

		mav.addObject("zipArtclStngMap", zipArtclStngMap);

		return mav;
	}


	/** 외주요청파일 서식 설정 정보를 저장한다.
	 * @return 저장 여부
	 */
	@RequestMapping(name="외주요청파일 서식 설정 정보 저장", value=METHOD_URL.saveOutsourcingStngInfo)
	public ModelAndView saveOutsourcingStngInfo(OutsourcingForm outsourcingForm) {
		ModelAndView mav = new ModelAndView("jsonView");
		boolean saved = false;

		//saved = outsourcingStngBean.saveBscStng(otptForm);
		//if(saved) {
			saved = outsourcingStngBean.saveOutsourcingArtclStng(outsourcingForm);
		//}

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