package cokr.xit.fims.cvlc.service.bean;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import cokr.xit.base.code.dao.CodeMapper;
import cokr.xit.base.code.service.CodeQuery;
import cokr.xit.base.user.ManagedUser;
import cokr.xit.base.user.dao.UserMapper;
import cokr.xit.fims.crdn.CrdnQuery;
import cokr.xit.fims.crdn.dao.CrdnInfoMapper;
import cokr.xit.fims.crdn.dao.CrdnInstMapper;
import cokr.xit.fims.crdn.dao.CrdnUpdtMapper;
import cokr.xit.fims.crdn.dao.GlobalStngMapper;
import cokr.xit.fims.cvlc.CrdnCvlcpt;
import cokr.xit.fims.cvlc.dao.AnswerWordsMapper;
import cokr.xit.fims.cvlc.dao.CrdnCvlcptMapper;
import cokr.xit.fims.cvlc.dao.SaCvlcptIndviDmndMapper;
import cokr.xit.foundation.AbstractComponent;
import cokr.xit.foundation.UserInfo;
import cokr.xit.foundation.data.DataObject;
import cokr.xit.interfaces.smg.Petition;
import cokr.xit.interfaces.smg.service.bean.SmgSenderBean;

/** 민원 주 기능 Bean
 * @author leebj
 */
@Component("crdnCvlcptMainBean")
public class CrdnCvlcptMainBean extends AbstractComponent {

	@Resource(name="smgSenderBean")
	protected SmgSenderBean smgSenderBean;

	@Resource(name = "codeMapper")
	private CodeMapper codeMapper;

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

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

	@Resource(name = "crdnCvlcptMapper")
	private CrdnCvlcptMapper crdnCvlcptMapper;

	@Resource(name = "answerWordsMapper")
	private AnswerWordsMapper answerWordsMapper;

	@Resource(name = "saCvlcptIndviDmndMapper")
	SaCvlcptIndviDmndMapper saCvlcptIndviDmndMapper;

	@Resource(name = "crdnInfoMapper")
	private CrdnInfoMapper crdnInfoMapper;

	@Resource(name = "crdnInstMapper")
	private CrdnInstMapper crdnInstMapper;

	@Resource(name = "crdnUpdtMapper")
	private CrdnUpdtMapper crdnUpdtMapper;

	/**민원 원본 정보를 조회한다.
	 * @param query 조회 요청
	 * @return 민원 원본 정보
	 */
	public DataObject getCivilComplaintOriginalInfo(CrdnQuery query) {
		return crdnCvlcptMapper.selectCivilComplaintOriginalInfo(query);
	}

	/**민원 처리 정보를 수정한다.
	 * @param editDataExist 편집 정보 존재 여부, crdnCvlcpt 민원 정보
	 * @return 저장 여부
	 * <ul><li>저장됐으면 true</li>
	 *     <li>그렇지 않으면 false</li>
	 * </ul>
	 */
	public boolean updateCvlcptPrcsSe(boolean editDataExist, CrdnCvlcpt cvlcpt) {
		DataObject params = new DataObject();
		UserInfo userInfo = currentUser();
		params.set("currentUser", userInfo);
		params.set("crdnCvlcpt", cvlcpt);
		if(editDataExist) {
			params.set("editDataExist", "Y");
		} else {
			params.set("editDataExist", "N");
		}
		return crdnCvlcptMapper.updateCvlcptProcessSection(params) == 1 ? true : false;
	}

