package egovframework.dbnt.kcsc.standardCode;

import egovframework.com.cmm.ResponseCode;
import egovframework.com.cmm.service.ResultVO;
import egovframework.com.cmm.LoginVO;
import egovframework.dbnt.kcsc.standardCode.entity.TnDocumentInfoVO;
import egovframework.dbnt.kcsc.standardCode.service.StandardCodeListService;
import egovframework.dbnt.kcsc.standardCode.service.StandardCodeService;
import egovframework.let.cop.bbs.service.BoardVO;
import org.egovframe.rte.fdl.property.EgovPropertyService;
import org.egovframe.rte.ptl.mvc.tags.ui.pagination.PaginationInfo;

import egovframework.dbnt.kcsc.standardCode.service.StandardCodeVO;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 건설기준코드 관리를 위한 컨트롤러 클래스
 *
 * <pre>
 * << 개정이력(Modification Information) >>
 *
 *   수정일      수정자          수정내용
 *  -------    --------    ---------------------------
 *  2023.10.11  최강석          최초 생성
 *
 *  </pre>
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/standardCode")
@Tag(name="StandardCodeController",description = "건설기준코드 관리 컨트롤러")
public class StandardCodeController {
	/*
	@Resource(name = "EgovBBSManageService")
	private EgovBBSManageService bbsMngService;

	@Resource(name = "EgovBBSAttributeManageService")
	private EgovBBSAttributeManageService bbsAttrbService;

	@Resource(name = "EgovFileMngService")
	private EgovFileMngService fileMngService;*/

	/*///*/

	
	/**
	 * 게시판 마스터 상세내용을 조회한다.
	 * 파일 첨부 가능 여부 조회용
	 *
	 * @param request
	 * @param searchVO
	 * @return resultVO
	 * @throws Exception
	 */
	/*@Operation(
			summary = "게시판 마스터 상세 조회",
			description = "게시판 마스터 상세내용을 조회 (파일 첨부가능 여부 조회용)",
			tags = {"EgovBBSManageApiController"}
	)
	@ApiResponses(value = {
			@ApiResponse(responseCode = "200", description = "조회 성공"),
			@ApiResponse(responseCode = "403", description = "인가된 사용자가 아님")
	})
	@PostMapping(value = "/cop/bbs/selectUserBBSMasterInfAPI.do", consumes = MediaType.APPLICATION_JSON_VALUE)
	public ResultVO selectUserBBSMasterInf(@RequestBody BoardMasterVO searchVO)
		throws Exception {
		ResultVO resultVO = new ResultVO();
		Map<String, Object> resultMap = new HashMap<String, Object>();
		
		BoardMasterVO master = bbsAttrbService.selectBBSMasterInf(searchVO);
		resultMap.put("brdMstrVO", master);

		resultVO.setResult(resultMap);
		resultVO.setResultCode(ResponseCode.SUCCESS.getCode());
		resultVO.setResultMessage(ResponseCode.SUCCESS.getMessage());
		
		return resultVO;
	}*/

