package com.haobang.controller;

import com.common.entity.DeviceInterlockingCmd;
import com.common.entity.DeviceInterlockingLog;
import com.common.entity.DeviceInterlocking;
import com.common.service.DeviceInterlockingCmdService;
import com.common.service.DeviceInterlockingLogService;
import com.common.service.DeviceInterlockingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 探针联动控制器
 * 提供REST API接口给syslog-serve模块调用
 * API-KEY认证机制
 */
@RestController
@RequestMapping("/interlocking")
public class InterlockingController {

    @Autowired
    private DeviceInterlockingCmdService cmdService;

    @Autowired
    private DeviceInterlockingLogService logService;

    @Autowired
    private DeviceInterlockingService interlockingService;

    /**
     * 健康检查接口（不需要API-KEY认证）
     */
    @GetMapping("/health")
    public ResponseEntity<Map<String, Object>> health() {
        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("message", "OK");
        result.put("service", "interlocking-api");
        return ResponseEntity.ok(result);
    }

    // ==================== 封禁指令接口 ====================

    /**
     * 1.1 获取待执行的封禁指令记录
     * GET /interlocking/cmd/pending?probeId=1
     */
    @GetMapping("/cmd/pending")
    public ResponseEntity<Map<String, Object>> getPendingCommands(@RequestParam Long probeId) {
        Map<String, Object> result = new HashMap<>();
        try {
            List<DeviceInterlockingCmd> commands = cmdService.selectPendingCommands(probeId);
            result.put("code", 200);
            result.put("message", "success");
            result.put("data", commands);
            result.put("total", commands.size());
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "获取待执行指令失败: " + e.getMessage());
            return ResponseEntity.status(500).body(result);
        }
    }

    /**
     * 1.2 获取指定状态的封禁指令记录
     * GET /interlocking/cmd?probeId=1&cmdStatus=0
     */
    @GetMapping("/cmd")
    public ResponseEntity<Map<String, Object>> getCommands(
            @RequestParam Long probeId,
            @RequestParam(required = false) String cmdStatus) {
        Map<String, Object> result = new HashMap<>();
        try {
            List<DeviceInterlockingCmd> commands;
            if (cmdStatus != null && !cmdStatus.isEmpty()) {
                commands = cmdService.selectByProbeIdAndStatus(probeId, cmdStatus);
            } else {
                commands = cmdService.selectPendingCommands(probeId);
            }
            result.put("code", 200);
            result.put("message", "success");
            result.put("data", commands);
            result.put("total", commands.size());
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "获取指令失败: " + e.getMessage());
            return ResponseEntity.status(500).body(result);
        }
    }

    /**
     * 1.3 获取单个指令详情
     * GET /interlocking/cmd/{id}
     */
    @GetMapping("/cmd/{id}")
    public ResponseEntity<Map<String, Object>> getCommandById(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        try {
            DeviceInterlockingCmd command = cmdService.selectById(id);
            if (command == null) {
                result.put("code", 404);
                result.put("message", "指令不存在");
                return ResponseEntity.status(404).body(result);
            }
            result.put("code", 200);
            result.put("message", "success");
            result.put("data", command);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "获取指令详情失败: " + e.getMessage());
            return ResponseEntity.status(500).body(result);
        }
    }

    /**
     * 1.4 创建新的封禁指令
     * POST /interlocking/cmd
     */
    @PostMapping("/cmd")
    public ResponseEntity<Map<String, Object>> createCommand(@RequestBody DeviceInterlockingCmd cmd) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 设置默认状态为待执行
            if (cmd.getCmdStatus() == null || cmd.getCmdStatus().isEmpty()) {
                cmd.setCmdStatus("0");
            }
            int rows = cmdService.insert(cmd);
            result.put("code", 200);
            result.put("message", "指令创建成功");
            result.put("data", rows);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "创建指令失败: " + e.getMessage());
            return ResponseEntity.status(500).body(result);
        }
    }

    // ==================== 指令状态更新接口 ====================

    /**
     * 2.1 更新封禁指令状态为执行中
     * PUT /interlocking/cmd/{id}/status/executing
     */
    @PutMapping("/cmd/{id}/status/executing")
    public ResponseEntity<Map<String, Object>> updateStatusToExecuting(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        try {
            int rows = cmdService.updateStatusToExecuting(id);
            if (rows > 0) {
                result.put("code", 200);
                result.put("message", "状态已更新为执行中");
                result.put("data", rows);
            } else {
                result.put("code", 404);
                result.put("message", "指令不存在");
            }
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "更新状态失败: " + e.getMessage());
            return ResponseEntity.status(500).body(result);
        }
    }

    /**
     * 2.2 更新封禁指令状态为执行完成
     * PUT /interlocking/cmd/{id}/status/completed
     */
    @PutMapping("/cmd/{id}/status/completed")
    public ResponseEntity<Map<String, Object>> updateStatusToCompleted(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        try {
            int rows = cmdService.updateStatusToCompleted(id);
            if (rows > 0) {
                result.put("code", 200);
                result.put("message", "状态已更新为执行完成");
                result.put("data", rows);
            } else {
                result.put("code", 404);
                result.put("message", "指令不存在");
            }
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "更新状态失败: " + e.getMessage());
            return ResponseEntity.status(500).body(result);
        }
    }

    /**
     * 2.3 更新封禁指令状态为执行失败
     * PUT /interlocking/cmd/{id}/status/failed
     */
    @PutMapping("/cmd/{id}/status/failed")
    public ResponseEntity<Map<String, Object>> updateStatusToFailed(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        try {
            int rows = cmdService.updateStatusToFailed(id);
            if (rows > 0) {
                result.put("code", 200);
                result.put("message", "状态已更新为执行失败");
                result.put("data", rows);
            } else {
                result.put("code", 404);
                result.put("message", "指令不存在");
            }
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "更新状态失败: " + e.getMessage());
            return ResponseEntity.status(500).body(result);
        }
    }

    /**
     * 2.4 批量更新封禁指令状态
     * PUT /interlocking/cmd/status
     */
    @PutMapping("/cmd/status")
    public ResponseEntity<Map<String, Object>> batchUpdateStatus(@RequestBody Map<String, Object> request) {
        Map<String, Object> result = new HashMap<>();
        try {
            @SuppressWarnings("unchecked")
            List<Long> ids = (List<Long>) request.get("ids");
            String cmdStatus = (String) request.get("cmdStatus");

            if (ids == null || ids.isEmpty()) {
                result.put("code", 400);
                result.put("message", "指令ID列表不能为空");
                return ResponseEntity.badRequest().body(result);
            }

            int total = 0;
            for (Long id : ids) {
                total += cmdService.updateStatus(id, cmdStatus);
            }

            result.put("code", 200);
            result.put("message", "批量更新成功");
            result.put("data", total);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "批量更新状态失败: " + e.getMessage());
            return ResponseEntity.status(500).body(result);
        }
    }

    // ==================== 封禁记录接口 ====================

    /**
     * 3.1 批量插入封禁记录
     * POST /interlocking/log/batch
     */
    @PostMapping("/log/batch")
    public ResponseEntity<Map<String, Object>> batchInsertLog(@RequestBody Map<String, Object> request) {
        Map<String, Object> result = new HashMap<>();
        try {
            // Spring无法直接将List<LinkedHashMap>转为List<DeviceInterlockingLog>
            // 需要手动转换
            Object logsObj = request.get("logs");
            List<DeviceInterlockingLog> logs;
            if (logsObj instanceof List) {
                logs = ((List<?>) logsObj).stream()
                        .map(item -> convertToDeviceInterlockingLog(item))
                        .collect(Collectors.toList());
            } else {
                result.put("code", 400);
                result.put("message", "logs字段格式错误，应为数组");
                return ResponseEntity.badRequest().body(result);
            }

            if (logs == null || logs.isEmpty()) {
                result.put("code", 400);
                result.put("message", "封禁记录列表不能为空");
                return ResponseEntity.badRequest().body(result);
            }

            int rows = logService.batchInsert(logs);
            result.put("code", 200);
            result.put("message", "批量插入成功");
            result.put("data", rows);
            result.put("total", logs.size());
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "批量插入记录失败: " + e.getMessage());
            return ResponseEntity.status(500).body(result);
        }
    }

    /**
     * 将Map转换为DeviceInterlockingLog实体
     */
    private DeviceInterlockingLog convertToDeviceInterlockingLog(Object item) {
        DeviceInterlockingLog log = new DeviceInterlockingLog();
        if (item instanceof Map) {
            @SuppressWarnings("unchecked")
            Map<String, Object> map = (Map<String, Object>) item;

            if (map.get("id") != null) log.setId(((Number) map.get("id")).longValue());
            if (map.get("deviceInterlockingCmdId") != null) log.setDeviceInterlockingCmdId(((Number) map.get("deviceInterlockingCmdId")).longValue());
            if (map.get("deviceInterlockingId") != null) log.setDeviceInterlockingId(((Number) map.get("deviceInterlockingId")).longValue());
            if (map.get("banIp") != null) log.setBanIp(String.valueOf(map.get("banIp")));
            if (map.get("deviceName") != null) log.setDeviceName(String.valueOf(map.get("deviceName")));
            if (map.get("banMethod") != null) log.setBanMethod(String.valueOf(map.get("banMethod")));
            if (map.get("banResult") != null) {
                Object banResult = map.get("banResult");
                if (banResult instanceof Number) {
                    log.setBanResult(((Number) banResult).intValue());
                } else {
                    log.setBanResult(Integer.parseInt(String.valueOf(banResult)));
                }
            }
            if (map.get("tenantId") != null) log.setTenantId(String.valueOf(map.get("tenantId")));
            if (map.get("createDept") != null) log.setCreateDept(((Number) map.get("createDept")).longValue());
            if (map.get("createBy") != null) log.setCreateBy(((Number) map.get("createBy")).longValue());
            if (map.get("remark") != null) log.setRemark(String.valueOf(map.get("remark")));
            if (map.get("respBody") != null) log.setRespBody(String.valueOf(map.get("respBody")));
            if (map.get("reqBody") != null) log.setReqBody(String.valueOf(map.get("reqBody")));
        }
        return log;
    }

    /**
     * 3.2 获取封禁记录列表
     * GET /interlocking/log?cmdId=1
     */
    @GetMapping("/log")
    public ResponseEntity<Map<String, Object>> getLogs(@RequestParam(required = false) Long cmdId) {
        Map<String, Object> result = new HashMap<>();
        try {
            List<DeviceInterlockingLog> logs;
            if (cmdId != null) {
                logs = logService.selectByCmdId(cmdId);
            } else {
                logs = logService.selectAll();
            }
            result.put("code", 200);
            result.put("message", "success");
            result.put("data", logs);
            result.put("total", logs.size());
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "获取记录失败: " + e.getMessage());
            return ResponseEntity.status(500).body(result);
        }
    }

    // ==================== 联动设备接口 ====================

    /**
     * 获取联动设备列表
     * GET /interlocking/device
     */
    @GetMapping("/device")
    public ResponseEntity<Map<String, Object>> getDevices(
            @RequestParam(required = false) String deptId,
            @RequestParam(required = false) String vendor) {
        Map<String, Object> result = new HashMap<>();
        try {
            List<DeviceInterlocking> devices;
            if (deptId != null && !deptId.isEmpty()) {
                devices = interlockingService.selectByDeptId(deptId);
            } else if (vendor != null && !vendor.isEmpty()) {
                devices = interlockingService.selectByVendor(vendor);
            } else {
                devices = interlockingService.selectAll();
            }
            result.put("code", 200);
            result.put("message", "success");
            result.put("data", devices);
            result.put("total", devices.size());
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "获取设备失败: " + e.getMessage());
            return ResponseEntity.status(500).body(result);
        }
    }

    /**
     * 获取单个联动设备详情
     * GET /interlocking/device/{id}
     */
    @GetMapping("/device/{id}")
    public ResponseEntity<Map<String, Object>> getDeviceById(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        try {
            DeviceInterlocking device = interlockingService.selectById(id);
            if (device == null) {
                result.put("code", 404);
                result.put("message", "设备不存在");
                return ResponseEntity.status(404).body(result);
            }
            result.put("code", 200);
            result.put("message", "success");
            result.put("data", device);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "获取设备详情失败: " + e.getMessage());
            return ResponseEntity.status(500).body(result);
        }
    }
}
