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

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
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.ds.other.repository.DepartmentRepository;
import com.ecep.contract.model.Department;

/**
 * 部门
 */
@Lazy
@Service
@CacheConfig(cacheNames = "department")
public class DepartmentService implements IEntityService<Department> {
    @Lazy
    @Autowired
    private DepartmentRepository repository;

    @Cacheable(key = "#p0")
    @Override
    public Department findById(Integer id) {
        return repository.findById(id).orElse(null);
    }

    @Cacheable(key = "'code-'+#p0")
    public Department findByCode(String code) {
        return repository.findByCode(code).orElse(null);
    }

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

    @Override
    public Specification<Department> getSpecification(String searchText) {
        if (!StringUtils.hasText(searchText)) {
            return null;
        }
        return (root, query, builder) -> {
            // 使用或条件组合查询，以实现对员工代码或名称的模糊搜索
            return builder.or(
                    builder.like(root.get("code"), "%" + searchText + "%"),
                    builder.like(root.get("name"), "%" + searchText + "%")
            );
        };
    }

    public List<Department> search(String searchText) {
        Specification<Department> spec = getSpecification(searchText);
        return repository.findAll(spec, Pageable.ofSize(10)).getContent();
    }

    @Caching(
            evict = {
                    @CacheEvict(key = "#p0.id"),
                    @CacheEvict(key = "'code-'+#p0.code")
            }
    )
    @Override
    public void delete(Department entity) {
        repository.delete(entity);
    }

    @Caching(
            evict = {
                    @CacheEvict(key = "#p0.id"),
                    @CacheEvict(key = "'code-'+#p0.code")
            }
    )
    @Override
    public Department save(Department entity) {
        return repository.save(entity);
    }
}
