package cokr.xit.ens.modules.ktsigntalk.direct.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.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.ktsigntalk.direct.code.KtSigntalkStatusCd;
import cokr.xit.ens.modules.ktsigntalk.direct.domain.SendDetailKtSigntalk;
import cokr.xit.ens.modules.ktsigntalk.direct.domain.SendDetailKtSigntalkReqHist;
import cokr.xit.ens.modules.ktsigntalk.direct.domain.repository.SendDetailKtSigntalkRepository;
import cokr.xit.ens.modules.ktsigntalk.direct.domain.repository.SendDetailKtSigntalkReqHistRepository;
import cokr.xit.ens.modules.ktsigntalk.direct.model.KtSigntalkApiRespVO;
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.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

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

    private final ApplicationEventPublisher applicationEventPublisher;
    private final SendMastRepository sendMastRepository;
    private final SendDetailKtSigntalkRepository sendDetailKtSigntalkRepository;
    private final SendDetailKtSigntalkReqHistRepository sendDetailKtSigntalkReqHistRepository;
    private final OrgMngService orgMngService;
    private final KtSigntalkApi ktSigntalkApi;
    @Value("${contract.kt.signtalk.direct.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<SendDetailKtSigntalk> 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 = sendDetailKtSigntalkRepository.findAllFetchBySendMastId(sendMast.getSendMastId());
            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, orgMng);
                            if (!(EnsErrCd.OK.equals(message.getErrCode()) || null == message.getErrCode())) 
                                throw new EnsException(message.getErrCode(), message.getErrMsg());
                            jsonStr = String.valueOf(message.getResultInfo());



                            ResponseEntity<String> resp = ktSigntalkApi.bulkSend(orgMng.getKtStAccessToken(), jsonStr);
                            if (log.isDebugEnabled()) {
                                StringBuffer sb = new StringBuffer();
                                sb.append("\n==============================================================================")
                                        .append("\n[ Kt 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>> documents = (List<Map<String, Object>>) ((Map<String, Object>) mResponse.getResultInfo()).get("results");




                            Map<String, KtSigntalkApiRespVO<String>> mApiRespVOBySrcKey = documents.stream()
                                    .map(row -> this.toApiRespVOMap(row))
                                    .collect(Collectors.toMap(m -> String.valueOf(m.get("key")), m -> (KtSigntalkApiRespVO) m.get("value"), (k1, k2) -> k1));
                           
                            list.stream()
                                    .forEach(row -> this.modifyDocSendRsltBySrcKey(row, mApiRespVOBySrcKey));

                        } catch (EnsException e) {
                           
                            list.stream()
                                    .forEach(row -> {
                                        row.setDocStat(KtSigntalkStatusCd.SENT_FAIL);
                                        row.setError(FieldError.initBuilder()
                                                .errorCode(e.getErrCd().getCode())
                                                .errorMessage(e.getMessage())
                                                .build());
                                    });
                        } catch (Exception e) {
                           
                            list.stream()
                                    .forEach(row -> {
                                        row.setDocStat(KtSigntalkStatusCd.SENT_FAIL);
                                        row.setError(FieldError.initBuilder()
                                                .errorCode(EnsErrCd.SEND500.getCode())
                                                .errorMessage(e.getMessage())
                                                .build());
                                    });
                        } finally {
                            if (!CmmnUtil.isEmpty(jsonStr))
                                sendDetailKtSigntalkReqHistRepository.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.ktSigntalk)
                                    .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<SendDetailKtSigntalk> list, OrgMng orgMng) {
        String result = null;
        EnsResponseVO resp = null;
        try {

           
            Map<String, Object> hdr = new HashMap<>();
            hdr.put("biz_cd", list.get(0).getSendMast().getOrgCd());  
            hdr.put("msg_cd", list.get(0).getSendMast().getTmpltCd());
            hdr.put("make_dt", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));
            hdr.put("send_seq", "0000");               
            hdr.put("data_cnt", list.size());          


           
            List<Map<String, Object>> documents = new ArrayList<>();
            for (SendDetailKtSigntalk row : list) {
               
                Map<String, Object> document = new HashMap<>();
                document.put("src_key", row.getSrcKey());              
                document.put("src_seq", row.getSrcSeq());              
                document.put("d_birth", row.getDBirth());              
                document.put("jumin_first_no", row.getJuminFirstNo()); 
                document.put("cn_person", row.getCnPerson());          
                document.put("c_zip", row.getCZip());                  
                document.put("addr", row.getAddr());                   
                document.put("rcv_tel_no", row.getRcvTelNo());         
                document.put("snd_tel_no", row.getSndTelNo());         
                document.put("rcv_pwd_use_yn", row.getRcvPwdUseYn());  
                document.put("ci", row.getCi());                       
                document.put("mms_dtl_cnts", row.getMmsDtlCnts());     
                document.put("mms_title", row.getMmsTitle());          
                document.put("send_tel", row.getSendTel());            
                document.put("url", row.getUrl());                     
                document.put("ex_time", row.getExTime());              
                document.put("doc_hash", row.getHash());               
                document.put("m_type", row.getMType());                
                document.put("rcv_type", row.getRcvType());            

                documents.add(document);
            }
            Map<String, Object> mJson = new HashMap<>();
            mJson.put("service_cd", orgMng.getKtStServiceCd());
            mJson.put("service_key", orgMng.getKtStServiceKey());
            mJson.put("req_type", "1");
            mJson.put("hdr", hdr);
            mJson.put("reqs", documents);

           
            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) {
        KtSigntalkApiRespVO<String> ktSigntalkApiRespVO = KtSigntalkApiRespVO.<String>builder()
                .err_code(row.containsKey("err_code") ? String.valueOf(row.get("err_code")) : null)
                .err_msg(row.containsKey("err_msg") ? String.valueOf(row.get("err_msg")) : null)
                .data(row.containsKey("src_key") ? String.valueOf(row.get("src_key")) : null)
                .build();

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

    private void modifyDocSendRsltBySrcKey(SendDetailKtSigntalk row, Map<String, KtSigntalkApiRespVO<String>> mSigntalkApiRespVOBySrcKey) {
        KtSigntalkApiRespVO ktSigntalkApiRespVO = mSigntalkApiRespVOBySrcKey.get(row.getSrcKey());
        if ("0000".equals(ktSigntalkApiRespVO.getErr_code())) {
            row.setDocStat(KtSigntalkStatusCd.SENT);
            row.setError(FieldError.initBuilder().build());
        } else {
            row.setDocStat(KtSigntalkStatusCd.valueOfEnum("E" + ktSigntalkApiRespVO.getErr_code()));
            row.setError(FieldError.initBuilder()
                    .errorCode(EnsErrCd.SEND630.getCode())
                    .errorMessage(String.format("%s %s", ktSigntalkApiRespVO.getErr_code(), ktSigntalkApiRespVO.getErr_msg()))
                    .build());
        }

    }


    private Map<String, String> toResultInfo(SendDetailKtSigntalk row) {
        Map<String, String> m = new HashMap<>();
        m.put("clientSrcKey", row.getClientSrcKey());
        m.put("srcKey", row.getSrcKey());
        if (!CmmnUtil.isEmpty(row.getError())) {
            m.put("errCd", row.getError().getErrorCode());
            m.put("errMsg", row.getError().getErrorMessage());
        }
        return m;
    }


    private List<SendDetailKtSigntalkReqHist> toSendDetailReqHist(List<SendDetailKtSigntalk> list, String sendMsg, String respMsg) {


        List<Map<String, Object>> sendMsgList = (List<Map<String, Object>>) gson.fromJson(sendMsg, Map.class).get("reqs");
        Map<String, Long> mSendDetailIds = list.stream()
                .map(row -> {
                    Map<String, Object> m = new HashMap<>();
                    m.put("key", row.getSrcKey());
                    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>> documents = (List<Map<String, String>>) mRespBody.get("results");
            Map<String, Map<String, String>> mRespMsg = documents.stream()
                    .map(row -> {
                        Map<String, Object> m = new HashMap<>();
                        m.put("key", String.valueOf(row.get("src_key")));
                        Map<String, String> mValue = new HashMap<>();
                        mValue.put("err_code", row.get("err_code"));
                        mValue.put("err_msg", row.get("err_msg"));
                        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 srcKey = (String) row.get("src_key");
                        boolean isSuccess = "0000".equals(mRespMsg.get(srcKey).get("err_code"));

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

        } else {
            return sendMsgList.stream()
                    .map(row -> {
                        String srcKey = (String) row.get("src_key");
                        return SendDetailKtSigntalkReqHist.builder()
                                .sendDetailId(mSendDetailIds.get(srcKey)) 
                                .sendRawMsg(gson.toJson(row))             
                                .srcKey(srcKey)                           
                                .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 (!"0000".equals(mResp.get("code")))
                throw new EnsException(EnsErrCd.SEND620, String.format("전송요청 실패. [ERR] %s %s", mResp.get("code"), mResp.get("message")));
            if (CmmnUtil.isEmpty(mResp.get("results")))
                throw new EnsException(EnsErrCd.SEND620, String.format("전송요청API 오류. results 키값이 없습니다. %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();
    }
}
