package com.dbnt.kcscbackend.admin.committee.schedules.service.impl;


import com.dbnt.kcscbackend.admin.committee.schedules.model.CreateScheduleVO;
import com.dbnt.kcscbackend.admin.committee.schedules.model.UpdateScheduleVO;
import com.dbnt.kcscbackend.admin.committee.schedules.service.EgovIndvdlSchdulManageService;
import com.dbnt.kcscbackend.auth.entity.LoginVO;
import com.dbnt.kcscbackend.commonCode.entity.TcCodeItem;
import com.dbnt.kcscbackend.commonCode.entity.TnCmtEvent;
import com.dbnt.kcscbackend.commonCode.entity.TnCmtOrg;
import com.dbnt.kcscbackend.config.common.ResponseCode;
import com.dbnt.kcscbackend.commonCode.repository.TcCodeItemRepository;
import com.dbnt.kcscbackend.commonCode.repository.TnCmtEventRepository;
import com.dbnt.kcscbackend.commonCode.repository.TnCmtOrgRepository;
import com.dbnt.kcscbackend.config.common.ResultVO;
import lombok.RequiredArgsConstructor;
import org.egovframe.rte.fdl.cmmn.EgovAbstractServiceImpl;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 일정관리를 처리하는 ServiceImpl Class 구현
 * @since 2009.04.10
 * @see
 * <pre>
 * << 개정이력(Modification Information) >>  수정일      수정자           수정내용 -------    ---
 * -----    --------------------------- 2009.04.10  장동한          최초 생성 2011.05.31
 * JJY           경량환경 커스터마이징버전 생성
 * </pre>
 * @author 조재영
 * @version 1.0
 * @created 09-6-2011 오전 10:08:05
 */
@Service("egovIndvdlSchdulManageService")
@RequiredArgsConstructor
public class EgovIndvdlSchdulManageServiceImpl extends EgovAbstractServiceImpl implements EgovIndvdlSchdulManageService {



	private final TcCodeItemRepository tcCodeItemRepository;
	private final TnCmtOrgRepository tnCmtOrgRepository;
	private final TnCmtEventRepository tnCmtEventRepository;



	@Override
	public ResultVO scheduleInit(ResultVO resultVO) throws Exception {

		Map<String, Object> resultMap = new HashMap<String, Object>();

		List<Map<String, Object>> listCodes = tcCodeItemRepository.findByGrpCdAndUseYnOrderByGrpOrder("EVT_TYPE", "Y")
				.stream()
				.map(item -> {
					Map<String, Object> codeMap = new HashMap<>();
					codeMap.put("id", item.getItemCd());
					codeMap.put("name", item.getItemNm());
					return codeMap;
				})

				.collect(Collectors.toList());
		List<Map<String, Object>> listSubOrg = tnCmtOrgRepository.findByUseYnAndUpCmtSeqOrderByCmtOrder("Y", 3L).stream()
				.map(item -> {
					Map<String, Object> codeMap = new HashMap<>();
					codeMap.put("id", item.getCmtSeq());
					codeMap.put("name", item.getCmtNm());
					return codeMap;
				})
				.collect(Collectors.toList());
		List<Map<String, Object>> listTopOrg = tnCmtOrgRepository.findByUseYnAndUpCmtSeqOrderByCmtOrder("Y", 2L).stream()
				.map(item -> {
					Map<String, Object> codeMap = new HashMap<>();
					codeMap.put("id", item.getCmtSeq());
					codeMap.put("name", item.getCmtNm());
					return codeMap;
				})
				.collect(Collectors.toList());

		resultMap.put("listCodes", listCodes);
		resultMap.put("listSubOrg", listSubOrg);
		resultMap.put("listTopOrg", listTopOrg);
		resultVO.setResult(resultMap);
		resultVO.setResultCode(ResponseCode.SUCCESS.getCode());
		resultVO.setResultMessage(ResponseCode.SUCCESS.getMessage());

		return resultVO;
	}