	/** 국민신문고 답변전송 인터페이스 테이블에 자료를 등록한다.
	 * @param isSendBack 반송여부, cvlcptLinkId 민원 연계 ID
	 * @return 저장 여부
	 * <ul><li>저장됐으면 true</li>
	 *     <li>그렇지 않으면 false</li>
	 * </ul>
	 */
	public boolean insertTransmitInfo(boolean isSendBack, String cvlcptLinkId) {

		//민원처리정보 조회
		DataObject cvlcptInfo = crdnCvlcptMapper.selectCivilComplaintProcessInfo(cvlcptLinkId);

		//전송 인터페이스 테이블 등록
		Petition petition = new Petition();
		petition.setInterfaceSeqN(cvlcptInfo.string("CVLCPT_LINK_ID")); //민원연계키

		petition.setSysGubunC("EC010008");	      //시스템 구분("EC010008")
		petition.setPetiAncCodeV(cvlcptInfo.string("PETI_ANC_CODE_V"));   //민원 기관 코드(최초신청기관코드)

		petition.setPetiGubunC(isSendBack ? "140" : "180"); //민원구분
		petition.setSendYnC(isSendBack? "1" : "2");         // 송신 여부

		petition.setPetiNoC(cvlcptInfo.string("CVLCPT_APLY_NO")); //민원 신청 번호
		petition.setCivilNoC(cvlcptInfo.string("CVLCPT_RCPT_NO"));//민원 접수 번호
		petition.setPetiTitleV(cvlcptInfo.string("CVLCPT_APLY_TTL_NM"));    //민원제목
		petition.setCivilGistV(cvlcptInfo.string("CVLCPT_GIST"));           //민원요지
		petition.setCivilAbstractL(cvlcptInfo.string("CVLCPT_PRCS_SUMRY")); //민원 처리 요약
		petition.setAncCodeV(cvlcptInfo.string("CVLCPT_PRCS_NSTT_CD"));	  //기관 코드
		petition.setPcdDeptV(cvlcptInfo.string("CVLCPT_PRCS_DEPT_CD"));	  //처리 부서 코드
		petition.setPcdAncCodeV(cvlcptInfo.string("CVLCPT_PRCS_DEPT_CD"));	//민원 실 처리 기관 코드
		petition.setPcdDeptNmV(cvlcptInfo.string("CVLCPT_PRCS_DEPT_NM")); //민원 처리 부서명
		petition.setDutyIdV(cvlcptInfo.string("CVLCPT_PRCS_PIC_NM")); //민원 처리 담당자 명
		petition.setPcdEmailV(cvlcptInfo.string("CVLCPT_PRCS_PIC_EMAIL")); //담당자 이메일
		petition.setPcdTelV(cvlcptInfo.string("CVLCPT_PRCS_PIC_TELNO")); //담당자 전화번호
		petition.setPcdRstContL(cvlcptInfo.string("CVLCPT_PRCS_RSLT_CN")); //민원 처리 결과
		petition.setDoRegD(cvlcptInfo.string("CVLCPT_PRCS_CMPTN_DT")); //민원 처리 완료 일자

		petition.setRegD((new SimpleDateFormat("yyyyMMddHHmmss")).format(new Date()));  // 등록 일자

		//not use
		petition.setPcdRstContAttachYnC("N");	//민원 처리 결과 첨부 여부
		petition.setPcdGubunV(""); //처리 구분1
		petition.setPcdGubun2V("");//처리 구분2
		petition.setPcdGubun3V("");//처리 구분3

		//DB --> XML
		petition.setApplyGubunC("N"); //완료구분
		petition.setSendD("");  //송신 일자
		petition.setApplyD(""); //적용 일자
	    petition.setSendInterfaceSeqN("");//전송인터페이스키
	    petition.setSendStatus("");//전송상태
		petition.setSendStatusMsg("");//전송상태메시지

		return smgSenderBean.createReply(petition);
	}

	/**답변 내용을 초기화한다.
	 * @param cvlcptLinkId 민원 연계 아이디
	 * @return 저장 여부
	 * <ul><li>저장됐으면 true</li>
	 *     <li>그렇지 않으면 false</li>
	 * </ul>
	 */
	public boolean initCvlcptPrcsRsltCn(String cvlcptLinkId) {
		CrdnCvlcpt crdnCvlcpt = new CrdnCvlcpt();
		crdnCvlcpt.setCvlcptLinkId(cvlcptLinkId);

		return crdnCvlcptMapper.initCvlcptPrcsRsltCn(crdnCvlcpt) == 1 ? true : false;
	}

