package org.example.controller;

import org.example.entity.Department;
import org.example.entity.PageResult;
import org.example.service.DepartmentService;
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;

/**
 * 科室控制器
 */
@RestController
@RequestMapping("/api/department")
public class DepartmentController {

    @Autowired
    private DepartmentService departmentService;

    /**
     * 查询科室列表（支持分页）
     */
    @GetMapping("/list")
    public Map<String, Object> list(
            @RequestParam(required = false) String name,
            @RequestParam(required = false) Integer enabled,
            @RequestParam(required = false, defaultValue = "1") Integer page,
            @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        Map<String, Object> result = new HashMap<>();
        List<Department> list = departmentService.findList(name, enabled);
        // 分页处理
        PageResult<Department> pageResult = PageResult.of(list, page, pageSize);
        result.put("code", 200);
        result.put("data", pageResult);
        return result;
    }

    /**
     * 获取科室详情
     */
    @GetMapping("/detail/{id}")
    public Map<String, Object> detail(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        Department department = departmentService.findById(id);
        if (department != null) {
            result.put("code", 200);
            result.put("data", department);
        } else {
            result.put("code", 404);
            result.put("message", "科室不存在");
        }
        return result;
    }

    /**
     * 保存科室
     */
    @PostMapping("/save")
    public Map<String, Object> save(@RequestBody Department department) {
        Map<String, Object> result = new HashMap<>();
        try {
            departmentService.save(department);
            result.put("code", 200);
            result.put("message", "保存成功");
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "保存失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 删除科室
     */
    @DeleteMapping("/delete/{id}")
    public Map<String, Object> delete(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        try {
            departmentService.deleteById(id);
            result.put("code", 200);
            result.put("message", "删除成功");
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "删除失败：" + e.getMessage());
        }
        return result;
    }
}