	@Override
	public ResultVO scheduleApiOrgApiDepthList(ResultVO resultVO, Long paramCodeGroup) throws Exception {
		Map<String, Object> resultMap = new HashMap<String, Object>();


		List<Map<String, Object>> list = tnCmtOrgRepository.findByUseYnAndUpCmtSeqOrderByCmtOrder("Y", paramCodeGroup)
				.stream()
				.map(item -> {
					Map<String, Object> codeMap = new HashMap<>();
					codeMap.put("id", item.getCmtSeq());
					codeMap.put("name", item.getCmtNm());
					return codeMap;
				})
				.collect(Collectors.toList());

		resultMap.put("list", list);
		resultVO.setResult(resultMap);

		return resultVO;
	}

	@Override
	public ResultVO createSchedule(ResultVO resultVO, HttpServletRequest request, CreateScheduleVO createScheduleVO) throws Exception {

			System.out.println(
			"\n--------------------------------------------------------------\n" +
			request.getRequestURI() + " IN:" +
			"\n--------------------------------------------------------------\n" +
			"createScheduleVO:" + "\n" +
			createScheduleVO.toString() + "\n" +
			"\n--------------------------------------------------------------\n"
		);

		// 유효성 검사 실시
		if( Long.parseLong(createScheduleVO.getStartDate()) > Long.parseLong(createScheduleVO.getEndDate()) ) {
			throw new Exception("종료일시는 시작일시보다 앞 설 수 없습니다.");
		}


		Map<String, Object> response = tnCmtEventRepository.spAddTnCmtEvent(
				createScheduleVO.getDivMeet(),			// 구분
				createScheduleVO.getUpCommittee(),		// 심의위원회 상위 코드 번호
				createScheduleVO.getCommittee(),		// 심의위원회 하위 코드 번호
				createScheduleVO.getTitle(),			// 제목
				createScheduleVO.getLocation(),			// 장소
				createScheduleVO.getContents(),			// 내용
				createScheduleVO.getStartDate(),		// 날짜/시간의 시작 일시
				createScheduleVO.getEndDate(),			// 날짜/시간의 종료 일시
				"admin",
				null,
				null,
				null,
				null
		);

		Map<String, Object> dto = new HashMap<String, Object>();
		dto.put("schdulId", response.get("_evt_seq") );

		resultVO.setResult(dto);
		resultVO.setResultCode(ResponseCode.SUCCESS.getCode());
		resultVO.setResultMessage(ResponseCode.SUCCESS.getMessage());

		return resultVO;
	}


	@Override
	public ResultVO updateSchedule(ResultVO resultVO, HttpServletRequest request, UpdateScheduleVO updateScheduleVO) throws Exception {

		System.out.println(
				"\n--------------------------------------------------------------\n" +
						request.getRequestURI() + " IN:" +
						"\n--------------------------------------------------------------\n" +
						"updateScheduleVO:" + "\n" +
						updateScheduleVO.toString() + "\n" +
						"\n--------------------------------------------------------------\n"
		);

		// 유효성 검사 실시
		int isValid = tnCmtEventRepository.spIsValidTnCmtEventId( updateScheduleVO.getEvtSeq() );

		if( isValid == 0 ) {
			throw new Exception("대상이 존재하지 않습니다.");
		}

		if( Long.parseLong(updateScheduleVO.getStartDate()) > Long.parseLong(updateScheduleVO.getEndDate()) ) {
			throw new Exception("종료일시는 시작일시보다 앞 설 수 없습니다.");
		}

		Map<String, Object> response = tnCmtEventRepository.spUpdateTnCmtEvent(
			updateScheduleVO.getEvtSeq(),
			updateScheduleVO.getDivMeet(),			// 구분
			updateScheduleVO.getUpCommittee(),		// 심의위원회 상위 코드 번호
			updateScheduleVO.getCommittee(),		// 심의위원회 하위 코드 번호
			updateScheduleVO.getTitle(),			// 제목
			updateScheduleVO.getLocation(),			// 장소
			updateScheduleVO.getContents(),			// 내용
			updateScheduleVO.getStartDate(),		// 날짜/시간의 시작 일시
			updateScheduleVO.getEndDate(),			// 날짜/시간의 종료 일시
			"admin",
			null,
			null,
			null
		);

		Map<String, Object> dto = new HashMap<String, Object>();
		dto.put("errorMessage", response.get("_error_message") );
		dto.put("schdulId", updateScheduleVO.getEvtSeq() );

		resultVO.setResult(dto);
		resultVO.setResultCode(ResponseCode.SUCCESS.getCode());
		resultVO.setResultMessage(ResponseCode.SUCCESS.getMessage());

		return resultVO;
	}

