package org.example.controller;

import org.example.entity.HospitalRoom;
import org.example.service.HospitalRoomService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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

@RestController
@RequestMapping("/api/rooms")
public class HospitalRoomController {
    
    @Autowired
    private HospitalRoomService hospitalRoomService;
    
    /**
     * 获取所有病房列表（支持按条件查询）
     * @param code 病房代码
     * @param department 所属科室
     * @param ward 所属病区
     * @param enabled 是否启用
     * @return 病房列表
     */
    @GetMapping
    public List<HospitalRoom> getAllRooms(
            @RequestParam(required = false) String code,
            @RequestParam(required = false) String department,
            @RequestParam(required = false) String ward,
            @RequestParam(required = false) Boolean enabled) {
        
        List<HospitalRoom> allRooms = hospitalRoomService.findAll();
        
        // 如果提供了病房代码参数，则进行精确匹配
        if (code != null && !code.isEmpty()) {
            allRooms = allRooms.stream()
                    .filter(room -> room.getCode() != null && room.getCode().equals(code))
                    .collect(Collectors.toList());
        }
        
        // 如果提供了所属科室参数，则进行匹配
        if (department != null && !department.isEmpty()) {
            allRooms = allRooms.stream()
                    .filter(room -> room.getBelongDept() != null && room.getBelongDept().contains(department))
                    .collect(Collectors.toList());
        }
        
        // 如果提供了所属病区参数，则进行匹配
        if (ward != null && !ward.isEmpty()) {
            allRooms = allRooms.stream()
                    .filter(room -> room.getBelongWard() != null && room.getBelongWard().contains(ward))
                    .collect(Collectors.toList());
        }
        
        // 如果提供了启用状态参数，则进行筛选
        if (enabled != null) {
            allRooms = allRooms.stream()
                    .filter(room -> enabled.equals(room.getEnabled()))
                    .collect(Collectors.toList());
        }
        
        return allRooms;
    }
    
    /**
     * 根据病房代码获取病房信息
     * @param code 病房代码
     * @return 病房信息
     */
    @GetMapping("/{code}")
    public Map<String, Object> getRoomByCode(@PathVariable String code) {
        Map<String, Object> result = new HashMap<>();
        try {
            HospitalRoom room = hospitalRoomService.findByCode(code);
            if (room != null) {
                result.put("success", true);
                result.put("data", room);
            } else {
                result.put("success", false);
                result.put("message", "未找到该病房信息");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取病房信息失败: " + e.getMessage());
        }
        return result;
    }
    
    /**
     * 添加新病房
     * @param room 病房信息
     * @return 操作结果
     */
    @PostMapping
    public Map<String, Object> addRoom(@RequestBody HospitalRoom room) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 检查同一病区下是否已存在相同的病房代码
            if (hospitalRoomService.existsByCodeAndWard(room.getCode(), room.getBelongWard())) {
                result.put("success", false);
                result.put("message", "该病区下已存在相同代码的病房");
                return result;
            }
            
            hospitalRoomService.addRoom(room);
            result.put("success", true);
            result.put("message", "病房添加成功");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "病房添加失败: " + e.getMessage());
        }
        return result;
    }
    
    /**
     * 更新病房信息
     * @param code 病房代码
     * @param room 病房信息
     * @return 操作结果
     */
    @PutMapping("/{code}")
    public Map<String, Object> updateRoom(@PathVariable String code, @RequestBody HospitalRoom room) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 检查同一病区下是否已存在相同的病房代码（排除自身）
            if (hospitalRoomService.existsByCodeAndWardExcluding(room.getCode(), room.getBelongWard(), code)) {
                result.put("success", false);
                result.put("message", "该病区下已存在相同代码的病房");
                return result;
            }
            
            hospitalRoomService.updateRoom(code, room);
            result.put("success", true);
            result.put("message", "病房更新成功");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "病房更新失败: " + e.getMessage());
        }
        return result;
    }
    
    /**
     * 删除病房
     * @param code 病房代码
     * @return 操作结果
     */
    @DeleteMapping("/{code}")
    public Map<String, Object> deleteRoom(@PathVariable String code) {
        Map<String, Object> result = new HashMap<>();
        try {
            hospitalRoomService.deleteRoom(code);
            result.put("success", true);
            result.put("message", "病房删除成功");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "病房删除失败: " + e.getMessage());
        }
        return result;
    }
}