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.utils.CmmnUtil;
import cokr.xit.ens.core.utils.DateUtil;
import cokr.xit.ens.core.utils.MapDeserailizer;
import cokr.xit.ens.modules.common.biztmplt.ResultProcTemplate;
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.ktsigntalk.direct.code.KtSigntalkStatusCd;
import cokr.xit.ens.modules.ktsigntalk.direct.domain.SendDetailKtSigntalk;
import cokr.xit.ens.modules.ktsigntalk.direct.domain.SendDetailKtSigntalkStatHist;
import cokr.xit.ens.modules.ktsigntalk.direct.domain.repository.SendDetailKtSigntalkRepository;
import cokr.xit.ens.modules.ktsigntalk.direct.domain.repository.SendDetailKtSigntalkStatHistRepository;
import cokr.xit.ens.modules.ktsigntalk.direct.model.KtSigntalkApiRespVO;
import cokr.xit.ens.modules.ktsigntalk.direct.model.config.DocStatResp;
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.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Component
@RequiredArgsConstructor
public class KtSigntalkRsltFetcher extends ResultProcTemplate {

    private final ApplicationEventPublisher applicationEventPublisher;

    private final SendMastRepository sendMastRepository;
    private final SendDetailKtSigntalkRepository sendDetailKtSigntalkRepository;
    private final SendDetailKtSigntalkStatHistRepository sendDetailKtSigntalkStatHistRepository;
    private final OrgMngService orgMngService;
    private final KtSigntalkApi ktSigntalkApi;
    @Value("${contract.kakao.pay.mydoc.api.bulksend-batch-unit}")
    private int SEND_BATCH_UNIT;

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


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

