package org.example.service;

import org.example.config.CacheConstants;
import org.example.entity.Department;
import org.example.mapper.DepartmentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 科室服务
 */
@Service
public class DepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    /**
     * 查询科室列表
     */
    @Cacheable(value = CacheConstants.CACHE_DEPARTMENT, key = "'list:' + #name + ':' + #enabled")
    public List<Department> findList(String name, Integer enabled) {
        return departmentMapper.findList(name, enabled);
    }

    /**
     * 根据ID查询科室
     */
    @Cacheable(value = CacheConstants.CACHE_DEPARTMENT, key = "'id:' + #id")
    public Department findById(Long id) {
        return departmentMapper.findById(id);
    }

    /**
     * 保存科室
     */
    @CacheEvict(value = CacheConstants.CACHE_DEPARTMENT, allEntries = true)
    public void save(Department department) {
        // 如果外部代码为空，默认等于科室代码
        if (department.getOutCode() == null || department.getOutCode().isEmpty()) {
            department.setOutCode(department.getCode());
        }
        if (department.getId() == null) {
            departmentMapper.insert(department);
        } else {
            departmentMapper.update(department);
        }
    }

    /**
     * 删除科室
     */
    @CacheEvict(value = CacheConstants.CACHE_DEPARTMENT, allEntries = true)
    public void deleteById(Long id) {
        departmentMapper.deleteById(id);
    }
}
