package com.its.api.its.service.vms;

import com.its.api.its.global.CodeManager;
import com.its.api.its.model.dto.code.TbCmmnCdDto;
import com.its.api.its.model.dto.common.*;
import com.its.api.its.model.dto.vms.TbVmsCtlrDto;
import com.its.api.its.model.dto.vms.TbVmsSttsDto;
import com.its.api.its.model.entity.vms.TbVmsCtlr;
import com.its.api.its.repository.vms.TbVmsCtlrRepository;
import com.its.api.its.repository.vms.TbVmsSttsHsRepository;
import com.its.api.its.service.code.TbCmmnCdService;
import com.its.api.utils.ItsUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@RequiredArgsConstructor
@Service
public class TbVmsCtlrService {

    private final TbVmsCtlrRepository repo;
    private final TbVmsSttsHsRepository sttsHsRepo;
    private final TbCmmnCdService cmmnCdService;

    // 데이터 1건 조회, 없으면 exception
    private TbVmsCtlr requireOne(Long id) {
        return repo.findById(id)
                .orElseThrow(() -> new NoSuchElementException("데이터가 존재하지 않습니다: " + id));
    }

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

    /**
     * 삭제되지 않은 전체 VMS 목록 조회
     * @return
     */
    @Transactional(readOnly = true)
    public List<TbVmsCtlrDto> findAllList() {
        List<TbVmsCtlrDto> result = new ArrayList<>();
        List<TbVmsCtlr> data = this.repo.findAllList();
        data.forEach(obj -> {
            result.add(obj.toDto());
        });
        return result;
    }

    /**
     * 삭제되지 않은 전체 VMS 상태정보 목록 조회
     * @return
     */
    @Transactional(readOnly = true)
    public List<TbVmsSttsDto> findAllStts() {
        List<TbVmsSttsDto> result = new ArrayList<>();
        List<TbVmsCtlr> data = this.repo.findAllList();
        data.forEach(obj -> {
            result.add(obj.toSttsDto());
        });
        return result;
    }

    /**
     * 삭제되지 않은 VMS 중 유형에 해당하는 VMS 목록 조회
     * @param vmsSizeType
     * @return
     */
    @Transactional(readOnly = true)
    public List<TbVmsCtlrDto> findAllListByType(String vmsSizeType) {
        List<TbVmsCtlrDto> result = new ArrayList<>();
        List<TbVmsCtlr> data = this.repo.findAllListByTypeCd(vmsSizeType);
        data.forEach(obj -> {
            result.add(obj.toDto());
        });
        return result;
    }

    // 데이터 1건 조회(기존 데이터가 반드시 존재해야 함)
    public TbVmsCtlrDto findById(Long id) {
        TbVmsCtlr entity = requireOne(id);
        return entity.toDto();
    }

    // 데이터 변경
    public TbVmsCtlrDto updateById(Long id, TbVmsCtlrDto.TbVmsCtlrUpdReq req) {
        TbVmsCtlr entity = requireOne(id);
        entity.updateInfo(req);
        this.repo.save(entity);
        return entity.toDto();
    }

    // 데이터 변경 또는 생성-목록(데이터가 존재하면 업데이트 없으면 신규로 생성)
    public List<TbVmsCtlrDto> mergeInfoList(List<TbVmsCtlrDto.TbVmsCtlrUpdReq> reqList) {
        List<TbVmsCtlrDto> result = new ArrayList<>();
        for (TbVmsCtlrDto.TbVmsCtlrUpdReq req : reqList) {
            TbVmsCtlr obj = req.toEntity();
            this.repo.save(obj);
            result.add(obj.toDto());
        }
        return result;
    }

    // 데이터 변경 또는 생성-개별(데이터가 존재하면 업데이트 없으면 신규로 생성)
    public TbVmsCtlrDto mergeInfo(TbVmsCtlrDto.TbVmsCtlrUpdReq req) {
        TbVmsCtlr obj = req.toEntity();
        this.repo.save(obj);
        return obj.toDto();
    }

    // 정보 삭제-개별, 데이터 존재하지 않으면 Exception
    public TbVmsCtlrDto deleteById(Long id) {
        TbVmsCtlr entity = requireOne(id);
        this.repo.deleteById(id);
        return entity.toDto();
    }

    // 정보 삭제-목록, 존재하는 데이터 만 삭제
    public List<TbVmsCtlrDto> deleteByIds(List<Long> ids) {
        List<TbVmsCtlrDto> result = new ArrayList<>();
        for (Long id : ids) {
            Optional<TbVmsCtlr> obj = this.repo.findById(id);
            if (obj.isPresent()) {
                this.repo.deleteById(id);
                result.add(obj.get().toDto());
            }
        }
        return result;
    }

