package com.testor.module.video.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.testor.biz.sys.org.model.domain.SysOrg;
import com.testor.biz.sys.org.service.SysOrgService;
import com.testor.common.constant.IotUrlAttributes;
import com.testor.ddd.safetyControl.application.service.spaceManage.SpaceManageService;
import com.testor.ddd.safetyControl.application.service.spaceManage.SpaceTypeManageService;
import com.testor.ddd.safetyControl.interfaces.model.dto.space.TSafeSpaceDTO;
import com.testor.ddd.safetyControl.interfaces.model.dto.space.TSafeSpaceTypeDTO;
import com.testor.module.video.model.domain.*;
import com.testor.module.video.service.TVideoEquipmentCareService;
import com.testor.module.video.service.TVideoEquipmentInfoService;
import com.testor.module.video.service.VideoAlarmService;
import com.testor.module.video.util.Beans;
import com.testor.module.video.util.RestUtil;
import com.tongtech.tfw.backend.common.biz.models.BaseResponse;
import com.tongtech.tfw.backend.common.biz.models.BaseResponseList;
import com.tongtech.tfw.backend.common.context.ContextUtils;
import com.tongtech.tfw.backend.common.exception.BusinessException;
import com.tongtech.tfw.backend.common.models.supers.SuperController;
import com.tongtech.tfw.backend.common.models.sys.UserInfo;
import com.tongtech.tfw.backend.core.helper.StringHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;

/**
 * (VideoAlarm)视频告警 -- 表控制器
 *
 * @author makejava
 * @since 2022-06-01 11:23:55
 */
@RestController
@AllArgsConstructor
@RequestMapping("/model/videochanel")
@Api(tags = "视频告警表接口", value = "视频告警表")
@Slf4j
public class VideoAlarmController extends SuperController {

    @Autowired
    private VideoAlarmService videoAlarmService;

    @Autowired
    private TVideoEquipmentCareService tVideoEquipmentCareService;

    @Autowired
    private RestUtil restUtil;
    //空间场所
    @Autowired
    private SpaceManageService spaceManageService;
    //空间场所类型
    @Autowired
    private SpaceTypeManageService spaceTypeManageService;

    @Autowired
    private SysOrgService sysOrgService;

    @Autowired
    private TVideoEquipmentInfoService infoService;

    @Autowired
    private TVideoEquipmentCareService careService;

