package cokr.xit.ens.modules.nvsigntalk.service.support;

import cokr.xit.ens.core.aop.EnsResponseVO;
import cokr.xit.ens.core.exception.EnsException;
import cokr.xit.ens.core.exception.code.EnsErrCd;
import cokr.xit.ens.core.monitor.slack.event.MonitorEvent;
import cokr.xit.ens.core.utils.CmmnUtil;
import cokr.xit.ens.core.utils.DateUtil;
import cokr.xit.ens.core.utils.MapDeserailizer;
import cokr.xit.ens.modules.common.biztmplt.SendProcTemplate;
import cokr.xit.ens.modules.common.code.PostSeCd;
import cokr.xit.ens.modules.common.code.StatCd;
import cokr.xit.ens.modules.common.ctgy.sys.mng.domain.OrgMng;
import cokr.xit.ens.modules.common.ctgy.sys.mng.service.OrgMngService;
import cokr.xit.ens.modules.common.domain.SendMast;
import cokr.xit.ens.modules.common.domain.repository.SendMastRepository;
import cokr.xit.ens.modules.common.domain.support.FieldError;
import cokr.xit.ens.modules.common.event.SendMastStatUpdateEvent;
import cokr.xit.ens.modules.common.monitor.MessageByPhase;
import cokr.xit.ens.modules.nvsigntalk.code.NvSigntalkStatusCd;
import cokr.xit.ens.modules.nvsigntalk.domain.SendDetailNvSigntalk;
import cokr.xit.ens.modules.nvsigntalk.domain.SendDetailNvSigntalkReqHist;
import cokr.xit.ens.modules.nvsigntalk.domain.repository.SendDetailNvSigntalkRepository;
import cokr.xit.ens.modules.nvsigntalk.domain.repository.SendDetailNvSigntalkReqHistRepository;
import cokr.xit.ens.modules.nvsigntalk.model.NvSigntalkApiRespVO;
import cokr.xit.ens.modules.nvsigntalk.model.config.DocSendResp;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Component
@RequiredArgsConstructor
public class NvSigntalkSender extends SendProcTemplate {

    private final ApplicationEventPublisher applicationEventPublisher;

    private final SendMastRepository sendMastRepository;
    private final SendDetailNvSigntalkRepository sendDetailNvSigntalkRepository;
    private final SendDetailNvSigntalkReqHistRepository sendDetailNvSigntalkReqHistRepository;
    private final OrgMngService orgMngService;
    private final NvSigntalkApiSpec nvSigntalkApi;
    @Value("${contract.naver.signtalk.api.bulksend-batch-unit}")
    private int SEND_BATCH_UNIT;

