package org.example.controller;

import org.example.entity.PageResult;
import org.example.entity.Terminal;
import org.example.entity.Department;
import org.example.entity.WardArea;
import org.example.service.TerminalService;
import org.example.service.DepartmentService;
import org.example.service.WardAreaService;
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/terminal")
public class TerminalController {

    @Autowired
    private TerminalService terminalService;
    
    @Autowired
    private DepartmentService departmentService;
    
    @Autowired
    private WardAreaService wardAreaService;

    /**
     * 获取页面初始化数据（合并接口，支持分页）
     */
    @GetMapping("/init-data")
    public Map<String, Object> initData(
            @RequestParam(required = false, defaultValue = "1") Integer page,
            @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("data", terminalService.getInitData(page, pageSize));
        return result;
    }

    /**
     * 查询设备列表（支持分页）
     */
    @GetMapping("/list")
    public Map<String, Object> list(
            @RequestParam(required = false) String terminalType,
            @RequestParam(required = false) String deptCode,
            @RequestParam(required = false) String wardCode,
            @RequestParam(required = false) Integer isOnline,
            @RequestParam(required = false) String terminalDesc,
            @RequestParam(required = false, defaultValue = "1") Integer page,
            @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        Map<String, Object> result = new HashMap<>();
        List<Terminal> list = terminalService.findList(terminalType, deptCode, wardCode, isOnline, terminalDesc);
        // 分页处理
        PageResult<Terminal> pageResult = PageResult.of(list, page, pageSize);
        result.put("code", 200);
        result.put("data", pageResult);
        return result;
    }

    /**
     * 获取设备类型列表（用于下拉框）
     */
    @GetMapping("/type-list")
    public Map<String, Object> typeList() {
        Map<String, Object> result = new HashMap<>();
        List<String> list = terminalService.findAllTerminalTypes();
        result.put("code", 200);
        result.put("data", list);
        return result;
    }

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

    /**
     * 根据科室获取病区列表（用于联动下拉框）
     */
    @GetMapping("/ward-list")
    public Map<String, Object> wardList(@RequestParam(required = false) String deptCode) {
        Map<String, Object> result = new HashMap<>();
        List<String> list = terminalService.findWardsByDept(deptCode);
        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<>();
        Terminal terminal = terminalService.findById(id);
        if (terminal != null) {
            result.put("code", 200);
            result.put("data", terminal);
        } else {
            result.put("code", 404);
            result.put("message", "设备不存在");
        }
        return result;
    }
    
    /**
     * 新增设备
     */
    @PostMapping("/add")
    public Map<String, Object> add(@RequestBody Terminal terminal,
                                   @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;
        }
        
        String error = terminalService.addTerminal(terminal);
        if (error == null) {
            result.put("code", 200);
            result.put("message", "新增成功");
        } else {
            result.put("code", 400);
            result.put("message", error);
        }
        return result;
    }
    
    /**
     * 获取科室列表（真实数据）
     */
    @GetMapping("/department-list")
    public Map<String, Object> departmentList() {
        Map<String, Object> result = new HashMap<>();
        List<Department> list = departmentService.findList(null, 1);
        result.put("code", 200);
        result.put("data", list);
        return result;
    }
    
    /**
     * 根据科室获取病区列表（真实数据）
     */
    @GetMapping("/ward-list-by-dept")
    public Map<String, Object> wardListByDept(@RequestParam(required = false) String deptName) {
        Map<String, Object> result = new HashMap<>();
        List<WardArea> list = wardAreaService.findList(null, deptName, 1);
        result.put("code", 200);
        result.put("data", list);
        return result;
    }
    
    /**
     * 检查IP地址是否存在
     */
    @GetMapping("/check-ip")
    public Map<String, Object> checkIp(@RequestParam String ipAddress) {
        Map<String, Object> result = new HashMap<>();
        boolean exists = terminalService.checkIpExists(ipAddress);
        result.put("code", 200);
        result.put("exists", exists);
        return result;
    }
}
