package com.dbnt.kcscbackend.admin.contents.popUp.service.impl;


import com.dbnt.kcscbackend.admin.contents.popUp.model.CreatePopupVO;
import com.dbnt.kcscbackend.admin.contents.popUp.model.FileVO;
import com.dbnt.kcscbackend.admin.contents.popUp.model.UpdatePopupVO;
import com.dbnt.kcscbackend.admin.contents.popUp.repository.TnPopupMngRepositoryWithoutPopupContents;
import com.dbnt.kcscbackend.admin.contents.popUp.service.PopUpApiService;
import com.dbnt.kcscbackend.auth.entity.LoginVO;
import com.dbnt.kcscbackend.commonCode.entity.TnPopupMng;
import com.dbnt.kcscbackend.commonCode.repository.TnPopupMngRepository;
import com.dbnt.kcscbackend.config.common.ResponseCode;
import com.dbnt.kcscbackend.config.common.ResultVO;
import lombok.RequiredArgsConstructor;
import org.egovframe.rte.fdl.cmmn.EgovAbstractServiceImpl;
import org.egovframe.rte.ptl.mvc.tags.ui.pagination.PaginationInfo;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service("popUpApiService")
@RequiredArgsConstructor
public class PopUpApiServiceImpl extends EgovAbstractServiceImpl implements PopUpApiService {

	private final TnPopupMngRepository tnPopupMngRepository;
	private final TnPopupMngRepositoryWithoutPopupContents tnPopupMngRepositoryWithoutPopupContents;


	@Override
	public ResultVO contentsApiPopUpManageList(ResultVO resultVO, HttpServletRequest request, LoginVO user, Pageable pageable) throws Exception {

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


		Long totalRecordCount = tnPopupMngRepositoryWithoutPopupContents.count();
		//List<Map<String, Object>> listPopup = tnPopupMngRepositoryWithoutPopupContents.findAll(Sort.by(Sort.Direction.DESC, "popupSeq"))
		List<Map<String, Object>> listPopup = tnPopupMngRepositoryWithoutPopupContents.findAll(pageable)
				.stream()
				.map(item -> {
					Map<String, Object> codeMap = new HashMap<>();
					codeMap.put("seq", item.getPopupSeq());
					codeMap.put("popupTitle", item.getPopupTitle());
					codeMap.put("startDate", item.getPopupStartDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
					codeMap.put("endDate", item.getPopupEndDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
					codeMap.put("createUserId", item.getFrstCrtId());
					codeMap.put("updateUserId", item.getLastChgId());
					codeMap.put("fileGrpId", item.getFileGrpId());
					codeMap.put("contents", null);
					codeMap.put("useYn", item.getUseYn());
					codeMap.put("createDate", item.getFrstCrtDt());
					codeMap.put("updateDate", item.getLastChgDt());
					codeMap.put("base64String", null);
					return codeMap;
				})
				.collect(Collectors.toList());

		PaginationInfo paginationInfo = new PaginationInfo();
		paginationInfo.setCurrentPageNo(pageable.getPageNumber()+1);
		paginationInfo.setRecordCountPerPage(pageable.getPageSize());
		paginationInfo.setPageSize(5);//hard coded
		paginationInfo.setTotalRecordCount(totalRecordCount.intValue());//hard coded

		Map<String, Object> dto = new HashMap<String, Object>();
		dto.put("listPopup", listPopup);
		dto.put("paginationInfo", paginationInfo);
		resultVO.setResult(dto);
		resultVO.setResultCode(ResponseCode.SUCCESS.getCode());
		resultVO.setResultMessage(ResponseCode.SUCCESS.getMessage());

		return resultVO;
	}





	@Override
	public ResultVO contentsApiPopUpManageCreate(ResultVO resultVO, HttpServletRequest request, LoginVO user, final MultipartHttpServletRequest multiRequest, CreatePopupVO createPopupVO) throws Exception {

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

		// 첨부파일 관련 첨부파일ID 생성
		List<FileVO> _result = null;
		String _atchFileId = "";

		final Map<String, MultipartFile> files = multiRequest.getFileMap();

		if (!files.isEmpty()) {
			//_atchFileId = fileMngService.insertFileInfs(_result); //파일이 생성되고나면 생성된 첨부파일 ID를 리턴한다.
		}

		Map<String, Object> response = tnPopupMngRepository.spAddTnPopupMng(
				createPopupVO.getTitle(),
				createPopupVO.getStartDate(),
				createPopupVO.getEndDate(),
				null,
				createPopupVO.getContents(),
				"kcsc_admin",
				null,
				null,
				null,
				null
		);


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

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

		return resultVO;
	}


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

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


		int isValid = tnPopupMngRepository.spIsValidTnPopupMngId( popupId.intValue() );

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

		TnPopupMng tnPopupMng 				= tnPopupMngRepository.findByPopupSeq(popupId);


		Map<String, Object> dto 			= new HashMap<String, Object>();
		dto.put("title", tnPopupMng.getPopupTitle());																					// 팝업 제목
		dto.put("contents", tnPopupMng.getPopupContents());																				// 팝업 내용
		dto.put("schdulBgnde", tnPopupMng.getPopupStartDate().plusHours(9).format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));		// 날짜/시간의 시작 일시 - yyyyMMddHHmmss
		dto.put("schdulEndde", tnPopupMng.getPopupEndDate().plusHours(9).format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));		// 날짜/시간의 종료 일시 - yyyyMMddHHmmss


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