    private Gson gson = new GsonBuilder().registerTypeAdapter(Map.class, new MapDeserailizer()).disableHtmlEscaping().create();

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public EnsResponseVO execute(Long sendMastId) {

        SendMast sendMast = null;
        List<SendDetailNvSigntalk> sendDetails = null;
        EnsResponseVO respVO = null;
        try {
            if (CmmnUtil.isEmpty(sendMastId))
                throw new EnsException(EnsErrCd.SEND410, "발송마스터ID(은)는 필수조건 입니다.");

            sendMast = sendMastRepository.findById(sendMastId).orElseThrow(() -> new EnsException(EnsErrCd.SEND404, String.format("일치하는 발송마스터 자료가 없습니다. [ sendMastId %s ]", sendMastId)));
            sendDetails = sendDetailNvSigntalkRepository.findAllBySendMast(sendMast);
            OrgMng orgMng = orgMngService.find(sendMast.getOrgCd()).getResultInfo();


            Lists.partition(sendDetails, SEND_BATCH_UNIT).stream()
                    .forEach(list -> {

                        String sendRespBody = null;
                        String jsonStr = null;
                        try {

                            EnsResponseVO message = this.makeMessage(list);
                            if (!(EnsErrCd.OK.equals(message.getErrCode()) || null == message.getErrCode())) 
                                throw new EnsException(message.getErrCode(), message.getErrMsg());
                            jsonStr = String.valueOf(message.getResultInfo());



                            ResponseEntity<String> resp = nvSigntalkApi.bulkSend(orgMng.getNvStXNaverClientId(), orgMng.getNvStXNaverClientSecret(), jsonStr);
                            if (log.isDebugEnabled()) {
                                StringBuffer sb = new StringBuffer();
                                sb.append("\n==============================================================================")
                                        .append("\n[ Naver Signtalk - Sending ]")
                                        .append("\n### Request Info...")
                                        .append("\n" + jsonStr)
                                        .append("\n### Response Info...")
                                        .append("\n" + resp.getBody())
                                        .append("\n==============================================================================");
                                log.debug(sb.toString());
                            }
                           
                            sendRespBody = resp.getBody();
                            if (resp.getStatusCode() != HttpStatus.OK)  
                                throw new EnsException(EnsErrCd.SEND620, String.format("전송요청 중.. %s %s", resp.getStatusCode().toString(), resp.getBody()));
                            EnsResponseVO mResponse = this.respMsgToMap(resp.getBody());
                            if (!EnsErrCd.OK.equals(mResponse.getErrCode()))
                                throw new EnsException(mResponse.getErrCode(), mResponse.getErrMsg());
                            List<Map<String, Object>> data = (List<Map<String, Object>>) ((Map<String, Object>) mResponse.getResultInfo()).get("data");




                            Map<String, NvSigntalkApiRespVO<DocSendResp>> mApiRespVOByClientDocId = data.stream()
                                    .map(row -> this.toApiRespVOMap(row))
                                    .collect(Collectors.toMap(m -> String.valueOf(m.get("key")), m -> (NvSigntalkApiRespVO<DocSendResp>) m.get("value"), (k1, k2) -> k1));
                           
                            list.stream()
                                    .forEach(row -> this.modifyDocSendRsltByClientDocId(row, mApiRespVOByClientDocId));

                        } catch (EnsException e) {
                           
                            list.stream()
                                    .forEach(row -> {
                                        row.setNvDocStat(NvSigntalkStatusCd.SENT_FAIL);
                                        row.setError(FieldError.initBuilder()
                                                .errorCode(e.getErrCd().getCode())
                                                .errorMessage(e.getMessage())
                                                .build());
                                    });
                        } catch (Exception e) {
                           
                            list.stream()
                                    .forEach(row -> {
                                        row.setNvDocStat(NvSigntalkStatusCd.SENT_FAIL);
                                        row.setError(FieldError.initBuilder()
                                                .errorCode(EnsErrCd.SEND500.getCode())
                                                .errorMessage(e.getMessage())
                                                .build());
                                    });
                        } finally {
                            if (!CmmnUtil.isEmpty(jsonStr))
                                sendDetailNvSigntalkReqHistRepository.saveAll(this.toSendDetailReqHist(list, jsonStr, sendRespBody));
                        }

                    });

           
            Optional<Integer> cntSuccess = sendDetails.stream()
                    .map(row -> CmmnUtil.isEmpty(row.getError()) || CmmnUtil.isEmpty(row.getError().getErrorCode()) ? 1 : 0)
                    .reduce(Integer::sum);
            if (cntSuccess.get() > 0) 
                respVO = EnsResponseVO.okBuilder()
                        .resultInfo(sendDetails.stream()
                                .map(row -> this.toResultInfo(row))
                                .collect(Collectors.toList()))
                        .build();
            else
                throw new EnsException(EnsErrCd.SEND500, String.format("전체건수 전송 실패(총 %d 건)", sendDetails.size()));

        } catch (EnsException e) {
           
            respVO = EnsResponseVO.errBuilder().errCode(e.getErrCd()).errMsg(e.getMessage()).build();
        } catch (Exception e) {
           
            respVO = EnsResponseVO.errBuilder().errCode(EnsErrCd.SEND500).errMsg(e.getMessage()).build();
        } finally {
            if (!CmmnUtil.isEmpty(sendMast))
                if (EnsErrCd.OK.equals(respVO.getErrCode())) {
                    sendMast.setStatCd(StatCd.sendok);
                    sendMast.setError(FieldError.initBuilder().build());
                } else {
                    sendMast.setStatCd(StatCd.sendfail);
                    sendMast.setError(FieldError.initBuilder()
                            .errorCode(respVO.getErrCode().getCode())
                            .errorMessage(respVO.getErrMsg())
                            .build());

                    applicationEventPublisher.publishEvent(MonitorEvent.builder()
                            .message(MessageByPhase.builder()
                                    .oClass(getClass().getSimpleName() + "." + new Throwable().getStackTrace()[0].getMethodName())
                                    .postSeCd(PostSeCd.nvSigntalk)
                                    .statCd(StatCd.sendfail)
                                    .errCd(respVO.getErrCode())
                                    .message("-.SendMastId: " + sendMastId + "\n" + respVO.getErrMsg())
                                    .build())
                            .build());
                }



            applicationEventPublisher.publishEvent(SendMastStatUpdateEvent.builder().sendMastId(sendMastId).build());
        }


        return respVO;
    }


