package org.example.service;

import org.example.config.CacheConstants;
import org.example.entity.WardArea;
import org.example.mapper.WardAreaMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 病区服务
 */
@Service
public class WardAreaService {

    @Autowired
    private WardAreaMapper wardAreaMapper;

    /**
     * 查询病区列表
     */
    @Cacheable(value = CacheConstants.CACHE_WARD_AREA, key = "'list:' + #name + ':' + #glkeshi + ':' + #enabled")
    public List<WardArea> findList(String name, String glkeshi, Integer enabled) {
        return wardAreaMapper.findList(name, glkeshi, enabled);
    }

    /**
     * 根据ID查询病区
     */
    @Cacheable(value = CacheConstants.CACHE_WARD_AREA, key = "'id:' + #id")
    public WardArea findById(Long id) {
        return wardAreaMapper.findById(id);
    }

    /**
     * 保存病区
     */
    @CacheEvict(value = CacheConstants.CACHE_WARD_AREA, allEntries = true)
    public void save(WardArea wardArea) {
        // 如果外部代码为空，默认等于病区代码
        if (wardArea.getOutCode() == null || wardArea.getOutCode().isEmpty()) {
            wardArea.setOutCode(wardArea.getCode());
        }
        if (wardArea.getId() == null) {
            wardAreaMapper.insert(wardArea);
        } else {
            wardAreaMapper.update(wardArea);
        }
    }

    /**
     * 批量设置病区代码
     * @return 返回设置失败的信息
     */
    @CacheEvict(value = CacheConstants.CACHE_WARD_AREA, 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{2}$")) {
                WardArea ward = wardAreaMapper.findById(id);
                errors.add("病区[" + (ward != null ? ward.getName() : id) + "]代码格式错误，应为01~99");
                continue;
            }
            
            // 校验代码是否重复
            WardArea existing = wardAreaMapper.findByCode(code);
            if (existing != null && !existing.getId().equals(id)) {
                WardArea ward = wardAreaMapper.findById(id);
                errors.add("病区[" + (ward != null ? ward.getName() : id) + "]代码[" + code + "]已被使用");
                continue;
            }
            
            // 更新代码
            wardAreaMapper.updateCode(id, code);
        }
        
        return errors;
    }

    /**
     * 格式化病区代码为两位数字
     */
    private String formatCode(String code) {
        if (code == null || code.isEmpty()) {
            return "00";
        }
        // 去除非数字字符
        code = code.replaceAll("\\D", "");
        if (code.isEmpty()) {
            return "00";
        }
        // 取后两位
        int num = Integer.parseInt(code);
        if (num > 99) num = 99;
        if (num < 0) num = 0;
        return String.format("%02d", num);
    }

    /**
     * 清除病区缓存
     */
    @CacheEvict(value = CacheConstants.CACHE_WARD_AREA, allEntries = true)
    public void clearCache() {
        // 清除所有病区相关缓存
    }

    /**
     * 删除病区
     */
    @CacheEvict(value = CacheConstants.CACHE_WARD_AREA, allEntries = true)
    public void deleteById(Long id) {
        wardAreaMapper.deleteById(id);
    }
    
    /**
     * 获取所有不重复的关联科室列表
     */
    @Cacheable(value = CacheConstants.CACHE_OPTIONS, key = "'wardArea:glkeshi'")
    public List<String> findAllGlkeshi() {
        List<String> result = new ArrayList<>();
        List<String> list = wardAreaMapper.findAllGlkeshi();
        // 处理多个科室用逗号分隔的情况
        for (String item : list) {
            if (item != null && !item.isEmpty()) {
                String[] parts = item.split(",");
                for (String part : parts) {
                    String trimmed = part.trim();
                    if (!trimmed.isEmpty() && !result.contains(trimmed)) {
                        result.add(trimmed);
                    }
                }
            }
        }
        return result;
    }
}
