package com.its.op.service.its.ifsc;

import com.its.op.dao.repository.its.ifsc.TbReptCngsSectRepository;
import com.its.op.dao.repository.its.ifsc.TbReptCngsSectTrafRepository;
import com.its.op.dto.its.code.TbCmmnCdDto;
import com.its.op.dto.its.ifsc.TbReptCngsSectDto;
import com.its.op.dto.its.ifsc.TbReptCngsSectKeyDto;
import com.its.op.dto.its.ifsc.TbReptCngsSectTrafDto;
import com.its.op.entity.its.ifsc.TbReptCngsSect;
import com.its.op.entity.its.ifsc.TbReptCngsSectKey;
import com.its.op.entity.its.ifsc.TbReptCngsSectTraf;
import com.its.op.global.CodeManager;
import com.its.op.service.its.code.TbCmmnCdService;
import com.its.utils.ItsUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Slf4j
@RequiredArgsConstructor
@Service
public class TbReptCngsSectService {

    private final TbReptCngsSectRepository repo;
    private final TbReptCngsSectTrafRepository trafRepo;
    private final TbCmmnCdService cmmnCdService;

    // 전체 데이터 조회
    @Transactional(readOnly = true)
    public List<TbReptCngsSectDto> findAll() {
        List<TbReptCngsSectDto> result = new ArrayList<>();
        List<TbReptCngsSect> data = this.repo.findAll();
        for (TbReptCngsSect entity : data) {
            result.add(entity.toDto());
        }
        return result;
    }

    /**
     * 반복정체관리 - 현재 반복정체 정보 조회
     * @param dcsnYn
     * @return
     */
    @Transactional(readOnly = true)
    public List<TbReptCngsSectDto> findAllCurrent(String dcsnYn) {
        //String dayTypeCd = ItsUtils.getDayOfWeek();
        List<TbReptCngsSectDto> result = new ArrayList<>();
        List<TbReptCngsSect> data = this.repo.findAllCurrent(dcsnYn, ItsUtils.getDayOfWeek());
        for (TbReptCngsSect entity : data) {
            result.add(entity.toDto());
        }
        return result;
    }

    /**
     * 반복정체관리 - 현재 반복정체 정보 조회(소통정보 포함)
     * 지도 화면 반복정체구간 목록에서 조회
     * @param
     * @return
     */
    @Transactional(readOnly = true)
    public List<TbReptCngsSectTrafDto> findAllCurrentTraf() {
        List<TbReptCngsSectTrafDto> result = new ArrayList<>();
        List<TbReptCngsSectTraf> data = this.trafRepo.findAllCurrent("Y", ItsUtils.getDayOfWeek());
        for (TbReptCngsSectTraf entity : data) {
            result.add(entity.toDto());
        }
        return result;
    }

    /**
     * 반복정체구간관리 - 운영자가 입력한 경우 확정으로 데이터 저장
     * @param reqList
     * @return
     */
    @Transactional
    public List<TbReptCngsSectDto> mergeInfoList(List<TbReptCngsSectDto.TbReptCngsSectUpdReq> reqList) {
        List<TbReptCngsSectDto> result = new ArrayList<>();
        for (TbReptCngsSectDto.TbReptCngsSectUpdReq req : reqList) {
            req.setStatYm(ItsUtils.getSysMonth());
            req.setDcsnYn("Y");
            req.setReptCngsSectOrgnCd("RCS2");
            req.setCrtnYmd(ItsUtils.getSysDay());

            TbReptCngsSect obj = req.toEntity();
            this.repo.save(obj);
            result.add(obj.toDto());
        }
        return result;
    }

    /**
     * 반복정체구간 - 확정취소, 예정취소 : 데이터 삭제
     * @param ids
     * @return
     */
    @Transactional
    public List<TbReptCngsSectKeyDto> deleteByIds(List<TbReptCngsSectKeyDto> ids) {
        for (TbReptCngsSectKeyDto id : ids) {
            TbReptCngsSectKey key = new TbReptCngsSectKey(id.getIfscId(), id.getStatYm(), id.getDayTypeCd(), id.getCnfsStrtHm());
            Optional<TbReptCngsSect> obj = this.repo.findById(key);
            if (obj.isPresent()) {
                this.repo.deleteById(key);
            }
        }
        return ids;
    }

    /**
     * 반복정체구간 - 확정취소, 예정취소 : 데이터 업데이트
     * @param ids
     * @return
     */
    @Transactional
    public List<TbReptCngsSectKeyDto> cancelCnfmByIds(List<TbReptCngsSectKeyDto> ids) {
        for (TbReptCngsSectKeyDto id : ids) {
            TbReptCngsSectKey key = new TbReptCngsSectKey(id.getIfscId(), id.getStatYm(), id.getDayTypeCd(), id.getCnfsStrtHm());
            Optional<TbReptCngsSect> obj = this.repo.findById(key);
            if (obj.isPresent()) {
                // 데이터가 있는 경우에만 확정 플래그 설정해서 업데이트
                obj.get().cancelCnfm();
                this.repo.save(obj.get());
            }
        }
        return ids;
    }

    /**
     * 반복정체구간관리 - 반복정체구간 확정
     * @param ids
     * @return
     */
    public List<TbReptCngsSectKeyDto> cnfmInfoList(List<TbReptCngsSectKeyDto> ids) {
        for (TbReptCngsSectKeyDto id : ids) {
            TbReptCngsSectKey key = new TbReptCngsSectKey(id.getIfscId(), id.getStatYm(), id.getDayTypeCd(), id.getCnfsStrtHm());
            Optional<TbReptCngsSect> obj = this.repo.findById(key);
            if (obj.isPresent()) {
                // 데이터가 있는 경우에만 확정 플래그 설정해서 업데이트
                obj.get().cnfm();
                this.repo.save(obj.get());
            }
        }
        return ids;
    }


    /**
     * 반복정체구간 분석: 반복정체 요일 유형 코드 목록 조회
     * @return
     */
    @Transactional(readOnly = true)
    public List<TbReptCngsSectDto.ReptCngsDayType> findAllDayType() {
        List<TbReptCngsSectDto.ReptCngsDayType> result = new ArrayList<>();
        TbCmmnCdDto allEntity = TbCmmnCdDto.builder().cmmnCd("ALL").cmmnCdKorNm("전체").build();
        TbReptCngsSectDto.ReptCngsDayType all = new TbReptCngsSectDto.ReptCngsDayType(allEntity);
        result.add(all);

        List<TbCmmnCdDto> data = this.cmmnCdService.findAllByCmmnClsfCd(CodeManager.DAY_TYPE_CD);
        if (data != null) {
            data.forEach(obj -> {
                if (obj.getUseYn().equals("Y")) {
                    result.add(new TbReptCngsSectDto.ReptCngsDayType(obj));
                }
            });
        }
        return result;
    }

    /**
     * 반복정체구간 분석: 반복정체구간 이력 조회
     * @param dayTypeCd
     * @param baseMn
     * @return
     */
    public List<TbReptCngsSectDto> findAllAnalByDayTypeCdAndStatYm(String dayTypeCd, String baseMn) {
        List<TbReptCngsSectDto> result = new ArrayList<>();

        List<TbReptCngsSect> data = null;
        if ("ALL".equals(dayTypeCd)) {
            data = this.repo.findAllAnalByStatYm(baseMn);
        }
        else {
            data = this.repo.findAllAnalByDayTypeCdAndStatYm(dayTypeCd, baseMn);
        }
        if (data != null) {
            data.forEach(obj -> {
                result.add(obj.toDto());
            });
        }
        return result;
    }
}
