package com.yfd.platform.modules.basedata.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.*;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.yfd.platform.annotation.Log;
import com.yfd.platform.config.HttpServerConfig;
import com.yfd.platform.config.ResponseResult;
import com.yfd.platform.modules.auxcontrol.domain.GatewayDevice;
import com.yfd.platform.modules.auxcontrol.service.IGatewayDeviceService;
import com.yfd.platform.modules.basedata.domain.DeviceChannel;
import com.yfd.platform.modules.basedata.domain.PatroldeviceResume;
import com.yfd.platform.modules.basedata.domain.SubstationPatroldevice;
import com.yfd.platform.modules.basedata.service.IDeviceChannelService;
import com.yfd.platform.modules.basedata.service.IPatroldeviceResumeService;
import com.yfd.platform.modules.basedata.service.ISubstationDeviceService;
import com.yfd.platform.modules.basedata.service.ISubstationPatroldeviceService;
import com.yfd.platform.modules.deviceapi.CameraUtil;
import com.yfd.platform.modules.robotapi.service.IRobotOfflineLogService;
import com.yfd.platform.system.domain.RolePatroldevice;
import com.yfd.platform.system.domain.SysUser;
import com.yfd.platform.system.service.IRolePatroldeviceService;
import com.yfd.platform.system.service.IUserService;
import com.yfd.platform.utils.FileUtil;
import com.yfd.platform.utils.HttpRESTfulUtils;
import com.yfd.platform.utils.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * <p>
 * 变电站_巡视设备 前端控制器
 * </p>
 *
 *
 * @since 2023-03-28
 */
@RestController
@RequestMapping("/basedata/substation-patroldevice")
@Api(value = "SubstationPatroldeviceController", tags = "巡视设备")
@Slf4j
public class SubstationPatroldeviceController {

    @Resource
    private ISubstationPatroldeviceService substationPatroldeviceService;

    @Resource
    private ISubstationDeviceService substationDeviceService;


    @Resource
    private Map<String, List<Map<String, Object>>> typeList;

    @Resource
    private IDeviceChannelService deviceChannelService;

    @Resource
    private IUserService userService;

    @Resource
    private IPatroldeviceResumeService patroldeviceResumeService;

    @Resource
    private IRolePatroldeviceService rolePatroldeviceService;
    @Resource
    private HttpServerConfig config;
    @Resource
    private HttpRESTfulUtils httpUtil;
    @Resource
    private IRobotOfflineLogService robotOfflineLogService;
    @Resource
    private IGatewayDeviceService gatewayDeviceService;

    @Value("${file-space.system}")
    private String systempath;

    @PostMapping("/getPatrolDeviceList")
    @ApiOperation("分页查询巡视设备")
    @PreAuthorize("@el.check('select:patroldevice')")
    public ResponseResult getPatrolDeviceList(@RequestBody String param) {
        JSONObject jsonObject = JSONUtil.parseObj(param);
        Page<Map<String, Object>> page = new Page<>();
        page.setCurrent(jsonObject.getInt("current"));
        page.setSize(jsonObject.getInt("size"));
        String stationId = jsonObject.getStr("stationId");
        String areaId = jsonObject.getStr("areaId");
        String patrolDeviceName = jsonObject.getStr("patrolDeviceName");
        String type = jsonObject.getStr("type");
        String deviceModel = jsonObject.getStr("deviceModel");
        String ids = jsonObject.getStr("ids");
        String manufacturer = jsonObject.getStr("manufacturer");
        String flag = jsonObject.getStr("flag");
        String online = jsonObject.getStr("online");
        SysUser userInfo = userService.getUserInfo();
        Integer usertype = userInfo.getUsertype();
        LambdaQueryWrapper<SubstationPatroldevice> queryWrapper = new LambdaQueryWrapper<>();
        if (usertype != 0 && ("10".equals(type) || StrUtil.isBlank(type))) {
            //if (usertype != 0 && !"14".equals(type)) {
            // 非管理员只可以查看指定摄像头
            List<String> cameraIds = substationPatroldeviceService.getCameraIds(userInfo.getId());
            // 获取用户所有的摄像头
            if (cameraIds.size() > 0) {
                queryWrapper.in(SubstationPatroldevice::getPatroldeviceId, cameraIds);
            } else {
                return ResponseResult.successData(null);
            }
        }
        if ("1".equals(flag)) {
            queryWrapper.and(i -> i.isNull(SubstationPatroldevice::getAreaId).or().eq(SubstationPatroldevice::getAreaId, ""));
        } else {
            queryWrapper.eq(SubstationPatroldevice::getStationId, stationId);
            if (StrUtil.isNotBlank(areaId)) {
                queryWrapper.eq(SubstationPatroldevice::getAreaId, areaId);
            }
        }

        // 模糊查询(设备名称)
        if (StrUtil.isNotBlank(patrolDeviceName)) {
            queryWrapper.like(SubstationPatroldevice::getPatroldeviceName, patrolDeviceName);
        }
        if (StrUtil.isNotBlank(online)) {
            queryWrapper.eq(SubstationPatroldevice::getOnline, online);
        }
        // 模糊查询(设备型号)
        if (StrUtil.isNotBlank(deviceModel)) {
            queryWrapper.like(SubstationPatroldevice::getDeviceModel, deviceModel);
        }

        // 模糊查询(生产厂家)
        if (StrUtil.isNotBlank(manufacturer)) {
            queryWrapper.like(SubstationPatroldevice::getManufacturer, manufacturer);
        }
        if (StrUtil.isNotBlank(ids)) {
            String[] split = ids.split(",");
            queryWrapper.notIn(SubstationPatroldevice::getPatroldeviceId, Arrays.asList(split));
        }
        // 类型
        if (StrUtil.isNotBlank(type)) {
            List<String> typeList = Arrays.asList(type.split(","));
            queryWrapper.in(SubstationPatroldevice::getType, typeList);
            if ("10".equals(type) || "11".equals(type)) {
                queryWrapper.and(i -> i.isNull(SubstationPatroldevice::getRobotsCode).or().eq(SubstationPatroldevice::getRobotsCode, ""));
            }
        } else {
            String[] code = {"10", "11"};
            List<String> codeList = Arrays.asList(code);
            //            queryWrapper.in(SubstationPatroldevice::getType, codeList).and(i -> i.isNull(SubstationPatroldevice::getRobotsCode).or().eq(SubstationPatroldevice::getRobotsCode, ""));
            queryWrapper.in(SubstationPatroldevice::getType, codeList).and(i -> i.isNull(SubstationPatroldevice::getRobotsCode).or().eq(SubstationPatroldevice::getRobotsCode, ""));
        }
        queryWrapper.orderByAsc(SubstationPatroldevice::getPatroldeviceCode);
        Page<Map<String, Object>> mapPage = substationPatroldeviceService.pageMaps(page, queryWrapper);
        List<Map<String, Object>> records = page.getRecords();
        List<Map<String, Object>> patrolDevices = new ArrayList<>();
        String[] code = {"1", "2", "3", "13"};
        List<String> codeList = Arrays.asList(code);
        for (Map<String, Object> record : records) {
            record.remove("lastmodifydate");
            String type2 = (String) record.get("type");
            String patroldeviceCode = null;
            if (codeList.contains(type2)) {
                record.put("patrolDeviceOnline", record.get("online"));
            } else {
                patroldeviceCode = record.get("internationalId").toString();
            }

            if (ObjUtil.isNotEmpty(record.get("channelinfo")) && JSONUtil.isTypeJSONArray(record.get("channelinfo").toString())) {
                JSONArray channels = JSONUtil.parseArray(record.get("channelinfo").toString());
                List<Map<String, Object>> mapList = new ArrayList<>();
                for (int i = 0; i < channels.size(); i++) {
                    JSONObject channel = channels.getJSONObject(i);
                    Map<String, Object> map = new HashMap<>();
                    map.put("channelType", channel.getStr("channel_type"));
                    // 1:摄像机
                    if ("1".equals(channel.getStr("from_device"))) {
                        map.put("deviceId", record.get("internationalId").toString());
                        map.put("channelId", channel.getStr("channel_code"));
                    } else {
                        // 2:来源录像机
                        map.put("deviceId", channel.getStr("recorder_code"));
                        map.put("channelId", channel.getStr("recorder_channelcode"));
                    }
                    mapList.add(map);
                }
                record.put("channelList", mapList);
            } else {
                //没有配置
                LambdaQueryWrapper<DeviceChannel> deviceChannelLambdaQueryWrapper = new LambdaQueryWrapper<>();
                deviceChannelLambdaQueryWrapper.eq(DeviceChannel::getDeviceid, patroldeviceCode);
                deviceChannelLambdaQueryWrapper.select(DeviceChannel::getDeviceid, DeviceChannel::getChannelid);
                List<Map<String, Object>> mapList = deviceChannelService.listMaps(deviceChannelLambdaQueryWrapper);
                if (mapList != null && mapList.size() > 0) {
                    record.put("channelList", mapList);
                }
            }
            Map<String, List<Map<String, Object>>> deviceType = typeList;
            // 巡视设备类型
            List<Map<String, Object>> list = deviceType.get("PatrolEquipmentType");
            for (Map<String, Object> map : list) {
                String itemcode = (String) map.get("itemcode");
                String type1 = (String) record.get("type");
                if (itemcode.equals(type1)) {
                    record.put("typeName", map.get("dictname"));
                    break;
                }
            }
            patrolDevices.add(record);
        }
        mapPage.setRecords(patrolDevices);
        return ResponseResult.successData(mapPage);
    }

