package org.example.controller;

import org.example.entity.PageResult;
import org.example.entity.Room;
import org.example.service.RoomService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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

/**
 * 病房控制器
 */
@RestController
@RequestMapping("/api/room")
public class RoomController {

    @Autowired
    private RoomService roomService;

    /**
     * 查询病房列表（支持分页）
     */
    @GetMapping("/list")
    public Map<String, Object> list(
            @RequestParam(required = false) String code,
            @RequestParam(required = false) String belongDept,
            @RequestParam(required = false) String belongWard,
            @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<Room> list = roomService.findList(code, belongDept, belongWard, enabled);
        // 分页处理
        PageResult<Room> pageResult = PageResult.of(list, page, pageSize);
        result.put("code", 200);
        result.put("data", pageResult);
        return result;
    }

    /**
     * 获取所属科室列表（用于下拉框）
     */
    @GetMapping("/dept-list")
    public Map<String, Object> deptList() {
        Map<String, Object> result = new HashMap<>();
        List<String> list = roomService.findAllBelongDept();
        result.put("code", 200);
        result.put("data", list);
        return result;
    }

    /**
     * 根据科室获取病区列表（用于联动下拉框）
     */
    @GetMapping("/ward-list")
    public Map<String, Object> wardList(@RequestParam(required = false) String belongDept) {
        Map<String, Object> result = new HashMap<>();
        List<String> list = roomService.findWardsByDept(belongDept);
        result.put("code", 200);
        result.put("data", list);
        return result;
    }

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

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

    /**
     * 批量设置病房代码
     */
    @PostMapping("/batch-set-code")
    public Map<String, Object> batchSetCode(@RequestBody Map<String, Object> params,
                                            @RequestHeader(value = "X-User-Type", required = false) String userType) {
        Map<String, Object> result = new HashMap<>();
        
        // 权限校验：只有管理员才能设置病房代码
        if (!"admin".equals(userType)) {
            result.put("code", 403);
            result.put("message", "无权操作，只有管理员才能设置病房代码");
            return result;
        }
        
        try {
            @SuppressWarnings("unchecked")
            List<?> idList = (List<?>) params.get("ids");
            @SuppressWarnings("unchecked")
            List<String> codes = (List<String>) params.get("codes");
            
            if (idList == null || codes == null || idList.size() != codes.size()) {
                result.put("code", 400);
                result.put("message", "参数错误");
                return result;
            }
            
            // 将id转换为Long类型
            List<Long> ids = new ArrayList<>();
            for (Object id : idList) {
                if (id instanceof Integer) {
                    ids.add(((Integer) id).longValue());
                } else if (id instanceof Long) {
                    ids.add((Long) id);
                } else {
                    ids.add(Long.parseLong(id.toString()));
                }
            }
            
            List<String> errors = roomService.batchSetCode(ids, codes);
            if (errors.isEmpty()) {
                result.put("code", 200);
                result.put("message", "设置成功");
            } else {
                result.put("code", 200);
                result.put("message", "部分设置成功");
                result.put("errors", errors);
            }
        } 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 {
            roomService.deleteById(id);
            result.put("code", 200);
            result.put("message", "删除成功");
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "删除失败：" + e.getMessage());
        }
        return result;
    }
}