    @GetMapping("enterpriseDeviceChannelTree")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "企业设备通道树 ", notes = "层级说明 1 企业 2 场所3 空间")
    public BaseResponse<List<VideoChannelInfo>> enterpriseDeviceChannelTree(@ApiParam("是否盯防 mark 1是 0否 ") @RequestParam(name = "mark", defaultValue = "0", required = true) Integer mark, @ApiParam("基层粮库id") @RequestParam(name = "orgId", required = false) String orgId) throws ExecutionException, InterruptedException, BusinessException {
        BaseResponse<List<VideoChannelInfo>> result = new BaseResponse<>();
        //如果没有传基层粮库信息，则根据登录用户获取，默认默认展示组织机构下属第一个基层粮库
        if (StringUtils.isBlank(orgId)) {
            //获取登录用户信息
            UserInfo loginUser = ContextUtils.getLoginUser();
            //判断登录用户属于组织的那一集别
            String loginOrgId = loginUser.getOrgId();
            List<VideoChannelInfo> listInfo = this.getCommeListInfo(mark, loginOrgId);
            result.setData(listInfo);
        } else {
            List<VideoChannelInfo> listInfo = this.getCommeListInfo(mark, orgId);
            result.setData(listInfo);
        }
        return result;
    }

    private List<VideoChannelInfo> getCommeListInfo(Integer mark, String loginOrgId) throws BusinessException, ExecutionException, InterruptedException {
        List<VideoChannelInfo> list = new ArrayList();
        SysOrg byId = sysOrgService.getById(loginOrgId);
        if (byId != null) {
            BigDecimal treeLevel = byId.getTreeLevel();
            if (treeLevel != null) {
                int flag = treeLevel.compareTo(BigDecimal.valueOf(3));
                if (flag == -1) {
                    //总公司,获取粮库列表
                    int flag2 = treeLevel.compareTo(BigDecimal.valueOf(2));
                    if (flag2 == 0) {
                        //区域公司
                        List<SysOrg> childrenById = this.getChildrenById(loginOrgId);
                        if (!CollectionUtils.isEmpty(childrenById)) {
                            List<SysOrg> collect = childrenById.stream().filter(orgInfos -> orgInfos.getParentIds().split(",").length > 2).filter(sysOrg -> sysOrg.getParentIds().split(",")[2].equals(loginOrgId)).collect(Collectors.toList());
                            String childrenOrgId = "";
                            for (SysOrg sysOrg : collect) {
                                if (sysOrg.getTreeSort() != null) {
                                    if (sysOrg.getTreeSort().compareTo(BigDecimal.ONE) == 0) {
                                        childrenOrgId = sysOrg.getOrgId();
                                    }
                                }
                            }
                            if (StringUtils.isBlank(childrenOrgId)) {
                                childrenOrgId = collect.get(0).getOrgId();
                            }
                            list = this.getListInfo(mark, childrenOrgId);
                        }
                    } else {
                        //总部
                        List<SysOrg> childrenById = this.getChildrenById(loginOrgId);
                        //获取总部下面的区域公司
                        List<SysOrg> collect = childrenById.stream().filter(orgInfos -> orgInfos.getParentIds().split(",").length == 2).filter(sysOrg -> sysOrg.getParentIds().split(",")[1].equals(loginOrgId)).collect(Collectors.toList());
                        if (!CollectionUtils.isEmpty(collect)) {
                            //获取总部下面第一个区域公司
                            String parentId = "";
                            String childrenOrgId = "";
                            for (SysOrg sysOrg : collect) {
                                if (sysOrg.getTreeSort() != null) {
                                    if (sysOrg.getTreeSort().compareTo(BigDecimal.ONE) == 0) {
                                        parentId = sysOrg.getOrgId();
                                    }
                                }
                            }
                            if (StringUtils.isBlank(parentId)) {
                                parentId = collect.get(0).getOrgId();
                            }
                            String finalParentId = parentId;
                            List<SysOrg> collect2 = childrenById.stream().filter(orgInfos -> orgInfos.getParentIds().split(",").length > 2).filter(sysOrg -> sysOrg.getParentIds().split(",")[2].equals(finalParentId)).collect(Collectors.toList());
                            //获取区域公司下面的第一个粮库
                            if (!CollectionUtils.isEmpty(collect2)) {
                                for (SysOrg sysOrg2 : collect2) {
                                    if (sysOrg2.getTreeSort() != null) {
                                        if (sysOrg2.getTreeSort().compareTo(BigDecimal.ONE) == 0) {
                                            childrenOrgId = sysOrg2.getOrgId();
                                        }
                                    }
                                }
                                if (StringUtils.isBlank(childrenOrgId)) {
                                    childrenOrgId = collect2.get(0).getOrgId();
                                }
                                list = this.getListInfo(mark, childrenOrgId);
                            }

                        }
                    }
                } else if (flag == 0) {
                    //粮库
                    list = this.getListInfo(mark, loginOrgId);
                }
            } else {
                throw new BusinessException("组织结构错误");
            }
        }
        return list;
    }

    private List<SysOrg> getChildrenById(String orgId) {
        QueryWrapper<SysOrg> queryWrapper = new QueryWrapper();
        queryWrapper.eq("is_dept", 0);
        queryWrapper.eq("status", "0");
        return sysOrgService.list(queryWrapper);
    }

    private List<VideoChannelInfo> getListInfo(Integer mark, String orgId) throws ExecutionException, InterruptedException {
        //根据粮库id查询监控设备信息
        QueryWrapper<VideoEquipmentInfo> queryWrapper = new QueryWrapper<>();
        //查询正常的
        //查询正常的
        if (mark != 1) {
            List<Integer> markList = new ArrayList<>();
            markList.add(1);
            markList.add(0);
            queryWrapper.in("is_eye", markList);
        } else {
            queryWrapper.eq("is_eye", 1);
        }
        queryWrapper.eq("org_id", orgId);
        queryWrapper.eq("status", "0");
        //获取监控数据
        List<VideoEquipmentInfo> list = videoAlarmService.list(queryWrapper);
        //可以获取所有的空间类型和场所
        //获取空间类型列表数据
        CompletableFuture<List<TSafeSpaceTypeDTO>> future1 = CompletableFuture.supplyAsync(() -> {
            return spaceTypeManageService.selectList();
        });
        //获取空间位置列表数据
        CompletableFuture<List<TSafeSpaceDTO>> future2 = CompletableFuture.supplyAsync(() -> {
            return spaceManageService.selectList(orgId);
        });
        List<TSafeSpaceTypeDTO> localeManagementList = future1.get();
        List<TSafeSpaceDTO> spatialPositionLedgerList = future2.get();
        //判断是否为空
        List<VideoChannelInfo> lists = new ArrayList<>();
        Set<String> oneList = new HashSet<>();
        Set<String> twoList = new HashSet<>();
        List<String> threeList = new ArrayList<>();
        List<TSafeSpaceDTO> collect = new ArrayList<>();
        //根据数据库中的孙子信息获取父亲和爷爷信息
        List<String> simpleList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            for (VideoEquipmentInfo videoEquipmentInfo : list) {
                String monitorLocation = videoEquipmentInfo.getMonitorLocation();
//                if (monitorLocation != null && monitorLocation.contains(",")) {
                if (monitorLocation != null) {
                    String[] split = videoEquipmentInfo.getMonitorLocation().split(",");
                    for (int i = 0; i < split.length; i++) {
                        String spaceId = split[i];
                        spatialPositionLedgerList.stream().forEach(spaceInfo -> {
                            if (spaceInfo.getId().equals(spaceId) && !simpleList.contains(spaceId)) {
                                collect.add(spaceInfo);
                                simpleList.add(spaceId);
                            }
                        });
                    }
                }
            }
        }
        if (!CollectionUtils.isEmpty(collect)) {
            for (TSafeSpaceDTO tSafeSpaceDTO : collect) {
                oneList.add(tSafeSpaceDTO.getSpaceTypeId());
                twoList.add(tSafeSpaceDTO.getSpaceId());
                threeList.add(tSafeSpaceDTO.getId());
            }
        }
        List<TSafeSpaceDTO> collect1 = spatialPositionLedgerList.stream().filter(spaceInfo -> twoList.contains(spaceInfo.getId())).collect(Collectors.toList());
        //将空间位置信息转换为树状结构
        if (!CollectionUtils.isEmpty(oneList)) {
            for (String typeId : oneList) {
                for (TSafeSpaceTypeDTO tSafeSpaceTypeDTO : localeManagementList) {
                    if (tSafeSpaceTypeDTO.getId().equals(typeId)) {
                        VideoChannelInfo oneLevel = new VideoChannelInfo();
                        oneLevel.setId(tSafeSpaceTypeDTO.getId());
                        oneLevel.setName(tSafeSpaceTypeDTO.getName());
                        oneLevel.setLevel(1);
                        List<VideoChannelInfo> child = new ArrayList<>();
                        for (TSafeSpaceDTO tSafeSpaceDTO : collect1) {
                            if (tSafeSpaceDTO.getSpaceTypeId().equals(typeId)) {
                                VideoChannelInfo twoLevel = new VideoChannelInfo();
                                twoLevel.setId(tSafeSpaceDTO.getId());
                                twoLevel.setName(tSafeSpaceDTO.getName());
                                twoLevel.setLevel(2);
                                List<VideoChannelInfo> childs = new ArrayList<>();
                                for (TSafeSpaceDTO safeSpaceDTO : collect) {
                                    if (safeSpaceDTO.getSpaceId().equals(tSafeSpaceDTO.getId())) {
                                        VideoChannelInfo threeLevel = new VideoChannelInfo();
                                        threeLevel.setId(safeSpaceDTO.getId());
                                        threeLevel.setName(safeSpaceDTO.getName());
                                        threeLevel.setLevel(3);
                                        if (!childs.contains(threeLevel)) {
                                            childs.add(threeLevel);
                                        }
                                    }
                                }
                                twoLevel.setChilds(childs);
                                child.add(twoLevel);
                            }
                        }
                        oneLevel.setChilds(child);
                        lists.add(oneLevel);
                    }
                }
            }
        }
        return lists;
    }

    @GetMapping("enterpriseDeviceChannelTreeVideo")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "根据组织id查询视频通道，查询多个,最多4个")
    public BaseResponse<BaseResponseList<VideoChannelUrl>>
    enterpriseDeviceChannelTreeVideo(@ApiParam("是否盯防 mark 1是 0否 ") @RequestParam(name = "mark", defaultValue = "0", required = true) Integer mark,
                                     @ApiParam("基层粮库id") @RequestParam(name = "orgId", required = false) String orgId,
                                     @ApiParam("当前页数") @RequestParam("page") String page, @ApiParam("当前条数") @RequestParam(name = "size", defaultValue = "4", required = true) String size) throws ExecutionException, InterruptedException {
        BaseResponse<BaseResponseList<VideoChannelUrl>> result = new BaseResponse<>();
        //如果没有传基层粮库信息，则根据登录用户获取，默认默认展示组织机构下属第一个基层粮库
        Long pages =
                StringHelper.isEmpty(page) ? 1l : Long.valueOf(page);
        Long limits = StringHelper.isEmpty(size) ? 4l : Long.valueOf(size);
        Page<VideoEquipmentInfo> resultPage = new Page(pages, limits);
        if (StringUtils.isBlank(orgId)) {
            //获取登录用户信息
            UserInfo loginUser = ContextUtils.getLoginUser();
            //判断登录用户属于组织的那一集别
            String loginOrgId = loginUser.getOrgId();
            SysOrg byId = sysOrgService.getById(loginOrgId);
            if (byId != null) {
                BigDecimal treeLevel = byId.getTreeLevel();
                int flag = treeLevel.compareTo(BigDecimal.valueOf(3));
                if (flag == -1) {
                    //总公司,获取粮库列表
                    List<SysOrg> childrenById = this.getChildrenById(loginOrgId);
                    String childrenOrgId = childrenById.get(0).getOrgId();
                    BaseResponseList<VideoChannelUrl> listInfo = this.getVideoListInfo(mark, childrenOrgId, resultPage);
                    result.setData(listInfo);
                } else if (flag == 1) {
                    //粮库下面的分部门，通过parneids里面获取粮库id
                    String[] split = byId.getParentIds().split(",");
                    String parentId = split[2];
                    BaseResponseList<VideoChannelUrl> listInfo = this.getVideoListInfo(mark, parentId, resultPage);
                    result.setData(listInfo);
                }
            }
        } else {
            BaseResponseList<VideoChannelUrl> listInfo = this.getVideoListInfo(mark, orgId, resultPage);
            result.setData(listInfo);
        }
        return result;
    }

    @PostMapping("enterpriseDeviceChannelTreeVideoByType")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "根据场所类型,场所，设备id，查询4个视频分页接口")
    public BaseResponse<BaseResponseList<VideoChannelUrl>> enterpriseDeviceChannelTreeVideoByType(@RequestBody VideoQueryParam param) throws ExecutionException, InterruptedException {
        BaseResponse<BaseResponseList<VideoChannelUrl>> result = new BaseResponse<>();
        //如果没有传基层粮库信息，则根据登录用户获取，默认默认展示组织机构下属第一个基层粮库
        Long pages =
                StringHelper.isEmpty(param.getPage()) ? 0l : Long.valueOf(param.getPage());
        Long limits = StringHelper.isEmpty(param.getSize()) ? 4l : Long.valueOf(param.getSize());
        Page<VideoEquipmentInfo> resultPage = new Page(pages, limits);
        if (StringUtils.isBlank(param.getOrgId())) {
            //获取登录用户信息
            UserInfo loginUser = ContextUtils.getLoginUser();
            //判断登录用户属于组织的那一集别
            String loginOrgId = loginUser.getOrgId();
            SysOrg byId = sysOrgService.getById(loginOrgId);
            if (byId != null) {
                BigDecimal treeLevel = byId.getTreeLevel();
                int flag = treeLevel.compareTo(BigDecimal.valueOf(3));
                if (flag == -1) {
                    //总公司,获取粮库列表
                    List<SysOrg> childrenById = this.getChildrenById(loginOrgId);
                    String childrenOrgId = childrenById.get(0).getOrgId();
                    param.setOrgId(childrenOrgId);
                    BaseResponseList<VideoChannelUrl> listInfo = this.getVideoListInfoPage(resultPage, param);
                    result.setData(listInfo);
                } else if (flag == 1) {
                    //粮库下面的分部门，通过parneids里面获取粮库id
                    String[] split = byId.getParentIds().split(",");
                    String parentId = split[2];
                    param.setOrgId(parentId);
                    BaseResponseList<VideoChannelUrl> listInfo = this.getVideoListInfoPage(resultPage, param);
                    result.setData(listInfo);
                }
            }
        } else {
            BaseResponseList<VideoChannelUrl> listInfo = this.getVideoListInfoPage(resultPage, param);
            result.setData(listInfo);
        }
        return result;
    }

    @PostMapping("getMonitorInfo")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "获取单个监控设备信息")
    public BaseResponse<BaseResponseList<VideoChannelUrl>> getMonitorInfo(@RequestBody VideoQueryInfoParam infoParam) throws ExecutionException, InterruptedException {
        BaseResponseList<VideoChannelUrl> resultList = new BaseResponseList();
        //todo 查询视频信息
        List<TVideoEquipmentInfo> list = infoService.list(new QueryWrapper<TVideoEquipmentInfo>()
                .eq("device_id", infoParam.getUid()).eq("status", "0").eq("org_id", infoParam.getOrgId()));
        if (!CollectionUtils.isEmpty(list)) {
            List<VideoChannelUrl> lists = new ArrayList<>();
            for (TVideoEquipmentInfo videoEquipmentInfo : list) {
                VideoChannelUrl res;
                //根据id获取视频地址信息
                if (videoEquipmentInfo != null) {
                    if (StringUtils.isNotBlank(videoEquipmentInfo.getDeviceId())) {
                        ResponseEntity<Map> result = restUtil.get(IotUrlAttributes.START_LIVE_STREAM_PARAMETER_PATH + videoEquipmentInfo.getDeviceId(), Map.class);
                        if (result == null) {
                            continue;
                        }
                        Map body = result.getBody();
                        if ("200".equals(body.get("code").toString())) {
                            res = JSONObject.parseObject(JSON.toJSONString(body.get("result")), VideoChannelUrl.class);
                        } else {
                            res = new VideoChannelUrl();
                        }
                    } else {
                        res = new VideoChannelUrl();
                    }
                } else {
                    res = new VideoChannelUrl();
                }
                res.setId(videoEquipmentInfo.getId());
                res.setDeviceId(videoEquipmentInfo.getDeviceId());
                res.setIsEye(videoEquipmentInfo.getIsEye());
                res.setEquipmentName(videoEquipmentInfo.getEquipmentName());
                lists.add(res);
            }
            resultList.setData(lists);
        }
        BaseResponse<BaseResponseList<VideoChannelUrl>> response = new BaseResponse<>();
        response.setData(resultList);
        return response;
    }

    @GetMapping("getMonitorCoorList")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "获取设备坐标列表")
    public BaseResponse<BaseResponseList<VideoParam>> getMonitorCoorList(String orgId) throws ExecutionException, InterruptedException {
        BaseResponseList<VideoParam> resultList = new BaseResponseList();
        //todo 查询视频信息
        List<TVideoEquipmentInfo> list = infoService.list(new QueryWrapper<TVideoEquipmentInfo>()
                .select("coor_x", "coor_y", "coor_z", "device_id", "equipment_name", "position")
                .eq("status", "0").eq("org_id", orgId));
        List<VideoParam> videoParams = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            videoParams = Beans.listToBean(list, VideoParam.class);
        }
        resultList.setData(videoParams);
        resultList.setTotal(videoParams.size());
        BaseResponse<BaseResponseList<VideoParam>> response = new BaseResponse<>();
        response.setData(resultList);
        return response;
    }

    private BaseResponseList<VideoChannelUrl> getVideoListInfoPage(Page<VideoEquipmentInfo> resultPage, VideoQueryParam param) {
        // TODO 根据需求修改查询条件及查询参数

        IPage<VideoEquipmentInfo> list = this.createQueryWrapper(resultPage, param);
        //可以获取所有的空间类型和场所
        //判断是否为空
        BaseResponseList<VideoChannelUrl> resultList = new BaseResponseList();
        List<VideoChannelUrl> lists = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list.getRecords())) {
            VideoChannelUrl res;
            for (VideoEquipmentInfo videoEquipmentInfo : list.getRecords()) {
                //根据id获取视频地址信息
                if (videoEquipmentInfo != null) {
                    if (StringUtils.isNotBlank(videoEquipmentInfo.getDeviceId())) {
                        //ResponseEntity<Map> result = restUtil.get("iotbmp/app/camera/getStartLiveStream?gbDeviceId=" + videoEquipmentInfo.getDeviceId(), Map.class);
                        ResponseEntity<Map> result = restUtil.get(IotUrlAttributes.START_LIVE_STREAM_PARAMETER_PATH + videoEquipmentInfo.getDeviceId(), Map.class);
                        if (result == null) {
                            continue;
                        }
                        Map body = result.getBody();
                        if ("200".equals(body.get("code").toString())) {
                            res = JSONObject.parseObject(JSON.toJSONString(body.get("result")), VideoChannelUrl.class);
                        } else {
                            res = new VideoChannelUrl();
                        }
                    } else {
                        res = new VideoChannelUrl();
                    }
                } else {
                    res = new VideoChannelUrl();
                }
                res.setId(videoEquipmentInfo.getId());
                res.setDeviceId(videoEquipmentInfo.getDeviceId());
                res.setIsEye(videoEquipmentInfo.getIsEye());
                res.setEquipmentName(videoEquipmentInfo.getEquipmentName());
                lists.add(res);
            }

        }
        resultList.setData(lists);
        resultList.setTotal(list.getTotal());
        return resultList;
    }

    private IPage<VideoEquipmentInfo> createQueryWrapper(Page<VideoEquipmentInfo> resultPage, VideoQueryParam param) {
        //空间场所类型
        return videoAlarmService.myPage(resultPage, param);
    }

    private BaseResponseList<VideoChannelUrl> getVideoListInfo(Integer mark, String orgId, Page<VideoEquipmentInfo> resultPage) {
        //根据粮库id查询监控设备信息
        QueryWrapper<VideoEquipmentInfo> queryWrapper = new QueryWrapper<>();
        //查询盯防数据
        if (mark == 1) {
            List<String> deviceIdsByUserId = careService.findDeviceIdsByUserId(getUserId());
            //如果用户盯防列表是空的，查空数据
            if (CollectionUtils.isEmpty(deviceIdsByUserId)) {
                queryWrapper.eq("id", -1);
            }else {
                queryWrapper.in("id", deviceIdsByUserId);
            }
        }
        queryWrapper.eq("org_id", orgId);
        queryWrapper.eq("status", "0");
        // TODO 根据需求修改查询条件及查询参数
        Page<VideoEquipmentInfo> list = videoAlarmService.page(resultPage, queryWrapper);
        //可以获取所有的空间类型和场所
        //判断是否为空
        BaseResponseList<VideoChannelUrl> resultList = new BaseResponseList();
        List<VideoChannelUrl> lists = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list.getRecords())) {
            for (VideoEquipmentInfo videoEquipmentInfo : list.getRecords()) {
                VideoChannelUrl res = new VideoChannelUrl();
                //根据id获取视频地址信息
                if (videoEquipmentInfo != null) {
                    if (StringUtils.isNotBlank(videoEquipmentInfo.getDeviceId())) {
                        ResponseEntity<Map> result = restUtil.get(IotUrlAttributes.START_LIVE_STREAM_PARAMETER_PATH + videoEquipmentInfo.getDeviceId(), Map.class);
                        HttpStatus statusCode = result.getStatusCode();
                        if (statusCode == HttpStatus.OK) {
                            Map body = result.getBody();
                            if ("200".equals(body.get("code").toString())) {
                                res = JSONObject.parseObject(JSON.toJSONString(body.get("result")), VideoChannelUrl.class);
                            }
                        }
                    }
                }
                int isEye = careService.count(new LambdaQueryWrapper<TVideoEquipmentCare>().eq(TVideoEquipmentCare::getUserId, getUserId()).eq(TVideoEquipmentCare::getDeviceId, videoEquipmentInfo.getId()));
                res.setId(videoEquipmentInfo.getId());
                res.setDeviceId(videoEquipmentInfo.getDeviceId());
                res.setIsEye(isEye);
                res.setEquipmentName(videoEquipmentInfo.getEquipmentName());
                lists.add(res);
            }

        }
        resultList.setData(lists);
        resultList.setTotal(list.getTotal());
        return resultList;
    }

    @GetMapping("enterpriseDeviceChannelOneVideo")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "根据国标id查询视频通道")
    public BaseResponse<VideoChannelUrl> getVideoUrlById(@ApiParam("国标id") @RequestParam(name = "deviceId") String deviceId) throws BusinessException {
        BaseResponse<VideoChannelUrl> res = new BaseResponse();
        if (StringUtils.isNotBlank(deviceId)) {
            ResponseEntity<Map> result = restUtil.get(IotUrlAttributes.START_LIVE_STREAM_PARAMETER_PATH + deviceId, Map.class);
            Map body = result.getBody();
            if ("200".equals(body.get("code").toString())) {
                VideoChannelUrl rest = JSONObject.parseObject(JSON.toJSONString(body.get("result")), VideoChannelUrl.class);
                res.setData(rest);
            } else {
                res.setCode(400);
                res.setMsg(body.get("message").toString());
            }
        }
        return res;
    }