    private EnsResponseVO makeMessage(List<SendDetailNvSigntalk> list) {
        String result = null;
        EnsResponseVO resp = null;
        try {

           
            List<Map<String, Object>> data = new ArrayList<>();
            for (SendDetailNvSigntalk row : list) {

               
                Map<String, Object> message = null;
                try {
                    if (!CmmnUtil.isEmpty(row.getMessage()))
                        message = gson.fromJson(row.getMessage(), Map.class);
                } catch (Exception e) {
                    throw new EnsException(EnsErrCd.SEND411, String.format("message 데이터 변환에 실패 했습니다. [ sendDetailId %s message %s ]", row.getSendDetailId(), row.getMessage()));
                }
               
                Map<String, Object> notification = null;
                try {
                    if (!CmmnUtil.isEmpty(row.getNotification()))
                        notification = gson.fromJson(row.getNotification(), Map.class);
                } catch (Exception e) {
                    throw new EnsException(EnsErrCd.SEND411, String.format("notification 데이터 변환에 실패 했습니다. [ sendDetailId %s notification %s ]", row.getSendDetailId(), row.getNotification()));
                }

               
                Map<String, Object> document = new HashMap<>();
                document.put("clientDocId", row.getClientDocId());            
                document.put("ci", row.getCi());                              
                document.put("title", row.getTitle());                        
                document.put("message", message);                             
                if (CmmnUtil.isEmpty(row.getValidDurationAt())) {
                    if (!CmmnUtil.isEmpty(row.getValidDuration()))
                        document.put("validDuration", row.getValidDuration());        
                } else {
                    document.put("validDuration", DateUtil.dateToRelTime(DateUtil.absTimeSecToDate(row.getValidDurationAt(), "yyyyMMddHHmmss")) / 1000);  
                }
//                document.put("redirectUrl", "Y".equals(row.getMkBillUseYn())?row.getKkoBillMast().getUrl():row.getRedirectUrl());            
//                document.put("redirectUrl", CmmnUtil.isEmpty(row.getRedirectUrl()) ? ("Y".equals(row.getMkBillUseYn()) ? row.getKkoBillMast().getUrl() : null) : row.getRedirectUrl());            
                document.put("redirectUrl", row.getRedirectUrl());            
                document.put("publishDocumentYn", row.getPublishDocumentYn());
                document.put("documentHash", row.getDocumentHash());          
                document.put("callCenterNo", row.getCallCenterNo());          
                if (!CmmnUtil.isEmpty(row.getOrgId()))
                    document.put("orgId", row.getOrgId());                        
                document.put("authRequireYn", row.getAuthRequireYn());        
                document.put("notification", notification);                   


                data.add(document);
            }
            Map<String, Object> mJson = new HashMap<>();
            mJson.put("data", data);

           
            result = gson.toJson(mJson);

            resp = EnsResponseVO.okBuilder()
                    .resultInfo(result)
                    .build();
        } catch (EnsException e) {
            resp = EnsResponseVO.errBuilder()
                    .errCode(e.getErrCd())
                    .errMsg(e.getMessage())
                    .build();
        } catch (Exception e) {
            resp = EnsResponseVO.errBuilder()
                    .errCode(EnsErrCd.SEND502)
                    .errMsg(String.format("발송메시지 생성 중 오류 발생. %s", e.getMessage()))
                    .build();
        }

        return resp;
    }


