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

import com.dbnt.kcscbackend.admin.config.model.CreateCommitteeCodeManagementVO;
import com.dbnt.kcscbackend.admin.config.model.SetCommitteeCodeManagementVO;
import com.dbnt.kcscbackend.admin.config.service.AdminCommitteeCodeManagementService;
import com.dbnt.kcscbackend.admin.standardResearch.model.CreateStandardResearchVO;
import com.dbnt.kcscbackend.admin.standardResearch.model.UpdateStandardResearchVO;
import com.dbnt.kcscbackend.auth.entity.LoginVO;
import com.dbnt.kcscbackend.commonCode.entity.TnCmtOrg;
import com.dbnt.kcscbackend.commonCode.repository.TnCmtOrgRepository;
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.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("adminCommitteeCodeManagementService")
@RequiredArgsConstructor
public class AdminCommitteeCodeManagementServiceImpl extends EgovAbstractServiceImpl implements AdminCommitteeCodeManagementService {

    private final TnCmtOrgRepository tnCmtOrgRepository;

    @Override
    public ResultVO createCommitteeCodeManagement(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.");
        }
        Integer upCmtSeq = null;
        if( createCommitteeCodeManagementVO.getParamOrgId().trim().equals("00") == false ) {  // 00은 '중앙건설기술심의' 항목의 부모 sequnce이다. 그러나 DB에 실제 00이란 sequence는 존재하지 않는다.
            upCmtSeq = Integer.parseInt(createCommitteeCodeManagementVO.getParamOrgId());
        }

        Map<String, Object> response = tnCmtOrgRepository.spAddTnCmtOrg(
                createCommitteeCodeManagementVO.getParamOrgNm(),			            // 위원회 이름
                createCommitteeCodeManagementVO.getParamCodeLevel(),		            // 위원회 등급
                createCommitteeCodeManagementVO.getParamOrgDesc(),	                    // 위원회 설명
                upCmtSeq,		                                                        // 상위 위원회 sequence
                1,			                                                            // 정렬 순서
                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 getCommitteeCodeManagement(ResultVO resultVO, HttpServletRequest request, LoginVO user, Long upCmtSeq, String cmtType) throws Exception {

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

        List<Map<String, Object>> list = tnCmtOrgRepository.findByUseYnAndUpCmtSeqAndCmtTypeOrderByCmtOrder("Y", upCmtSeq, cmtType).stream()
                .map(item -> {
                    Map<String, Object> returnMap = new HashMap<>();
                    returnMap.put("orgId",          item.getCmtSeq());
                    returnMap.put("orgNm",          item.getCmtNm());
                    returnMap.put("orgDesc",        item.getCmtDesc());
                    returnMap.put("omtOrder",       item.getCmtOrder());
                    returnMap.put("upCmtSeq",       item.getUpCmtSeq());
                    return returnMap;
                })
                .collect(Collectors.toList());

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

        return resultVO;
    }

    @Override
    public ResultVO setCommitteeCodeManagement(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 = tnCmtOrgRepository.spIsValidTnCmtOrgId(cmtSeq.intValue());

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

        TnCmtOrg tnCmtOrg = tnCmtOrgRepository.findByCmtSeq(cmtSeq);

        Map<String, Object> response = tnCmtOrgRepository.spUpdateTnCmtOrg(
            cmtSeq.intValue(),
            setCommitteeCodeManagementVO.getParamOrgNm(),
            setCommitteeCodeManagementVO.getParamOrgDesc(),
            tnCmtOrg.getCmtOrder(),
            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 deleteCommitteeCodeManagement(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 = tnCmtOrgRepository.spDeleteTnCmtOrg(
                cmtSeq.intValue(),
                user.getId(),
                null,
                null,
                null
        );

        // 자식 코드들을 모두 제거한다.
        getChildrenOrg(user, cmtSeq);


        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;
    }

    private void getChildrenOrg(LoginVO user, Long upCmtSeq) {
        List<Map<String, Object>> list = tnCmtOrgRepository.findByUpCmtSeq(upCmtSeq).stream()
                .map(item -> {
                    Map<String, Object> returnMap = new HashMap<>();
                    returnMap.put("cmtSeq",          item.getCmtSeq());
                    getChildrenOrg( user, item.getCmtSeq() );
                    Map<String, Object> response = tnCmtOrgRepository.spDeleteTnCmtOrg(
                            item.getCmtSeq().intValue(),
                            user.getId(),
                            null,
                            null,
                            null
                    );
                    return returnMap;
                }).collect(Collectors.toList());

        System.out.println("for Debugging");
    }
}