    @GetMapping("/getPatrolCameraList")
    @ApiOperation("获取联动信号摄像机")
    public ResponseResult getPatrolCameraList(String stationId, String areaId, String patrolDeviceName, String type) {
        SysUser userInfo = userService.getUserInfo();
        Integer usertype = userInfo.getUsertype();
        LambdaQueryWrapper<SubstationPatroldevice> queryWrapper = new LambdaQueryWrapper<>();
        if (usertype != 0) {
            //if (usertype != 0 && !"14".equals(type)) {
            // 非管理员只可以查看指定摄像头
            List<String> ids = substationPatroldeviceService.getCameraIds(userInfo.getId());
            // 获取用户所有的摄像头
            if (ids.size() > 0) {
                queryWrapper.in(SubstationPatroldevice::getPatroldeviceId, ids);
            } else {
                return ResponseResult.successData(null);
            }
        }
        queryWrapper.eq(SubstationPatroldevice::getStationId, stationId);
        if (StrUtil.isNotBlank(areaId)) {
            queryWrapper.eq(SubstationPatroldevice::getAreaId, areaId);
        }
        // 模糊查询(设备名称)
        if (StrUtil.isNotBlank(patrolDeviceName)) {
            queryWrapper.like(SubstationPatroldevice::getPatroldeviceName, patrolDeviceName);
        }
        // 类型
        if (StrUtil.isNotBlank(type)) {
            queryWrapper.eq(SubstationPatroldevice::getType, type);
        }
        queryWrapper.eq(SubstationPatroldevice::getDatastatus, "1").eq(SubstationPatroldevice::getType, "10")//摄像机
                .orderByAsc(SubstationPatroldevice::getType);
        List<Map<String, Object>> maps = substationPatroldeviceService.listMaps(queryWrapper);
        List<Map<String, Object>> patrolDevices = new ArrayList<>();
        for (Map<String, Object> record : maps) {
            if (ObjUtil.isNotEmpty(record.get("channelinfo")) && JSONUtil.isTypeJSONArray(record.get("channelinfo").toString())) {
                JSONArray channels = JSONUtil.parseArray(record.get("channelinfo").toString());
                for (int i = 0; i < channels.size(); i++) {
                    JSONObject channel = channels.getJSONObject(i);
                    Map<String, Object> copyMap = new HashMap<>(record);
                    copyMap.put("channelType", channel.getStr("channel_type"));
                    if ("2".equals(channel.getStr("channel_type"))) {
                        copyMap.put("patroldeviceName", record.get("patroldeviceName").toString() + "_红外");
                    }
                    // 1:摄像机
                    if ("1".equals(channel.getStr("from_device"))) {
                        copyMap.put("deviceId", record.get("internationalId").toString());
                        copyMap.put("channelId", channel.getStr("channel_code"));
                    } else {
                        // 2:来源录像机
                        copyMap.put("deviceId", channel.getStr("recorder_code"));
                        copyMap.put("channelId", channel.getStr("recorder_channelcode"));
                    }
                    //如果指定了视频流地址，则优先取指定的地址
                    copyMap.put("channelRtspurl", channel.getStr("channel_rtspurl"));
                    patrolDevices.add(copyMap);
                }
            } else {
                //没有配置
                String patroldeviceCode = record.get("internationalId").toString();
                LambdaQueryWrapper<DeviceChannel> queryWrapper1 = new LambdaQueryWrapper<>();
                queryWrapper1.eq(DeviceChannel::getDeviceid, patroldeviceCode).eq(DeviceChannel::getAddress, "Address")
                        .select(DeviceChannel::getDeviceid,
                                DeviceChannel::getChannelid)
                        .orderByAsc(DeviceChannel::getChannelid);
                List<Map<String, Object>> channels = deviceChannelService.listMaps(queryWrapper1);
                for (int i = 0; i < channels.size(); i++) {
                    Map<String, Object> channel = channels.get(i);
                    Map<String, Object> copyMap = new HashMap<>(record);
                    copyMap.put("patroldeviceName", record.get("patroldeviceName").toString() + "_" + (i + 1));
                    copyMap.put("deviceId", patroldeviceCode);
                    copyMap.put("channelId", channel.get("channelId").toString());
                    patrolDevices.add(copyMap);
                }
            }

        }
        return ResponseResult.successData(patrolDevices);
    }