    /**
     * VMS 용도 유형 코드 조회
     * @return
     */
    @Transactional(readOnly = true)
    public List<TbVmsCtlrDto.TbVmsUsageType> findAllVmsUsageType() {

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

    /**
     * VMS 유형 코드 조회
     * @return
     */
    @Transactional(readOnly = true)
    public List<TbVmsCtlrDto.TbVmsType> findAllVmsType() {

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

    /**
     * 통신이상 시설물 정보 조회
     * @return
     */
    public List<SttsCommErrDto> findAllListCommError() {

        Map<String, SttsCommErrDto> result = new HashMap<>();
        List<TbVmsCtlr> data = this.repo.findAllList();
        List<SttsHsErrCntInf> errList = this.sttsHsRepo.findAllCommErrorCount(ItsUtils.getFromToday());

        // 통신 상태가 오류 인 제어기 정보만 조회한다.
        data.forEach(obj -> {
            TbVmsSttsDto dto = obj.toSttsDto();
            if (!CodeManager.CMNC_STTS_NORMAL.equals(dto.getCmncSttsCd())) {
                SttsCommErrDto commErrorDto = new SttsCommErrDto();
                commErrorDto.setCtlrNmbr(String.valueOf(dto.getVmsCtlrNmbr()));
                commErrorDto.setCtlrId(dto.getVmsCtlrId());
                commErrorDto.setCtlrNm(dto.getVmsNm());
                commErrorDto.setUpdtDt(dto.getUpdtDt());
                commErrorDto.setCommCd(dto.getCmncSttsCd());
                commErrorDto.setCommDesc(CodeManager.getCodeDescShort(CodeManager.CMNC_STTS_CD, commErrorDto.getCommCd()));
                commErrorDto.setCommErrCnt(0);
                commErrorDto.setColCnt(0);
                result.put(commErrorDto.getCtlrNmbr(), commErrorDto);
            }
        });

        // 오늘 00:00:00 이후 발생한 오류 건수를 업데이트
        errList.forEach(obj -> {
            SttsCommErrDto dto = result.get(obj.getNmbr());
            if (dto != null) {
                dto.setCommErrCnt(obj.getErrCnt().intValue());
            }
        });

        return new ArrayList<>(result.values());
    }

    /**
     * 상태 목록
     * @param
     */
    public FcltSttsListDto findAllSttsListTotal() {

        String fcltType = "VMS";
        FcltSttsListDto result = new FcltSttsListDto();

        AtomicInteger error = new AtomicInteger(0);
        AtomicInteger normal = new AtomicInteger(0);
        AtomicInteger doorOpen = new AtomicInteger(0);
        AtomicInteger fanRun = new AtomicInteger(0);
        AtomicInteger hetrRun = new AtomicInteger(0);
        AtomicInteger modlErr = new AtomicInteger(0);
        AtomicInteger modlPwerErr = new AtomicInteger(0);
        AtomicInteger tempErr = new AtomicInteger(0);

        List<FcltSttsDto> sttsDtoList = new ArrayList<>();
        List<TbVmsCtlr> ctlrList = this.repo.findAllList();
        ctlrList.forEach(obj -> {
            TbVmsSttsDto dto = obj.toSttsDto();
            FcltSttsDto stts = FcltSttsDto.builder()
                    .fcltType(fcltType)
                    .fcltNmbr(String.valueOf(obj.getVmsCtlrNmbr()))
                    .fcltId(obj.getVmsCtlrId())
                    .fcltNm(obj.getIstlLctnNm())
                    .fcltKind(obj.getIstlLctnNm())
                    .xCrdn(obj.getXCrdn())
                    .yCrdn(obj.getYCrdn())
                    .strmUrl(obj.getStrmSesnNm())
                    .sttsCd(dto.getCmncSttsCd())
                    .sttsDesc(dto.getCmncSttsDesc())
                    .build();

            sttsDtoList.add(stts);

            if (CodeManager.CMNC_STTS_NORMAL.equals(dto.getCmncSttsCd())) {
                normal.getAndIncrement();
                if (("CDS1").equals(dto.getCboxDoorSttsCd())) {
                    doorOpen.getAndIncrement();
                }
                if (("PAS0").equals(dto.getFanSttsCd())) {
                    fanRun.getAndIncrement();
                }
                if (("HTS0").equals(dto.getHetrSttsCd())) {
                    hetrRun.getAndIncrement();
                }
                if (("MOS1").equals(dto.getModlSttsCd())) {
                    modlErr.getAndIncrement();
                }
                if (("PWS1").equals(dto.getPwerSttsCd())) {
                    modlPwerErr.getAndIncrement();
                }
                if (dto.getCboxTmpr() > 30 || dto.getCboxTmpr() < -5) {
                    tempErr.getAndIncrement();
                }
            }
            else {
                error.getAndIncrement();
            }
        });

        FcltSttsSummaryDto summaryDto = FcltSttsSummaryDto.builder()
                .fcltType(fcltType)
                .fcltNm(fcltType)
                .totalCnt(ctlrList.size())
                .normalCnt(normal.get())
                .errorCnt(error.get())
                .colErrCnt(0)
                .build();

        summaryDto.init();
        summaryDto.setDoorOpen(doorOpen.get());
        summaryDto.setFanRun(fanRun.get());
        summaryDto.setHetrRun(hetrRun.get());
        summaryDto.setModlErr(modlErr.get());
        summaryDto.setModlPwerErr(modlPwerErr.get());
        summaryDto.setTempErr(tempErr.get());
        summaryDto.setFcltObjs(sttsDtoList);
        result.getFcltList().add(summaryDto);

        return result;
    }

}
