package com.usky.sas.controller.web;

import com.usky.common.core.bean.ApiResult;
import com.usky.common.core.bean.CommonPage;
import com.usky.common.core.utils.poi.ExcelUtil;
import com.usky.sas.enums.SystemTypeCodeEnum;
import com.usky.sas.service.SasDeviceService;
import com.usky.sas.service.vo.*;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 设备配置与心跳接口
 *
 * GET  /prod-api/service-sas/device/heartbeat          设备心跳分页
 * GET  /prod-api/service-sas/device/config             设备配置分页
 * GET  /prod-api/service-sas/device/config/{id}        设备详情
 * POST /prod-api/service-sas/device/config             新增设备
 * PUT  /prod-api/service-sas/device/config/{id}        编辑设备
 * DELETE /prod-api/service-sas/device/config/{id}      删除设备
 * POST /prod-api/service-sas/device/config/batch-delete 批量删除
 * POST /prod-api/service-sas/device/setAlarmGroup      设置报警联动组
 * POST /prod-api/service-sas/device/setAlarmGroupBatch 批量设置报警联动组
 * POST /prod-api/service-sas/device/setVideoGroup      设置视频监控组
 * POST /prod-api/service-sas/device/setVideoGroupBatch 批量设置视频监控组
 * GET  /prod-api/service-sas/device/notBindIPCList     未绑定IPC列表
 * POST /prod-api/service-sas/device/bindingIPC         绑定IPC
 * POST /prod-api/service-sas/device/unbindIPC          解绑IPC
 * POST /prod-api/service-sas/device/syncAgboxDevice    同步AG设备
 * GET  /prod-api/service-sas/device/import/template    获取设备导入模板（Excel）
 * POST /prod-api/service-sas/device/importBatchDeviceByExcel 批量设备导入
 * POST /prod-api/service-sas/device/config/batch-add   批量新增设备配置
 * GET  /prod-api/service-sas/device/unitySearchDevice  扫描获取周边设备
 * POST /prod-api/service-sas/device/unityAddSearchDevice  统一扫描添加设备
 * POST /prod-api/service-sas/device/getProtocolCode    视频协议下拉列表
 * POST /prod-api/service-sas/device/getVideoTypeCode   视频设备类型下拉列表
 * POST /prod-api/service-sas/device/updateDeviceIp     海康更改设备IP地址
 */
@RestController
@RequestMapping("/device")
public class SasDeviceController {

    @Autowired
    private SasDeviceService sasDeviceService;

    @GetMapping("/heartbeat")
    public ApiResult<CommonPage<DeviceHeartbeatResponse>> heartbeat(DeviceHeartbeatRequest request) {
        return ApiResult.success(sasDeviceService.heartbeatPage(request));
    }

    @GetMapping("/config")
    public ApiResult<CommonPage<DeviceConfigVO>> configPage(DeviceConfigPageRequest request) {
        return ApiResult.success(sasDeviceService.configPage(request));
    }

    @GetMapping("/config/{id}")
    public ApiResult<DeviceDetailVO> getDetail(@PathVariable("id") String id) {
        return ApiResult.success(sasDeviceService.getDetail(id));
    }

    @PostMapping("/config")
    public ApiResult<CreateDeviceResponse> createConfig(@RequestBody DeviceConfigSaveRequest request) {
        String id = sasDeviceService.createConfig(request);
        CreateDeviceResponse resp = new CreateDeviceResponse();
        resp.setId(id);
        return ApiResult.success(resp);
    }

    /**
     * 批量新增设备配置（按 channels 生成多条记录）
     */
    @PostMapping("/config/batch-add")
    public ApiResult<Void> addDeviceBatch(@RequestBody DeviceBatchAddRequest request) {
        sasDeviceService.addDeviceBatch(request);
        return ApiResult.success();
    }

    @PutMapping("/config/{id}")
    public ApiResult<Void> updateConfig(@PathVariable("id") String id, @RequestBody DeviceConfigSaveRequest request) {
        sasDeviceService.updateConfig(id, request);
        return ApiResult.success();
    }

    @DeleteMapping("/config/{id}")
    public ApiResult<Void> deleteConfig(@PathVariable("id") String id) {
        sasDeviceService.deleteConfig(id);
        return ApiResult.success();
    }

    @PostMapping("/config/batch-delete")
    public ApiResult<Void> deleteConfigBatch(@RequestBody DeviceDeleteBatchRequest request) {
        sasDeviceService.deleteConfigBatch(request.getIds());
        return ApiResult.success();
    }

    @PostMapping("/setAlarmGroup")
    public ApiResult<Void> setAlarmGroup(@RequestBody DeviceAlarmGroupSetRequest request) {
        sasDeviceService.setAlarmGroup(request.getId(), request.getAlarmGroupType());
        return ApiResult.success();
    }

