package com.sooka.sponest.monitor.camera.controller;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.constant.UserConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.sooka.sponest.monitor.camera.domain.*;
import com.sooka.sponest.monitor.camera.service.ICentermonitorTCameraService;
import com.sooka.sponest.monitor.device.mapper.CentermonitorTMonitoringEquipmentPositionMapper;
import com.sooka.sponest.monitor.util.HikSubscription;
import io.swagger.annotations.*;
import jdk.nashorn.internal.ir.annotations.Ignore;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

/**
 * 摄像头Controller
 *
 * @author ruoyi
 * @date 2022-06-08
 */
@Api(tags = "摄像头管理控制器")
@RestController
@RequestMapping("/camera")
public class CentermonitorTCameraController extends BaseController {

    @Resource
    private RedisService redisService;

    private final ICentermonitorTCameraService centermonitorTCameraService;

    public CentermonitorTCameraController(ICentermonitorTCameraService centermonitorTCameraService) {
        this.centermonitorTCameraService = centermonitorTCameraService;
    }

    @Resource
    private CentermonitorTMonitoringEquipmentPositionMapper centermonitorTMonitoringEquipmentPositionMapper;

    /**
     * 根据ID查询摄像头详细信息
     */
    @Log(title = "摄像头", businessType = BusinessType.OTHER)
    @ApiOperation(value = "根据ID查询摄像头详细信息", notes = "根据ID查询摄像头详细信息")
    @RequestMapping(value = "/selectByCameraId/{id}", method = GET)
    @ApiImplicitParam(name = "id", value = "主键id", paramType = "query")
    public AjaxResult selectByCameraId(@PathVariable("id") String id) {
        return AjaxResult.success(centermonitorTCameraService.selectCentermonitorTCameraById(id));
    }

    /**
     * 通过摄像头编码获取摄像头详细信息
     */
    @Log(title = "摄像头", businessType = BusinessType.OTHER)
    @ApiOperation(value = "通过摄像头编码获取摄像头详细信息", notes = "通过摄像头编码获取摄像头详细信息")
    @RequestMapping(value = "/s/{cameraCode}", method = GET)
    @ApiImplicitParam(name = "cameraCode", value = "摄像头编码", dataType = "String", paramType = "query")
    public R<CentermonitorTCamera> getInfoByCameraCode(@PathVariable("cameraCode") String cameraCode) {
        return R.ok(centermonitorTCameraService.selectCentermonitorTCameraByCameraCode(cameraCode));
    }


    /**
     * 通过通道编码获取摄像头详细信息
     */
    @Log(title = "摄像头", businessType = BusinessType.OTHER)
    @ApiOperation(value = "通过通道编码获取摄像头详细信息", notes = "通过通道编码获取摄像头详细信息")
    @RequestMapping(value = "/ss/{channelCode}", method = GET)
    @ApiImplicitParam(name = "channelCode", value = "通道编码", dataType = "String", paramType = "query")
    public R<CentermonitorTCamera> getInfoByChannelCode(@PathVariable("channelCode") String channelCode) {
        return R.ok(centermonitorTCameraService.selectCentermonitorTCameraByChannelCode(channelCode));
    }

    /**
     * 通过摄像头账号获取摄像头详细信息
     */
    @Log(title = "摄像头", businessType = BusinessType.OTHER)
    @ApiOperation(value = "通过摄像头账号获取摄像头详细信息", notes = "通过摄像头账号获取摄像头详细信息")
    @RequestMapping(value = "/sss/{cameraAccount}", method = GET)
    @ApiImplicitParam(name = "cameraAccount", value = "摄像头编码", dataType = "String", paramType = "query")
    public R<CentermonitorTCamera> getInfoByCameraAccount(@PathVariable("cameraAccount") String cameraAccount) {
        return R.ok(centermonitorTCameraService.selectCentermonitorTCameraByCameraAccount(cameraAccount));
    }

    /**
     * 查询状态日志
     */
    @ApiOperation(value = "查询状态日志列表", notes = "查询状态日志列表")
    @RequiresPermissions("camera:camera:listLog")
    @GetMapping("/listStateLog")
    @Log(title = "摄像头", businessType = BusinessType.OTHER)
    public TableDataInfo listStateLog(CentermonitorTCameraStateLog centermonitorTCameraStateLog) {
        startPage();
        List<CentermonitorTCameraStateLog> list = centermonitorTCameraService.selectCentermonitorTCameraListStateLog(centermonitorTCameraStateLog);
        return getDataTable(list);
    }