    @GetMapping("/getCameraList")
    @ApiOperation("获取摄像头")
    public ResponseResult getCameraList(String stationId, String patroldeviceName, String type) {
        String[] code = {"11", "12", "15", "20", "21"};
        List<String> codeList = Arrays.asList(code);
        SysUser userInfo = userService.getUserInfo();
        Integer usertype = userInfo.getUsertype();
        // 根据用户id查询所有摄像头id
        LambdaQueryWrapper<SubstationPatroldevice> queryWrapper = new LambdaQueryWrapper<>();
        if (usertype != 0) {
            // 非管理员只可以查看指定摄像头
            List<String> ids = substationPatroldeviceService.getCameraIds(userInfo.getId());
            // 获取用户所有的摄像头
            if (ids.size() > 0) {
                queryWrapper.in(SubstationPatroldevice::getPatroldeviceId, ids);
            } else {
                return ResponseResult.successData(null);
            }
        }
        queryWrapper.eq(SubstationPatroldevice::getStationId, stationId);
        if (StrUtil.isNotBlank(patroldeviceName)) {
            queryWrapper.like(SubstationPatroldevice::getPatroldeviceName, patroldeviceName);
        }
        if (StrUtil.isNotBlank(type)) {
            queryWrapper.eq(SubstationPatroldevice::getType, type);
        } else {
            queryWrapper.notIn(SubstationPatroldevice::getType, codeList);
        }
        //        queryWrapper.and(i -> i.isNull(SubstationPatroldevice::getRobotsCode).or().eq(SubstationPatroldevice::getRobotsCode, ""));
        queryWrapper.eq(SubstationPatroldevice::getDatastatus, "1");
        queryWrapper.select(SubstationPatroldevice::getPatroldeviceId, SubstationPatroldevice::getAreaId,SubstationPatroldevice::getInternationalId,
                SubstationPatroldevice::getAreaName, SubstationPatroldevice::getPatroldeviceName,
                SubstationPatroldevice::getPatroldeviceCode, SubstationPatroldevice::getPlace,
                SubstationPatroldevice::getType,SubstationPatroldevice::getVideoMode, SubstationPatroldevice::getUseMode, SubstationPatroldevice::getOnline, SubstationPatroldevice::getChannelinfo);
        List<Map<String, Object>> list = substationPatroldeviceService.listMaps(queryWrapper);
        List<Map<String, Object>> cameraList = new ArrayList<>();
        Map<String, List<Map<String, Object>>> deviceType = substationDeviceService.getDeviceType();
        List<Map<String, Object>> list1 = deviceType.get("PatrolEquipmentType");
        // 机器人无人机类型
        for (Map<String, Object> map : list) {
            String type1 = (String) map.get("type");
            for (Map<String, Object> stringObjectMap : list1) {
                String itemcode = (String) stringObjectMap.get("itemcode");
                if (type1.equals(itemcode)) {
                    map.put("typeName", stringObjectMap.get("dictname"));
                    break;
                }
            }

            //郑顺利2023-08-27修改，不从DeviceChannel 获取摄像头信息，修改为从摄像机对应channelinfo中获取通道信息
            // channelinfo=[{"channel_type":"2","channel_code":"","channel_rtspurl":"","from_device":"1","recorder_code":"","recorder_channelcode":""}]
            // channel_type: 1=可见光，2=红外 "from_device":1=摄像机 2=硬盘录像机
            if("15".equals(type)){
                map.put("deviceId", map.get("internationalId").toString());
                map.put("channelId", map.get("internationalId").toString());
                cameraList.add(map);
            }
            if (ObjUtil.isNotEmpty(map.get("channelinfo")) && JSONUtil.isTypeJSONArray(map.get("channelinfo").toString())) {
                JSONArray channels = JSONUtil.parseArray(map.get("channelinfo").toString());
                for (int i = 0; i < channels.size(); i++) {
                    JSONObject channel = channels.getJSONObject(i);
                    Map<String, Object> copyMap = new HashMap<>(map);
                    copyMap.put("channelType", channel.getStr("channel_type"));
                    if ("2".equals(channel.getStr("channel_type"))) {
                        copyMap.put("patroldeviceName", map.get("patroldeviceName").toString() + "_红外");
                    }
                    // 1：摄像机
                    if ("1".equals(channel.getStr("from_device"))) {
                        copyMap.put("deviceId", map.get("internationalId").toString());
                        copyMap.put("channelId", channel.getStr("channel_code"));
                    } else {
                        // 2：来源录像机
                        copyMap.put("deviceId", channel.getStr("recorder_code"));
                        copyMap.put("channelId", channel.getStr("recorder_channelcode"));
                    }
                    //如果指定了视频流地址，则优先取指定的地址
                    copyMap.put("channelRtspurl", channel.getStr("channel_rtspurl"));
                    cameraList.add(copyMap);
                }
            } else {
                //没有配置
                String patroldeviceCode = map.get("internationalId").toString();  //修改为取国标码
                LambdaQueryWrapper<DeviceChannel> queryWrapper1 = new LambdaQueryWrapper<>();
                queryWrapper1.eq(DeviceChannel::getDeviceid, patroldeviceCode).eq(DeviceChannel::getAddress, "Address")
                        .select(DeviceChannel::getDeviceid,
                                DeviceChannel::getChannelid)
                        .orderByAsc(DeviceChannel::getChannelid);
                List<Map<String, Object>> channels = deviceChannelService.listMaps(queryWrapper1);
                for (int i = 0; i < channels.size(); i++) {
                    Map<String, Object> channel = channels.get(i);
                    Map<String, Object> copyMap = new HashMap<>(map);
                    String patroldeviceName1 = ObjectUtil.isEmpty(map.get("patroldeviceName")) ? "" : map.get("patroldeviceName").toString();
                    copyMap.put("patroldeviceName", patroldeviceName1 + "_" + (i + 1));
                    copyMap.put("deviceId", patroldeviceCode);
                    copyMap.put("channelId", channel.get("channelId").toString());
                    cameraList.add(copyMap);
                }
            }
        }
        return ResponseResult.successData(cameraList);
    }

