package org.example.service;

import org.example.config.CacheConstants;
import org.example.entity.Room;
import org.example.mapper.RoomMapper;
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.ArrayList;
import java.util.List;

/**
 * 病房服务
 */
@Service
public class RoomService {

    @Autowired
    private RoomMapper roomMapper;

    /**
     * 查询病房列表
     */
    @Cacheable(value = CacheConstants.CACHE_ROOM, key = "'list:' + #code + ':' + #belongDept + ':' + #belongWard + ':' + #enabled")
    public List<Room> findList(String code, String belongDept, String belongWard, Integer enabled) {
        return roomMapper.findList(code, belongDept, belongWard, enabled);
    }

    /**
     * 根据ID查询病房
     */
    @Cacheable(value = CacheConstants.CACHE_ROOM, key = "'id:' + #id")
    public Room findById(Long id) {
        return roomMapper.findById(id);
    }

    /**
     * 保存病房
     */
    @CacheEvict(value = {CacheConstants.CACHE_ROOM, CacheConstants.CACHE_OPTIONS}, allEntries = true)
    public void save(Room room) {
        if (room.getOutCode() == null || room.getOutCode().isEmpty()) {
            room.setOutCode(room.getCode());
        }
        if (room.getId() == null) {
            roomMapper.insert(room);
        } else {
            roomMapper.update(room);
        }
    }

    /**
     * 批量设置病房代码
     * @return 返回设置失败的信息
     */
    @CacheEvict(value = CacheConstants.CACHE_ROOM, allEntries = true)
    public List<String> batchSetCode(List<Long> ids, List<String> codes) {
        List<String> errors = new ArrayList<>();
        
        for (int i = 0; i < ids.size(); i++) {
            Long id = ids.get(i);
            String code = codes.get(i);
            
            // 格式化代码为四位数字
            code = formatCode(code);
            
            // 校验代码格式
            if (!code.matches("^\\d{4}$")) {
                Room room = roomMapper.findById(id);
                errors.add("病房[" + (room != null ? room.getName() : id) + "]代码格式错误，应为0001~9999");
                continue;
            }
            
            // 获取病房信息以获取所属病区
            Room room = roomMapper.findById(id);
            if (room == null) {
                errors.add("病房ID[" + id + "]不存在");
                continue;
            }
            
            // 校验同病区下代码是否重复
            Room existing = roomMapper.findByCodeAndWard(code, room.getBelongWard());
            if (existing != null && !existing.getId().equals(id)) {
                errors.add("病房[" + room.getName() + "]代码[" + code + "]在病区[" + room.getBelongWard() + "]下已被使用");
                continue;
            }
            
            // 更新代码
            roomMapper.updateCode(id, code);
        }
        
        return errors;
    }

    /**
     * 格式化病房代码为四位数字
     */
    private String formatCode(String code) {
        if (code == null || code.isEmpty()) {
            return "0000";
        }
        // 去除非数字字符
        code = code.replaceAll("\\D", "");
        if (code.isEmpty()) {
            return "0000";
        }
        int num = Integer.parseInt(code);
        if (num > 9999) num = 9999;
        if (num < 0) num = 0;
        return String.format("%04d", num);
    }

    /**
     * 删除病房
     */
    @CacheEvict(value = {CacheConstants.CACHE_ROOM, CacheConstants.CACHE_OPTIONS}, allEntries = true)
    public void deleteById(Long id) {
        roomMapper.deleteById(id);
    }

    /**
     * 获取所有不重复的所属科室
     */
    @Cacheable(value = CacheConstants.CACHE_OPTIONS, key = "'room:dept'")
    public List<String> findAllBelongDept() {
        return roomMapper.findAllBelongDept();
    }

    /**
     * 根据科室获取病区列表
     */
    @Cacheable(value = CacheConstants.CACHE_OPTIONS, key = "'room:ward:' + #belongDept")
    public List<String> findWardsByDept(String belongDept) {
        return roomMapper.findWardsByDept(belongDept);
    }
}