    @PostMapping("/setAlarmGroupBatch")
    public ApiResult<Void> setAlarmGroupBatch(@RequestBody DeviceAlarmGroupBatchSetRequest request) {
        sasDeviceService.setAlarmGroupBatch(request.getIds(), request.getAlarmGroupType());
        return ApiResult.success();
    }

    @PostMapping("/setVideoGroup")
    public ApiResult<Void> setVideoGroup(@RequestBody DeviceVideoGroupSetRequest request) {
        sasDeviceService.setVideoGroup(request.getId(), request.getVideoGroupType());
        return ApiResult.success();
    }

    @PostMapping("/setVideoGroupBatch")
    public ApiResult<Void> setVideoGroupBatch(@RequestBody DeviceVideoGroupBatchSetRequest request) {
        sasDeviceService.setVideoGroupBatch(request.getIds(), request.getVideoGroupType());
        return ApiResult.success();
    }

    @GetMapping("/notBindIPCList")
    public ApiResult<List<DeviceIPCItemVO>> getNotBindIPCList() {
        return ApiResult.success(sasDeviceService.getNotBindIPCList());
    }

    @PostMapping("/bindingIPC")
    public ApiResult<Void> bindingIPC(@RequestParam("id") String id, @RequestParam("ipcId") String ipcId) {
        sasDeviceService.bindingIPC(id, ipcId);
        return ApiResult.success();
    }

    @PostMapping("/unbindIPC")
    public ApiResult<Void> unbindIPC(@RequestParam("id") String id) {
        sasDeviceService.unbindIPC(id);
        return ApiResult.success();
    }

    /** 从 AG（Agbox）同步设备到 sas_device */
    @PostMapping("/syncAgboxDevice")
    public ApiResult<Void> syncAgboxDevice() {
        sasDeviceService.syncAgboxDevice();
        return ApiResult.success();
    }

    /**
     * 扫描获取周边设备（统一扫描接口）
     */
    @GetMapping("/unitySearchDevice")
    public ApiResult<List<SearchDeviceInfoVO>> unitySearchDevice(@RequestParam("second") Integer second,
                                                                 @RequestParam("code") Integer code) {
        return ApiResult.success(sasDeviceService.unitySearchDevice(second, code));
    }

    /**
     * 统一扫描添加设备：根据前端选择的扫描结果和协议类型，批量生成设备记录
     */
    @PostMapping("/unityAddSearchDevice")
    public ApiResult<List<String>> unityAddSearchDevice(@RequestBody UnityAddSearchDeviceRequest request) {
        return ApiResult.success(sasDeviceService.unityAddSearchDevice(request));
    }

    /**
     * 视频协议下拉列表
     */
    @PostMapping("/getProtocolCode")
    public ApiResult<List<DeviceProtocolOptionVO>> getProtocolCode() {
        return ApiResult.success(sasDeviceService.getProtocolCodes());
    }

    /**
     * 视频设备类型下拉列表
     */
    @PostMapping("/getVideoTypeCode")
    public ApiResult<List<DeviceVideoTypeOptionVO>> getVideoTypeCode() {
        return ApiResult.success(sasDeviceService.getVideoTypeCodes());
    }

    /**
     * 海康更改设备 IP 地址
     */
    @PostMapping("/updateDeviceIp")
    public ApiResult<Void> updateHikDeviceIp(@RequestBody UpdateDeviceIpAddrRequest request) {
        sasDeviceService.updateHikDeviceIp(request);
        return ApiResult.success();
    }

    /**
     * 获取设备导入模板（Excel）
     */
    @GetMapping("/import/template")
    public void getDeviceImportTemplate(HttpServletResponse response) throws IOException {
        List<DeviceImportTemplateVO> list = new ArrayList<>();
        DeviceImportTemplateVO demo = new DeviceImportTemplateVO();
        demo.setDeviceType(SystemTypeCodeEnum.snap.getCode());
        demo.setDeviceId("test-01");
        demo.setIpAddr("192.168.3.141");
        demo.setPort(8000);
        demo.setChannel(1);
        demo.setVideoDeviceType(1);
        demo.setVideoProtocol(2);
        demo.setUsername("admin");
        demo.setPassword("admin");
        demo.setNote("备注");
        demo.setAddress("位置示例");
        demo.setHouseCode("示例-houseCode");
        list.add(demo);

        ExcelUtil<DeviceImportTemplateVO> util = new ExcelUtil<>(DeviceImportTemplateVO.class);
        util.exportExcel(response, list, "设备导入模板", "设备导入模板");
    }

    /**
     * 批量设备导入（Excel）
     */
    @PostMapping("/importBatchDeviceByExcel")
    public ApiResult<String> importBatchDeviceByExcel(@RequestParam("file") MultipartFile file) {
        String msg = sasDeviceService.importDeviceByExcel(file);
        return ApiResult.success(msg);
    }

    @Data
    public static class CreateDeviceResponse {
        private String id;
    }
}