	/**지정한 민원 자료의 답변 예정 문구를 반환한다.
	 * @param crdnId 단속 ID
	 * @return 답변 예정 문구
	 */
	public String mappingAnswerWords(String crdnId, String currentUserInstitute, String currentUserAcnt) {

		DataObject dataInfo = crdnInfoMapper.selectCrdnInfo(crdnId);

		CrdnQuery crdnQuery = new CrdnQuery();
		crdnQuery.setTaskSeCd(dataInfo.string("TASK_SE_CD"));
		crdnQuery.setSggCd(dataInfo.string("SGG_CD"));

		if(dataInfo.string("CVLCPT_PRCS_CD").equals("02")) {
			crdnQuery.setAnsSeCd("3");
			crdnQuery.setAnsRsnCd("3"+dataInfo.string("VLTN_CD"));

			if(crdnQuery.getAnsRsnCd().equals("301") && dataInfo.string("DSTRBNC_YN").equals("Y")) {
				crdnQuery.setDstrbncYn("Y");
			}

		} else if(dataInfo.string("CVLCPT_PRCS_CD").equals("03")
				|| dataInfo.string("CVLCPT_PRCS_CD").equals("04")){
			crdnQuery.setAnsSeCd(dataInfo.string("LEVY_EXCL_SE_CD"));
			crdnQuery.setAnsRsnCd(dataInfo.string("LEVY_EXCL_RSN_CD"));
		} else {
			return "";
		}

		DataObject bodyWordsInfo = answerWordsMapper.selectCvlcptAnswerWordsInfo(crdnQuery);
		DataObject basicWordsInfo = answerWordsMapper.selectCvlcptAnswerBasicWordsInfo(crdnQuery);

		String body = bodyWordsInfo.string("PRCS_RSLT_CN");
		String head = basicWordsInfo.string("HEADER_CN");
		String tail = basicWordsInfo.string("FOOTER_CN");

		if(body.equals("")) {
			return "";
		}

		String joinWords = head + "\n\n" + body + "\n\n" + tail;

		ManagedUser currentUser = userMapper.getUser(currentUserAcnt, currentUserInstitute);

		String completeWords = this.replaceMacroString(joinWords , currentUser.getPhoneNo(), currentUser.getName());

		return completeWords;
	}

	/**문구의 매크로 문자열을 치환한다.
	 * @param joinWords 전체 문구, telNo 담당자 전화번호
	 * @return 치환된 문구
	 */
	private String replaceMacroString(String joinWords, String telNo, String picNm) {

		int seq = 1;

		joinWords = joinWords.replaceAll("＠", "@");
		String[] splited = joinWords.split(CrdnCvlcpt.MACRO_SEQ);
		var seqCount = splited.length - 1;
		if(seqCount > 0){
			for(; seq <= seqCount; seq++){
				joinWords = joinWords.replaceFirst(CrdnCvlcpt.MACRO_SEQ, Integer.toString(seq));
			}
		}

		joinWords = joinWords.replace(CrdnCvlcpt.MACRO_TELNO, telNo);
		joinWords = joinWords.replace(CrdnCvlcpt.MACRO_PIC_NM, picNm);
		return joinWords;
	}

	/**민원 답변 기본 문구 설정을 조회한다.
	 * @param query 조회 요청
	 * @return 민원 답변 기본 문구
	 */
	public DataObject selectCvlcptAnswerBasicWordsInfo(CrdnQuery crdnQuery) {
		return answerWordsMapper.selectCvlcptAnswerBasicWordsInfo(crdnQuery);
	}

	/**민원 답변 본문 문구 목록을 조회한다.
	 * @param query 조회 요청, ansSeCd 답변구분코드
	 * @return 민원 답변 본문 문구 목록
	 */
	public List<DataObject> selectAnswerBodyWordsList(CrdnQuery crdnQuery, String ansSeCd) {

		if("3".equals(ansSeCd)) {
			return answerWordsMapper.selectLevyCaseWordsList(crdnQuery);
		} else if("2".equals(ansSeCd)) {
			return answerWordsMapper.selectWarningCaseWordsList(crdnQuery);
		} else if("1".equals(ansSeCd)) {
			return answerWordsMapper.selectNonlevyCaseWordsList(crdnQuery);
		} else {
			return null;
		}

	}

	/**민원답변 기본문구를 저장한다.
	 * @param crdnCvlcpt 민원답변 기본문구 정보
	 * @return 저장 여부
	 * <ul><li>저장됐으면 true</li>
	 *     <li>그렇지 않으면 false</li>
	 * </ul>
	 */
	public boolean saveAnswerBasicWordsInfo(CrdnCvlcpt crdnCvlcpt) {

		CrdnQuery query = new CrdnQuery();
		query.setSggCd(crdnCvlcpt.getSggCd());
		query.setTaskSeCd(crdnCvlcpt.getTaskSeCd());

		DataObject info = answerWordsMapper.selectCvlcptAnswerBasicWordsInfo(query);

		if(ifEmpty(info, ()-> "").equals("")) {
			return answerWordsMapper.insertAnswerBasicWordsInfo(crdnCvlcpt) == 1 ? true : false;
		} else {
			return answerWordsMapper.updateAnswerBasicWordsInfo(crdnCvlcpt) == 1 ? true : false;
		}

	}