	@Override
	public ResultVO deleteSchedule(ResultVO resultVO, HttpServletRequest request, Long scheduleId) throws Exception {

		System.out.println(
				"\n--------------------------------------------------------------\n" +
						request.getRequestURI() + " IN:" +
						"\n--------------------------------------------------------------\n" +
						"scheduleId:" + "\n" +
						scheduleId + "\n" +
						"\n--------------------------------------------------------------\n"
		);


		Map<String, Object> response = tnCmtEventRepository.spDeleteTnCmtEvent(
				scheduleId.intValue(),
				"admin",
				null,
				null,
				null
		);

		Map<String, Object> dto = new HashMap<String, Object>();
		dto.put("errorMessage", response.get("_error_message") );
		dto.put("schdulId", scheduleId );

		resultVO.setResult(dto);
		resultVO.setResultCode(ResponseCode.SUCCESS.getCode());
		resultVO.setResultMessage(ResponseCode.SUCCESS.getMessage());

		return resultVO;
	}




	@Override
	public ResultVO scheduleDetail(ResultVO resultVO, HttpServletRequest request, LoginVO user, Long scheduleId) throws Exception {

		System.out.println(
			"\n--------------------------------------------------------------\n" +
			request.getRequestURI() + " IN:" +
			"\n--------------------------------------------------------------\n" +
			"scheduleId:" + "\n" +
			scheduleId + "\n" +
			"\n--------------------------------------------------------------\n"
		);


		int isValid = tnCmtEventRepository.spIsValidTnCmtEventId( scheduleId.intValue() );

		if( isValid == 0 ) {
			throw new Exception("대상이 존재하지 않습니다.");
		}

		TnCmtEvent tnCmtEvent 				= tnCmtEventRepository.findByEvtSeq(scheduleId);

		TcCodeItem tcCodeItem 				= tcCodeItemRepository.findByItemCdAndUseYn(tnCmtEvent.getEvtType(), "Y");

		TnCmtOrg tnCmtOrgForUpCommitteeNm 	= tnCmtOrgRepository.findByUseYnAndCmtSeq("Y", tnCmtEvent.getUpCmtSeq());
		TnCmtOrg tnCmtOrgForCommitteeNm 	= tnCmtOrgRepository.findByUseYnAndCmtSeq("Y", tnCmtEvent.getCmtSeq());

		Map<String, Object> dto 			= new HashMap<String, Object>();
		dto.put("evtSeq", tnCmtEvent.getEvtSeq());																					// sequence
		dto.put("divMeetNm", tcCodeItem.getItemNm());																				// 구분 명
		dto.put("divMeet", tnCmtEvent.getEvtType());																				// 구분 코드
		dto.put("upCommittee", tnCmtEvent.getUpCmtSeq());																			// 심의위원회 상위 코드
		dto.put("upCommitteeNm", tnCmtOrgForUpCommitteeNm.getCmtNm());																// 심의위원회 상위 이름
		dto.put("committee", tnCmtEvent.getCmtSeq());																				// 심의위원회 하위 코드
		dto.put("committeeNm", tnCmtOrgForCommitteeNm.getCmtNm());																	// 심의위원회 하위 이름
		dto.put("title", tnCmtEvent.getEvtTitle());																					// 제목
		dto.put("location", tnCmtEvent.getEvtLocation());																			// 장소
		dto.put("contents", tnCmtEvent.getEvtContents());																			// 내용
		dto.put("startDate", tnCmtEvent.getEvtStartDt().plusHours(9));																// 날짜/시간의 시작 일시
		dto.put("endDate", tnCmtEvent.getEvtEndDt().plusHours(9));																	// 날짜/시간의 종료 일시
		dto.put("schdulBgnde", tnCmtEvent.getEvtStartDt().plusHours(9).format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));		// 날짜/시간의 시작 일시 - yyyyMMddHHmmss
		dto.put("schdulEndde", tnCmtEvent.getEvtEndDt().plusHours(9).format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));		// 날짜/시간의 종료 일시


		resultVO.setResult(dto);
		resultVO.setResultCode(ResponseCode.SUCCESS.getCode());
		resultVO.setResultMessage(ResponseCode.SUCCESS.getMessage());

		return resultVO;
	}


	@Override
	public ResultVO scheduleMonth(ResultVO resultVO, HttpServletRequest request, LoginVO user, Map<String, Object> commandMap) throws Exception {

		System.out.println(
			"\n--------------------------------------------------------------\n" +
			request.getRequestURI() + " IN:" +
			"\n--------------------------------------------------------------\n" +
			"String.valueOf(commandMap.get(\"year\")):" + "\n" +
			String.valueOf(commandMap.get("year")) + "\n" +
			"String.valueOf(commandMap.get(\"month\")):" + "\n" +
			String.valueOf(commandMap.get("month")) + "\n" +
			"\n--------------------------------------------------------------\n"
		);

		Map<String, Object> dto = new HashMap<String, Object>();

		//일정구분 검색 유지
		dto.put("searchKeyword",
				commandMap.get("searchKeyword") == null ? "" : (String)commandMap.get("searchKeyword"));
		dto.put("searchCondition",
				commandMap.get("searchCondition") == null ? "" : (String)commandMap.get("searchCondition"));

		Calendar cal = Calendar.getInstance();

		String sYear = String.valueOf(commandMap.get("year")); // 예 "2024"
		String sMonth = String.valueOf(commandMap.get("month")); // 예 "2" zeo-base. 0= 1월, 1=2월, 2=3월. 즉 "2"라면 3월

		int iYear = cal.get(Calendar.YEAR);
		int iMonth = cal.get(Calendar.MONTH);
		//int iDate = cal.get(java.util.Calendar.DATE);

		//검색 설정
		String sSearchDate = "";
		if (sYear == null || sMonth == null) {
			sSearchDate += Integer.toString(iYear);
			sSearchDate += Integer.toString(iMonth + 1).length() == 1 ? "0" + Integer.toString(iMonth + 1)
					: Integer.toString(iMonth + 1);
		} else {
			iYear = Integer.parseInt(sYear);
			iMonth = Integer.parseInt(sMonth);
			sSearchDate += sYear;
			sSearchDate += Integer.toString(iMonth + 1).length() == 1 ? "0" + Integer.toString(iMonth + 1)
					: Integer.toString(iMonth + 1);
		}

		// sSearchDate는 검색할 월. 예 202403
		commandMap.put("searchMonth", sSearchDate);
		commandMap.put("searchMode", "MONTH");

		List<Map<String, Object>> resultList = tnCmtEventRepository.getByYyyyMm(sSearchDate)
				.stream()
				.map(item -> {
					Map<String, Object> mapDto = new HashMap<>();
					mapDto.put("evt_start_dt", item.getEvtStartDt().plusHours(9).format(DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss.SSS")));
					mapDto.put("evt_end_dt", item.getEvtEndDt().plusHours(9).format(DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss.SSS")));
					mapDto.put("schdulId", item.getEvtSeq());
					mapDto.put("schdulNm", item.getEvtTitle());

					return mapDto;
				})
				.collect(Collectors.toList());

		dto.put("prevRequest", commandMap);
		dto.put("resultList", resultList);

		resultVO.setResult(dto);

		resultVO.setResultCode(ResponseCode.SUCCESS.getCode());
		resultVO.setResultMessage(ResponseCode.SUCCESS.getMessage());

		return resultVO;
	}






}