	/**
	 * 게시물에 대한 목록을 조회한다.
	 *
	 * @param boardVO
	 * @return resultVO
	 * @throws Exception
	 */
	/*@Operation(
			summary = "게시물 목록 조회",
			description = "게시물에 대한 목록을 조회",
			tags = {"EgovBBSManageApiController"}
	)
	@ApiResponses(value = {
			@ApiResponse(responseCode = "200", description = "조회 성공"),
			@ApiResponse(responseCode = "403", description = "인가된 사용자가 아님")
	})
	@PostMapping(value = "/cop/bbs/selectBoardListAPI.do", consumes = MediaType.APPLICATION_JSON_VALUE)
	public ResultVO selectBoardArticles(@RequestBody BoardVO boardVO, @AuthenticationPrincipal LoginVO user)
		throws Exception {
		ResultVO resultVO = new ResultVO();

		BoardMasterVO vo = new BoardMasterVO();
		vo.setBbsId(boardVO.getBbsId());
		vo.setUniqId(user.getUniqId());

		BoardMasterVO master = bbsAttrbService.selectBBSMasterInf(vo);

		PaginationInfo paginationInfo = new PaginationInfo();
		paginationInfo.setCurrentPageNo(boardVO.getPageIndex());
		paginationInfo.setRecordCountPerPage(propertyService.getInt("Globals.pageUnit"));
		paginationInfo.setPageSize(propertyService.getInt("Globals.pageSize"));

		boardVO.setFirstIndex(paginationInfo.getFirstRecordIndex());
		boardVO.setLastIndex(paginationInfo.getLastRecordIndex());
		boardVO.setRecordCountPerPage(paginationInfo.getRecordCountPerPage());

		Map<String, Object> resultMap = bbsMngService.selectBoardArticles(boardVO, vo.getBbsAttrbCode());

		int totCnt = Integer.parseInt((String)resultMap.get("resultCnt"));
		paginationInfo.setTotalRecordCount(totCnt);

		resultMap.put("boardVO", boardVO);
		resultMap.put("brdMstrVO", master);
		resultMap.put("paginationInfo", paginationInfo);
		resultMap.put("user", user);

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

		return resultVO;
	}*/

	/**
	 * 게시물에 대한 상세 정보를 조회한다.
	 *
	 * @return resultVO
	 * @throws Exception
	 */
	/*@Operation(
			summary = "게시물 상세 조회",
			description = "게시물에 대한 상세 정보를 조회",
			tags = {"EgovBBSManageApiController"}
	)
	@ApiResponses(value = {
			@ApiResponse(responseCode = "200", description = "조회 성공"),
			@ApiResponse(responseCode = "403", description = "인가된 사용자가 아님")
	})
	@PostMapping(value = "/cop/bbs/selectBoardArticleAPI.do")
	public ResultVO selectBoardArticle(@RequestBody BoardVO boardVO,@AuthenticationPrincipal LoginVO user)
		throws Exception {

		ResultVO resultVO = new ResultVO();

		// 조회수 증가 여부 지정
		boardVO.setPlusCount(true);

		//---------------------------------
		// 2009.06.29 : 2단계 기능 추가
		//---------------------------------
		if (!boardVO.getSubPageIndex().equals("")) {
			boardVO.setPlusCount(false);
		}
		////-------------------------------

		boardVO.setLastUpdusrId(user.getUniqId());
		BoardVO vo = bbsMngService.selectBoardArticle(boardVO);

		//----------------------------
		// template 처리 (기본 BBS template 지정  포함)
		//----------------------------
		BoardMasterVO master = new BoardMasterVO();

		master.setBbsId(boardVO.getBbsId());
		master.setUniqId(user.getUniqId());

		BoardMasterVO masterVo = bbsAttrbService.selectBBSMasterInf(master);
		
		//model.addAttribute("brdMstrVO", masterVo);

		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("boardVO", vo);
		resultMap.put("sessionUniqId", user.getUniqId());
		resultMap.put("brdMstrVO", masterVo);
		resultMap.put("user", user);

		// 2021-06-01 신용호 추가
		// 첨부파일 확인
		if (vo != null && vo.getAtchFileId() != null && !vo.getAtchFileId().isEmpty()) {
			FileVO fileVO = new FileVO();
			fileVO.setAtchFileId(vo.getAtchFileId());
			List<FileVO> resultFiles = fileService.selectFileInfs(fileVO);
			
			// FileId를 유추하지 못하도록 암호화하여 표시한다. (2022.12.06 추가) - 파일아이디가 유추 불가능하도록 조치
			for (FileVO file : resultFiles) {
				String toEncrypt = file.atchFileId;
				file.setAtchFileId(Base64.getEncoder().encodeToString(cryptoService.encrypt(toEncrypt.getBytes(),EgovFileDownloadController.ALGORITM_KEY)));
			}
						
			resultMap.put("resultFiles", resultFiles);
		}

		resultVO.setResult(resultMap);
		resultVO.setResultCode(ResponseCode.SUCCESS.getCode());
		resultVO.setResultMessage(ResponseCode.SUCCESS.getMessage());
		return resultVO;
	}*/

