package com.its.op.service.its.link;

import com.its.op.dto.its.link.LinkParaClctSystDto;
import com.its.op.dto.its.link.LinkPrcsParaDto;
import com.its.op.entity.its.link.TbLinkParaClctSyst;
import com.its.op.entity.its.link.TbLinkParaDetl;
import com.its.op.entity.its.link.TbLinkParaStup;
import com.its.op.entity.its.link.TbLink;
import com.its.op.dao.mapper.its.link.LinkPrcsParaDao;
import com.its.op.dao.repository.its.link.TbLinkParaClctSystRepository;
import com.its.op.dao.repository.its.link.TbLinkParaDetlRepository;
import com.its.op.dao.repository.its.link.TbLinkParaStupRepository;
import com.its.op.dao.repository.its.link.TbLinkRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;
import java.util.Optional;

@Slf4j
@RequiredArgsConstructor
@Service
public class LinkPrcsParaService {

    private final TbLinkParaStupRepository stupRepo;
    private final TbLinkParaDetlRepository detlRepo;
    private final TbLinkParaClctSystRepository systRepo;

    private final TbLinkRepository linkRepo;
    private final LinkPrcsParaDao dao;

    public LinkPrcsParaDto.LinkPrcsParaInfo findListById(Long id) {

        LinkPrcsParaDto.LinkPrcsParaInfo result = null;
        TbLinkParaStup stup = null;
        TbLinkParaDetl detl = null;
        Optional<TbLinkParaStup> stupOpt = this.stupRepo.findById(id);
        Optional<TbLinkParaDetl> detlOpt = this.detlRepo.findById(id);
        List<TbLinkParaClctSyst> systOpt = null;//this.systRepo.findListById(id);
        if (stupOpt.isPresent()) {
            stup = stupOpt.get();
        }
        if (detlOpt.isPresent()) {
            detl = detlOpt.get();
        }
        result = new LinkPrcsParaDto.LinkPrcsParaInfo(stup, detl, systOpt);
        return result;
    }

    @Transactional
    public LinkPrcsParaDto.LinkPrcsParaUpdateReq mergeById(List<Long> ids, LinkPrcsParaDto.LinkPrcsParaUpdateReq req) {
        for (Long id : ids) {
            TbLinkParaStup stup = new TbLinkParaStup(id);
            //stup.updateInfo(req.getStup());
            this.stupRepo.save(stup);

            TbLinkParaDetl detl = new TbLinkParaDetl(id);
            //detl.updateInfo(req.getDetl());
            this.detlRepo.save(detl);

            this.systRepo.deleteListById(id);
            for (LinkParaClctSystDto.LinkParaClctSystUpdateReq obj : req.getSystList()) {
                if (obj != null) {
                    TbLinkParaClctSyst syst = null;//new TbLinkParaClctSyst(id);
                    //syst.updateInfo(obj);
                    this.systRepo.save(syst);
                }
            }
        }
        return req;
    }

    @Transactional
    public LinkPrcsParaDto.LinkPrcsParaUpdateReq mergeAll(LinkPrcsParaDto.LinkPrcsParaUpdateReq req) {
        List<TbLink> links = this.linkRepo.findAll();
        this.dao.mergeAll(req, links);
        return req;
    }
}
