package org.example.service;

import org.example.config.CacheConstants;
import org.example.entity.PageResult;
import org.example.entity.Terminal;
import org.example.mapper.TerminalMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;

import org.springframework.cache.annotation.Cacheable;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 设备服务
 */
@Service
public class TerminalService {

    @Autowired
    private TerminalMapper terminalMapper;

    /**
     * 获取页面初始化数据（合并查询，支持分页）
     */
    public Map<String, Object> getInitData(int page, int pageSize) {
        Map<String, Object> data = new HashMap<>();
        data.put("deptList", terminalMapper.findAllDeptCode());
        data.put("wardList", terminalMapper.findWardsByDept(null));
        // 分页处理设备列表
        List<Terminal> allTerminals = terminalMapper.findList(null, null, null, null, null);
        data.put("terminalList", PageResult.of(allTerminals, page, pageSize));
        return data;
    }

    /**
     * 查询设备列表
     */
    public List<Terminal> findList(String terminalType, String deptCode, String wardCode,
                                    Integer isOnline, String terminalDesc) {
        return terminalMapper.findList(terminalType, deptCode, wardCode, isOnline, terminalDesc);
    }

    /**
     * 根据ID查询设备
     */
    @Cacheable(value = CacheConstants.CACHE_TERMINAL, key = "'id:' + #id")
    public Terminal findById(Long id) {
        return terminalMapper.findById(id);
    }

    /**
     * 获取所有不重复的设备类型
     */
    @Cacheable(value = CacheConstants.CACHE_OPTIONS, key = "'terminal:types'")
    public List<String> findAllTerminalTypes() {
        return terminalMapper.findAllTerminalTypes();
    }

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

    /**
     * 根据科室获取病区列表
     */
    @Cacheable(value = CacheConstants.CACHE_OPTIONS, key = "'terminal:ward:' + #deptCode")
    public List<String> findWardsByDept(String deptCode) {
        return terminalMapper.findWardsByDept(deptCode);
    }
    
    /**
     * 新增设备
     * @return null表示成功，否则返回错误信息
     */
    @CacheEvict(value = CacheConstants.CACHE_TERMINAL, allEntries = true)
    public String addTerminal(Terminal terminal) {
        // 校验IP地址是否重复
        if (terminal.getIpAddress() != null && !terminal.getIpAddress().isEmpty()) {
            int count = terminalMapper.checkIpExists(terminal.getIpAddress());
            if (count > 0) {
                return "IP地址存在重复";
            }
        }
        
        // 生成设备编码
        String terminalNumber = generateTerminalNumber(terminal);
        terminal.setTerminalNumber(terminalNumber);
        
        // 设置默认在线状态为离线
        if (terminal.getIsOnline() == null) {
            terminal.setIsOnline(0);
        }
        
        terminalMapper.insert(terminal);
        return null;
    }
    
    /**
     * 生成设备编码
     * 规则：设备类型编号 + 病区代码 + 病房代码 + 床位号 / 设备号
     */
    private String generateTerminalNumber(Terminal terminal) {
        StringBuilder sb = new StringBuilder();
        String type = terminal.getTerminalType();
        
        // 设备类型编号
        sb.append(type != null ? type : "");
        
        // 病区代码（从terminalDesc中解析或使用wardCode）
        String wardCode = terminal.getWardCode();
        if (wardCode != null && !wardCode.isEmpty()) {
            sb.append(wardCode);
        }
        
        // 根据设备名称解析其他部分
        String desc = terminal.getTerminalDesc();
        if (desc != null) {
            sb.append(desc);
        }
        
        return sb.toString();
    }
    
    /**
     * 检查IP地址是否存在
     */
    public boolean checkIpExists(String ipAddress) {
        return terminalMapper.checkIpExists(ipAddress) > 0;
    }
}
