package com.dbnt.kcscbackend.admin.boards;

import com.dbnt.kcscbackend.admin.boards.entity.TnBbs;
import com.dbnt.kcscbackend.admin.boards.entity.TnBbsContents;
import com.dbnt.kcscbackend.admin.boards.service.AdminBoardsService;
import com.dbnt.kcscbackend.admin.config.entity.TcMenu;
import com.dbnt.kcscbackend.auth.entity.LoginVO;
import com.dbnt.kcscbackend.commonCode.CommonCodeController;
import com.dbnt.kcscbackend.commonCode.service.CommonCodeService;
import com.dbnt.kcscbackend.config.common.BaseController;
import com.dbnt.kcscbackend.config.common.ResponseCode;
import com.dbnt.kcscbackend.config.common.ResultVO;
import com.dbnt.kcscbackend.config.util.ClientUtils;
import com.dbnt.kcscbackend.file.entity.TnAttachFile;
import com.dbnt.kcscbackend.file.service.FileService;
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.security.core.annotation.AuthenticationPrincipal;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequiredArgsConstructor
@RequestMapping("/admin/boards")
@Tag(name = "AdminBoardsController", description = "사이트관리 게시판현황")
public class AdminBoardsController extends BaseController {

    private final AdminBoardsService adminBoardsService;
    private final CommonCodeService commonCodeService;
    private final FileService fileService;

