package com.ecep.contract.ds.project.service;

import java.time.LocalDate;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.ecep.contract.IEntityService;
import com.ecep.contract.ProjectFileType;
import com.ecep.contract.ds.project.repository.ProjectFileRepository;
import com.ecep.contract.model.Project;
import com.ecep.contract.model.ProjectFile;

@Lazy
@Service
public class ProjectFileService implements IEntityService<ProjectFile> {
    private static final Logger logger = LoggerFactory.getLogger(ProjectFileService.class);

    @Autowired
    private ProjectFileRepository projectFileRepository;

    public ProjectFile findById(Integer id) {
        return projectFileRepository.findById(id).orElse(null);
    }

    @Override
    public Page<ProjectFile> findAll(Specification<ProjectFile> spec, Pageable pageable) {
        return projectFileRepository.findAll(spec, pageable);
    }

    public List<ProjectFile> findAllByProject(Project project) {
        return projectFileRepository.findByProject(project);
    }

    public void verify(Project project, LocalDate verifyDate, Consumer<String> status) {
        status.accept("待开发");
    }

    public void deleteById(int id) {
        Optional<ProjectFile> optional = projectFileRepository.findById(id);
        if (optional.isEmpty()) {
            return;
        }
        ProjectFile customerFile = optional.get();
        projectFileRepository.delete(customerFile);
    }

    public List<ProjectFile> findAll(Specification<ProjectFile> spec, Sort sort) {
        return projectFileRepository.findAll(spec, sort);
    }

    @Override
    public Specification<ProjectFile> getSpecification(String searchText) {
        if (!StringUtils.hasText(searchText)) {
            return null;
        }
        return (root, query, builder) -> {
            return builder.like(root.get("filePath"), "%" + searchText + "%");
        };
    }

    public ProjectFile save(ProjectFile dbFile) {
        return projectFileRepository.save(dbFile);
    }

    @Override
    public void delete(ProjectFile entity) {
        projectFileRepository.delete(entity);
    }

    public List<ProjectFile> saveAll(List<ProjectFile> files) {
        return projectFileRepository.saveAll(files);
    }

    public List<ProjectFile> findAllByProjectAndType(Project project, ProjectFileType type) {
        return projectFileRepository.findByProjectAndType(project, type);
    }


}