    /**
     * 查询摄像头列表
     */
    @ApiOperation(value = "查询摄像头列表", notes = "查询摄像头列表")
    @RequiresPermissions("camera:camera:list")
    @GetMapping("/list")
    @Log(title = "摄像头", businessType = BusinessType.OTHER)
    public TableDataInfo list(CentermonitorTCamera centermonitorTCamera) {
        startPage();
        List<CentermonitorTCamera> list = centermonitorTCameraService.selectCentermonitorTCameraList(centermonitorTCamera);
        return getDataTable(list);
    }

    /**
     * 导出摄像头列表
     */
    @ApiOperation(value = "导出摄像头列表", notes = "导出摄像头列表")
    @RequiresPermissions("camera:camera:export")
    @Log(title = "摄像头", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CentermonitorTCamera centermonitorTCamera) {
        List<CentermonitorTCamera> list = centermonitorTCameraService.selectCentermonitorTCameraList(centermonitorTCamera);
        ExcelUtil<CentermonitorTCamera> util = new ExcelUtil<>(CentermonitorTCamera.class);
        util.exportExcel(response, list, "摄像头数据");
    }

    /**
     * 获取摄像头详细信息
     */
    @ApiOperation(value = "获取摄像头详细信息", notes = "获取摄像头详细信息")
    @RequiresPermissions("camera:camera:query")
    @GetMapping(value = "/{id}")
    @Log(title = "摄像头", businessType = BusinessType.OTHER)
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return AjaxResult.success(centermonitorTCameraService.selectCentermonitorTCameraById(id));
    }

    /**
     * 获取摄像头详细信息(多个)
     */
    @ApiOperation(value = "获取摄像头详细信息(多个)", notes = "获取摄像头详细信息(多个)")
    @GetMapping(value = "/selectIdTCameraByIds/{ids}")
    @Log(title = "摄像头", businessType = BusinessType.OTHER)
    public AjaxResult selectIdTCameraById(@PathVariable("ids") String[] ids) {
        return AjaxResult.success(centermonitorTCameraService.selectIdTCameraById(ids));
    }

    /**
     * 新增摄像头
     */
    @ApiOperation(value = "新增摄像头", notes = "新增摄像头")
    @RequiresPermissions("camera:camera:add")
    @Log(title = "摄像头", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CentermonitorTCamera centermonitorTCamera) {
        if (UserConstants.NOT_UNIQUE.equals(centermonitorTCameraService.checkIpUnique(centermonitorTCamera))) {
            return AjaxResult.error("新增摄像头失败，摄像头ip已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(centermonitorTCameraService.checkCodeUnique(centermonitorTCamera))) {
            return AjaxResult.error("新增摄像头失败，摄像头编码已存在");
        }
        return toAjax(centermonitorTCameraService.insertCentermonitorTCamera(centermonitorTCamera));
    }

    /**
     * 修改摄像头
     */
    @ApiOperation(value = "修改摄像头", notes = "修改摄像头")
    @RequiresPermissions("camera:camera:edit")
    @Log(title = "摄像头", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CentermonitorTCamera centermonitorTCamera) {
        if (UserConstants.NOT_UNIQUE.equals(centermonitorTCameraService.checkIpUnique(centermonitorTCamera))) {
            return AjaxResult.error("修改摄像头失败，摄像头ip已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(centermonitorTCameraService.checkCodeUnique(centermonitorTCamera))) {
            return AjaxResult.error("修改摄像头失败，摄像头编码已存在");
        }
        return toAjax(centermonitorTCameraService.updateCentermonitorTCamera(centermonitorTCamera));
    }

    /**
     * 删除摄像头
     */
    @ApiOperation(value = "删除摄像头", notes = "删除摄像头")
    @RequiresPermissions("camera:camera:remove")
    @Log(title = "摄像头", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(centermonitorTCameraService.deleteCentermonitorTCameraByIds(ids));
    }

    /**
     * 查询附近摄像头列表
     */
    @Log(title = "摄像头", businessType = BusinessType.OTHER)
    @ApiOperation(value = "查询附近摄像头列表", notes = "查询附近摄像头列表")
    @GetMapping({"/selectFjsxt/{longitude}/{latitude}", "/selectFjsxt/{longitude}/{latitude}/{type}"})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "longitude", value = "经度", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "latitude", value = "纬度", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "type", value = "类型", dataType = "String", paramType = "query")
    })
    public AjaxResult selectFjsxt(@PathVariable String longitude, @PathVariable String latitude, @PathVariable(value = "type", required = false) String type) {
        return AjaxResult.success(centermonitorTCameraService.selectFjsxt(longitude, latitude, type));
    }

    /**
     * 根据设备用途查询摄像头列表
     */
    @Log(title = "根据设备用途查询摄像头列表", businessType = BusinessType.OTHER)
    @ApiOperation(value = "根据设备用途查询摄像头列表", notes = "根据设备用途查询摄像头列表")
    @GetMapping({"/ListCameraType/{cameraUse}"})
    public AjaxResult ListCameraType(@PathVariable String cameraUse) {
        return AjaxResult.success(centermonitorTCameraService.selectCentermonitorTCameraListByCameraUse(cameraUse));
    }

    /**
     * 查询摄像头列表(App)
     */
    @ApiOperation(value = "查询摄像头列表(App)", notes = "查询摄像头列表(App)")
    @PostMapping("/cameraList")
    @Log(title = "摄像头", businessType = BusinessType.OTHER)
    public AjaxResult cameraList(@RequestBody CentermonitorTCamera centermonitorTCamera) {
        List<CentermonitorTCamera> list = centermonitorTCameraService.selectCentermonitorTCameraListForApp(centermonitorTCamera);
        return AjaxResult.success(list);
    }

    /**
     * 根据部门ID获取摄像头列表
     */
    @Log(title = "摄像头", businessType = BusinessType.OTHER)
    @ApiOperation(value = "根据部门ID获取摄像头列表", notes = "根据部门ID获取摄像头列表")
    @RequestMapping(value = "selectCameraByDeptId", method = POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "deptId", value = "部门ID", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "day", value = "日期", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "eventCode", value = "事件编码", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "type", value = "类型", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "cameraUse", value = "摄像头用途", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "cameraName", value = "摄像头名称", dataType = "String", paramType = "query")
    })
    public AjaxResult selectCameraByDeptId(@RequestBody VisuForestCloudMapVO vo) {
        return centermonitorTCameraService.selectCameraByDepId(vo);
    }

    /**
     * 获取覆盖范围摄像头数量
     */
    @ApiOperation(value = "获取覆盖范围摄像头数量", notes = "获取覆盖范围摄像头数量")
    @PostMapping("selectCameraByCoverage")
    public AjaxResult selectCameraByCoverage(@RequestBody VisuForestCloudMapVO vo) {
        return centermonitorTCameraService.selectCameraByCoverage(vo);
    }

    /**
     * 获取各部门摄像头数量
     */
    @Log(title = "摄像头", businessType = BusinessType.OTHER)
    @ApiOperation(value = "获取各部门摄像头数量", notes = "获取各部门摄像头数量")
    @PostMapping("selectCameraGroupByDept")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "deptId", value = "部门ID", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "deviceId", value = "设备ID", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "deviceType", value = "设备类型", dataType = "String", paramType = "query")
    })
    public AjaxResult selectCameraGroupByDept(@RequestBody VisuForestMonitorCenterVO vo) {
        return centermonitorTCameraService.selectCameraGroupByDept(vo);
    }

    /**
     * 获取各部门摄像头,传感器,云广播数量
     */
    @Log(title = "摄像头", businessType = BusinessType.OTHER)
    @ApiOperation(value = "获取各部门摄像头,传感器,云广播数量", notes = "获取各部门摄像头,传感器,云广播数量")
    @PostMapping("selectDeviceType")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "deptId", value = "部门ID", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "day", value = "日期", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "eventCode", value = "事件编码", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "type", value = "类型", dataType = "String", paramType = "query")
    })
    public AjaxResult selectDeviceType(@RequestBody VisuForestCloudMapVO visuForestMonitorCenterVO) {
        return centermonitorTCameraService.selectDeviceType(visuForestMonitorCenterVO);
    }

    /**
     * 根据类别获取摄像头数量
     */
    @Log(title = "摄像头", businessType = BusinessType.OTHER)
    @ApiOperation(value = "根据类别获取摄像头数量", notes = "根据类别获取摄像头数量")
    @PostMapping("selectDeviceTypeR")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "deptId", value = "部门ID", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "day", value = "日期", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "eventCode", value = "事件编码", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "type", value = "类型", dataType = "String", paramType = "query")
    })
    public R selectDeviceTypeR(@RequestBody VisuForestCloudMapVO visuForestMonitorCenterVO) {
        return R.ok(centermonitorTCameraService.selectDeviceTypeR(visuForestMonitorCenterVO));
    }

    /**
     * 可视化前端根据不同入参查询摄像头、传感器、大喇叭、无人机等设备的数量、列表、部门分组数量
     *
     * @param visuForestCloudMapVO
     * @return
     */
    @Log(title = "摄像头", businessType = BusinessType.OTHER)
    @ApiOperation(value = "可视化前端根据不同入参查询摄像头、传感器、大喇叭、无人机等设备的数量、列表、部门分组数量", notes = "可视化前端根据不同入参查询摄像头、传感器、大喇叭、无人机等设备的数量、列表、部门分组数量")
    @RequestMapping(value = "selectDeviceTypeGong", method = POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "deptId", value = "部门ID", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "day", value = "日期", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "eventCode", value = "事件编码", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "type", value = "类型", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "eventStatusValue", value = "事件状态value", dataType = "String", paramType = "query")
    })
    public AjaxResult selectDeviceTypeGong(@RequestBody VisuForestCloudMapVO visuForestCloudMapVO) {
        return centermonitorTCameraService.selectDeviceTypeGong(visuForestCloudMapVO);
    }

    /**
     * 通过摄像头通道编码获取摄像头实时画面
     *
     * @param channelCode
     * @return
     */
    @Log(title = "摄像头", businessType = BusinessType.OTHER)
    @ApiOperation(value = "通过摄像头通道编码获取摄像头实时画面", notes = "通过摄像头通道编码获取摄像头实时画面")
    @GetMapping(value = "getCameraPreviewURL/{channelCode}")
    @ApiImplicitParam(name = "channelCode", value = "通道编码", dataType = "String", paramType = "query")
    public AjaxResult getCameraPreviewURL(@PathVariable String channelCode) {
        String result = HikSubscription.previewURLs(channelCode, "ws");
        JSONObject jsonObject = JSONObject.parseObject(result);
        String code = jsonObject.get("code").toString();
        if (code.equals("0")) {
            return AjaxResult.success(result);
        }
        return AjaxResult.error("未查询到数据，请检查参数是否正确");
    }

    /**
     * 电视墙 过期
     */
    @Ignore
    @Deprecated
    @RequestMapping(value = "selectCameraByDepIdGong", method = POST)
    @ApiParam
    @Log(title = "摄像头", businessType = BusinessType.OTHER)
    public AjaxResult selectCameraByDepIdGong(@RequestBody VisuForestCloudMapVO visuForestCloudMapVO) {
        return centermonitorTCameraService.selectCameraByDepIdGong(visuForestCloudMapVO);
    }

    /**
     * 根据部门查询摄像头列表
     */
    @Log(title = "摄像头", businessType = BusinessType.OTHER)
    @ApiOperation(value = "根据部门查询摄像头列表", notes = "根据部门查询摄像头列表")
    @Deprecated
    @RequestMapping(value = "selectCameraGroupByDeptGong", method = POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "deptId", value = "部门ID", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "day", value = "日期", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "eventCode", value = "事件编码", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "type", value = "类型", dataType = "String", paramType = "query")
    })
    public AjaxResult selectCameraGroupByDeptGong(@RequestBody VisuForestCloudMapVO visuForestCloudMapVO) {
        return centermonitorTCameraService.selectCameraGroupByDeptGong(visuForestCloudMapVO);
    }

    /**
     * 获取正常工作摄像头数量
     */
    @GetMapping("cameraCount")
    @Log(title = "摄像头", businessType = BusinessType.OTHER)
    public R<CameraVO> cameraCount() {

        return R.ok(centermonitorTCameraService.cameraCount());
    }


    /**
     * 根据搜索的部门查询摄像头列表（摄像头半径包含当前部门点位的摄像头）
     *
     * @return
     * @Version 1.0
     * @author wang_xy
     * @since 2023/3/27 15:07
     */
    @ApiOperation(value = "根据搜索的部门查询摄像头列表（摄像头半径包含当前部门点位的摄像头）", notes = "根据搜索的部门查询摄像头列表（摄像头半径包含当前部门点位的摄像头）")
    @PostMapping("/findCameraByDept")
    @Log(title = "摄像头", businessType = BusinessType.OTHER)
    public AjaxResult findCameraByDept(@RequestBody VisuForestCloudMapVO visuForestCloudMapVO) {
        return AjaxResult.success(centermonitorTCameraService.findCameraByDept(visuForestCloudMapVO));
    }

    /**
     * 根据经纬度查询在范围内的摄像头列表
     */
    @Log(title = "摄像头", businessType = BusinessType.OTHER)
    @ApiOperation(value = "根据经纬度查询在范围内的摄像头列表", notes = "根据经纬度查询在范围内的摄像头列表")
    @GetMapping({"/findCameraByEventCoordinate/{longitude}/{latitude}", "/findCameraByEventCoordinate/{longitude}/{latitude}/{type}"})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "longitude", value = "经度", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "latitude", value = "纬度", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "type", value = "类型", dataType = "String", paramType = "query")
    })
    public AjaxResult findCameraByEventCoordinate(@PathVariable String longitude, @PathVariable String latitude, @PathVariable(value = "type", required = false) String type) {
        return AjaxResult.success(centermonitorTCameraService.findCameraByEventCoordinate(longitude, latitude, type));
    }

    /**
     * 根据经纬度和半径查询在范围内的摄像头列表
     */
    @Log(title = "摄像头", businessType = BusinessType.OTHER)
    @ApiOperation(value = "根据经纬度和半径查询在范围内的摄像头列表", notes = "根据经纬度和半径查询在范围内的摄像头列表")
    @GetMapping("/findNearbyCameras/{longitude}/{latitude}/{radius}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "longitude", value = "经度", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "latitude", value = "纬度", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "radius", value = "范围", dataType = "String", paramType = "query")
    })
    public AjaxResult findNearbyCameras(@PathVariable String longitude, @PathVariable String latitude, @PathVariable(value = "radius", required = false) String radius) {
        return AjaxResult.success(centermonitorTCameraService.findNearbyCameras(longitude, latitude, radius));
    }

    /**
     * 摄像头订阅接收消息方法
     *
     * @param request
     * @return
     */
    @Log(title = "摄像头", businessType = BusinessType.OTHER)
    @RequestMapping(value = "/receiveCameraState", method = POST)
    public AjaxResult receiveEvents(HttpServletRequest request) {
        String blody = "";
        try {
            blody = ReadAsChars(request);
            logger.info("接收报文----" + blody);
            String category = JSONObject.parseObject(blody).getString("category");
            JSONObject info = JSONObject.parseObject(blody).getJSONObject("info");
            if (info != null) {
                String offlineReason = category.equals("alarm") ? info.getString("alarmType") : info.getString("offlineReason");
                String deviceCode = info.getString("deviceCode");
                logger.info("offlineReason----{}, deviceCode----{}", offlineReason, deviceCode);
                CentermonitorTCamera camera = centermonitorTCameraService.getCameraByChannelNum(deviceCode);
                if (camera != null) {
                    //摄像头状态修改对象
                    camera.setOfflineReason(offlineReason);
                    camera.setWorkingStatus(offlineReason.equals("0") || offlineReason.equals("225") ? "0" : "1");//0上线 1下线 225低电压
                    //日志插入对象
                    CentermonitorTCameraStateLog stateLog = new CentermonitorTCameraStateLog();
                    stateLog.setCameraId(camera.getId());
                    stateLog.setCreateTime(DateUtils.getTime());
                    stateLog.setState(offlineReason);
                    stateLog.setReportText(blody);
                    //更改状态并加入日志
                    centermonitorTCameraService.updateCameraWorkingStatus(camera, stateLog);
                } else {
                    logger.info("未查询到摄像头，deviceCode----{}", deviceCode);
                }
            }
            return AjaxResult.success("接收报文成功", blody);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.error("接收报文失败", blody);
    }

    public static String ReadAsChars(HttpServletRequest request) {
        BufferedReader br = null;
        StringBuilder sb = new StringBuilder("");
        try {
            br = request.getReader();
            String str;
            while ((str = br.readLine()) != null) {
                sb.append(str);
            }
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sb.toString();
    }

    /**
     * 监控中心首页-右上角四个数
     **/
    @Log(title = "摄像头", businessType = BusinessType.OTHER)
    @GetMapping("/selectAlldeviceCountAndDetailCount")
    @ApiOperation(value = "监控中心首页-右上角四个数", notes = "查询全部区县设备在线状态")
    public AjaxResult DistrictEquipment(CentermonitorTCamera centermonitorTCamera) {
        List<CentermonitorTCamera> list = centermonitorTCameraService.selectAlldeviceCountAndDetailCount(centermonitorTCamera);
        return AjaxResult.success(list);
    }

    /**
     * 监控中心首页-当前设备状态
     **/
    @Log(title = "摄像头", businessType = BusinessType.OTHER)
    @GetMapping("/selectDeviceAndCameraOnlineAndOfflineList")
    @ApiOperation(value = "监控中心首页-当前设备状态", notes = "监控中心首页-当前设备状态")
    public TableDataInfo QueryDistrictCountyTable(CentermonitorTCamera centermonitorTCamera) {

        List<CentermonitorTCamera> list = centermonitorTCameraService.selectDeviceAndCameraOnlineAndOfflineList(centermonitorTCamera);
        return getDataTable(list);
    }

    /**
     * 区县离线设备扇形图
     **/
    @Log(title = "摄像头", businessType = BusinessType.OTHER)
    @GetMapping("/selectQxOfflineDeviceCount")
    @ApiOperation(value = "区县离线设备", notes = "区县离线设备")
    public AjaxResult QueryDevice(CentermonitorTCamera centermonitorTCamera) {
        List<CentermonitorTCamera> list = centermonitorTCameraService.selectQxOfflineDeviceCount(centermonitorTCamera);
        return AjaxResult.success(list);
    }

    /**
     * 离线设备类型扇形图
     **/
    @Log(title = "摄像头", businessType = BusinessType.OTHER)
    @GetMapping("/selectQxOfflineDeviceTypeCount")
    @ApiOperation(value = "设备类型", notes = "设备类型")
    public AjaxResult deviceType(CentermonitorTCamera centermonitorTCamera) {
        List<CentermonitorTCamera> list = centermonitorTCameraService.selectQxOfflineDeviceTypeCount(centermonitorTCamera);
        return AjaxResult.success(list);
    }

    /**
     * 根据部门ID和工作状态查询摄像头列表
     *
     * @param centermonitorTCamera 摄像头
     * @return 摄像头集合
     */
    @Log(title = "摄像头", businessType = BusinessType.OTHER)
    @GetMapping("/selectCameraListByDeptIdAndWorkingStatus")
    @ApiOperation(value = "根据部门ID和工作状态查询摄像头列表", notes = "根据部门ID和工作状态查询摄像头列表")
    public TableDataInfo selectCameraListByDeptIdAndWorkingStatus(CentermonitorTCamera centermonitorTCamera) {
        startPage();
        List<CentermonitorTCamera> list = centermonitorTCameraService.selectCameraListByDeptIdAndWorkingStatus(centermonitorTCamera);
        return getDataTable(list);
    }

    /**
     * 监控中心首页-离线设备日折线图
     **/
    @GetMapping("/selectDayLineChartCount/{yearAndMonth}")
    @ApiOperation(value = "监控中心首页-日折线图", notes = "监控中心首页-日折线图")
    public Map<String, String[]> selectDayLineChartCount(@PathVariable("yearAndMonth") String yearAndMonth) {
        List<IndexLineChartsVo> list;
        Boolean b = redisService.hasKey("selectDayLineChartCount" + yearAndMonth);
        if (!b) {
            list = centermonitorTCameraService.dayLineChart(yearAndMonth);
            redisService.setCacheObject("selectDayLineChartCount" + yearAndMonth, list);
        } else {
            list = redisService.getCacheObject("selectDayLineChartCount" + yearAndMonth);
        }
        Map<String, String[]> map = new HashMap<>();
        String[] name = new String[list.size()];
        String[] data = new String[list.size()];
        for (int i = 0; i < list.size(); i++) {
            name[i] = list.get(i).getTime();
            data[i] = list.get(i).getCount();
        }
        map.put("names", name);
        map.put("datas", data);
        return map;
    }

    /**
     * 监控中心首页-离线设备月折线图
     **/
    @GetMapping("/selectMonthlyLineChartCount/{year}")
    @ApiOperation(value = "监控中心首页-月折线图", notes = "监控中心首页-月折线图")
    public Map<String, String[]> selectMonthlyLineChartCount(@PathVariable("year") String year) {
        List<IndexLineChartsVo> list;
        Boolean b = redisService.hasKey("monthlyLineChartCount" + year);
        if (!b) {
            list = centermonitorTCameraService.monthlyLineChart(year);
            redisService.setCacheObject("monthlyLineChartCount" + year, list);
        } else {
            list = redisService.getCacheObject("monthlyLineChartCount" + year);
        }
        Map<String, String[]> map = new HashMap<>();
        String[] name = new String[list.size()];
        String[] data = new String[list.size()];
        for (int i = 0; i < list.size(); i++) {
            name[i] = list.get(i).getTime();
            data[i] = list.get(i).getCount();
        }
        map.put("names", name);
        map.put("datas", data);
        return map;
    }

    /**
     * 监控中心首页-离线设备季度折线图
     **/
    @GetMapping("/selectquarterlineChartCount/{year}")
    @ApiOperation(value = "监控中心首页-季度折线图", notes = "监控中心首页-季折线图")
    public Map<String, String[]> quarterlineChart(@PathVariable("year") String year) {
        List<IndexLineChartsVo> list;
        Boolean b = redisService.hasKey("quarterlineChart" + year);
        if (!b) {
            list = centermonitorTCameraService.quarterLineChart(year);
            redisService.setCacheObject("quarterlineChart" + year, list);
        } else {
            list = redisService.getCacheObject("quarterlineChart" + year);
        }
        Map<String, String[]> map = new HashMap<>();
        String[] name = new String[list.size()];
        String[] data = new String[list.size()];
        for (int i = 0; i < list.size(); i++) {
            name[i] = list.get(i).getTime();
            data[i] = list.get(i).getCount();
        }
        map.put("names", name);
        map.put("datas", data);
        return map;
    }

    /**
     * 监控中心首页-离线设备年折线图
     **/
    @GetMapping("/selectYearlineChartCount/{year}")
    @ApiOperation(value = "监控中心首页-年度折线图", notes = "监控中心首页-年折线图")
    public Map<String, String[]> yearlineChart(@PathVariable("year") String year) {
        List<IndexLineChartsVo> list;
        Boolean b = redisService.hasKey("yearlineChart" + year);
        if (!b) {
            list = centermonitorTCameraService.yearLineChart(year);
            redisService.setCacheObject("yearlineChart" + year, list);
        } else {
            list = redisService.getCacheObject("yearlineChart" + year);
        }
        Map<String, String[]> map = new HashMap<>();
        String[] name = new String[list.size()];
        String[] data = new String[list.size()];
        for (int i = 0; i < list.size(); i++) {
            name[i] = list.get(i).getTime();
            data[i] = list.get(i).getCount();
        }
        map.put("names", name);
        map.put("datas", data);
        return map;
    }

    /**
     * 摄像头调用、被调用部门保存
     **/
    @Log(title = "摄像头调用、被调用部门保存", businessType = BusinessType.INSERT)
    @ApiOperation(value = "摄像头调用、被调用部门保存", notes = "摄像头调用、被调用部门保存")
    @PostMapping(value = "/saveCameraCallLog")
    public R saveCameraCallLog(@RequestBody JSONObject deviceCode) {
        return centermonitorTCameraService.saveCameraCallLog(deviceCode);
    }

    /**
     * 视频融合中台统一入口
     * @param deptId 部门id
     **/
    @Log(title = "视频融合中台统一入口", businessType = BusinessType.OTHER)
    @ApiOperation(value = "视频融合中台统一入口", notes = "视频融合中台统一入口")
    @GetMapping(value = "/getVideoFusionUnifyInlet")
    public R getVideoFusionUnifyInlet(@RequestParam(value = "deptId", required = false) Long deptId) {
        return centermonitorTCameraService.getVideoFusionUnifyInlet(deptId);

    }
        /**
         * 海康插件融合预览回放
         */
        @Value("${sooka.haikang_video_server.loginIp}")
        private String loginIp;
        @Value("${sooka.haikang_video_server.appkey}")
        private String appkey;
        @Value("${sooka.haikang_video_server.secret}")
        private String secret;
        @Value("${sooka.haikang_video_server.loginPort}")
        private String loginPort;

        @GetMapping("/HKTVWall")
        @ApiOperation(value = "海康插件融合预览回放", notes = "海康插件融合预览回放")
        public AjaxResult getHKTVWall (Integer playMode){
            Map<String, Object> data = new HashMap<>();
            data.put("loginIp", loginIp);
            data.put("appkey", appkey);
            data.put("secret", secret);
            data.put("loginPort", Integer.valueOf(loginPort));
            data.put("playMode", playMode);
            data.put("layout", "1x1");
            return AjaxResult.success(data);
        }


        /**
         * 查询全部摄像头用于和检测设备一对多绑定
         */
        @Log(title = "摄像头", businessType = BusinessType.OTHER)
        @ApiOperation(value = "查询全部摄像头用于和检测设备一对多绑定", notes = "查询全部摄像头用于和检测设备一对多绑定")
        @RequestMapping(value = "/selectAllCameraList", method = GET)
        public R<?> selectAllCameraList () {
            return R.ok(centermonitorTCameraService.selectAllCameraList());
        }


        /**
         * 根据部门ID获取本部门及以下执法记录仪列表
         */
        @Log(title = "执法记录仪", businessType = BusinessType.OTHER)
        @ApiOperation(value = "根据部门ID获取本部门及以下执法记录仪列表", notes = "根据部门ID获取本部门及以下执法记录仪列表")
        @RequestMapping(value = "selectRecorderByDeptId", method = POST)
        @ApiImplicitParams({
                @ApiImplicitParam(name = "deptId", value = "部门ID", dataType = "Integer", paramType = "query"),
                @ApiImplicitParam(name = "type", value = "类型", dataType = "String", paramType = "query"),
                @ApiImplicitParam(name = "cameraUse", value = "摄像头用途", dataType = "String", paramType = "query"),
                @ApiImplicitParam(name = "workingStatus", value = "运行状态", dataType = "String", paramType = "query"),
                @ApiImplicitParam(name = "deviceCode", value = "设备编码", dataType = "String", paramType = "query")
        })
        public AjaxResult selectRecorderByDeptId (@RequestBody VisuForestCloudMapVO vo){
            return centermonitorTCameraService.selectRecorderByDeptId(vo);
        }

        /**
         * 根据部门ID获取执法记录仪在离线状态数量
         */
        @Log(title = "执法记录仪", businessType = BusinessType.OTHER)
        @ApiOperation(value = "根据部门ID获取执法记录仪在离线状态数量", notes = "根据部门ID获取执法记录仪在离线状态数量")
        @RequestMapping(value = "selectRecorderCountByDeptId", method = POST)
        @ApiImplicitParams({
                @ApiImplicitParam(name = "deptId", value = "部门ID", dataType = "Integer", paramType = "query"),
                @ApiImplicitParam(name = "type", value = "类型", dataType = "String", paramType = "query"),
        })
        public AjaxResult selectRecorderCountByDeptId (@RequestBody VisuForestCloudMapVO vo){
            return AjaxResult.success(centermonitorTCameraService.selectRecorderCountByDeptId(vo));
        }


        /**
         * 根据通道编码查询摄像头信息和通道信息
         */
        @ApiOperation(value = "根据通道编码查询摄像头信息和通道信息", notes = "根据通道编码查询摄像头信息和通道信息")
        @GetMapping(value = "selectCameraInfoByChannelCode/{channelCode}")
        @Log(title = "摄像头通道", businessType = BusinessType.OTHER)
        public R<CentermonitorTCamera> selectCameraInfoByChannelCode (@PathVariable("channelCode") String channelCode){
            return R.ok(centermonitorTCameraService.selectCameraInfoByChannelCode(channelCode));
        }

}



