package com.pm.web.controller.subsystem;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.pm.common.annotation.Log;
import com.pm.common.core.controller.BaseController;
import com.pm.common.core.domain.AjaxResult;
import com.pm.common.enums.BusinessType;
import com.pm.common.config.PageData;
import com.pm.common.utils.poi.ExcelUtilPageData;
import com.pm.subsystem.service.IVideoDeviceService;
import com.pm.common.core.page.TableDataInfo;

/**
 * 视频监控系统Controller
 *
 * @author lxf
 * @date 2025-06-03
 */
@RestController
@RequestMapping("/subsystem/video")
public class VideoDeviceController extends BaseController
{
    @Autowired
    private IVideoDeviceService videoDeviceService;

    /**
     * 查询摄像机设备列表
     */
    @PreAuthorize("@ss.hasPermi('subsystem:video:list')")
    @GetMapping("/cameras/list")
    public TableDataInfo listCameras()
    {
        PageData pd = this.getPageData();
        startPage();
        List<PageData> list = videoDeviceService.selectCameraList(pd);
        return getDataTable(list);
    }

    /**
     * 导出摄像机设备列表
     */
    @PreAuthorize("@ss.hasPermi('subsystem:video:export')")
    @Log(title = "摄像机设备", businessType = BusinessType.EXPORT)
    @PostMapping("/cameras/export")
    public void exportCameras(HttpServletResponse response)
    {
        try {
            PageData pd = this.getPageData();
            List<PageData> list = videoDeviceService.selectCameraList(pd);
            String filename = "摄像机设备数据";
            String[] titles = {
                    "摄像机ID,id",
                    "摄像机编号,cameraCode",
                    "摄像机名称,cameraName",
                    "监控区域,monitorArea",
                    "楼栋,building",
                    "楼层,floor",
                    "详细位置,locationDetail",
                    "IP地址,ipAddress",
                    "端口,port",
                    "品牌,brand",
                    "型号,model",
                    "分辨率,resolution",
                    "帧率,frameRate",
                    "设备状态,deviceStatus",
                    "云台支持,ptzSupport",
                    "红外支持,infraredSupport",
                    "录像状态,recordingStatus"
            };
            ExcelUtilPageData.exportXLSX(response, null, null, filename, titles, list);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取摄像机设备详细信息
     */
    @PreAuthorize("@ss.hasPermi('subsystem:video:query')")
    @GetMapping(value = "/cameras/{id}")
    public AjaxResult getCameraInfo(@PathVariable("id") Long id)
    {
        return success(videoDeviceService.selectCameraById(id));
    }

    /**
     * 新增摄像机设备
     */
    @PreAuthorize("@ss.hasPermi('subsystem:video:add')")
    @Log(title = "摄像机设备", businessType = BusinessType.INSERT)
    @PostMapping("/cameras")
    public AjaxResult addCamera(@RequestBody PageData pd)
    {
        return toAjax(videoDeviceService.insertCamera(pd));
    }

    /**
     * 修改摄像机设备
     */
    @PreAuthorize("@ss.hasPermi('subsystem:video:edit')")
    @Log(title = "摄像机设备", businessType = BusinessType.UPDATE)
    @PutMapping("/cameras")
    public AjaxResult editCamera(@RequestBody PageData pd)
    {
        return toAjax(videoDeviceService.updateCamera(pd));
    }

    /**
     * 删除摄像机设备
     */
    @PreAuthorize("@ss.hasPermi('subsystem:video:remove')")
    @Log(title = "摄像机设备", businessType = BusinessType.DELETE)
    @DeleteMapping("/cameras/{ids}")
    public AjaxResult removeCameras(@PathVariable Long[] ids)
    {
        return toAjax(videoDeviceService.deleteCameraByIds(ids));
    }

    /**
     * 获取摄像机视频流
     */
    @PreAuthorize("@ss.hasPermi('subsystem:video:stream')")
    @GetMapping("/stream/{cameraCode}")
    public AjaxResult getCameraStream(@PathVariable("cameraCode") String cameraCode)
    {
        PageData streamData = videoDeviceService.getCameraStream(cameraCode);
        return success(streamData);
    }

    /**
     * 云台控制
     */
    @PreAuthorize("@ss.hasPermi('subsystem:video:ptz')")
    @Log(title = "云台控制", businessType = BusinessType.OTHER)
    @PostMapping("/ptz/control")
    public AjaxResult ptzControl(@RequestBody PageData pd)
    {
        pd.put("controlUser", getUsername());
        int result = videoDeviceService.ptzControl(pd);
        if (result > 0) {
            return success("云台控制指令发送成功");
        } else {
            return error("云台控制指令发送失败");
        }
    }

    /**
     * 录像控制
     */
    @PreAuthorize("@ss.hasPermi('subsystem:video:recording')")
    @Log(title = "录像控制", businessType = BusinessType.OTHER)
    @PostMapping("/recording/control")
    public AjaxResult recordingControl(@RequestBody PageData pd)
    {
        int result = videoDeviceService.recordingControl(pd);
        if (result > 0) {
            return success("录像控制指令执行成功");
        } else {
            return error("录像控制指令执行失败");
        }
    }

    /**
     * 抓拍
     */
    @PreAuthorize("@ss.hasPermi('subsystem:video:snapshot')")
    @Log(title = "摄像机抓拍", businessType = BusinessType.OTHER)
    @PostMapping("/snapshot/{cameraCode}")
    public AjaxResult takeSnapshot(@PathVariable("cameraCode") String cameraCode)
    {
        int result = videoDeviceService.takeSnapshot(cameraCode);
        if (result > 0) {
            return success("抓拍成功");
        } else {
            return error("抓拍失败");
        }
    }

    /**
     * 查询联动规则列表
     */
    @PreAuthorize("@ss.hasPermi('subsystem:video:linkage')")
    @GetMapping("/linkage/list")
    public TableDataInfo listLinkageRules()
    {
        PageData pd = this.getPageData();
        startPage();
        List<PageData> list = videoDeviceService.selectLinkageRuleList(pd);
        return getDataTable(list);
    }

    /**
     * 获取联动规则详细信息
     */
    @PreAuthorize("@ss.hasPermi('subsystem:video:linkage')")
    @GetMapping(value = "/linkage/{id}")
    public AjaxResult getLinkageRuleInfo(@PathVariable("id") Long id)
    {
        return success(videoDeviceService.selectLinkageRuleById(id));
    }

    /**
     * 新增联动规则
     */
    @PreAuthorize("@ss.hasPermi('subsystem:video:linkage:add')")
    @Log(title = "联动规则", businessType = BusinessType.INSERT)
    @PostMapping("/linkage")
    public AjaxResult addLinkageRule(@RequestBody PageData pd)
    {
        return toAjax(videoDeviceService.insertLinkageRule(pd));
    }

    /**
     * 修改联动规则
     */
    @PreAuthorize("@ss.hasPermi('subsystem:video:linkage:edit')")
    @Log(title = "联动规则", businessType = BusinessType.UPDATE)
    @PutMapping("/linkage")
    public AjaxResult editLinkageRule(@RequestBody PageData pd)
    {
        return toAjax(videoDeviceService.updateLinkageRule(pd));
    }

    /**
     * 删除联动规则
     */
    @PreAuthorize("@ss.hasPermi('subsystem:video:linkage:remove')")
    @Log(title = "联动规则", businessType = BusinessType.DELETE)
    @DeleteMapping("/linkage/{id}")
    public AjaxResult removeLinkageRule(@PathVariable("id") Long id)
    {
        return toAjax(videoDeviceService.deleteLinkageRuleById(id));
    }

    /**
     * 启用/禁用联动规则
     */
    @PreAuthorize("@ss.hasPermi('subsystem:video:linkage:toggle')")
    @Log(title = "联动规则状态切换", businessType = BusinessType.UPDATE)
    @PutMapping("/linkage/toggle/{id}")
    public AjaxResult toggleLinkageRule(@PathVariable("id") Long id, @RequestBody PageData pd)
    {
        return toAjax(videoDeviceService.toggleLinkageRule(id, pd));
    }

    /**
     * 查询联动执行记录列表
     */
    @PreAuthorize("@ss.hasPermi('subsystem:video:linkage:records')")
    @GetMapping("/linkage/records/list")
    public TableDataInfo listLinkageRecords()
    {
        PageData pd = this.getPageData();
        startPage();
        List<PageData> list = videoDeviceService.selectLinkageRecordList(pd);
        return getDataTable(list);
    }

    /**
     * 查询录像文件列表
     */
    @PreAuthorize("@ss.hasPermi('subsystem:video:recordings')")
    @GetMapping("/recordings/list")
    public TableDataInfo listRecordingFiles()
    {
        PageData pd = this.getPageData();
        startPage();
        List<PageData> list = videoDeviceService.selectRecordingFileList(pd);
        return getDataTable(list);
    }

    /**
     * 查询预置位列表
     */
    @PreAuthorize("@ss.hasPermi('subsystem:video:presets')")
    @GetMapping("/presets/{cameraCode}")
    public AjaxResult listPresets(@PathVariable("cameraCode") String cameraCode)
    {
        List<PageData> list = videoDeviceService.selectPresetList(cameraCode);
        return success(list);
    }

    /**
     * 设置预置位
     */
    @PreAuthorize("@ss.hasPermi('subsystem:video:presets:set')")
    @Log(title = "设置预置位", businessType = BusinessType.INSERT)
    @PostMapping("/presets")
    public AjaxResult setPreset(@RequestBody PageData pd)
    {
        return toAjax(videoDeviceService.setPreset(pd));
    }

    /**
     * 删除预置位
     */
    @PreAuthorize("@ss.hasPermi('subsystem:video:presets:remove')")
    @Log(title = "删除预置位", businessType = BusinessType.DELETE)
    @DeleteMapping("/presets/{id}")
    public AjaxResult deletePreset(@PathVariable("id") Long id)
    {
        return toAjax(videoDeviceService.deletePresetById(id));
    }

    /**
     * 摄像机健康检测
     */
    @PreAuthorize("@ss.hasPermi('subsystem:video:health')")
    @PostMapping("/health/check/{cameraCode}")
    public AjaxResult checkCameraHealth(@PathVariable("cameraCode") String cameraCode)
    {
        PageData healthData = videoDeviceService.checkCameraHealth(cameraCode);
        return success(healthData);
    }

    /**
     * 获取摄像机统计数据
     */
    @PreAuthorize("@ss.hasPermi('subsystem:video:statistics')")
    @GetMapping("/statistics")
    public AjaxResult getCameraStatistics()
    {
        PageData statistics = videoDeviceService.getCameraStatistics();
        return success(statistics);
    }

    /**
     * 数据同步
     */
    @PreAuthorize("@ss.hasPermi('subsystem:video:sync')")
    @Log(title = "视频数据同步", businessType = BusinessType.OTHER)
    @PostMapping("/sync")
    public AjaxResult syncVideoData(@RequestBody PageData pd)
    {
        int result = videoDeviceService.syncVideoData(pd);
        if (result > 0) {
            return success("数据同步成功");
        } else {
            return error("数据同步失败");
        }
    }
}