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.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.nvsigntalk.code.NvSigntalkStatusCd;
import cokr.xit.ens.modules.nvsigntalk.domain.SendDetailNvSigntalk;
import cokr.xit.ens.modules.nvsigntalk.domain.SendDetailNvSigntalkStatHist;
import cokr.xit.ens.modules.nvsigntalk.domain.repository.SendDetailNvSigntalkRepository;
import cokr.xit.ens.modules.nvsigntalk.domain.repository.SendDetailNvSigntalkStatHistRepository;
import cokr.xit.ens.modules.nvsigntalk.model.NvSigntalkApiRespVO;
import cokr.xit.ens.modules.nvsigntalk.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.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

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

    private final ApplicationEventPublisher applicationEventPublisher;

    private final SendMastRepository sendMastRepository;
    private final SendDetailNvSigntalkRepository sendDetailNvSigntalkRepository;
    private final SendDetailNvSigntalkStatHistRepository sendDetailNvSigntalkStatHistRepository;
    private final OrgMngService orgMngService;
    private final NvSigntalkApiSpec nvSigntalkApi;
    @Value("${contract.kakao.pay.mydoc.api.bulksend-batch-unit}")
    private int SEND_BATCH_UNIT;

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

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


        SendMast sendMast = null;
        List<SendDetailNvSigntalk> 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 = sendDetailNvSigntalkRepository.findAllBySendMastAndDocIdIsNotNull(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.bulkStatus(orgMng.getNvStXNaverClientId(), orgMng.getNvStXNaverClientSecret(), jsonStr);
                            if (log.isDebugEnabled()) {
                                StringBuffer sb = new StringBuffer();
                                sb.append("\n==============================================================================")
                                        .append("\n[ Naver 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>> data = (List<Map<String, Object>>) ((Map<String, Object>) mResponse.getResultInfo()).get("data");


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

                            list.stream().forEach(row -> this.modifyStatInfoByDocId(row, mApiRespVOByDocId));

                        } 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))
                                sendDetailNvSigntalkStatHistRepository.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 -> NvSigntalkStatusCd.success.equals(row.getNvDocStat()) ? 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<SendDetailNvSigntalk> list) {
        String result = null;
        EnsResponseVO resp = null;
        try {

            List<String> docIds = list.stream()
                    .map(row -> row.getDocId())
                    .collect(Collectors.toList());
            List<String> additionalErrorResponseFieldList = Arrays.asList("clientDocId");
            Map<String, Object> mJson = new HashMap<>();
            mJson.put("docIdList", docIds);
            mJson.put("additionalErrorResponseFieldList", additionalErrorResponseFieldList);


            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()
                .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)
                .sendTs((Long) row.get("sendTs"))
                .recvTs((Long) row.get("recvTs"))
                .authReqTs((Long) row.get("authReqTs"))
                .authViewTs((Long) row.get("authViewTs"))
                .authCompleteTs((Long) row.get("authCompleteTs"))
                .expireTs((Long) row.get("expireTs"))
                .orgNotifiedTs((Long) row.get("orgNotifiedTs"))
                .errorCode(row.containsKey("errorCode") ? String.valueOf(row.get("errorCode")) : null)
                .errorMsg(row.containsKey("errorMsg") ? String.valueOf(row.get("errorMsg")) : null)
                .build();

        NvSigntalkApiRespVO<DocStatResp> nvSigntalkApiRespVO = NvSigntalkApiRespVO.<DocStatResp>builder()
                .data(docStatResp)
                .build();


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


    private void modifyStatInfoByDocId(SendDetailNvSigntalk row, Map<String, NvSigntalkApiRespVO<DocStatResp>> mSigntalkApiRespVOByDocId) {
        NvSigntalkApiRespVO<DocStatResp> apiRespVO = mSigntalkApiRespVOByDocId.get(row.getDocId());
        DocStatResp docStatResp = apiRespVO.getData();

        NvSigntalkStatusCd docStatusCd = NvSigntalkStatusCd.valueOfEnum(docStatResp.getResult());
        if (!NvSigntalkStatusCd.UNKNOWN.equals(docStatusCd)) {
//            String docBoxStatus = docStatResp.getResult();
            Long docBoxSentAt = docStatResp.getSendTs();
            Long docBoxReceivedAt = docStatResp.getRecvTs();
            Long authenticatedAt = docStatResp.getAuthCompleteTs();
            Long tokenUsedAt = null;
            Long docBoxReadAt = docStatResp.getOrgNotifiedTs();

//            row.setNvDocStat(CmmnUtil.isEmpty(docBoxStatus)           ?row.getNvDocStat(): NvSigntalkStatusCd.valueOfEnum(docBoxStatus));
            row.setNvDocStat(docStatusCd);
            row.setNvDocSentDt(CmmnUtil.isEmpty(row.getNvDocSentDt()) ? DateUtil.absTimeMillisecToDate(docBoxSentAt, "yyyyMMddHHmmss") : row.getNvDocSentDt());
            row.setNvDocReceivedDt(CmmnUtil.isEmpty(row.getNvDocReceivedDt()) ? DateUtil.absTimeMillisecToDate(docBoxReceivedAt, "yyyyMMddHHmmss") : row.getNvDocReceivedDt());
            row.setNvDocAuthFrstDt(CmmnUtil.isEmpty(row.getNvDocAuthFrstDt()) ? DateUtil.absTimeMillisecToDate(authenticatedAt, "yyyyMMddHHmmss") : row.getNvDocAuthFrstDt());
            row.setNvDocTokenVrfyFrstDt(CmmnUtil.isEmpty(row.getNvDocTokenVrfyFrstDt()) ? DateUtil.absTimeMillisecToDate(tokenUsedAt, "yyyyMMddHHmmss") : row.getNvDocTokenVrfyFrstDt());
            row.setNvDocReadFrstDt(CmmnUtil.isEmpty(row.getNvDocReadFrstDt()) ? DateUtil.absTimeMillisecToDate(docBoxReadAt, "yyyyMMddHHmmss") : row.getNvDocReadFrstDt());

            row.setError(FieldError.initBuilder().build());
        } else {
            row.setError(FieldError.initBuilder()
                    .errorCode(EnsErrCd.RSLT630.getCode())
                    .errorMessage(String.format("%s %s", docStatResp.getErrorCode(), docStatResp.getErrorMsg()))
                    .build());
        }
    }

    private List<SendDetailNvSigntalkStatHist> toSendDetailStatHist(List<SendDetailNvSigntalk> list, String respMsg) {

        EnsResponseVO respVO = this.respMsgToMap(respMsg);

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

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

            return list.stream()
                    .map(row -> {
                        NvSigntalkApiRespVO<DocStatResp> apiRespVO = mApiRespVOByDocId.get(row.getDocId());
                        DocStatResp statusData = apiRespVO.getData();
                        return SendDetailNvSigntalkStatHist.builder()
                                .sendDetailId(row.getSendDetailId())
                                .docId(row.getDocId())
                                .clientDocId(statusData.getClientDocId())
                                .result(statusData.getResult())
                                .sendTs(statusData.getSendTs())
                                .recvTs(statusData.getRecvTs())
                                .authReqTs(statusData.getAuthReqTs())
                                .authViewTs(statusData.getAuthViewTs())
                                .authCompleteTs(statusData.getAuthCompleteTs())
                                .expireTs(statusData.getExpireTs())
                                .orgNotifiedTs(statusData.getOrgNotifiedTs())
//                                .error(FieldError.initBuilder()
//                                        .errorCode(signtalkApiApiRespVO.getError_code())
//                                        .errorMessage(signtalkApiApiRespVO.getError_message())
//                                        .build())
                                .error(FieldError.initBuilder()
                                        .errorCode(statusData.getErrorCode())
                                        .errorMessage(statusData.getErrorMsg())
                                        .build())
                                .build();
                    })
                    .collect(Collectors.toList());

        } else {
            return list.stream()
                    .map(row -> {
                        return SendDetailNvSigntalkStatHist.builder()
                                .sendDetailId(row.getSendDetailId())
                                .docId(row.getDocId())
                                .clientDocId(row.getClientDocId())
                                .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.RSLT620, String.format("문서상태조회API 오류. documents 키값이 없습니다. %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();
    }

}