//    @GetMapping("enterpriseDeviceChannelVideoList")
//    @ApiOperationSupport(order = 1)
//    @ApiOperation(value = "根据空间场所id查询视频通道列表")
//    public BaseResponse<BaseResponseList<VideoChannelUrl>> getVideoUrlBySpaceId(@ApiParam("空间场所id") @RequestParam(name = "monitorId") String monitorId,@ApiParam("是否盯防 mark 1是 0否 ") @RequestParam(name = "mark", defaultValue = "0", required = true) Integer mark, @ApiParam("当前页数")@RequestParam("page") String page) throws BusinessException {
//        BaseResponse<BaseResponseList<VideoChannelUrl>> result = new BaseResponse<>();
//        //如果没有传基层粮库信息，则根据登录用户获取，默认默认展示组织机构下属第一个基层粮库
//        Long pages=
//                StringHelper.isEmpty(page)?1l:Long.valueOf(page);
//        Long limits=4l;
//        Page<VideoEquipmentInfo> resultPage=new Page(pages,limits);
//        resultPage =videoAlarmService.selectSpaceList(resultPage,mark,monitorId);
//        if (StringUtils.isNotBlank(deviceId)){
//            ResponseEntity<Map> result = restUtil.get("iotbmp/app/camera/getStartLiveStream?gbDeviceId="+deviceId, Map.class);
//            Map body = result.getBody();
//            if ("0".equals(body.get("status"))){
//                List data = (List) body.get("data");
//                VideoChannelUrl rest = JSONObject.parseObject(JSON.toJSONString(data.get(0)),VideoChannelUrl.class);
//                res.setData(rest);
//            }else{
//                throw new BusinessException((String) body.get("msg"));
//            }
//        }
//        return res;
//    }

    @GetMapping("playbackurl")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "根据国标id,开始时间，结束时间，查询回放地址")
    public BaseResponse<String> getPlayBcakUrl(@ApiParam("国标id") @RequestParam(name = "deviceId") String deviceId, @ApiParam("录像开始时间") @RequestParam("startTime") String startTime, @ApiParam("录像结束时间") @RequestParam("endTime") String endTime) throws BusinessException {
        BaseResponse<String> res = new BaseResponse<>();
        if (StringUtils.isBlank(deviceId)) {
            throw new BusinessException("国标id不能为空");
        }
        if (StringUtils.isBlank(startTime)) {
            Date today = new Date(System.currentTimeMillis() - 1000 * 60 * 60 * 24);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
            startTime = simpleDateFormat.format(today);
        }
        if (StringUtils.isBlank(endTime)) {
            Date today = new Date(System.currentTimeMillis());
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
            endTime = simpleDateFormat.format(today);
        }
        ResponseEntity<Map> result = restUtil.get(IotUrlAttributes.QUERY_PLAYBACK_VOD_STREAM+"?sn=" + deviceId + "&startTime=" + startTime + "&endTime=" + endTime+"&type=SHIDE&recordType=all", Map.class);
        Map body = result.getBody();
        if ("0".equals(body.get("status"))) {
            List data = (List) body.get("data");
            if (data.size() > 0) {
                Map map = JSONObject.parseObject(JSON.toJSONString(data.get(0)), Map.class);
                String hlsUrl = (String) map.get("HlsUrl");
                res.setData(hlsUrl);
            }

        }
        return res;
    }


    @GetMapping("enterpriseDeviceChannelList")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "首页重点盯防列表,只需要返回6个")
    public BaseResponse<List<VideoEquipmentInfo>> enterpriseDeviceChannelTreeVideo(String orgId) {
        log.info("enterpriseDeviceChannelList,startTime:{}", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        BaseResponse<List<VideoEquipmentInfo>> result = new BaseResponse<>();
        //如果没有传基层粮库信息，则根据登录用户获取，默认默认展示组织机构下属第一个基层粮库
        //获取登录用户信息
        UserInfo loginUser = ContextUtils.getLoginUser();
        //获取重点盯防设备
        List<String> deviceIdsByUserId = tVideoEquipmentCareService.findDeviceIdsByUserId(loginUser.getUserId());
        if (deviceIdsByUserId != null && deviceIdsByUserId.size() > 0) {


        List<VideoEquipmentInfo> listInfo  = videoAlarmService.list(new QueryWrapper<VideoEquipmentInfo>().eq("status", "0").in("id",deviceIdsByUserId).last("limit 24"));
        if (listInfo != null) {
            for (VideoEquipmentInfo videoEquipmentInfo : listInfo) {
                if (StringUtils.isNotBlank(videoEquipmentInfo.getDeviceId())) {
                    //ResponseEntity<Map> res = restUtil.get("iotbmp/app/camera/getStartLiveStream?gbDeviceId=" + videoEquipmentInfo.getDeviceId(), Map.class);
                    ResponseEntity<Map> res = restUtil.get(IotUrlAttributes.START_LIVE_STREAM_PARAMETER_PATH + videoEquipmentInfo.getDeviceId(), Map.class);
                    if (res != null && res.getBody()!= null) {
                        Map body = res.getBody();
                        if (body.get("code") != null && "200".equals(body.get("code").toString())) {
                            VideoChannelUrl rest = JSONObject.parseObject(JSON.toJSONString(body.get("result")), VideoChannelUrl.class);
                            if (rest != null) {
                                videoEquipmentInfo.setChannelUrl(rest.getHttpFlvUrl());
                            }
                        }
                    }
                }
                //根据位置id返回位置名称
                if (StringUtils.isNotBlank(videoEquipmentInfo.getMonitorLocation())) {
                    String[] split = videoEquipmentInfo.getMonitorLocation().split(",");
                    List<String> monitorLocationName = new ArrayList<>();
                    for (int i = 0; i < split.length; i++) {
                        String s = split[i];
                        //获取区域
                        if (StringUtils.isNotBlank(s)) {
                            TSafeSpaceDTO monitorLocation = spaceManageService.findById(s);
                            //获取场所
                            TSafeSpaceDTO spaceInfo = spaceManageService.findById(monitorLocation.getSpaceId());
                            monitorLocationName.add(spaceInfo.getName() + " > " + monitorLocation.getName());
                        }
                    }
                    videoEquipmentInfo.setMonitorLocationName(monitorLocationName);
                }
            }
        }
        if (!CollectionUtils.isEmpty(listInfo)) {
            for (VideoEquipmentInfo videoEquipmentInfo : listInfo) {
                if (CollectionUtils.isEmpty(videoEquipmentInfo.getMonitorLocationName())) {
                    List<String> list = new ArrayList<>();
                    videoEquipmentInfo.setMonitorLocationName(list);
                }
                if (StringUtils.isBlank(videoEquipmentInfo.getMonitorLocation())) {
                    videoEquipmentInfo.setMonitorLocation("");
                }

            }
        }
        result.setData(listInfo);
        }
        log.info("enterpriseDeviceChannelList,resultTime:{}", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        return result;
    }
}