            sendMast = sendMastRepository.findById(sendMastId).orElseThrow(() -> new EnsException(EnsErrCd.RSLT404, String.format("일치하는 발송마스터 자료가 없습니다. [ sendMastId %s ]", sendMastId)));
            sendDetails = sendDetailKtSigntalkRepository.findAllBySendMastAndSrcKeyIsNotNull(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, 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.bulkStatus(orgMng.getKtStAccessToken(), jsonStr);
                            if (log.isDebugEnabled()) {
                                StringBuffer sb = new StringBuffer();
                                sb.append("\n==============================================================================")
                                        .append("\n[ Kt Signtalk - StatFetch ]")
                                        .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.RSLT620, 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("rsps");



                            Map<String, KtSigntalkApiRespVO<DocStatResp>> 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.modifyStatInfoBySrcKey(row, mApiRespVOBySrcKey));

                        } catch (EnsException e) {

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

                            list.stream()
                                    .forEach(row -> row.setError(FieldError.initBuilder()
                                            .errorCode(EnsErrCd.RSLT500.getCode())
                                            .errorMessage(e.getMessage())
                                            .build())
                                    );
                        } finally {
                            if (!CmmnUtil.isEmpty(jsonStr))
                                sendDetailKtSigntalkStatHistRepository.saveAll(this.toSendDetailStatHist(list, sendRespBody));
                        }

                    });


            respVO = EnsResponseVO.okBuilder().resultInfo(resultInfo).build();
        } catch (EnsException e) {

            respVO = EnsResponseVO.errRsltBuilder().errCode(e.getErrCd()).errMsg(e.getMessage()).resultInfo(resultInfo).build();
        } catch (Exception e) {

            respVO = EnsResponseVO.errRsltBuilder().errCode(EnsErrCd.RSLT500).errMsg(e.getMessage()).resultInfo(resultInfo).build();
        } finally {
            if (!CmmnUtil.isEmpty(sendMast))
                if (EnsErrCd.OK.equals(respVO.getErrCode())) {
                    sendMast.setError(FieldError.initBuilder().build());


                    Integer readCnt = sendDetails.stream()
                            .map(row -> KtSigntalkStatusCd.E50.equals(row.getDocStat()) ? 1 : 0)
                            .reduce(Integer::sum)
                            .orElseGet(() -> 0);
                    sendMast.setReadCnt(readCnt);

                    if (StatCd.sendok.equals(sendMast.getStatCd())) {
                        if (readCnt > 0)
                            sendMast.setStatCd(StatCd.open);
                        else
                            sendMast.setStatCd(StatCd.sendcmplt);
                    } else if (StatCd.sendcmplt.equals(sendMast.getStatCd())) {
                        if (readCnt > 0)
                            sendMast.setStatCd(StatCd.open);
                    }
                } else {
                    sendMast.setError(FieldError.initBuilder()
                            .errorCode(respVO.getErrCode().getCode())
                            .errorMessage(respVO.getErrMsg())
                            .build());
                }


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


        return respVO;
    }


    private EnsResponseVO makeMessage(List<SendDetailKtSigntalk> list, OrgMng orgMng) {
        String result = null;
        Gson gson = new GsonBuilder().disableHtmlEscaping().create();
        EnsResponseVO resp = null;
        try {

            List<String> srcKeys = list.stream()
                    .map(row -> row.getSrcKey())
                    .collect(Collectors.toList());
            Map<String, Object> mJson = new HashMap<>();
            mJson.put("service_cd", orgMng.getKtStServiceCd());
            mJson.put("service_key", orgMng.getKtStServiceKey());
            mJson.put("src_keys", srcKeys);


            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.RSLT502)
                    .errMsg(String.format("요청 메시지 생성 중 오류 발생. %s", e.getMessage()))
                    .build();
        }

        return resp;
    }


    private Map<String, Object> toApiRespVOMap(Map<String, Object> row) {
        DocStatResp docStatResp = DocStatResp.builder()
                .src_key((String) row.get("src_key"))
                .mms_sndg_rslt_sqno((Integer) row.get("mms_sndg_rslt_sqno"))
                .prcs_dt((String) row.get("prcs_dt"))
                .mms_bsns_dvcd((String) row.get("mms_bsns_dvcd"))
                .approve_yn((String) row.get("approve_yn"))
                .approve_date((String) row.get("approve_date"))
                .receive_refuse_yn((String) row.get("receive_refuse_yn"))
                .receive_refuse_date((String) row.get("receive_refuse_date"))
                .choice_channel((String) row.get("choice_channel"))
                .mbl_bzowr_dvcd((String) row.get("mbl_bzowr_dvcd"))
                .rl_mms_sndg_telno((String) row.get("rl_mms_sndg_telno"))
                .mms_sndg_rslt_dvcd((String) row.get("mms_sndg_rslt_dvcd"))
                .mms_sndg_tmst((String) row.get("mms_sndg_tmst"))
                .mms_rcv_tmst((String) row.get("mms_rcv_tmst"))
                .mms_rdg_tmst((String) row.get("mms_rdg_tmst"))
                .build();


        KtSigntalkApiRespVO<DocStatResp> ktSigntalkApiRespVO = KtSigntalkApiRespVO.<DocStatResp>builder()
//                .err_code()
//                .err_msg()
                .data(docStatResp)
                .build();

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


    private void modifyStatInfoBySrcKey(SendDetailKtSigntalk row, Map<String, KtSigntalkApiRespVO<DocStatResp>> mApiRespVOBySrcKey) {
        KtSigntalkApiRespVO<DocStatResp> apiRespVO = mApiRespVOBySrcKey.get(row.getSrcKey());

        if (CmmnUtil.isEmpty(apiRespVO.getErr_code())) {
            DocStatResp docStatResp = apiRespVO.getData();
            KtSigntalkStatusCd docStatusCd = KtSigntalkStatusCd.valueOfEnum("E" + docStatResp.getMms_sndg_rslt_dvcd());

            String docBoxSentAt = docStatResp.getMms_sndg_tmst();
            String docBoxReceivedAt = docStatResp.getMms_rcv_tmst();
            String authenticatedAt = docStatResp.getMms_rdg_tmst();
            Long tokenUsedAt = null;
            String docBoxReadAt = docStatResp.getMms_rdg_tmst();

            row.setDocStat(docStatusCd);
            row.setDocSentDt(CmmnUtil.isEmpty(row.getDocSentDt()) ? docBoxSentAt : row.getDocSentDt());
            row.setDocReceivedDt(CmmnUtil.isEmpty(row.getDocReceivedDt()) ? docBoxReceivedAt : row.getDocReceivedDt());
            row.setDocAuthFrstDt(CmmnUtil.isEmpty(row.getDocAuthFrstDt()) ? authenticatedAt : row.getDocAuthFrstDt());
            row.setDocTokenVrfyFrstDt(CmmnUtil.isEmpty(row.getDocTokenVrfyFrstDt()) ? DateUtil.absTimeSecToDate(tokenUsedAt, "yyyyMMddHHmmss") : row.getDocTokenVrfyFrstDt());
            row.setDocReadFrstDt(CmmnUtil.isEmpty(row.getDocReadFrstDt()) ? docBoxReadAt : row.getDocReadFrstDt());

            row.setError(FieldError.initBuilder().build());
        } else {
            row.setError(FieldError.initBuilder()
                    .errorCode(EnsErrCd.RSLT630.getCode())
                    .errorMessage(String.format("%s %s", apiRespVO.getErr_code(), apiRespVO.getErr_msg()))
                    .build());
        }
    }

    private List<SendDetailKtSigntalkStatHist> toSendDetailStatHist(List<SendDetailKtSigntalk> list, String respMsg) {

        EnsResponseVO respVO = this.respMsgToMap(respMsg);

                
        if (EnsErrCd.OK.equals(respVO.getErrCode())) {

            List<Map<String, Object>> documents = (List<Map<String, Object>>) ((Map<String, Object>) respVO.getResultInfo()).get("documents");
            Map<String, KtSigntalkApiRespVO<DocStatResp>> mApiRespVOBySrcKey = documents.stream()
                    .map(row -> this.toApiRespVOMap(row))
                    .collect(Collectors.toMap(m -> String.valueOf(m.get("key")), m -> (KtSigntalkApiRespVO<DocStatResp>) m.get("value"), (k1, k2) -> k1));

            return list.stream()
                    .map(row -> {
                        KtSigntalkApiRespVO<DocStatResp> apiRespVO = mApiRespVOBySrcKey.get(row.getSrcKey());
                        DocStatResp statusData = apiRespVO.getData();
                        return SendDetailKtSigntalkStatHist.builder()
                                .sendDetailId(row.getSendDetailId())
                                .srcKey(row.getSrcKey())
                                .mmsSndgRsltSqno(statusData.getMms_sndg_rslt_sqno())
                                .prcsDt(statusData.getPrcs_dt())
                                .mmsBsnsDvcd(statusData.getMms_bsns_dvcd())
                                .approveYn(statusData.getApprove_yn())
                                .approveDate(statusData.getApprove_date())
                                .receiveRefuseYn(statusData.getReceive_refuse_yn())
                                .receiveRefuseDate(statusData.getReceive_refuse_date())
                                .choiceChannel(statusData.getChoice_channel())
                                .mblBzowrDvcd(statusData.getMbl_bzowr_dvcd())
                                .rlMmsSndgTelno(statusData.getRl_mms_sndg_telno())
                                .mmsSndgRsltDvcd(statusData.getMms_sndg_rslt_dvcd())
                                .mmsSndgTmst(statusData.getMms_sndg_tmst())
                                .mmsRcvTmst(statusData.getMms_rcv_tmst())
                                .mmsRdgTmst(statusData.getMms_rdg_tmst())
                                .error(FieldError.initBuilder()
                                        .errorCode("0000".equals(statusData.getMms_bsns_dvcd()) ? null : statusData.getMms_bsns_dvcd())
                                        .errorMessage("0000".equals(statusData.getMms_bsns_dvcd()) ? null : KtSigntalkStatusCd.valueOfEnum("E" + statusData.getMms_bsns_dvcd()).getCodeNm())
                                        .build())
                                .build();
                    })
                    .collect(Collectors.toList());

        } else {
            return list.stream()
                    .map(row -> {
                        return SendDetailKtSigntalkStatHist.builder()
                                .sendDetailId(row.getSendDetailId())
                                .srcKey(row.getSrcKey())
                                .error(FieldError.initBuilder()
                                        .errorCode(respVO.getErrCode().getCode())
                                        .errorMessage(respVO.getErrMsg())
                                        .build())
                                .build();
                    })
                    .collect(Collectors.toList());
        }
    }


    private EnsResponseVO respMsgToMap(String respMsg) {
        Gson gson = new GsonBuilder().registerTypeAdapter(Map.class, new MapDeserailizer()).serializeNulls().create();
        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.RSLT620, String.format("문서상태조회 실패. [ERR] %s %s", mResp.get("code"), mResp.get("message")));
            if (CmmnUtil.isEmpty(mResp.get("rsps")))
                throw new EnsException(EnsErrCd.RSLT620, String.format("문서상태조회API 오류. rsps 키값이 없습니다. %s", respMsg));
        } catch (EnsException e) {
            errCode = e.getErrCd();
            errMsg = e.getMessage();
        } catch (Exception e) {
            errCode = EnsErrCd.RSLT511;
            errMsg = String.format("문서상태조회API 응답 데이터 JSON 객체 변환 실패. %s", respMsg);
        }
        return EnsErrCd.OK.equals(errCode) ?
                EnsResponseVO.okBuilder().resultInfo(mResp).build()
                : EnsResponseVO.errBuilder()
                .errCode(errCode)
                .errMsg(errMsg)
                .build();
    }

}
