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.QueryService;
import com.ecep.contract.SpringApp;
import com.ecep.contract.ds.other.repository.DepartmentRepository;
import com.ecep.contract.model.Department;
import com.ecep.contract.model.Employee;
import com.ecep.contract.service.VoableService;
import com.ecep.contract.vo.DepartmentVo;
import com.fasterxml.jackson.databind.JsonNode;

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

    @Cacheable(key = "#p0")
    @Override
    public DepartmentVo findById(Integer id) {
        return repository.findById(id).map(Department::toVo).orElse(null);
    }
    
    public Department getById(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 Page<DepartmentVo> findAll(JsonNode paramsNode, Pageable pageable) {
        Specification<Department> spec = null;
        if (paramsNode.has("searchText")) {
            spec = getSpecification(paramsNode.get("searchText").asText());
        }
        // 可以根据需要添加更多参数处理
        return findAll(spec, pageable).map(Department::toVo);
    }

    @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);
    }

    @Override
    public void updateByVo(Department department, DepartmentVo vo) {
        department.setCode(vo.getCode());
        department.setName(vo.getName());
        department.setActive(vo.isActive());
        
        // 处理leader字段
        if (vo.getLeaderId() == null) {
            department.setLeader(null);
        } else {
            EmployeeService employeeService = SpringApp.getBean(EmployeeService.class);
            if (department.getLeader() == null || !department.getLeader().getId().equals(vo.getLeaderId())) {
                Employee leader = employeeService.getById(vo.getLeaderId());
                department.setLeader(leader);
            }
        }
    }
}
