package kr.xit.batch.ens.task;

import java.util.List;
import java.util.Map;

import org.slf4j.MDC;
import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.configuration.annotation.JobScope;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;

import kr.xit.batch.ens.task.cmm.TaskCmmUtils;
import kr.xit.biz.common.ApiConstants;
import kr.xit.biz.ens.model.EnsDTO;
import kr.xit.biz.ens.model.cmm.SndngMssageParam;
import kr.xit.biz.ens.service.IEnsBatchMakeService;
import kr.xit.core.exception.ErrorParse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * <pre>
 * description :
 *
 * packageName : kr.xit.batch.ens.task
 * fileName    : SndngMakeTasklet
 * author      : limju
 * date        : 2023-06-12
 * ======================================================================
 * 변경일         변경자        변경 내용
 * ----------------------------------------------------------------------
 * 2023-06-12    limju       최초 생성
 *
 * </pre>
 */
@Slf4j
@RequiredArgsConstructor
public class SndngMakeTasklet implements Tasklet {
    private final IEnsBatchMakeService service;
    @Override
    @JobScope
    public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) {
        final String isSlackEnabled = contribution.getStepExecution().getJobParameters().getString("isSlackEnabled");
        boolean isSuccess = true;
        final String SNDNG_PROCESS_STTUS = "sndngProcessSttus";
        final String UNITY_SNDNG_MST_ID = "unitySndngMastrId";


        try {
            MDC.put("service_error_msg", "");

            Map<String, List<SndngMssageParam>> tgtMap = service.findMakes(
                EnsDTO.BatchEnsRequest.builder()
                    .signguCode(contribution.getStepExecution().getJobParameters().getString("signguCode"))
                    .ffnlgCode(contribution.getStepExecution().getJobParameters().getString("ffnlgCode"))
                    .sndngProcessSttus(contribution.getStepExecution().getJobParameters().getString("sndngProcessSttus"))
                    .build()
            );

            for(String key :tgtMap.keySet()){
                List<SndngMssageParam> tgtList = tgtMap.get(key);

                for(SndngMssageParam dto : tgtList) {

                    try{
                        dto.setProfile(ApiConstants.IS_PROFILE_LOCAL? "local" : "prod");

                        if("tty1".equals(key)) {
                            MDC.put(UNITY_SNDNG_MST_ID, dto.getUnitySndngMastrId());
                            MDC.put(SNDNG_PROCESS_STTUS, "make-fail1");
                            dto.setProfile(ApiConstants.IS_PROFILE_LOCAL? "local" : "prod");
                            dto.setSndngProcessSttus(contribution.getStepExecution().getJobParameters().getString("sndngProcessSttus"));
                            dto.setNewSndngProcessSttus(ApiConstants.SndngProcessStatus.MAKE_OK.getCode());
                            //FIXME: try1,try2,tr3이 있는 경우 try1 이전에 try2,3이 실행될 수 있는 경우???
                            dto.setTrySeq(1);
                            dto.setSndngCo(dto.getSndngCo());
                            dto.setSndngSeCode(dto.getTry1());

                        }
                        else if("tty2".equals(key)) {
                            if(!service.makeIsNext(dto))    continue;
                        }

                        service.make(dto);


                    }catch(Exception e){
                        isSuccess = false;
                        String errMsg = ErrorParse.extractError(e).getMessage();
                        log.error("SndngMakeTasklet error :: {}", e.getMessage());
                        MDC.put("service_error_msg", errMsg);

                        TaskCmmUtils.taskBatchErrorLog(
                            contribution.getStepExecution().getJobExecution().getJobInstance().getJobName(),
                            errMsg,
                            isSlackEnabled
                        );

                        TaskCmmUtils.taskEnsBatchServiceUpdateErrorLog(
                            contribution.getStepExecution().getJobExecution().getJobInstance().getJobName(),
                            errMsg,
                            isSlackEnabled
                        );
                    }
                }
            }

        } finally {
            if(!isSuccess)  contribution.setExitStatus(ExitStatus.FAILED);
            else            contribution.setExitStatus(ExitStatus.COMPLETED);
            return RepeatStatus.FINISHED;
        }
    }
}