	@Resource(name = "propertiesService")
	protected EgovPropertyService propertyService;

	private final StandardCodeService standardCodeService;

	private final StandardCodeListService standardCodeListService;


	@Operation(
			summary = "건설기준코드 트리 조회",
			description = "건설기준코드 트리 조회",
			tags = {"StandardCodeController"}
	)
	@ApiResponses(value = {
			@ApiResponse(responseCode = "200", description = "조회 성공"),
			@ApiResponse(responseCode = "403", description = "인가된 사용자가 아님")
	})
	@PostMapping(value = "/getCodeTree.do", consumes = MediaType.APPLICATION_JSON_VALUE)
	public ResultVO getCodeTree(@RequestBody StandardCodeVO param, @AuthenticationPrincipal LoginVO user)
			throws Exception {
		ResultVO resultVO = new ResultVO();
		Map<String, Object> resultMap = new HashMap<>();
		resultMap.put("codeTree", standardCodeService.selectStandardCodeTree());
		resultVO.setResult(resultMap);
		return resultVO;
	}


	@Operation(
			summary = "건설기준코드 내용 조회",
			description = "건설기준코드 내용 조회",
			tags = {"StandardCodeController"}
	)
	@ApiResponses(value = {
			@ApiResponse(responseCode = "200", description = "조회 성공"),
			@ApiResponse(responseCode = "403", description = "인가된 사용자가 아님")
	})
	@PostMapping(value = "/getCodeDetailInfo.do", consumes = MediaType.APPLICATION_JSON_VALUE)
	public ResultVO getCodeDetailInfo(@RequestBody StandardCodeVO param, @AuthenticationPrincipal LoginVO user)
			throws Exception {
		ResultVO resultVO = new ResultVO();
		Map<String, Object> resultMap = new HashMap<>();
		resultMap.put("document", standardCodeService.selectStandardCodeDocument(param));
		resultVO.setResult(resultMap);
		return resultVO;
	}


	@Operation(
			summary = "건설기준코드 리스트 조회",
			description = "건설기준코드 리스트 조회",
			tags = {"StandardCodeController"}
	)
	@ApiResponses(value = {
			@ApiResponse(responseCode = "200", description = "조회 성공"),
			@ApiResponse(responseCode = "403", description = "인가된 사용자가 아님")
	})
	@PostMapping(value = "/selectStandardCodeList.do", consumes = MediaType.APPLICATION_JSON_VALUE)
	public ResultVO selectStandardCodeList(@RequestBody TnDocumentInfoVO tnDocumentInfoVO, @AuthenticationPrincipal LoginVO user)
			throws Exception {
		ResultVO resultVO = new ResultVO();

		PaginationInfo paginationInfo = new PaginationInfo();
		paginationInfo.setCurrentPageNo(tnDocumentInfoVO.getPageIndex());
		paginationInfo.setRecordCountPerPage(propertyService.getInt("Globals.pageUnit"));
		paginationInfo.setPageSize(propertyService.getInt("Globals.pageSize"));

		System.out.println("@@@ pageIndex : " + tnDocumentInfoVO.getPageIndex());

		tnDocumentInfoVO.setFirstIndex(paginationInfo.getFirstRecordIndex());
		tnDocumentInfoVO.setLastIndex(paginationInfo.getLastRecordIndex());
		tnDocumentInfoVO.setRecordCountPerPage(paginationInfo.getRecordCountPerPage());

		Map<String, Object> resultMap = standardCodeListService.selectStandardCodeList(tnDocumentInfoVO);

		int totCnt = Integer.parseInt((String)resultMap.get("resultCnt"));
		paginationInfo.setTotalRecordCount(totCnt);

		resultMap.put("tnDocumentInfoVO", tnDocumentInfoVO);
		resultMap.put("paginationInfo", paginationInfo);
		resultMap.put("user", user);

		resultVO.setResultCode(ResponseCode.SUCCESS.getCode());
		resultVO.setResultMessage(ResponseCode.SUCCESS.getMessage());
		resultVO.setResult(resultMap);
		return resultVO;
	}
}