package org.example.controller;

import org.example.entity.Bed;
import org.example.entity.PageResult;
import org.example.service.BedService;
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/bed")
public class BedController {

    @Autowired
    private BedService bedService;

    /**
     * 查询床位列表（支持分页）
     */
    @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) String belongRoom,
            @RequestParam(required = false, defaultValue = "1") Integer page,
            @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        Map<String, Object> result = new HashMap<>();
        List<Bed> list = bedService.findList(code, belongDept, belongWard, belongRoom);
        // 分页处理
        PageResult<Bed> 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 = bedService.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 = bedService.findWardsByDept(belongDept);
        result.put("code", 200);
        result.put("data", list);
        return result;
    }

    /**
     * 根据病区获取病房列表（用于联动下拉框）
     */
    @GetMapping("/room-list")
    public Map<String, Object> roomList(@RequestParam(required = false) String belongWard) {
        Map<String, Object> result = new HashMap<>();
        List<String> list = bedService.findRoomsByWard(belongWard);
        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<>();
        Bed bed = bedService.findById(id);
        if (bed != null) {
            result.put("code", 200);
            result.put("data", bed);
        } else {
            result.put("code", 404);
            result.put("message", "床位不存在");
        }
        return result;
    }

    /**
     * 保存床位
     */
    @PostMapping("/save")
    public Map<String, Object> save(@RequestBody Bed bed) {
        Map<String, Object> result = new HashMap<>();
        try {
            bedService.save(bed);
            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 = bedService.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 {
            bedService.deleteById(id);
            result.put("code", 200);
            result.put("message", "删除成功");
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "删除失败：" + e.getMessage());
        }
        return result;
    }
}
