package cokr.xit.ens.modules.kkoalimtalk.service.strategy;

import cokr.xit.ens.core.exception.EnsException;
import cokr.xit.ens.core.exception.code.EnsErrCd;
import cokr.xit.ens.modules.common.ctgy.sys.mng.domain.OrgMng;
import cokr.xit.ens.modules.common.ctgy.sys.mng.domain.repository.OrgMngRepository;
import cokr.xit.ens.modules.common.ctgy.sys.mng.domain.repository.TmpltMngRepository;
import cokr.xit.ens.modules.common.ctgy.sys.mng.model.TmpltMngDTO;
import cokr.xit.ens.modules.common.ctgy.sys.mng.model.TmpltMngSearchDTO;
import cokr.xit.ens.modules.common.ctgy.sys.mng.service.strategy.TmpltMngStrategyTemplate;
import cokr.xit.ens.modules.kkoalimtalk.domain.TmpltMngKkoAlimtalk;
import cokr.xit.ens.modules.kkoalimtalk.domain.repository.TmpltMngKkoAlimtalkRepository;
import cokr.xit.ens.modules.kkoalimtalk.model.TmpltMngKkoAlimtalkDTO;
import cokr.xit.ens.modules.kkoalimtalk.model.struct.TmpltMngKkoAlimtalkMapper;
import lombok.RequiredArgsConstructor;
import org.mapstruct.factory.Mappers;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.*;
import java.util.stream.Collectors;

@Component("tmpltMngStrategy_kkoat")
@RequiredArgsConstructor
public class TmpltMngStrategyKkoAlimtalk extends TmpltMngStrategyTemplate<Map<String, Object>, TmpltMngKkoAlimtalkDTO> {

    private final OrgMngRepository orgMngRepository;
    private final TmpltMngRepository tmpltMngRepository;
    private final TmpltMngKkoAlimtalkRepository tmpltMngKkoAlimtalkRepository;
    private TmpltMngKkoAlimtalkMapper kkoAlimtalkMapper = Mappers.getMapper(TmpltMngKkoAlimtalkMapper.class);
//    private final RedisTemplate redisTemplate;

    @Override
    public List<TmpltMngKkoAlimtalkDTO> findAll(TmpltMngSearchDTO tmpltMngSearchDTO) {
        return tmpltMngKkoAlimtalkRepository.findAllDtoBySearchDTO(tmpltMngSearchDTO);
    }

    @Override
    public Optional<TmpltMngKkoAlimtalkDTO> find(String orgCd, String tmpltCd) {
        return tmpltMngKkoAlimtalkRepository.findDtoByOrgCdAndTmpltCd(orgCd, tmpltCd);

//        String key = super.pushCache(redisTemplate, orgCd, tmpltCd, tmpltMngKkoAlimtalkRepository);
//        HashOperations<String, String, TmpltMngKkoAlimtalkDTO> hashOperations = redisTemplate.opsForHash();
//        return Optional.ofNullable(hashOperations.entries(KEY).get(key));
    }

    @Override
    protected TmpltMngKkoAlimtalkDTO validate(Map<String, Object> params) {
        try {
            TmpltMngKkoAlimtalkDTO dto = mapper.convertValue(params, TmpltMngKkoAlimtalkDTO.class);
            final Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
            Set<ConstraintViolation<TmpltMngKkoAlimtalkDTO>> list = validator.validate(dto);
            if (list.size() > 0) {
                throw new EnsException(EnsErrCd.ERR410, "유효하지 않은 요청 값 입니다.", list.stream()
                        .map(row -> String.format("%s [ %s ]", row.getMessageTemplate(), row.getPropertyPath()))
                        .collect(Collectors.toList())
                );
            }
            return dto;
        } catch (IllegalArgumentException e) {
            List<String> fields = Arrays.stream(TmpltMngDTO.class.getDeclaredFields()).map(row -> row.getName()).collect(Collectors.toList());
            fields.addAll(Arrays.stream(TmpltMngKkoAlimtalkDTO.class.getDeclaredFields()).map(row -> row.getName()).collect(Collectors.toList()));
            throw new EnsException(EnsErrCd.ERR403, "유효하지 않은 파라미터 입니다. 사용가능한 파라미터는 resultInfo 를 참고하시기 바랍니다.", fields);
        }

    }

    @Override
    protected void addProc(TmpltMngKkoAlimtalkDTO dto) {
        OrgMng orgMng = orgMngRepository.findById(dto.getOrgCd()).orElseThrow(() -> new EnsException(EnsErrCd.ERR404, String.format("기관코드(%s)가 일치하는 자료가 없습니다.", dto.getOrgCd())));
        tmpltMngRepository.findFetchByOrgCdAndTmpltCd(dto.getOrgCd(), dto.getTmpltCd())
                .ifPresent(tmpltMng -> {
                    throw new EnsException(EnsErrCd.ERR540, String.format("이미 등록된 템플릿코드[기관코드 %s 템플릿코드 %s] 입니다.", tmpltMng.getOrgMng().getOrgCd(), tmpltMng.getTmpltCd()));
                });

        TmpltMngKkoAlimtalk tmpltMng = kkoAlimtalkMapper.toEntity(dto);
        tmpltMng.setOrgMng(orgMng);
        tmpltMng.setRegistId("ENS_SYS");
        tmpltMngKkoAlimtalkRepository.save(tmpltMng);
    }

    @Override
    protected void modifyProc(TmpltMngKkoAlimtalkDTO dto) {
        TmpltMngKkoAlimtalk tmpltMng = tmpltMngKkoAlimtalkRepository.findFetchByOrgCdAndTmpltCd((dto).getOrgCd(), (dto).getTmpltCd())
                .orElseThrow(() -> new EnsException(EnsErrCd.ERR404, String.format("기관코드(%s) 및 템플릿코드(%s)가 일치하는 자료가 없습니다.", dto.getOrgCd(), dto.getTmpltCd())));
        if(!"Y".equals(tmpltMng.getUseYn()))
            throw new EnsException(EnsErrCd.ERR402, "\"미사용\" 상태의 템플릿은 수정 할 수 없습니다.");
        kkoAlimtalkMapper.updateFromDto(dto, tmpltMng);
        tmpltMng.setUpdId("ENS_SYS");

//        super.deleteCache(redisTemplate, dto.getOrgCd(), dto.getTmpltCd());
    }
}
