package com.dbnt.kcscbackend.admin.committee.service.impl;

import com.dbnt.kcscbackend.admin.committee.entity.TnCmtDraft;
import com.dbnt.kcscbackend.admin.committee.entity.TnCmtDraftAttend;
import com.dbnt.kcscbackend.admin.committee.service.AdminCommitteeProgressStatusService;
import com.dbnt.kcscbackend.admin.config.model.CreateCommitteeCodeManagementVO;
import com.dbnt.kcscbackend.admin.config.model.SetCommitteeCodeManagementVO;
import com.dbnt.kcscbackend.admin.contents.popUp.model.FileVO;
import com.dbnt.kcscbackend.auth.entity.LoginVO;
import com.dbnt.kcscbackend.commonCode.repository.TnCmtDraftAttendRepository;
import com.dbnt.kcscbackend.commonCode.repository.TnCmtDraftDetailRepository;
import com.dbnt.kcscbackend.commonCode.repository.TnCmtDraftRepository;
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 javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service("adminCommitteeProgressStatusService")
@RequiredArgsConstructor
public class AdminCommitteeProgressStatusServiceImpl extends EgovAbstractServiceImpl implements AdminCommitteeProgressStatusService {

    private final TnCmtDraftRepository tnCmtDraftRepository;
    private final TnCmtDraftAttendRepository tnCmtDraftAttendRepository;
    private final TnCmtDraftDetailRepository tnCmtDraftDetailRepository;

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

        // 아래 null로 전달 되는 부분 확인하기.
        // 유효성 검사 실시
        if(createCommitteeCodeManagementVO.getParamCodeLevel().trim().isEmpty()) {
            throw new Exception("오류가 발생했습니다. 시스템 담당자에게 문의 바랍니다. paramCodeLevel is empty.");
        }

        Map<String, Object> response = tnCmtDraftRepository.spAddTnCmtDraft(
                createCommitteeCodeManagementVO.getParamOrgNm(),			            // 위원회 이름
                null,		            // 위원회 등급
                createCommitteeCodeManagementVO.getParamOrgDesc(),	                    // 위원회 설명
                null,		                                                        // 상위 위원회 sequence
                null,			                                                            // 정렬 순서
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                user.getId(),
                null,
                null,
                null,
                null
        );

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

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

        return resultVO;
    }

    @Override
    public ResultVO getCommitteeProgressStatus(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" +
            "pageable.getPageSize():" + "\n" +
            pageable.getPageSize() + "\n" +
            "pageable.getPageNumber():" + "\n" +
            pageable.getPageNumber() + "\n" +
            "\n--------------------------------------------------------------\n"
        );


        List<Map<String, Object>> list = new ArrayList<>();
        long totalRecordCount = tnCmtDraftRepository.findByUseYnOrderByDrftSeqDesc("Y").size();
        List<Map<String, Object>> itemList = tnCmtDraftRepository.getCommitteeProgressStatus(pageable.getPageSize(),pageable.getPageNumber());
        AtomicInteger index = new AtomicInteger();
        for (Map<String, Object> item : itemList) {

            Map<String, Object> item2 = new HashMap<>();
            for (String key : item.keySet()) {
                item2.put(key, item.get(key));
            }
            item2.put("number", totalRecordCount - (long) pageable.getPageNumber() * pageable.getPageSize() - index.getAndIncrement());
            list.add(item2);
        }

        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 setCommitteeProgressStatus(ResultVO resultVO, HttpServletRequest request, LoginVO user, SetCommitteeCodeManagementVO setCommitteeCodeManagementVO, Long cmtSeq) throws Exception {
        System.out.println(
            "\n--------------------------------------------------------------\n" +
            request.getRequestURI() + " IN:" +
            "\n--------------------------------------------------------------\n" +
            "setCommitteeCodeManagementVO:" + "\n" +
            setCommitteeCodeManagementVO.toString() + "\n" +
            "cmtSeq:" + "\n" +
            cmtSeq + "\n" +
            "\n--------------------------------------------------------------\n"
        );

        // 유효성 검사 실시
        int isValid = tnCmtDraftRepository.spIsValidTnCmtDraftId(cmtSeq.intValue());

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

        //TnCmtDraft tnCmtDraft = tnCmtDraftRepository.findByDrftSeq(cmtSeq);

        Map<String, Object> response = tnCmtDraftRepository.spUpdateTnCmtDraft(
            cmtSeq.intValue(),
            setCommitteeCodeManagementVO.getParamOrgNm(),
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                user.getId(),
                null,
                null,
                null
        );


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

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

        return resultVO;
    }

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


        Map<String, Object> response = tnCmtDraftRepository.spDeleteTnCmtDraft(
                cmtSeq.intValue(),
                user.getId(),
                null,
                null,
                null
        );


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

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

        return resultVO;
    }

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

        Map<String, Object> item = tnCmtDraftRepository.getCommitteeProgressStatusDetail(drftSeq);
        Map<String, Object> dto = new HashMap<String, Object>();

        dto.put("item", item);
        resultVO.setResult(dto);
        resultVO.setResultCode(ResponseCode.SUCCESS.getCode());
        resultVO.setResultMessage(ResponseCode.SUCCESS.getMessage());

        return resultVO;
    }

}