    private Map<String, Object> toApiRespVOMap(Map<String, Object> row) {
        DocSendResp docSendResp = DocSendResp.builder()
                .result(row.containsKey("result") ? String.valueOf(row.get("result")) : null)
                .docId(row.containsKey("docId") ? String.valueOf(row.get("docId")) : null)
                .clientDocId(row.containsKey("clientDocId") ? String.valueOf(row.get("clientDocId")) : null)
                .errorCode(row.containsKey("errorCode") ? String.valueOf(row.get("errorCode")) : null)
                .errorMsg(row.containsKey("errorMsg") ? String.valueOf(row.get("errorMsg")) : null)
                .build();

        NvSigntalkApiRespVO<DocSendResp> nvSigntalkApiRespVO = NvSigntalkApiRespVO.<DocSendResp>builder()
                .data(docSendResp)
                .build();

        Map<String, Object> m = new HashMap<>();
        m.put("key", row.get("clientDocId"));
        m.put("value", nvSigntalkApiRespVO);
        return m;
    }

    private void modifyDocSendRsltByClientDocId(SendDetailNvSigntalk row, Map<String, NvSigntalkApiRespVO<DocSendResp>> mSigntalkApiRespVOByClientDocId) {
        NvSigntalkApiRespVO<DocSendResp> apiRespVO = mSigntalkApiRespVOByClientDocId.get(row.getClientDocId());
        DocSendResp docSendResp = apiRespVO.getData();
        if ("success".equals(docSendResp.getResult())) {
            row.setNvDocStat(NvSigntalkStatusCd.sent);
            row.setDocId(String.valueOf(docSendResp.getDocId()));
            row.setError(FieldError.initBuilder().build());
        } else {
            row.setNvDocStat(NvSigntalkStatusCd.valueOfEnum(docSendResp.getErrorMsg()));
            row.setError(FieldError.initBuilder()
                    .errorCode(EnsErrCd.SEND630.getCode())
                    .errorMessage(String.format("%s %s", docSendResp.getErrorCode(), docSendResp.getErrorMsg()))
                    .build());
            row.setDocId(docSendResp.getDocId());
        }

    }


    private Map<String, String> toResultInfo(SendDetailNvSigntalk row) {
        Map<String, String> m = new HashMap<>();
//        m.put("msgIdx", row.getMsgIdx());
        m.put("docId", row.getDocId());
        m.put("clientDocId", row.getClientDocId());
        if (!CmmnUtil.isEmpty(row.getError())) {
            m.put("errCd", row.getError().getErrorCode());
            m.put("errMsg", row.getError().getErrorMessage());
        }
        return m;
    }


