package com.dbnt.kcscbackend.admin.standardResearch.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.admin.standardResearch.model.CreateStandardResearchVO;
import com.dbnt.kcscbackend.admin.standardResearch.model.UpdateStandardResearchVO;
import com.dbnt.kcscbackend.admin.standardResearch.repository.TnResearchRepositoryLightweight;
import com.dbnt.kcscbackend.admin.standardResearch.service.AdminStandardResearchService;
import com.dbnt.kcscbackend.auth.entity.LoginVO;
import com.dbnt.kcscbackend.commonCode.entity.TnPopupMng;
import com.dbnt.kcscbackend.commonCode.entity.TnResearch;
import com.dbnt.kcscbackend.commonCode.repository.TnPopupMngRepository;
import com.dbnt.kcscbackend.commonCode.repository.TnResearchRepository;
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.data.repository.query.Param;
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("adminStandardResearchService")
@RequiredArgsConstructor
public class AdminStandardResearchServiceImpl extends EgovAbstractServiceImpl implements AdminStandardResearchService {

	private final TnResearchRepository tnResearchRepository;
	private final TnResearchRepositoryLightweight tnResearchRepositoryLightweight;


	@Override
	public ResultVO contentsStandardResearchList(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 = tnResearchRepositoryLightweight.count();
		List<Map<String, Object>> list = tnResearchRepositoryLightweight.findAll(pageable)
				.stream()
				.map(item -> {
					Map<String, Object> codeMap = new HashMap<>();
					codeMap.put("id", item.getRsSeq());
					codeMap.put("title", item.getRsTitle());
					codeMap.put("researchStartDate", item.getRsStartDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
					codeMap.put("researchEndDate", item.getRsEndDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
					codeMap.put("director", item.getRsDirector());
					codeMap.put("createDate", item.getFrstCrtDt());
					codeMap.put("createUserId", item.getFrstCrtId());
					codeMap.put("updateDate", item.getLastChgDt());
					codeMap.put("updateUserId", item.getLastChgId());
					codeMap.put("useYn", item.getUseYn());
					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((int) totalRecordCount);

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

		return resultVO;
	}





	@Override
	public ResultVO contentsStandardResearchCreate(ResultVO resultVO, HttpServletRequest request, LoginVO user, final MultipartHttpServletRequest multiRequest, CreateStandardResearchVO createStandardResearchVO) 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 = tnResearchRepository.spAddTnResearch(
				createStandardResearchVO.getTitle(),
				createStandardResearchVO.getResearchStartDate(),
				createStandardResearchVO.getResearchEndDate(),
				createStandardResearchVO.getDirector(),
				createStandardResearchVO.getPurpose(),
				createStandardResearchVO.getContent(),
				createStandardResearchVO.getEffectContent(),
				"kcsc_admin",
				null,
				null,
				null
		);


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

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

		return resultVO;
	}


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

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


		TnResearch tnResearch 				= tnResearchRepository.findByRsSeq(rsId);


		Map<String, Object> dto 			= new HashMap<String, Object>();
		dto.put("content", tnResearch.getRsContents());
		dto.put("createDate", tnResearch.getFrstCrtDt().plusHours(9).format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));		// 날짜/시간의 시작 일시 - yyyyMMddHHmmss
		dto.put("createUserId", tnResearch.getFrstCrtId());
		dto.put("director", tnResearch.getRsDirector());
		dto.put("effectContent", tnResearch.getRsEffect());
		dto.put("id", tnResearch.getRsSeq());
		dto.put("purpose", tnResearch.getRsPurpose());
		dto.put("researchEndDate", tnResearch.getRsEndDate().plusHours(9).format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));		// 날짜/시간의 시작 일시 - yyyyMMddHHmmss
		dto.put("researchStartDate", tnResearch.getRsStartDate().plusHours(9).format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));		// 날짜/시간의 종료 일시 - yyyyMMddHHmmss
		dto.put("title", tnResearch.getRsTitle());
		dto.put("updateDate", tnResearch.getLastChgDt().plusHours(9).format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));		// 날짜/시간의 종료 일시 - yyyyMMddHHmmss
		dto.put("updateUserId", tnResearch.getLastChgId());
		dto.put("useYn", tnResearch.getUseYn());





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

		return resultVO;
	}

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

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

		Map<String, Object> response = tnResearchRepository.spUpdateTnResearch(
			rsId.intValue(),
			updateStandardResearchVO.getResearchStartDate(),
			updateStandardResearchVO.getResearchEndDate(),
			updateStandardResearchVO.getDirector(),
			updateStandardResearchVO.getPurpose(),
			updateStandardResearchVO.getContent(),
			updateStandardResearchVO.getEffectContent(),
			"kcsc_admin",
			null,
			null,
			null
		);


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

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

		return resultVO;
	}


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





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

		Map<String, Object> response = tnResearchRepository.spDeleteTnResearch(
				rsId.intValue(),
				"admin",
				null,
				null,
				null
		);
		dto.put("errorMessage", response.get("_error_message") );


		dto.put("rsId", rsId );

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

		return resultVO;
	}


}
