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

import java.util.List;
import java.util.Optional;

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.EmployeeRoleRepository;
import com.ecep.contract.model.EmployeeRole;
import com.ecep.contract.model.Function;

import jakarta.transaction.Transactional;

/**
 * 员工角色服务
 */
@Service
@CacheConfig(cacheNames = "employee-role")
public class EmployeeRoleService implements IEntityService<EmployeeRole> {
    @Lazy
    @Autowired
    private EmployeeRoleRepository roleRepository;

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

    @Override
    public Specification<EmployeeRole> 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 + "%"));
        };
    }

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

    @Caching(evict = {
            @CacheEvict(key = "#p0.id"),
            @CacheEvict(key = "'code-'+#p0.code")
    })
    public EmployeeRole save(EmployeeRole role) {
        return roleRepository.save(role);
    }

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

    public Page<EmployeeRole> findAll(Specification<EmployeeRole> spec, Pageable pageable) {
        return roleRepository.findAll(spec, pageable);
    }

    @Transactional
    public List<Function> getFunctionsByRoleId(int roleId) {
        Optional<EmployeeRole> optional = roleRepository.findById(roleId);
        if (optional.isPresent()) {
            EmployeeRole role = optional.get();
            return role.getFunctions().stream().toList();
        }
        return null;
    }
}