    private List<SendDetailNvSigntalkReqHist> toSendDetailReqHist(List<SendDetailNvSigntalk> list, String sendMsg, String respMsg) {

        List<Map<String, Object>> sendMsgList = (List<Map<String, Object>>) gson.fromJson(sendMsg, Map.class).get("data");
        Map<String, Long> mSendDetailIds = list.stream()
                .map(row -> {
                    Map<String, Object> m = new HashMap<>();
                    m.put("key", row.getClientDocId());
                    m.put("value", row.getSendDetailId());
                    return m;
                })
                .collect(Collectors.toMap(m -> String.valueOf(m.get("key")), m -> (Long) m.get("value"), (k1, k2) -> k1));

        EnsResponseVO respVO = this.respMsgToMap(respMsg);


        if (EnsErrCd.OK.equals(respVO.getErrCode())) {
            Map<String, Object> mRespBody = (Map<String, Object>) respVO.getResultInfo();
            List<Map<String, String>> data = (List<Map<String, String>>) mRespBody.get("data");
            Map<String, Map<String, String>> mRespMsg = data.stream()
                    .map(row -> {
                        Map<String, Object> m = new HashMap<>();
                        m.put("key", String.valueOf(row.get("clientDocId")));
                        Map<String, String> mValue = new HashMap<>();
                        mValue.put("docId", row.get("docId"));
                        mValue.put("errorCode", row.get("errorCode"));
                        mValue.put("errorMsg", row.get("errorMsg"));
                        mValue.put("rawMsg", gson.toJson(row));
                        m.put("value", mValue);
                        return m;
                    })
                    .collect(Collectors.toMap(m -> String.valueOf(m.get("key")), m -> (Map<String, String>) m.get("value"), (k1, k2) -> k1));

            return sendMsgList.stream()
                    .map(row -> {
                        String clientDocId = (String) row.get("clientDocId");
                        boolean isSuccess = CmmnUtil.isEmpty(mRespMsg.get(clientDocId).get("errorCode"));

                        return SendDetailNvSigntalkReqHist.builder()
                                .sendDetailId(mSendDetailIds.get(clientDocId))        
                                .sendRawMsg(gson.toJson(row))                         
                                .clientDocId(clientDocId)                             
                                .docId(mRespMsg.get(clientDocId).get("docId"))        
                                .respRawMsg(mRespMsg.get(clientDocId).get("rawMsg"))  
                                .error(FieldError.initBuilder()
                                        .errorCode(isSuccess ? null : EnsErrCd.SEND620.getCode())
                                        .errorMessage(isSuccess ? null : String.format("%s %s"
                                                , mRespMsg.get(clientDocId).get("errorCode")
                                                , mRespMsg.get(clientDocId).get("errorMsg")
                                        ))
                                        .build())
                                .build();
                    })
                    .collect(Collectors.toList());

        } else {
            return sendMsgList.stream()
                    .map(row -> {
                        String clientDocId = (String) row.get("clientDocId");
                        return SendDetailNvSigntalkReqHist.builder()
                                .sendDetailId(mSendDetailIds.get(clientDocId)) 
                                .sendRawMsg(gson.toJson(row))                  
                                .clientDocId(clientDocId)                      
                                .respRawMsg(respMsg)                           
                                .error(FieldError.initBuilder()
                                        .errorCode(respVO.getErrCode().getCode())
                                        .errorMessage(respVO.getErrMsg())
                                        .build())
                                .build();
                    })
                    .collect(Collectors.toList());
        }
    }

    private EnsResponseVO respMsgToMap(String respMsg) {
        EnsErrCd errCode = EnsErrCd.OK;
        String errMsg = EnsErrCd.OK.getCodeNm();
        Map<String, Object> mResp = null;
        try {
            mResp = gson.fromJson(respMsg, Map.class);
            if (CmmnUtil.isEmpty(mResp.get("data")))
                throw new EnsException(EnsErrCd.SEND620, String.format("전송요청API 오류. data 키값이 없습니다. %s", respMsg));
        } catch (EnsException e) {
            errCode = e.getErrCd();
            errMsg = e.getMessage();
        } catch (Exception e) {
            errCode = EnsErrCd.SEND511;
            errMsg = String.format("전송요청API 응답데이터 JSON 객체 변환 실패. %s", respMsg);
        }
        return EnsErrCd.OK.equals(errCode) ?
                EnsResponseVO.okBuilder().resultInfo(mResp).build()
                : EnsResponseVO.errBuilder()
                .errCode(errCode)
                .errMsg(errMsg)
                .build();
    }
}
