package org.example.controller;

import org.example.entity.HospitalWard;
import org.example.service.HospitalWardService;
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/wards")
public class HospitalWardController {
    
    @Autowired
    private HospitalWardService hospitalWardService;
    
    /**
     * 获取所有病区列表（支持按名称模糊查询和启用状态筛选）
     * @param name 病区名称（模糊匹配）
     * @param glkeshi 关联科室（模糊匹配）
     * @param enabled 是否启用
     * @return 病区列表
     */
    @GetMapping
    public List<HospitalWard> getAllWards(@RequestParam(required = false) String name, 
                                         @RequestParam(required = false) String glkeshi,
                                         @RequestParam(required = false) Boolean enabled) {
        List<HospitalWard> allWards = hospitalWardService.findAll();
        
        // 如果提供了名称参数，则进行模糊匹配
        if (name != null && !name.isEmpty()) {
            allWards = allWards.stream()
                    .filter(ward -> ward.getName() != null && ward.getName().contains(name))
                    .collect(Collectors.toList());
        }
        
        // 如果提供了关联科室参数，则进行模糊匹配
        if (glkeshi != null && !glkeshi.isEmpty()) {
            allWards = allWards.stream()
                    .filter(ward -> ward.getGlkeshi() != null && ward.getGlkeshi().contains(glkeshi))
                    .collect(Collectors.toList());
        }
        
        // 如果提供了启用状态参数，则进行筛选
        if (enabled != null) {
            allWards = allWards.stream()
                    .filter(ward -> enabled.equals(ward.getEnabled()))
                    .collect(Collectors.toList());
        }
        
        return allWards;
    }
    
    /**
     * 根据病区代码获取病区信息
     * @param code 病区代码
     * @return 病区信息
     */
    @GetMapping("/{code}")
    public Map<String, Object> getWardByCode(@PathVariable String code) {
        Map<String, Object> result = new HashMap<>();
        try {
            HospitalWard ward = hospitalWardService.findByCode(code);
            if (ward != null) {
                result.put("success", true);
                result.put("data", ward);
            } else {
                result.put("success", false);
                result.put("message", "未找到该病区信息");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取病区信息失败: " + e.getMessage());
        }
        return result;
    }
    
    /**
     * 添加新病区
     * @param ward 病区信息
     * @return 操作结果
     */
    @PostMapping
    public Map<String, Object> addWard(@RequestBody HospitalWard ward) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 检查代码是否已存在
            if (hospitalWardService.findByCode(ward.getCode()) != null) {
                result.put("success", false);
                result.put("message", "病区代码已存在");
                return result;
            }
            
            hospitalWardService.addWard(ward);
            result.put("success", true);
            result.put("message", "病区添加成功");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "病区添加失败: " + e.getMessage());
        }
        return result;
    }
    
    /**
     * 更新病区信息
     * @param code 病区代码
     * @param ward 病区信息
     * @return 操作结果
     */
    @PutMapping("/{code}")
    public Map<String, Object> updateWard(@PathVariable String code, @RequestBody HospitalWard ward) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 检查新代码是否已存在（仅当代码确实改变时）
            if (!code.equals(ward.getCode())) {
                boolean exists = hospitalWardService.existsByCodeExcluding(ward.getCode(), code);
                if (exists) {
                    result.put("success", false);
                    result.put("message", "病区代码已存在");
                    return result;
                }
            }
            
            // 更新病区信息
            hospitalWardService.updateWard(code, ward);
            result.put("success", true);
            result.put("message", "病区更新成功");
        } catch (Exception e) {
            e.printStackTrace(); // 打印异常堆栈以便调试
            result.put("success", false);
            result.put("message", "病区更新失败: " + e.getMessage());
        }
        return result;
    }
    
    /**
     * 删除病区
     * @param code 病区代码
     * @return 操作结果
     */
    @DeleteMapping("/{code}")
    public Map<String, Object> deleteWard(@PathVariable String code) {
        Map<String, Object> result = new HashMap<>();
        try {
            hospitalWardService.deleteWard(code);
            result.put("success", true);
            result.put("message", "病区删除成功");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "病区删除失败: " + e.getMessage());
        }
        return result;
    }
}