		return resultVO;
	}

	@Override
	public ResultVO contentsApiPopUpManageUpdate(ResultVO resultVO, HttpServletRequest request, LoginVO user, UpdatePopupVO updatePopupVO, Long popupId) throws Exception {
		System.out.println(
				"\n--------------------------------------------------------------\n" +
						request.getRequestURI() + " IN:" +
						"\n--------------------------------------------------------------\n" +
						"updatePopupVO:" + "\n" +
						updatePopupVO.toString() + "\n" +
						"popupId:" + "\n" +
						popupId + "\n" +
						"\n--------------------------------------------------------------\n"
		);

		// 유효성 검사 실시
		int isValid = tnPopupMngRepository.spIsValidTnPopupMngId( popupId.intValue() );

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

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

		Map<String, Object> response = tnPopupMngRepository.spUpdateTnPopupMng(
			popupId.intValue(),
			updatePopupVO.getTitle(),
			updatePopupVO.getStartDate(),
			updatePopupVO.getEndDate(),
			null,
			updatePopupVO.getContents(),
			"kcsc_admin",
			null,
			null,
			null
		);


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

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

		return resultVO;
	}


	@Override
	public ResultVO contentsApiPopUpManageDelete(ResultVO resultVO, HttpServletRequest request, LoginVO user, Long popupId) throws Exception {
		System.out.println(
				"\n--------------------------------------------------------------\n" +
						request.getRequestURI() + " IN:" +
						"\n--------------------------------------------------------------\n" +
						"popupId:" + "\n" +
						popupId + "\n" +
						"\n--------------------------------------------------------------\n"
		);





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

		if( false ) {
			// 삭제 procedure가 삭제가 아닌 비활성화만 시키므로 해당 프로시저 사용 안 함.
			Map<String, Object> response = tnPopupMngRepository.spDeleteTnPopupMng(
					popupId.intValue(),
					"admin",
					null,
					null,
					null
			);
			dto.put("errorMessage", response.get("_error_message") );
		} else {
			tnPopupMngRepository.deleteById(popupId);
		}


		dto.put("popupId", popupId );

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

		return resultVO;
	}

	@Override
	public ResultVO contentsApiPopUpManageUpdateActivationSwitch(ResultVO resultVO, HttpServletRequest request, LoginVO user, String checked, Long popupId) throws Exception {
		System.out.println(
				"\n--------------------------------------------------------------\n" +
						request.getRequestURI() + " IN:" +
						"\n--------------------------------------------------------------\n" +
						"checked:" + "\n" +
						checked + "\n" +
						"popupId:" + "\n" +
						popupId + "\n" +
						"\n--------------------------------------------------------------\n"
		);



		// 유효성 검사 실시
		int isValid = tnPopupMngRepository.spIsValidTnPopupMngId( popupId.intValue() );

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

		TnPopupMng tnPopupMng = tnPopupMngRepository.findByPopupSeq(popupId);
		if( Boolean.parseBoolean(checked) ) {
			tnPopupMng.setUseYn("Y");
		} else {
			tnPopupMng.setUseYn("N");
		}

		tnPopupMngRepository.saveAndFlush(tnPopupMng);


		Map<String, Object> dto = new HashMap<String, Object>();
		dto.put("popupId",  popupId);

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

		return resultVO;
	}


}