    /* ---- 게시판관리 ----- */
    @Operation(
            summary = "게시판 목록 조회",
            description = "게시판 목록 조회",
            tags = {"AdminBoardsController"}
    )
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "조회 성공"),
            @ApiResponse(responseCode = "403", description = "인가된 사용자가 아님")
    })
    @RequestMapping(method = RequestMethod.GET, value = "/board-list", consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResultVO getBoardList() throws Exception {
        ResultVO resultVO = new ResultVO();
        Map<String, Object> resultMap = new HashMap<>();

        resultMap.put("boardList", adminBoardsService.selectBoardList());
        resultVO.setResult(resultMap);
        return resultVO;
    }

    @Operation(
            summary = "게시판 셀렉트박스 옵션 조회",
            description = "게시판 셀렉트박스 옵션 조회",
            tags = {"AdminBoardsController"}
    )
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "조회 성공"),
            @ApiResponse(responseCode = "403", description = "인가된 사용자가 아님")
    })
    @RequestMapping(method = RequestMethod.GET, value = "/get-option-list", consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResultVO getOptionList() throws Exception {
        ResultVO resultVO = new ResultVO();
        Map<String, Object> resultMap = new HashMap<>();

        resultMap.put("bbsTypeList", commonCodeService.selectCodeItemList("BBS_TYPE"));
        resultMap.put("roleList", commonCodeService.selectCodeItemList("ROLE"));
        resultVO.setResult(resultMap);
        return resultVO;
    }

    @Operation(
            summary = "게시판 저장",
            description = "게시판 저장",
            tags = {"AdminBoardsController"}
    )
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "저장 성공"),
            @ApiResponse(responseCode = "403", description = "인가된 사용자가 아님")
    })
    @RequestMapping(method = RequestMethod.PUT, value = "/board-mgt")
    public ResultVO saveBoardMgt(@RequestBody @Valid TnBbs bbs, Errors errors, @AuthenticationPrincipal LoginVO user) {
        ResultVO resultVO = new ResultVO();
        if (user == null) {
            resultVO.setResultCode(ResponseCode.TOKEN_EXPIRED.getCode());
        } else {
            if (errors.hasErrors()) {
                StringBuilder msg = new StringBuilder();
                for (FieldError error : errors.getFieldErrors()) {
                    msg.append(error.getDefaultMessage());
                    msg.append("\n");
                }
                resultVO.setResultCode(ResponseCode.INPUT_CHECK_ERROR.getCode());
                resultVO.setResultMessage(msg.toString());
            } else {
                System.out.println("@@@ bbs.getBbsSeq() : " + bbs.getBbsSeq());
                adminBoardsService.saveBoard(bbs, user.getId());
                resultVO.setResultCode(ResponseCode.SUCCESS.getCode());
            }
        }
        return resultVO;
    }

    @Operation(
            summary = "게시판 삭제",
            description = "게시판 삭제",
            tags = {"AdminBoardsController"}
    )
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "삭제 성공"),
            @ApiResponse(responseCode = "403", description = "인가된 사용자가 아님")
    })
    @RequestMapping(method = RequestMethod.DELETE, value = "/board-mgt")
    public ResultVO deleteBoardMgt(@RequestBody TnBbs bbs, @AuthenticationPrincipal LoginVO user) {
        ResultVO resultVO = new ResultVO();
        if (user == null) {
            resultVO.setResultCode(ResponseCode.TOKEN_EXPIRED.getCode());
        } else {
            String result = adminBoardsService.deleteBoard(bbs, user.getId());
            if (result == null) {
                resultVO.setResultCode(ResponseCode.SUCCESS.getCode());
            } else if (result.equals("notFind")) {
                resultVO.setResultCode(ResponseCode.SAVE_ERROR.getCode());
                resultVO.setResultMessage("대상이 존재하지 않습니다.");
            }
        }
        return resultVO;
    }

    /* ---- 게시물관리 ----- */
    @Operation(
            summary = "게시물 목록 조회",
            description = "게시물 목록 조회",
            tags = {"AdminBoardsController"}
    )
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "조회 성공"),
            @ApiResponse(responseCode = "403", description = "인가된 사용자가 아님")
    })
    @RequestMapping(method = RequestMethod.GET, value = "/post-list", consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResultVO getPostList() throws Exception {
        ResultVO resultVO = new ResultVO();
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("categoryList", adminBoardsService.selectBoardList());
        resultMap.put("postList", adminBoardsService.selectPostList());
        resultVO.setResult(resultMap);
        return resultVO;
    }

    @Operation(
            summary = "게시물 카테고리 셀렉트박스 옵션, 파일 목록 조회",
            description = "게시물 카테고리 셀렉트박스 옵션, 파일 목록 조회",
            tags = {"AdminBoardsController"}
    )
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "조회 성공"),
            @ApiResponse(responseCode = "403", description = "인가된 사용자가 아님")
    })
    @RequestMapping(method = RequestMethod.POST, value = "/get-category-and-file-list", consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResultVO getCategoryList(@RequestBody TnBbsContents tnBbsContents) throws Exception {
        ResultVO resultVO = new ResultVO();
        Map<String, Object> resultMap = new HashMap<>();

        resultMap.put("categoryList", adminBoardsService.selectBoardList());
        //첨부파일명을 가져온다.
        List<TnAttachFile> tnAttachFileList = fileService.findByFileGrpId(tnBbsContents.getFileGrpId());
        System.out.println("@@@ fileGrpId : " + tnBbsContents.getFileGrpId());

        if (tnAttachFileList != null) {
            List<Map<String, Object>> files = new ArrayList<Map<String, Object>>();
            for (TnAttachFile item : tnAttachFileList) {
                Map<String, Object> fileDto = new HashMap<String, Object>();
                fileDto.put("seq", item.getFileSeq());
                fileDto.put("name", item.getFileOldName());
                files.add(fileDto);
            }
            resultMap.put("files", files);
            System.out.println("@@@ files : " + files);
        } else {
            resultMap.put("files", null);
        }
        resultVO.setResult(resultMap);
        return resultVO;
    }

    @Operation(
            summary = "게시물 저장",
            description = "게시물 저장",
            tags = {"AdminBoardsController"}
    )
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "저장 성공"),
            @ApiResponse(responseCode = "403", description = "인가된 사용자가 아님")
    })
    @RequestMapping(method = RequestMethod.PUT, value = "/post-mgt")
    public ResultVO savePostMgt(
            @Valid TnBbsContents contents,
            HttpServletRequest request,
            Errors errors,
            @RequestParam(required = false) long[] survivingFiles,
            @RequestParam(required = false) MultipartFile[] files,
            @AuthenticationPrincipal LoginVO user) throws Exception {
        ResultVO resultVO = new ResultVO();
        if (user == null) {
            resultVO.setResultCode(ResponseCode.TOKEN_EXPIRED.getCode());
        } else {
            if (errors.hasErrors()) {
                StringBuilder msg = new StringBuilder();
                for (FieldError error : errors.getFieldErrors()) {
                    msg.append(error.getDefaultMessage());
                    msg.append("\n");
                }
                resultVO.setResultCode(ResponseCode.INPUT_CHECK_ERROR.getCode());
                resultVO.setResultMessage(msg.toString());
            } else {
                System.out.println("@@@ contents.getBbsSeq() : " + contents.getBbsSeq());
                contents.setIpAddress(ClientUtils.getRemoteIP(request));
                adminBoardsService.savePost(contents, request, user, files, survivingFiles);
                resultVO.setResultCode(ResponseCode.SUCCESS.getCode());
            }
        }
        return resultVO;
    }

    @Operation(
            summary = "게시물 삭제",
            description = "게시물 삭제",
            tags = {"AdminBoardsController"}
    )
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "삭제 성공"),
            @ApiResponse(responseCode = "403", description = "인가된 사용자가 아님")
    })
    @RequestMapping(method = RequestMethod.DELETE, value = "/post-mgt")
    public ResultVO deletePostMgt(@RequestBody TnBbsContents contents, HttpServletRequest request, @AuthenticationPrincipal LoginVO user) {
        ResultVO resultVO = new ResultVO();
        if (user == null) {
            resultVO.setResultCode(ResponseCode.TOKEN_EXPIRED.getCode());
        } else {
            contents.setIpAddress(ClientUtils.getRemoteIP(request));
            String result = adminBoardsService.deletePost(contents, user.getId());
            if (result == null) {
                resultVO.setResultCode(ResponseCode.SUCCESS.getCode());
            } else if (result.equals("notFind")) {
                resultVO.setResultCode(ResponseCode.SAVE_ERROR.getCode());
                resultVO.setResultMessage("대상이 존재하지 않습니다.");
            }
        }
        return resultVO;
    }

}