    @GetMapping("/getRobotList")
    @ApiOperation("获取机器人无人机")
    public ResponseResult getRobotList(String stationId, String patroldeviceName, String type) {
        LambdaQueryWrapper<SubstationPatroldevice> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SubstationPatroldevice::getStationId, stationId);
        if (StrUtil.isNotBlank(patroldeviceName)) {
            queryWrapper.like(SubstationPatroldevice::getPatroldeviceName, patroldeviceName);
        }
        if (StrUtil.isNotBlank(type)) {
            queryWrapper.in(SubstationPatroldevice::getType, Arrays.asList(type.split(",")));
        }
        List<Map<String, Object>> mapList = substationPatroldeviceService.listMaps(queryWrapper);
        String[] code = {"1", "2", "3", "13"};
        List<String> codeList = Arrays.asList(code);
        mapList.forEach(record -> {
            String type2 = (String) record.get("type");
            if (codeList.contains(type2)) {
                record.put("patrolDeviceOnline", record.get("online"));
            }
            LambdaQueryWrapper<SubstationPatroldevice> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(SubstationPatroldevice::getRobotsCode, record.get("patroldeviceCode").toString());
            List<Map<String, Object>> list = substationPatroldeviceService.listMaps(queryWrapper1);
            list.forEach(map -> {
                LambdaQueryWrapper<DeviceChannel> deviceChannelLambdaQueryWrapper = new LambdaQueryWrapper<>();
                deviceChannelLambdaQueryWrapper.eq(DeviceChannel::getDeviceid, map.get("internationalId").toString());
                DeviceChannel deviceChannel = deviceChannelService.getOne(deviceChannelLambdaQueryWrapper);
                if (deviceChannel != null) {
                    map.put("deviceId", deviceChannel.getDeviceid());
                    map.put("channelId", deviceChannel.getChannelid());
                } else {
                    map.put("deviceId", map.get("internationalId").toString());
                    map.put("channelId", map.get("internationalId").toString());
                }
            });

            if (ObjectUtil.isEmpty(record.get("channelList"))) {
                record.put("channelList", list);
            }
        });
        return ResponseResult.successData(mapList);
    }

    @GetMapping("/getCameraByRobot")
    @ApiOperation("根据机器人编码获取摄像头")
    public ResponseResult getCameraByRobot(String robotsCode) {
        List<SubstationPatroldevice> list =
                substationPatroldeviceService.list(new LambdaQueryWrapper<SubstationPatroldevice>().eq(SubstationPatroldevice::getRobotsCode, robotsCode));
        return ResponseResult.successData(list);
    }

    @GetMapping("/getPatrolDeviceByType")
    @ApiOperation("根据类型获取巡视设备")
    public ResponseResult getPatrolDeviceByType(Page<Map<String, Object>> page, String stationId, String type,
                                                String patrolDeviceName, String ids) {
        if (StrUtil.isBlank(type)) {
            return ResponseResult.error("参数错误");
        }
        String[] split = type.split(",");
        List<String> stringList = Arrays.asList(split);
        LambdaQueryWrapper<SubstationPatroldevice> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SubstationPatroldevice::getStationId, stationId).eq(SubstationPatroldevice::getDatastatus, "1"
        ).in(SubstationPatroldevice::getType, stringList);
        if (StrUtil.isNotBlank(patrolDeviceName)) {
            queryWrapper.like(SubstationPatroldevice::getPatroldeviceName, patrolDeviceName);
        }
        if (StrUtil.isNotBlank(ids)) {
            String[] split1 = ids.split(",");
            queryWrapper.notIn(SubstationPatroldevice::getPatroldeviceId, Arrays.asList(split1));
        }
        Page<Map<String, Object>> mapPage = substationPatroldeviceService.pageMaps(page, queryWrapper);
        List<Map<String, Object>> records = mapPage.getRecords();
        String[] code = {"1", "2", "3", "4", "13"};
        List<String> codeList = Arrays.asList(code);
        records.forEach(r -> {
            String type2 = (String) r.get("type");
            String patroldeviceCode = null;
            if (codeList.contains(type2)) {
                List<Map<String, Object>> substationPatroldevices = substationPatroldeviceService.listMaps(new LambdaQueryWrapper<SubstationPatroldevice>().eq(SubstationPatroldevice::getRobotsCode, r.get("patroldeviceCode").toString()).eq(SubstationPatroldevice::getDatastatus, "1"));
                substationPatroldevices.forEach(map -> {
                    LambdaQueryWrapper<DeviceChannel> deviceChannelLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    deviceChannelLambdaQueryWrapper.eq(DeviceChannel::getDeviceid, map.get("internationalId").toString());
                    DeviceChannel deviceChannel = deviceChannelService.getOne(deviceChannelLambdaQueryWrapper);
                    if (deviceChannel != null) {
                        map.put("deviceId", deviceChannel.getDeviceid());
                        map.put("channelId", deviceChannel.getChannelid());
                    } else {
                        map.put("deviceId", map.get("internationalId").toString());
                        map.put("channelId", map.get("internationalId").toString());
                    }
                });
                if (ObjectUtil.isEmpty(r.get("channelList"))) {
                    r.put("channelList", substationPatroldevices);
                }
            } else {
                patroldeviceCode = r.get("internationalId").toString();
                if (ObjUtil.isNotEmpty(r.get("channelinfo")) && JSONUtil.isTypeJSONArray(r.get("channelinfo").toString())) {
                    JSONArray channels = JSONUtil.parseArray(r.get("channelinfo").toString());
                    List<Map<String, Object>> mapList = new ArrayList<>();
                    for (int i = 0; i < channels.size(); i++) {
                        JSONObject channel = channels.getJSONObject(i);
                        Map<String, Object> map = new HashMap<>();
                        map.put("channelType", channel.getStr("channel_type"));
                        // 1：摄像机
                        if ("1".equals(channel.getStr("from_device"))) {
                            map.put("deviceId", patroldeviceCode);
                            map.put("channelId", channel.getStr("channel_code"));
                        } else {
                            // 2：来源录像机
                            map.put("deviceId", channel.getStr("recorder_code"));
                            map.put("channelId", channel.getStr("recorder_channelcode"));
                        }
                        mapList.add(map);
                    }
                    r.put("channelList", mapList);
                }
            }
        });

        mapPage.setRecords(records);
        return ResponseResult.successData(mapPage);
    }

    @GetMapping("/getPatrolDeviceResume")
    @ApiOperation("根据机器人编号查询设备履历")
    public ResponseResult getPatrolDeviceResume(String patrolDeviceCode, String type) {
        if (StrUtil.isBlank(patrolDeviceCode)) {
            return ResponseResult.error("设备编码为空");
        }
        if (StrUtil.isBlank(type)) {
            return ResponseResult.error("记录类型为空");
        }
        LambdaQueryWrapper<PatroldeviceResume> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PatroldeviceResume::getPatroldeviceCode, patrolDeviceCode).eq(PatroldeviceResume::getType,
                type);
        List<PatroldeviceResume> list = patroldeviceResumeService.list(queryWrapper);
        return ResponseResult.successData(list);
    }

    @Log(module = "巡视设备", value = "新增巡视设备",type = "1")
    @PostMapping("/addPatrolDevice")
    @ApiOperation("新增巡视设备")
    @PreAuthorize("@el.check('add:patroldevice')")
    public ResponseResult addPatrolDevice(@RequestBody SubstationPatroldevice substationPatroldevice) {
        String patroldeviceCode = substationPatroldevice.getPatroldeviceCode();
        String uuid = IdUtil.fastSimpleUUID();
        substationPatroldevice.setPatroldeviceId(uuid);
        String stationId = substationPatroldevice.getStationId();
        int count =
                substationPatroldeviceService.count(new LambdaQueryWrapper<SubstationPatroldevice>().eq(SubstationPatroldevice::getStationId, stationId).eq(SubstationPatroldevice::getPatroldeviceCode, patroldeviceCode));
        if (count > 0) {
            return ResponseResult.error("巡视设备已经存在");
        }
        if ("10".equals(substationPatroldevice.getType()) || "11".equals(substationPatroldevice.getType())) {
            SysUser userInfo = userService.getUserInfo();
            List<String> roleId = userService.getRoleId(userInfo.getId());
            // 用户角色加上摄像头权限
            for (String id : roleId) {
                log.info("roid--------------------" + id);
                RolePatroldevice rolePatroldevice = new RolePatroldevice();
                rolePatroldevice.setDeviceid(uuid);
                rolePatroldevice.setRoleid(id);
                log.info(rolePatroldevice.toString());
                rolePatroldeviceService.save(rolePatroldevice);
            }
        }

        substationPatroldevice.setPatroldeviceId(uuid);
        substationPatroldevice.setLastmodifier(SecurityUtils.getCurrentUsername());
        substationPatroldevice.setLastmodifydate(LocalDateTime.now());
        substationPatroldevice.setDatastatus("1");
        boolean ok = substationPatroldeviceService.save(substationPatroldevice);
        if (ok) {
            return ResponseResult.successData(uuid);
        } else {
            return ResponseResult.error("新增失败");
        }
    }

    @Log(module = "巡视设备", value = "新增或修改机器人", type = "1")
    @PostMapping("/addOrUpdatePatrolRobot")
    @ApiOperation("新增或修改机器人")
    public ResponseResult addOrUpdatePatrolRobot(String substationPatroldevices, MultipartFile image) {
        if (substationPatroldevices == null) {
            return ResponseResult.error("参数为空");
        }
        List<SubstationPatroldevice> substationPatroldeviceList = JSONUtil.toList(substationPatroldevices,
                SubstationPatroldevice.class);
        SubstationPatroldevice substationPatroldevice = substationPatroldeviceList.get(0);
        String stationId = substationPatroldevice.getStationId();
        Set<String> collect =
                substationPatroldeviceList.stream().map(SubstationPatroldevice::getPatroldeviceCode).collect(Collectors.toSet());
        if (collect.size() != substationPatroldeviceList.size()) {
            return ResponseResult.error("机器人编码与摄像头编码相同");
        }
        for (SubstationPatroldevice substationPatroldevice1 : substationPatroldeviceList) {
            LambdaQueryWrapper<SubstationPatroldevice> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SubstationPatroldevice::getStationId, stationId).eq(SubstationPatroldevice::getPatroldeviceCode, substationPatroldevice1.getPatroldeviceCode());
            String patroldeviceId = substationPatroldevice1.getPatroldeviceId();
            if (StrUtil.isNotBlank(patroldeviceId)) {
                queryWrapper.ne(SubstationPatroldevice::getPatroldeviceId, patroldeviceId);
            }
            int count =
                    substationPatroldeviceService.count(queryWrapper);
            if (count > 0) {
                return ResponseResult.error("当前设备已经存在");
            }
        }
        String fileName = "";
        List<String> codeList = Arrays.asList("1", "2", "3", "4", "13");
        if (image != null && !image.isEmpty()) {
            String filename = image.getOriginalFilename();
            String suffix = StrUtil.subAfter(filename, ".", true).toLowerCase();
            if (!"png".equals(suffix) && !"jpg".equals(suffix) && !"gif".equals(suffix)) {
                return ResponseResult.error("非法文件类型");
            }
            String contentType = image.getContentType();
            if (!"image/jpeg".equals(contentType) && !"image/png".equals(contentType) && !"image/gif".equals(contentType)) {
                return ResponseResult.error("非法文件内容");
            }
            // 图片存储地址
            String imgPath = systempath + "patrolDevice";
            String iconname =
                    IdUtil.fastSimpleUUID() + "." + FileUtil.getExtensionName(image.getOriginalFilename());
            //获取图片名称
            fileName = Objects.requireNonNull(FileUtil.upload(image, imgPath, iconname)).getName();
        }
        String finalFileName = fileName;
        substationPatroldeviceList.forEach(r -> {
            if (codeList.contains(r.getType())&&StrUtil.isNotBlank(finalFileName)) {
                r.setCustom2(finalFileName);
            }
            r.setOnline("1");
        });
        substationPatroldeviceService.addOrUpdatePatrolRobot(substationPatroldeviceList);
        return ResponseResult.success();
    }

    @Log(module = "巡视设备", value = "修改巡视设备",type = "1")
    @PostMapping("/updatePatrolDeviceById")
    @ApiOperation("修改巡视设备")
    @PreAuthorize("@el.check('update:patroldevice')")
    public ResponseResult updateSubstationDeviceById(@RequestBody SubstationPatroldevice substationPatroldevice) {
        String stationId = substationPatroldevice.getStationId();
        String patroldeviceCode = substationPatroldevice.getPatroldeviceCode();
        String patroldeviceId = substationPatroldevice.getPatroldeviceId();
        LambdaQueryWrapper<SubstationPatroldevice> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SubstationPatroldevice::getPatroldeviceCode, patroldeviceCode).eq(SubstationPatroldevice::getStationId, stationId).ne(SubstationPatroldevice::getPatroldeviceId, patroldeviceId);
        int count = substationPatroldeviceService.count(queryWrapper);
        if (count > 0) {
            return ResponseResult.error("当前巡视设备已经存在");
        }
        substationPatroldevice.setLastmodifier(SecurityUtils.getCurrentUsername());
        substationPatroldevice.setLastmodifydate(LocalDateTime.now());
        boolean ok = substationPatroldeviceService.updateById(substationPatroldevice);
        if (ok) {
            return ResponseResult.success();
        } else {
            return ResponseResult.error("修改失败");
        }
    }

    @GetMapping("/getSubstationDeviceById")
    @ApiOperation("根据Id查询巡视设备完整率")
    public ResponseResult getSubstationDeviceById(String id, String internationalId, String channelid) {
        LambdaQueryWrapper<SubstationPatroldevice> queryWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(id)) {
            queryWrapper.eq(SubstationPatroldevice::getPatroldeviceId, id);
        }
        if (StrUtil.isNotBlank(internationalId)) {
            queryWrapper.eq(SubstationPatroldevice::getInternationalId, internationalId);
        }
        List<SubstationPatroldevice> list = substationPatroldeviceService.list(queryWrapper);
        if (list.size() <= 0) {
            return ResponseResult.successData(null);
        }
        SubstationPatroldevice substationPatroldevice = list.get(0);
        if (StrUtil.isBlank(channelid)) {
            return ResponseResult.successData(substationPatroldevice);
        }
        Map<String, Object> map = BeanUtil.beanToMap(substationPatroldevice);
        DeviceChannel deviceChannel =
                substationPatroldeviceService.queryChannelByDeviceIp(substationPatroldevice.getIpaddr());
        if (deviceChannel == null) {
            map.put("duration", 0);
            map.put("rate", 0);
        } else {
            String cameraStatByCode = substationPatroldeviceService.getCameraStatByCode(deviceChannel.getChannelid());
            if (StrUtil.isBlank(cameraStatByCode)) {
                map.put("duration", 0);
                map.put("rate", 0);
            } else {
                long duration = Long.parseLong(cameraStatByCode) / 60;
                map.put("duration", duration);
                long sum = 90 * 24 * 60;
                map.put("rate", (int) (((float) duration / sum) * 100 + 0.5));
            }
        }
        map.put("cycle", 90);
        return ResponseResult.successData(map);
    }

    @GetMapping("/getPatroldeviceById")
    @ApiOperation("根据Id查询巡视设备")
    public ResponseResult getSubstationDeviceById(String id) {
        SubstationPatroldevice substationPatroldevice = substationPatroldeviceService.getById(id);
        return ResponseResult.successData(substationPatroldevice);
    }

    @Log(module = "巡视设备", value = "删除巡视设备", type = "1")
    @PostMapping("/deletePatrolDeviceById")
    @ApiOperation("删除巡视设备")
    @PreAuthorize("@el.check('del:patroldevice')")
    public ResponseResult deleteSubstationDeviceById(String id) {
        if (StrUtil.isBlank(id)) {
            return ResponseResult.error("参数为空");
        }
        boolean ok = substationPatroldeviceService.deleteSubstationDeviceById(id);
        if (ok) {
            return ResponseResult.success();
        } else {
            return ResponseResult.error("删除失败");
        }
    }

    @Log(module = "巡视设备", value = "设置巡视设备状态是否启用",type = "1")
    @PostMapping("/setPatrolDeviceStatus")
    @ApiOperation("设置巡视设备状态是否启用")
    public ResponseResult setSubstationDeviceStatus(String id, String dataStatus) {
        boolean ok = substationPatroldeviceService.setSubstationDeviceStatus(id, dataStatus);
        if (ok) {
            return ResponseResult.success();
        } else {
            return ResponseResult.error("修改失败");
        }
    }

    @GetMapping("/getSilentConfiguration")
    @ApiOperation("获取静默配置")
    public ResponseResult getSilentConfiguration(String code) {
        if (StrUtil.isBlank(code)) {
            return ResponseResult.error("参数为空");
        }
        return ResponseResult.success();
    }

    @GetMapping("/getCameraByArea")
    @ApiOperation("获取变电站下的摄像头（不包含机器人）")
    public ResponseResult getCameraByArea(String stationId, String deviceName, String status) {
        if (StrUtil.isBlank(stationId)) {
            return ResponseResult.error("未传变电站信息");
        }
        SysUser userInfo = userService.getUserInfo();
        Integer usertype = userInfo.getUsertype();
        LambdaQueryWrapper<SubstationPatroldevice> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SubstationPatroldevice::getStationId, stationId);
        if (usertype != 0) {
            //if (usertype != 0 && !"14".equals(type)) {
            // 非管理员只可以查看指定摄像头
            List<String> ids = substationPatroldeviceService.getCameraIds(userInfo.getId());
            // 获取用户所有的摄像头
            if (ids.size() > 0) {
                queryWrapper.in(SubstationPatroldevice::getPatroldeviceId, ids);
            } else {
                return ResponseResult.successData(null);
            }
        }
        if (StrUtil.isNotBlank(deviceName)) {
            queryWrapper.like(SubstationPatroldevice::getPatroldeviceName, deviceName);
        }
        if (StrUtil.isNotBlank(status)) {
            queryWrapper.eq(SubstationPatroldevice::getOnline, status);
        }
        queryWrapper.and(i -> i.isNull(SubstationPatroldevice::getRobotsCode).or().eq(SubstationPatroldevice::getRobotsCode, ""));
        queryWrapper.eq(SubstationPatroldevice::getType, "10").eq(SubstationPatroldevice::getDatastatus, "1").isNotNull(SubstationPatroldevice::getAreaName);
        List<Map<String, Object>> maps = substationPatroldeviceService.listMaps(queryWrapper);
        Map<Object, List<Map<String, Object>>> deviceList = maps.stream().filter(m -> StrUtil.isNotBlank(m.get(
                "areaName").toString())).collect(Collectors.groupingBy(m -> m.get("areaName")));
        // 将摄像头转成树
        List<Map<String, Object>> deviceTree = new ArrayList<>();
        for (Object o : deviceList.keySet()) {
            Map<String, Object> map = new HashMap<>();
            List<Map<String, Object>> maps1 = deviceList.get(o);
            List<Map<String, Object>> maps2 = new ArrayList<>();
            for (Map<String, Object> m : maps1) {
                if (ObjUtil.isNotEmpty(m.get("channelinfo")) && JSONUtil.isTypeJSONArray(m.get("channelinfo").toString())) {
                    JSONArray channels = JSONUtil.parseArray(m.get("channelinfo").toString());
                    for (int i = 0; i < channels.size(); i++) {
                        JSONObject channel = channels.getJSONObject(i);
                        Map<String, Object> copyMap = new HashMap<>(m);
                        copyMap.put("channelType", channel.getStr("channel_type"));
                        if ("2".equals(channel.getStr("channel_type"))) {
                            copyMap.put("patroldeviceName", m.get("patroldeviceName").toString() + "_红外");
                        }
                        // 1:摄像机
                        if ("1".equals(channel.getStr("from_device"))) {
                            copyMap.put("deviceId", m.get("internationalId").toString());
                            copyMap.put("channelId", channel.getStr("channel_code"));
                        } else {
                            // 2:来源录像机
                            copyMap.put("deviceId", channel.getStr("recorder_code"));
                            copyMap.put("channelId", channel.getStr("recorder_channelcode"));
                        }
                        copyMap.put("channelRtspurl", channel.getStr("channel_rtspurl"));//如果指定了视频流地址，则
                        maps2.add(copyMap);
                    }
                }
                else{//没有配置
                    String patroldeviceCode = m.get("internationalId").toString();
                    LambdaQueryWrapper<DeviceChannel> queryWrapper1 = new LambdaQueryWrapper<>();
                    queryWrapper1.eq(DeviceChannel::getDeviceid, patroldeviceCode).eq(DeviceChannel::getAddress, "Address")
                            .select(DeviceChannel::getDeviceid,
                                    DeviceChannel::getChannelid)
                            .orderByAsc(DeviceChannel::getChannelid);
                    List<Map<String, Object>> channels = deviceChannelService.listMaps(queryWrapper1);
                    for (int i = 0; i < channels.size(); i++) {
                        Map<String, Object> channel = channels.get(i);
                        Map<String, Object> copyMap = new HashMap<>(map);
                        copyMap.put("patroldeviceName", map.get("patroldeviceName").toString() + "_" + (i + 1));
                        copyMap.put("deviceId", patroldeviceCode);
                        copyMap.put("channelId", channel.get("channelId").toString());
                        maps2.add(copyMap);
                    }
                }
            }
            map.put("name", o);
            map.put("children", maps2);
            deviceTree.add(map);
        }
        return ResponseResult.successData(deviceTree);
    }

    @GetMapping("/getPatrolDeviceOnLine")
    @ApiOperation("获取巡视设备在线率(单站)")
    public ResponseResult getPatrolDeviceOnLine(String stationId) {
        if (StrUtil.isBlank(stationId)) {
            return ResponseResult.error("未传变电站信息");
        }
        LambdaQueryWrapper<SubstationPatroldevice> queryWrapper = new LambdaQueryWrapper<>();
        //        SysUser userInfo = userService.getUserInfo();
        //        Integer usertype = userInfo.getUsertype();
        //        if (usertype != 0) {
        //            // 非管理员只可以查看指定摄像头
        //            List<String> ids = substationPatroldeviceService.getCameraIds(userInfo.getId());
        //            // 获取用户所有的摄像头
        //            if (ids.size() > 0) {
        //                queryWrapper.in(SubstationPatroldevice::getPatroldeviceId, ids);
        //            } else {
        //                return ResponseResult.successData(null);
        //            }
        //        }
        List<String> typeList = Lists.newArrayList("10", "14");
        queryWrapper.eq(SubstationPatroldevice::getStationId, stationId).in(SubstationPatroldevice::getType,
                typeList).eq(SubstationPatroldevice::getDatastatus, "1");
        List<SubstationPatroldevice> list = substationPatroldeviceService.list(queryWrapper);
        Map<String, List<SubstationPatroldevice>> listMap =
                list.stream().filter(l -> (StrUtil.isNotBlank(l.getType()))).collect(Collectors.groupingBy(SubstationPatroldevice::getType));
        Map<String, Object> map = new HashMap<>();

        for (String type : typeList) {
            List<SubstationPatroldevice> substationPatroldevices = listMap.get(type);
            Map<String, Object> map1 = new HashMap<>();
            if (substationPatroldevices == null) {
                map1.put("allCount", 0);
                map1.put("online", 0);
                map1.put("onLineRate", 0);
                map.put(type, map1);
                continue;
            }
            List<SubstationPatroldevice> patroldevices =
                    substationPatroldevices.stream().filter(s -> "1".equals(s.getOnline())).collect(Collectors.toList());
            int allCount = substationPatroldevices.size();
            int online = patroldevices.size();

            map1.put("allCount", allCount);
            map1.put("online", online);
            map1.put("onLineRate", (int) (((float) online / allCount) * 100 + 0.5));
            map.put(type, map1);
        }
        Map<String, Object> cameraMap = BeanUtil.beanToMap(map.get("10"));
        Map<String, Object> voiceMap = BeanUtil.beanToMap(map.get("14"));
        map.put("camera", cameraMap);
        map.remove("10");
        map.put("voice", voiceMap);
        map.remove("14");

        List<GatewayDevice> gatewayDevices =
                gatewayDeviceService.list(new LambdaQueryWrapper<GatewayDevice>().eq(GatewayDevice::getStationId,
                        stationId).ne(GatewayDevice::getStatus, "00"));
        if (gatewayDevices.size() <= 0) {
            Map<String, Object> map1 = new HashMap<>();
            map1.put("allCount", 0);
            map1.put("online", 0);
            map1.put("onLineRate", 0);
            map.put("gateway", map1);
        } else {
            Map<String, Object> map1 = new HashMap<>();
            long online = gatewayDevices.stream().filter(g -> "01".equals(g.getStatus())).count();
            long allCount = gatewayDevices.size();
            map1.put("allCount", allCount);
            map1.put("online", online);
            map1.put("onLineRate", (int) (((float) online / allCount) * 100 + 0.5));
            map.put("gateway", map1);

        }
        return ResponseResult.successData(map);
    }

    @GetMapping("/getPatrolDeviceStat")
    @ApiOperation("巡视设备统计(多站)")
    public ResponseResult getPatrolDeviceStat(String stationId) {
        if (StrUtil.isBlank(stationId)) {
            return ResponseResult.error("未传变电站信息");
        }
        LambdaQueryWrapper<SubstationPatroldevice> queryWrapper = new LambdaQueryWrapper<>();
        SysUser userInfo = userService.getUserInfo();
        Integer usertype = userInfo.getUsertype();
        if (usertype != 0) {
            // 非管理员只可以查看指定摄像头
            List<String> ids = substationPatroldeviceService.getCameraIds(userInfo.getId());
            // 获取用户所有的摄像头
            if (ids.size() > 0) {
                queryWrapper.in(SubstationPatroldevice::getPatroldeviceId, ids);
            } else {
                return ResponseResult.successData(null);
            }
        }
        // 判断多个变电站的设备在线率
        List<String> idList = Arrays.asList(stationId.split(","));
        queryWrapper.in(SubstationPatroldevice::getStationId, idList).eq(SubstationPatroldevice::getDatastatus, "1");
        List<SubstationPatroldevice> list = substationPatroldeviceService.list(queryWrapper);
        String[] codeArray = {"1", "2", "3", "10", "11", "12", "13", "14", "15", "21"};
        List<String> codeList = Arrays.asList(codeArray);
        Map<String, List<SubstationPatroldevice>> collect =
                list.stream().filter(l -> (StrUtil.isNotBlank(l.getType()) && codeList.contains(l.getType()))).collect(Collectors.groupingBy(SubstationPatroldevice::getType));
        Map<String, Object> map = new HashMap<>();
        for (String code : codeList) {
            List<SubstationPatroldevice> substationPatroldevices = collect.get(code);
            Map<String, Object> map1 = new HashMap<>();
            if (substationPatroldevices == null) {
                map1.put("allCount", 0);
                map1.put("online", 0);
                map1.put("onLineRate", 0);
                Map<String, String> nameByCode = getNameByCode(code);
                if (nameByCode != null) {
                    map1.put("name", nameByCode.get("nameCn"));
                    map.put(nameByCode.get("nameEn"), map1);
                }
                continue;
            }
            List<SubstationPatroldevice> collect1 =
                    substationPatroldevices.stream().filter(s -> "1".equals(s.getOnline())).collect(Collectors.toList
                            ());
            int allCount1 = substationPatroldevices.size();
            int online1 = collect1.size();
            map1.put("allCount", allCount1);
            map1.put("online", online1);
            map1.put("onLineRate", (int) (((float) online1 / allCount1) * 100 + 0.5));
            Map<String, String> nameByCode = getNameByCode(code);
            if (nameByCode != null) {
                map1.put("name", nameByCode.get("nameCn"));
                map.put(nameByCode.get("nameEn"), map1);
            }

        }
        // 轮式机器人
        Map<String, Object> map1 = BeanUtil.beanToMap(map.get("outWheelRobot"));
        int allCount1 = (Integer) map1.get("allCount");
        int online1 = (Integer) map1.get("online");
        Map<String, Object> map2 = BeanUtil.beanToMap(map.get("inWheelRobot"));
        int allCount2 = (Integer) map2.get("allCount");
        int online2 = (Integer) map2.get("online");
        Map<String, Object> wheelMap = new HashMap<>();
        int count = allCount1 + allCount2;
        int online = online1 + online2;
        wheelMap.put("allCount", count);
        wheelMap.put("online", online);
        wheelMap.put("onLineRate", (int) (((float) online / count) * 100 + 0.5));
        wheelMap.put("name", "轮式机器人");
        map.put("wheelRobot", wheelMap);
        return ResponseResult.successData(map);
    }

    /**********************************
     * 用途说明: 根据字典编码获取Map集合Key值
     * 参数说明 code
     * 返回值说明: java.lang.String
     ***********************************/
    private Map<String, String> getNameByCode(String code) {
        Map<String, String> map = new HashMap<>();
        if ("1".equals(code)) {
            map.put("nameEn", "outWheelRobot");
            map.put("nameCn", "室外轮式机器人");
            return map;
        } else if ("2".equals(code)) {
            map.put("nameEn", "inWheelRobot");
            map.put("nameCn", "室内轮式机器人");
            return map;
        } else if ("3".equals(code)) {
            map.put("nameEn", "hangTrackRobot");
            map.put("nameCn", "挂轨机器人");
            return map;
        } else if ("10".equals(code)) {
            map.put("nameEn", "camera");
            map.put("nameCn", "摄像机");
            return map;
        } else if ("11".equals(code)) {
            map.put("nameEn", "dvr");
            map.put("nameCn", "硬盘录像机");
            return map;
        } else if ("12".equals(code)) {
            map.put("nameEn", "analysisHost");
            map.put("nameCn", "智能分析主机");
            return map;
        } else if ("13".equals(code)) {
            map.put("nameEn", "uav");
            map.put("nameCn", "无人机");
            return map;
        } else if ("14".equals(code)) {
            map.put("nameEn", "aVoicePrint");
            map.put("nameCn", "声纹");
            return map;
        } else if ("15".equals(code)) {
            map.put("nameEn", "uavNest");
            map.put("nameCn", "无人机机巢");
            return map;
        } else if ("20".equals(code)) {
            map.put("nameEn", "areaPatrolHost");
            map.put("nameCn", "区域巡视主机");
            return map;
        }
        return null;
    }

    @GetMapping("/isWorkingOfPatrolDevice")
    @ApiOperation("摄像头是否正在执行巡视任务")
    public ResponseResult isWorkingOfPatrolDevice(String stationcode, String devicecode) {
        String isWorking = substationPatroldeviceService.isWorkingofPatroldevice(stationcode, devicecode);
        return ResponseResult.successData(isWorking);
    }

    @GetMapping("/getPatrolDeviceStatus")
    @ApiOperation("获取摄像头状态")
    public ResponseResult getPatrolDeviceStatus(String patrolDeviceId) {

        if (StrUtil.isBlank(patrolDeviceId)) {
            return ResponseResult.success();
        }
        List<String> idList = Arrays.asList(patrolDeviceId.split(","));
        LambdaQueryWrapper<SubstationPatroldevice> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(SubstationPatroldevice::getPatroldeviceId, idList).select(SubstationPatroldevice::getPatroldeviceId, SubstationPatroldevice::getOnline);
        List<Map<String, Object>> mapList = substationPatroldeviceService.listMaps(queryWrapper);
        return ResponseResult.successData(mapList);
    }

    @Log(module = "巡视设备", value = "设置静默监视是否启用",type = "1")
    @PostMapping("/setDailyMonitorStatus")
    @ApiOperation("设置静默监视是否启用")
    public ResponseResult setDailyMonitorStatus(String id, String dailyMonitor) {
        boolean ok = substationPatroldeviceService.setDailyMonitorStatus(id, dailyMonitor);
        if (ok) {
            return ResponseResult.success();
        } else {
            return ResponseResult.error("修改失败");
        }
    }

    @GetMapping("/getCameraIntegrityRate")
    @ApiOperation("摄像机录像完整率统计")
    public ResponseResult getCameraIntegrityRate(Page<Map<String, Object>> page, String stationId,
                                                 String patrolDeviceName, String channel, String flag) {

        Page<Map<String, Object>> mapPage = substationPatroldeviceService.getCameraStat(page, stationId,
                patrolDeviceName, channel, flag);
        return ResponseResult.successData(mapPage);
    }

    @GetMapping("/getCameraStatByCode")
    @ApiOperation("单个摄像机完整率")
    public ResponseResult getCameraStatByCode(String channelId) {
        String cameraStatByCode = substationPatroldeviceService.getCameraStatByCode(channelId);
        Map<String, Object> map = new HashMap<>();
        long sum = 90 * 24 * 60;
        long duration = Long.parseLong(cameraStatByCode) / 60;
        map.put("rate", (int) (((float) duration / sum) * 100 + 0.5));
        map.put("duration", duration);
        map.put("cycle", 90);
        return ResponseResult.successData(map);
    }

    @GetMapping("/getRobotCamera")
    @ApiOperation("获取机器人的摄像头")
    public ResponseResult getRobotCamera(String patrolDeviceCode) {
        SubstationPatroldevice substationPatroldevice =
                substationPatroldeviceService.getOne(new LambdaQueryWrapper<SubstationPatroldevice>().eq(SubstationPatroldevice::getRobotsCode, patrolDeviceCode).eq(SubstationPatroldevice::getDatastatus, "1"));
        return ResponseResult.successData(substationPatroldevice);
    }

    @GetMapping("/getRobotOnlineRate")
    @ApiOperation("巡视设备累计运行天数")
    public ResponseResult getRobotOnlineRate(Page<Map<String, Object>> page, String stationId,
                                             String patrolDeviceName, String patrolDeviceCode,
                                             String type) {
        //
        //        Page<Map<String, Object>> mapPage = substationPatroldeviceService.getRobotOnlineRate(page, stationId,
        //                patrolDeviceName, patrolDeviceCode, type);
        Page<Map<String, Object>> onlineDurationPage = robotOfflineLogService.getOnlineDurationPage(page, stationId,
                patrolDeviceCode, patrolDeviceName, type);
        return ResponseResult.successData(onlineDurationPage);
    }

    @GetMapping("/getRobotAndUavList")
    @ApiOperation("获取机器人/无人机")
    public ResponseResult getRobotList() {
        LambdaQueryWrapper<SubstationPatroldevice> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(SubstationPatroldevice::getType, "1", "2", "3", "4", "13", "15");
        queryWrapper.select(SubstationPatroldevice::getPatroldeviceId,SubstationPatroldevice::getType, SubstationPatroldevice::getPatroldeviceCode,
                SubstationPatroldevice::getPatroldeviceName);
        List<Map<String, Object>> mapList = substationPatroldeviceService.listMaps(queryWrapper);
        return ResponseResult.successData(mapList);
    }

    @PostMapping("/setEffectiveArea")
    @ApiOperation("设置静默监视有效区域")
    public ResponseResult setEffectiveArea(String type, String id, String effecttivearea) {
        substationPatroldeviceService.setEffectiveArea(type, id, effecttivearea);
        return ResponseResult.success();
    }

    @GetMapping("/exportPatrolDeviceList")
    @ApiOperation("导出巡视设备台账")
    public void exportPatrolDeviceList(String stationId, String type, String patrolDeviceName, String deviceModel,
                                       String manufacturer, HttpServletResponse response) throws IOException {

        substationPatroldeviceService.exportPatrolDeviceList(stationId, type, patrolDeviceName, deviceModel,
                manufacturer, response);
    }

    @GetMapping("/getDvrStorageStatus")
    @ApiOperation("获取硬盘录像机存储数据")
    public ResponseResult getDvrStorageStatus(String rtspUrl) {
        if (StrUtil.isNotBlank(rtspUrl)) {
            String reg = "//([^/]+)";
            Pattern pattern = Pattern.compile(reg);
            Matcher matcher = pattern.matcher(rtspUrl);
            if (!matcher.find()) {
                throw new RuntimeException("rtsp地址错误");
            }
            String group = matcher.group(1);
            String replace = group.replace("@", ":");
            String[] split = replace.split(":");
            String username = split[0];
            String password = split[1];
            String ip = split[2];
            log.info("-------调用硬盘录像机存储方法--------");
            String nvrStatus = CameraUtil.getStorageStatus("haikang", ip, (short) 8000, username, password);
            JSONObject jsonObject = JSONUtil.parseObj(nvrStatus);
            // 硬盘容量
            String dwCapacity = jsonObject.getStr("dwCapacity");
            int capacity = NumberUtil.parseInt(dwCapacity);
            jsonObject.putOpt("dwCapacity", String.format("%.2f", (float) capacity / 1024));
            // 硬盘剩余空间
            String dwFreeSpace = jsonObject.getStr("dwFreeSpace");
            int freeSpace = NumberUtil.parseInt(dwFreeSpace);
            jsonObject.putOpt("dwFreeSpace", String.format("%.2f", (float) freeSpace / 1024));
            // 已用容量
            int usedSpace = capacity - freeSpace;
            jsonObject.putOnce("usedSpace", String.format("%.2f", (float) usedSpace / 1024));
            String rate = String.format("%.2f", ((float) usedSpace / (float) capacity) * 100);
            jsonObject.putOnce("rate", rate);
            return ResponseResult.successData(jsonObject);
        }
        return ResponseResult.successData(null);
    }

    @GetMapping("/login")
    @ApiOperation("登录黑卡摄像机登录")
    public ResponseResult login() {
        List<SubstationPatroldevice> heikaList =
                substationPatroldeviceService.list(new LambdaQueryWrapper<SubstationPatroldevice>().eq(SubstationPatroldevice::getManufacturer, "heika"));
        if (heikaList.size() > 0) {
            JSONArray jsonArray = new JSONArray();
            for (SubstationPatroldevice substationPatroldevice : heikaList) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.putOpt("ip", substationPatroldevice.getIpaddr());
                String reg = "//([^/]+)";
                Pattern pattern = Pattern.compile(reg);
                String channelinfo = substationPatroldevice.getChannelinfo();
                JSONArray jsonArray1 = JSONUtil.parseArray(channelinfo);
                String rtspurl = "";
                if (jsonArray1.size() > 0) {
                    JSONObject jsonObject1 = jsonArray1.getJSONObject(0);
                    rtspurl = jsonObject1.getStr("channel_rtspurl");
                }
                Matcher matcher = pattern.matcher(rtspurl);
                if (!matcher.find()) {
                    continue;
                }
                String group = matcher.group(1);
                int lastAtIndex = group.lastIndexOf('@');
                // 如果找到了@
                if (lastAtIndex != -1) {
                    // 检查@后面是否紧跟着IP地址和端口号，但在这个例子中我们假设没有
                    // 所以直接替换最后一个@为:
                    group = group.substring(0, lastAtIndex) + ":" + group.substring(lastAtIndex + 1);
                } else {
                    log.error("rtsp地址错误");
                }
                String[] split = group.split(":");
                String username = split[0];
                String password = split[1];
                jsonObject.putOpt("username", username);
                jsonObject.putOpt("password", password);
                jsonArray.add(jsonObject);

            }
            if (jsonArray.size() > 0) {
                Map<String, Object> param = new HashMap<>();
                param.put("list", jsonArray.toString());
                String api = "login";
                if (StrUtil.isNotBlank(config.getHeikaApp())) {
                    api = config.getHeikaApp() + "/login";
                }
                com.alibaba.fastjson.JSONObject result = new com.alibaba.fastjson.JSONObject();
                httpUtil.sendHttpPost("json", config.getSdkIp(),
                        config.getHeikaPort(), "", api, param, null);
            }
        }
        return ResponseResult.success();
    }

    @GetMapping("/logout")
    @ApiOperation("注销黑卡摄像机登录")
    public ResponseResult logout() {
        List<SubstationPatroldevice> heikaList =
                substationPatroldeviceService.list(new LambdaQueryWrapper<SubstationPatroldevice>().eq(SubstationPatroldevice::getManufacturer, "heika"));
        if (heikaList.size() > 0) {
            JSONArray jsonArray = new JSONArray();
            for (SubstationPatroldevice substationPatroldevice : heikaList) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.putOpt("ip", substationPatroldevice.getIpaddr());
                String reg = "//([^/]+)";
                Pattern pattern = Pattern.compile(reg);
                String channelinfo = substationPatroldevice.getChannelinfo();
                JSONArray jsonArray1 = JSONUtil.parseArray(channelinfo);
                String rtspurl = "";
                if (jsonArray1.size() > 0) {
                    JSONObject jsonObject1 = jsonArray1.getJSONObject(0);
                    rtspurl = jsonObject1.getStr("channel_rtspurl");
                }
                Matcher matcher = pattern.matcher(rtspurl);
                if (!matcher.find()) {
                    continue;
                }
                String group = matcher.group(1);
                int lastAtIndex = group.lastIndexOf('@');
                // 如果找到了@
                if (lastAtIndex != -1) {
                    // 检查@后面是否紧跟着IP地址和端口号，但在这个例子中我们假设没有
                    // 所以直接替换最后一个@为:
                    group = group.substring(0, lastAtIndex) + ":" + group.substring(lastAtIndex + 1);
                } else {
                    log.error("rtsp地址错误");
                }
                String[] split = group.split(":");
                String username = split[0];
                String password = split[1];
                jsonObject.putOpt("username", username);
                jsonObject.putOpt("password", password);
                jsonArray.add(jsonObject);

            }
            if (jsonArray.size() > 0) {
                Map<String, Object> param = new HashMap<>();
                param.put("list", jsonArray.toString());
                String api = "logout";
                if (StrUtil.isNotBlank(config.getHeikaApp())) {
                    api = config.getHeikaApp() + "/logout";
                }
                com.alibaba.fastjson.JSONObject result = new com.alibaba.fastjson.JSONObject();
                httpUtil.sendHttpPost("json", config.getSdkIp(),
                        config.getHeikaPort(), "", api, param, null);
            }
        }
        return ResponseResult.success();
    }

    @GetMapping("/getVoicePrintByArea")
    @ApiOperation("获取区域下的声纹")
    public ResponseResult getVoicePrintByArea(String stationId, String deviceName, String status) {
        if (StrUtil.isBlank(stationId)) {
            return ResponseResult.error("未传变电站信息");
        }
        LambdaQueryWrapper<SubstationPatroldevice> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SubstationPatroldevice::getStationId, stationId);
        if (StrUtil.isNotBlank(deviceName)) {
            queryWrapper.like(SubstationPatroldevice::getPatroldeviceName, deviceName);
        }
        if (StrUtil.isNotBlank(status)) {
            queryWrapper.eq(SubstationPatroldevice::getOnline, status);
        }
        queryWrapper.eq(SubstationPatroldevice::getType, "14");
        List<Map<String, Object>> maps = substationPatroldeviceService.listMaps(queryWrapper);
        if (maps.size() <= 0) {
            return ResponseResult.successData(null);
        }
        Map<String, List<Map<String, Object>>> deviceList = maps.stream().filter(m -> ObjectUtil.isNotEmpty(m.get(
                "areaName"))).collect(Collectors.groupingBy(m -> m.get("areaName").toString()));
        List<Map<String, Object>> deviceTree = new ArrayList<>();
        for (String key : deviceList.keySet()) {
            Map<String, Object> map = new HashMap<>();
            map.put("name", key);
            map.put("children", deviceList.get(key));
            deviceTree.add(map);
        }
        return ResponseResult.successData(deviceTree);
    }

}
