package cokr.xit.ens.modules.ktsigntalk.gibis.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.gibis.code.KtGibisStatusCd;
import cokr.xit.ens.modules.ktsigntalk.gibis.domain.SendDetailKtGibis;
import cokr.xit.ens.modules.ktsigntalk.gibis.domain.SendDetailKtGibisReqHist;
import cokr.xit.ens.modules.ktsigntalk.gibis.domain.repository.SendDetailKtGibisRepository;
import cokr.xit.ens.modules.ktsigntalk.gibis.domain.repository.SendDetailKtGibisReqHistRepository;
import cokr.xit.ens.modules.ktsigntalk.gibis.model.KtGibisApiRespVO;
import cokr.xit.ens.modules.ktsigntalk.gibis.model.TmpltMngKtGibisDTO;
import cokr.xit.ens.modules.ktsigntalk.gibis.service.strategy.TmpltMngStrategyKtGibis;
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 KtGibisSender extends SendProcTemplate {

    private final ApplicationEventPublisher applicationEventPublisher;
    private final SendMastRepository sendMastRepository;
    private final SendDetailKtGibisRepository sendDetailKtGibisRepository;
    private final SendDetailKtGibisReqHistRepository sendDetailKtGibisReqHistRepository;
    private final OrgMngService orgMngService;
    private final TmpltMngStrategyKtGibis tmpltMngService;
    private final KtGibisApi ktGibisApi;
    @Value("${contract.kt.signtalk.gibis.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<SendDetailKtGibis> 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 = sendDetailKtGibisRepository.findAllFetchBySendMastId(sendMast.getSendMastId());
            OrgMng orgMng = orgMngService.find(sendMast.getOrgCd()).getResultInfo();
            SendMast finalSendMast = sendMast;
            TmpltMngKtGibisDTO tmpltMngDTO = tmpltMngService.find(sendMast.getOrgCd(), sendMast.getTmpltCd())
                    .orElseThrow(() -> new EnsException(EnsErrCd.SEND404, String.format("일치하는 템플릿 자료가 없습니다. [ sendMastId %s orgCd %s TmpltCd %s ]", finalSendMast.getSendMastId(), finalSendMast.getOrgCd(), finalSendMast.getTmpltCd())));


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

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

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



                            ResponseEntity<String> resp = ktGibisApi.bulkSend(orgMng.getKtStAccessToken(), jsonStr);
                            if (log.isDebugEnabled()) {
                                StringBuffer sb = new StringBuffer();
                                sb.append("\n==============================================================================")
                                        .append("\n[ Kt Gibis - 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());




                            KtGibisApiRespVO ktGibisApiRespVO = this.toApiRespVO((Map<String, Object>) mResponse.getResultInfo());

                            list.stream()
                                    .forEach(row -> this.modifyDocSendRsltBySrcKey(row, ktGibisApiRespVO));

                        } catch (EnsException e) {

                            list.stream()
                                    .forEach(row -> {
                                        row.setDocStat(KtGibisStatusCd.SENT_FAIL);
                                        row.setError(FieldError.initBuilder()
                                                .errorCode(e.getErrCd().getCode())
                                                .errorMessage(e.getMessage())
                                                .build());
                                    });
                        } catch (Exception e) {

                            list.stream()
                                    .forEach(row -> {
                                        row.setDocStat(KtGibisStatusCd.SENT_FAIL);
                                        row.setError(FieldError.initBuilder()
                                                .errorCode(EnsErrCd.SEND500.getCode())
                                                .errorMessage(e.getMessage())
                                                .build());
                                    });
                        } finally {
                            if (!CmmnUtil.isEmpty(jsonStr))
                                sendDetailKtGibisReqHistRepository.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.ktGibis)
                                    .statCd(StatCd.sendfail)
                                    .errCd(respVO.getErrCode())
                                    .message("-.SendMastId: " + sendMastId + "\n" + respVO.getErrMsg())
                                    .build())
                            .build());
                }
            }

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

        }


        return respVO;
    }


    /**
     * 전송요청API body Message로 변환하여 반환 한다.
     *
     * @param list
     * @param orgMng
     * @param tmpltMngDTO
     * @return
     */
    private EnsResponseVO makeMessage(List<SendDetailKtGibis> list, OrgMng orgMng, TmpltMngKtGibisDTO tmpltMngDTO) {
        String result = null;
        EnsResponseVO resp = null;
        try {


            List<Map<String, Object>> documents = new ArrayList<>();
            final String expiredDe = list.get(0).getSendMast().getCloseDt().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
            for (SendDetailKtGibis row : list) {

                Map<String, Object> document = new HashMap<>();
                document.put("src_key", row.getSrcKey());
                document.put("src_seq", row.getSrcSeq());
                document.put("sci", row.getCi());
                document.put("mms_dtl_cnts", row.getMmsDtlCnts());
                document.put("mms_title", row.getMmsTitle());
                document.put("rcs_dtl_cnts", row.getRcsDtlCnts());
//                document.put("url", row.getUrl());
                document.put("url", CmmnUtil.isEmpty(row.getUrl()) ? row.getUrl() : String.format("%s?src_key=%s&service_cd=%s", row.getUrl(), row.getSrcKey(), orgMng.getKtStServiceCd()));
                document.put("doc_hash", row.getHash());
                document.put("mdn", row.getMdn());

                documents.add(document);
            }
            final String nowDt = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
            Map<String, Object> mJson = new HashMap<>();
            mJson.put("service_cd", orgMng.getKtStServiceCd());
            mJson.put("msg_cd", tmpltMngDTO.getMsgCd());
            mJson.put("make_dt", nowDt);
            mJson.put("data_cnt", list.size());
            mJson.put("sndn_ex_time", expiredDe);
            mJson.put("ex_time", expiredDe);
            mJson.put("snd_tel_no", tmpltMngDTO.getSndTelNo());
            mJson.put("m_type", tmpltMngDTO.getMtype().getOrdinal());
            mJson.put("opt_type", tmpltMngDTO.getOptType() == null ? null : tmpltMngDTO.getOptType().toString());
            mJson.put("msg_type", tmpltMngDTO.getMsgType());
            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;
    }


    /**
     * 전송요청 응답결과를 API응답VO 객체에 매핑하여 반환
     *
     * @param row
     * @return
     */
    private KtGibisApiRespVO toApiRespVO(Map<String, Object> row) {
        return KtGibisApiRespVO.builder()
                .result_cd(row.containsKey("result_cd") ? String.valueOf(row.get("result_cd")) : null)
                .result_dt(row.containsKey("result_dt") ? String.valueOf(row.get("result_dt")) : null)
                .errors(row.containsKey("errors") ? (List<Map<String, Object>>) row.get("err_msg") : null)
                .build();
    }

    /**
     * 전송요청결과 갱신(update)
     * -. 성공/실패 여부에 따라 Error 필드 갱신
     *
     * @param row
     * @param ktGibisApiRespVO
     */
    private void modifyDocSendRsltBySrcKey(SendDetailKtGibis row, KtGibisApiRespVO ktGibisApiRespVO) {
        if ("00".equals(ktGibisApiRespVO.getResult_cd())) {
            row.setDocStat(KtGibisStatusCd.SENT);
            row.setError(FieldError.initBuilder().build());
        } else {
            row.setDocStat(KtGibisStatusCd.valueOfEnum("E" + ktGibisApiRespVO.getResult_cd()));
            row.setError(FieldError.initBuilder()
                    .errorCode(EnsErrCd.SEND630.getCode())
                    .errorMessage(String.format("%s %s", ktGibisApiRespVO.getResult_cd(), ktGibisApiRespVO.getErrors()
                            .stream()
                            .map(stringObjectMap -> stringObjectMap.get("error_msg"))
                            .collect(Collectors.toList()))
                    )
                    .build());
        }

    }


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


    /**
     * 전송요청응답을 전송요청이력 Entity 데이터로 변환하여 반환 한다.
     *
     * @param sendMsg
     * @param respMsg
     * @return
     */
    private List<SendDetailKtGibisReqHist> toSendDetailReqHist(List<SendDetailKtGibis> 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())) {

            return sendMsgList.stream()
                    .map(row -> {
                        String srcKey = (String) row.get("src_key");

                        return SendDetailKtGibisReqHist.builder()
                                .sendDetailId(mSendDetailIds.get(srcKey))
                                .sendRawMsg(gson.toJson(row))
                                .srcKey(srcKey)
                                .respRawMsg(respMsg)
                                .error(FieldError.initBuilder().build())
                                .build();
                    })
                    .collect(Collectors.toList());

        } else {
            return sendMsgList.stream()
                    .map(row -> {
                        return SendDetailKtGibisReqHist.builder()
                                .sendDetailId(mSendDetailIds.get(row.get("src_key")))
                                .sendRawMsg(gson.toJson(row))
                                .srcKey((String) row.get("src_key"))
                                .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 (!"00".equals(mResp.get("result_cd"))) {
                errCode = EnsErrCd.SEND620;
                errMsg = String.format("전송요청 실패. [ERR] %s %s", mResp.get("result_cd"), ((List<Map<String, Object>>) mResp.get("errors"))
                        .stream()
                        .filter(o -> o.containsKey("error_msg"))
                        .map(o -> o.get("error_msg"))
                        .collect(Collectors.toList()).toString());
            }
//            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();
    }
}
