package com.dbnt.kcscbackend.admin.boards.service;

import com.dbnt.kcscbackend.admin.boards.entity.TnBbs;
import com.dbnt.kcscbackend.admin.boards.entity.TnBbsContents;
import com.dbnt.kcscbackend.admin.boards.repository.TnBbsContentsRepository;
import com.dbnt.kcscbackend.admin.boards.repository.TnBbsRepository;
import com.dbnt.kcscbackend.admin.config.entity.TcMenu;
import com.dbnt.kcscbackend.auth.entity.LoginVO;
import com.dbnt.kcscbackend.file.entity.TnAttachFile;
import com.dbnt.kcscbackend.file.service.FileService;
import lombok.RequiredArgsConstructor;
import org.egovframe.rte.fdl.cmmn.EgovAbstractServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
@RequiredArgsConstructor
public class AdminBoardsService extends EgovAbstractServiceImpl {

    private final TnBbsRepository tnBbsRepository;
    private final TnBbsContentsRepository tnBbsContentsRepository;
    private final FileService fileService;

    public List<TnBbs> selectBoardList() {
        return tnBbsRepository.findAllByOrderByBbsSeqDesc();
    }

    @Transactional
    public void saveBoard(TnBbs bbs, String userId) {
        if (bbs.getBbsSeq() == null) {
            bbs.setFrstCrtDt(LocalDateTime.now());
            bbs.setFrstCrtId(userId);
            tnBbsRepository.save(bbs);
        } else {
            TnBbs savedBoard = tnBbsRepository.findById(bbs.getBbsSeq()).orElse(null);
            savedBoard.setBbsId(bbs.getBbsId());
            savedBoard.setBbsTitle(bbs.getBbsTitle());
            savedBoard.setBbsDesc(bbs.getBbsDesc());
            savedBoard.setBbsType(bbs.getBbsType());
            savedBoard.setBbsAnsYn(bbs.getBbsAnsYn());
            savedBoard.setBbsReplYn(bbs.getBbsReplYn());
            savedBoard.setUseYn(bbs.getUseYn());
            savedBoard.setReadRole(bbs.getReadRole());
            savedBoard.setWriteRole(bbs.getWriteRole());
            savedBoard.setLastChgId(userId);
            savedBoard.setLastChgDt(LocalDateTime.now());
            tnBbsRepository.save(savedBoard);
        }
    }

    @Transactional
    public String deleteBoard(TnBbs bbs, String userId) {
        TnBbs savedBoard = tnBbsRepository.findById(bbs.getBbsSeq()).orElse(null);
        if (savedBoard == null) {
            return "notFind";
        } else {
            savedBoard.setUseYn("N");
            savedBoard.setLastChgDt(LocalDateTime.now());
            savedBoard.setLastChgId(userId);
            tnBbsRepository.save(savedBoard);
            return null;
        }
    }

    public List<TnBbsContents> selectPostList() {
        return tnBbsContentsRepository.findAll();
    }

    /**
     * 파일이 저장될 중간 경로를 생성한다.
     * D:/kcscUploadFiles/XXXX/abc.jpg XXXX에 해당하는 경로다.
     *
     * @return 중간 경로
     */
    private String getMiddlePath() {
        //파일이 저장될 경로를 생성한다.
        String domainPath = "post";
        Date nowDate = new Date();
        String strNowYyyy = new SimpleDateFormat("yyyy").format(nowDate);
        String strNowYyyyMmdd = new SimpleDateFormat("yyyyMMdd").format(nowDate);
        String middlePath = domainPath + "/" + strNowYyyy + "/" + strNowYyyyMmdd + "/";

        return middlePath;
    }

    public void savePost(TnBbsContents contents, HttpServletRequest request, LoginVO user, MultipartFile[] files, long[] survivingFiles) throws Exception {
        if (contents.getBbsContSeq() == null) {
            String fileGrpId = fileService.addTnAttachFile(request, user, files, this.getMiddlePath());
            // TODO 하드코딩
            contents.setBbsContLevel(1L);
            contents.setBbsReadCnt(0L);
            contents.setUseYn("Y");
            contents.setFrstCrtDt(LocalDateTime.now());
            contents.setFrstCrtId(user.getId());
            contents.setFileGrpId(fileGrpId);
            tnBbsContentsRepository.save(contents);
        } else {
            TnBbsContents savedPost = tnBbsContentsRepository.findById(contents.getBbsContSeq()).orElse(null);

            String fileGrpId = savedPost.getFileGrpId();
            List<TnAttachFile> tnAttachFileList = fileService.findByFileGrpId(fileGrpId);
            if (survivingFiles == null) {
                //기존 file을 모두 삭제한다.
                if (fileGrpId != null) {
                    if (tnAttachFileList != null) {
                        for (TnAttachFile item : tnAttachFileList) {
                            fileService.deleteTnAttachFile(request, user, item.getFileSeq().longValue());
                        }
                    }
                    fileGrpId = null;
                }
            } else {
                // 살아남은 file을 제외한 나머지 file을 삭제한다.
                if (tnAttachFileList != null) {
                    boolean isFound = false;
                    for (TnAttachFile item : tnAttachFileList) {
                        for (long oldFileSeq : survivingFiles) {
                            if (oldFileSeq == item.getFileSeq()) {
                                isFound = true;
                                break;
                            }
                        }
                        if (!isFound) {
                            fileService.deleteTnAttachFile(request, user, item.getFileSeq().longValue());
                        }
                        isFound = false;
                    }
                }

            }
            System.out.println("@@@ files : " + files);
            fileGrpId = fileService.addTnAttachFile(request, user, files, this.getMiddlePath(), fileGrpId);
            savedPost.setFixedYn(contents.getFixedYn());
            savedPost.setSecretYn(contents.getSecretYn());
            savedPost.setBbsId(contents.getBbsId());
            savedPost.setBbsSeq(contents.getBbsSeq());
            savedPost.setBbsContTitle(contents.getBbsContTitle());
            savedPost.setFileGrpId(contents.getFileGrpId());
            savedPost.setBbsContents(contents.getBbsContents());
            savedPost.setIpAddress(contents.getIpAddress());
            savedPost.setUseYn("Y");
            savedPost.setLastChgId(user.getId());
            savedPost.setLastChgDt(LocalDateTime.now());
            savedPost.setFileGrpId(fileGrpId);
            tnBbsContentsRepository.save(savedPost);
        }
    }

    @Transactional
    public String deletePost(TnBbsContents contents, String userId) {
        TnBbsContents savedPost = tnBbsContentsRepository.findById(contents.getBbsContSeq()).orElse(null);
        if (savedPost == null) {
            return "notFind";
        } else {
            savedPost.setIpAddress(contents.getIpAddress());
            savedPost.setUseYn("N");
            savedPost.setLastChgDt(LocalDateTime.now());
            savedPost.setLastChgId(userId);
            tnBbsContentsRepository.save(savedPost);
            return null;
        }
    }

}