	/**민원답변 본문문구를 저장한다.
	 * @param crdnCvlcpt 민원답변 본문문구 정보
	 * @return 저장 여부
	 * <ul><li>저장됐으면 true</li>
	 *     <li>그렇지 않으면 false</li>
	 * </ul>
	 */
	public boolean saveAnswerBodyWordsInfo(CrdnCvlcpt crdnCvlcpt) {

		if(ifEmpty(crdnCvlcpt.getAnsWordsId(), ()-> "").equals("")) {
			String codeGroupId = "";
			String code = "";
			if(crdnCvlcpt.getAnsRsnCd().startsWith("1") || crdnCvlcpt.getAnsRsnCd().startsWith("2")) {
				if(crdnCvlcpt.getAnsRsnCd().startsWith("1")) {
					crdnCvlcpt.setPrcsSumry("과태료 미부과");
				}
				if(crdnCvlcpt.getAnsRsnCd().startsWith("2")) {
					crdnCvlcpt.setPrcsSumry("과태료 계고");
				}

				codeGroupId = "FIM022";
				code = crdnCvlcpt.getAnsRsnCd();

			} else if(crdnCvlcpt.getAnsRsnCd().startsWith("3")) {
				crdnCvlcpt.setPrcsSumry("과태료 부과");
				switch(crdnCvlcpt.getTaskSeCd()) {
					case "PVS" -> codeGroupId = "WEB002";
					case "BPV" -> codeGroupId = "FIM005";
					case "DPV" -> codeGroupId = "FIM006";
					case "ECA" -> codeGroupId = "FIM061";
					case "TPV" -> codeGroupId = "";
				}
				code = crdnCvlcpt.getAnsRsnCd().substring(1);
			}

			CodeQuery codeQuery = new CodeQuery();
			codeQuery.setGroupIDs(codeGroupId);
			codeQuery.setCodes(code);
			List<DataObject> codeList = codeMapper.getCodeList(codeQuery);
			crdnCvlcpt.setAnsRsnNm(codeList.get(0).string("CODE_VAL"));

			return answerWordsMapper.insertAnswerBodyWordsInfo(crdnCvlcpt) == 1 ? true : false;
		} else {
			return answerWordsMapper.updateAnswerBodyWordsInfo(crdnCvlcpt) == 1 ? true : false;
		}

	}

	/**새올 요청 자료 목록을 조회한다.
	 * @param query 조회 요청
	 * @return 새올 요청 자료 목록
	 */
	public List<DataObject> selectDmndDataList(CrdnQuery query) {
		query.setOrderBy("INDIV_ID");
		return saCvlcptIndviDmndMapper.selectDmndDataList(query);
	}

	/**새올 요청 자료를 생성한다.
	 * @param crdnCvlcpt 새올요청자료 정보
	 * @return 저장 여부
	 * <ul><li>저장됐으면 true</li>
	 *     <li>그렇지 않으면 false</li>
	 * </ul>
	 */
	public boolean createDmndDataInfo(CrdnCvlcpt crdnCvlcpt) {
		return saCvlcptIndviDmndMapper.insertDmndDataInfo(crdnCvlcpt) == 1 ? true : false;
	}

	/**새올 요청 자료를 삭제한다.
	 * @param indivIDs 개별요청 ID 목록
	 * @return 저장 여부
	 * <ul><li>저장됐으면 true</li>
	 *     <li>그렇지 않으면 false</li>
	 * </ul>
	 */
	public boolean removeDmndDataInfo(String... indivIDs) {
		if (isEmpty(indivIDs)) return false;

		Map<String, Object> paramMap = new HashMap<String, Object>();
		List<String> indivIdList = Arrays.asList(indivIDs);
		paramMap.put("indivIDs", indivIdList);
		paramMap.put("removedBy", UserInfo.current().getId());

		return saCvlcptIndviDmndMapper.deleteDmndDataInfo(paramMap) >= 1 ? true : false;
	}

}
