package com.its.op.service.its.wcam;

import com.its.op.dao.repository.its.wcam.TbWcamCtlrRepository;
import com.its.op.dao.repository.its.wcam.TbWcamCtlrSttsHsRepository;
import com.its.op.dto.its.common.*;
import com.its.op.dto.its.facility.TbFcltSttsAlrmStupDto;
import com.its.op.dto.its.wcam.TbWcamCtlrDto;
import com.its.op.dto.its.wcam.TbWcamCtlrSttsDto;
import com.its.op.entity.its.wcam.TbWcamCtlr;
import com.its.op.global.CodeManager;
import com.its.op.service.its.facility.TbFcltSttsAlrmStupService;
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.*;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@RequiredArgsConstructor
@Service
public class TbWcamCtlrService {

    private final TbFcltSttsAlrmStupService alarmService;
    private final TbWcamCtlrRepository repo;
    private final TbWcamCtlrSttsHsRepository sttsHsRepo;
    private String fcltType = "WCAM";

    // 데이터 1건 조회, 없으면 exception
    private TbWcamCtlr requireOne(Long wcamCtlrNmbr) throws NoSuchElementException {
        Optional<TbWcamCtlr> info = this.repo.findById(wcamCtlrNmbr);
        if (info.isPresent()) {
            return info.get();
        }
        else {
            throw new NoSuchElementException("데이터가 존재하지 않습니다: " + wcamCtlrNmbr);
        }
    }

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

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

    /**
     * 삭제 되지 않은 제어기 상태 정보 조회
     * @return
     */
    @Transactional(readOnly = true)
    public List<TbWcamCtlrSttsDto> findAllStts() {
        Map<String, TbFcltSttsAlrmStupDto> alarmMap = this.alarmService.loadAlarmSetup(this.fcltType);
        List<TbWcamCtlrSttsDto> result = new ArrayList<>();
        List<TbWcamCtlr> data = this.repo.findAllList();
        data.forEach(obj -> {
            if (!CodeManager.CMNC_STTS_NORMAL.equals(obj.getCmncSttsCd())) {
                TbFcltSttsAlrmStupDto alarm = alarmMap.get(obj.getWcamCtlrId());
                if (alarm != null && "Y".equals(alarm.getUseYn())) {
                    if ("N".equals(alarm.getCmncStts())) {
                        obj.getState().setCmncSttsCd(CodeManager.CMNC_STTS_NORMAL);
                        if ("N".equals(alarm.getDoorStts())) {
                        }
                        if ("N".equals(alarm.getVideoInput())) {
                            //obj.getState().setVideoInput("VDI0");
                        }
                    }
                }
            }
            result.add(obj.toSttsDto());
        });
        return result;
    }

    // 데이터 1건 조회(기존 데이터가 반드시 존재해야 함)
    @Transactional(readOnly = true)
    public TbWcamCtlrDto findById(Long wcamCtlrNmbr) {
        TbWcamCtlr entity = requireOne(wcamCtlrNmbr);
        return entity.toDto();
    }

    // 데이터 변경
    @Transactional
    public TbWcamCtlrDto updateById(Long wcamCtlrNmbr, TbWcamCtlrDto.TbWcamCtlrUpdReq req) {
        TbWcamCtlr entity = requireOne(wcamCtlrNmbr);
        entity.updateInfo(req);
        this.repo.save(entity);
        return entity.toDto();
    }

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

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

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

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

    /**
     * 통신이상 시설물 정보 조회
     * @return
     */
    @Transactional(readOnly = true)
    public List<SttsCommErrDto> findAllListCommError() {
        Map<String, TbFcltSttsAlrmStupDto> alarmMap = this.alarmService.loadAlarmSetup(this.fcltType);
        Map<String, SttsCommErrDto> result = new HashMap<>();
        List<TbWcamCtlr> data = this.repo.findAllList();
        List<SttsHsErrCntInf> errList = this.sttsHsRepo.findAllCommErrorCount(ItsUtils.getFromToday());

        // 통신 상태가 오류 인 제어기 정보만 조회한다.
        data.forEach(obj -> {
            TbWcamCtlrSttsDto dto = obj.toSttsDto();
            if (!CodeManager.CMNC_STTS_NORMAL.equals(dto.getCmncSttsCd())) {
                TbFcltSttsAlrmStupDto alarm = alarmMap.get(obj.getWcamCtlrId());
                if (alarm != null && "Y".equals(alarm.getUseYn()) && "N".equals(alarm.getCmncStts())) {
                    return;
                }
                SttsCommErrDto commErrorDto = new SttsCommErrDto();
                commErrorDto.setCtlrNmbr(String.valueOf(dto.getWcamCtlrNmbr()));
                commErrorDto.setCtlrId(dto.getWcamCtlrId());
                commErrorDto.setCtlrNm(dto.getWcamNm());
                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
     */
    @Transactional(readOnly = true)
    public FcltSttsListDto findAllSttsListTotal(boolean total) {
        Map<String, TbFcltSttsAlrmStupDto> alarmMap = this.alarmService.loadAlarmSetup(this.fcltType);
        FcltSttsListDto result = new FcltSttsListDto();

        AtomicInteger error = new AtomicInteger(0);
        AtomicInteger normal = new AtomicInteger(0);

        List<FcltSttsDto> sttsDtoList = new ArrayList<>();
        List<TbWcamCtlr> ctlrList = this.repo.findAllList();
        ctlrList.forEach(obj -> {
            TbFcltSttsAlrmStupDto alarm = alarmMap.get(obj.getWcamCtlrId());
            if (alarm != null && "Y".equals(alarm.getUseYn()) && "N".equals(alarm.getCmncStts())) {
                obj.getState().setCmncSttsCd(CodeManager.CMNC_STTS_NORMAL);
                if ("N".equals(alarm.getDoorStts())) {
                }
                if ("N".equals(alarm.getVideoInput())) {
                    //obj.getState().setVideoInput("VDI0");
                }
            }

            TbWcamCtlrSttsDto dto = obj.toSttsDto();
            if (total) {
                FcltSttsDto stts = FcltSttsDto.builder()
                        .fcltType(this.fcltType)
                        .fcltNmbr(String.valueOf(obj.getWcamCtlrNmbr()))
                        .fcltId(obj.getWcamCtlrId())
                        .fcltNm(obj.getIstlLctnNm())
                        .fcltKind(obj.getWcamTypeCd())
                        .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();
            }
            else {
                error.getAndIncrement();
            }
        });

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

        summaryDto.init();
        if (total) {
            summaryDto.setFcltObjs(sttsDtoList);
        }
        result.getFcltList().add(summaryDto);

        return result;
    }

    /**
     * 신규 제어기 번호 조회
     * @return
     */
    @Transactional(readOnly = true)
    public NewIdLongDto getNewNmbr() {
        Long newId = this.repo.getNewNmbr();
        return NewIdLongDto.builder().newId(newId).build();
    }
}
