package com.ozs.web.controller.accountmanagment;

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.ozs.common.annotation.Log;
import com.ozs.common.core.controller.BaseController;
import com.ozs.common.core.domain.AjaxResult;
import com.ozs.common.core.domain.entity.SysDept;
import com.ozs.common.core.domain.entity.SysDictData;
import com.ozs.common.enums.BusinessType;
import com.ozs.common.exception.base.BaseException;
import com.ozs.common.utils.AppendUtils;
import com.ozs.common.utils.ChineseToPingyin;
import com.ozs.common.utils.IdempotenceUtils;
import com.ozs.common.utils.StringUtils;
import com.ozs.common.utils.file.FileUtils;
import com.ozs.common.utils.http.HttpUtils;
import com.ozs.common.utils.poi.ExcelUtil;
import com.ozs.entity.*;
import com.ozs.entity.response.BaseCameraManagementResponse;
import com.ozs.entity.vo.*;
import com.ozs.service.*;
import com.ozs.system.service.DataScoreUtil;
import com.ozs.system.service.ISysDeptService;
import com.ozs.system.service.ISysDictTypeService;
import com.ozs.utils.CameraUtil;
import com.ozs.web.core.config.GetCameraPreviewURL;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * <p>
 * 相机台账管理表 前端控制器
 * </p>
 *
 * @author ozs
 * @since 2023-02-17
 */
@RestController
@RequestMapping("/service/baseCameraManagement")
@Slf4j
public class BaseCameraManagementController extends BaseController {
    //    public static final String PATTERN = "^[0-9]*$";
    public static final String PATTERN = "^(\\d+.\\d{1,3}|\\d+)$";
    @Resource
    BaseCameraManagementService baseCameraManagementService;
    @Resource
    BaseDeviceDynamicManagementService baseDeviceDynamicManagementService;
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private MsgAlarmService msgAlarmService;
    @Autowired
    private BaseRailwayManagementService baseRailwayManagementService;
    @Autowired
    private IdempotenceUtils idempotenceUtils;
    @Autowired
    private DataScoreUtil dataScoreUtil;
    @Resource
    private BaseUserService baseUserService;

    @Autowired
    private CameraUtil cameraUtil;
    @Autowired
    private ISysDictTypeService dictTypeService;
    @Autowired
    private TerminalHeartbeatLogService terminalHeartbeatLogService;


    /**
     * 所有相机列表+权限
     */
    @GetMapping("/selectCameraAll")
    @Log(title = "相机台账管理", businessType = BusinessType.SELECT)
    public AjaxResult selectCameraAll() {
        BaseCameraManagementVo baseCameraManagementVo = (BaseCameraManagementVo) dataScoreUtil.setDataScore(getUserId(), new BaseCameraManagementVo());
        List<BaseCameraManagementHomeVo> baseCameraManagements = baseCameraManagementService.selectCameraAll(baseCameraManagementVo);
        return AjaxResult.success(baseCameraManagements);
    }

    /**
     * 相机状态修改
     */
    @GetMapping("/updateEnableOrNot")
    @Log(title = "相机台账管理", businessType = BusinessType.UPDATE)
    public AjaxResult updateEnableOrNot(String id, Integer enableOrNot) {
        BaseCameraManagement baseCameraManagement = baseCameraManagementService.getById(id);
        if (!ObjectUtils.isEmpty(baseCameraManagement)) {
            baseCameraManagement.setEnableOrNot(enableOrNot);
            if (baseCameraManagementService.updateById(baseCameraManagement)) {
                return AjaxResult.success();
            } else {
                return AjaxResult.error("修改失败");
            }
        } else {
            return AjaxResult.error("未查询该ID的相机台账信息");
        }
    }


    /**
     * 根据相机编码获取视频url
     */
    @GetMapping("/getCameraCode")
    @Log(title = "相机台账管理", businessType = BusinessType.SELECT)
    public AjaxResult getCameraCode(String cameraCode) {
        LambdaQueryWrapper<BaseCameraManagement> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BaseCameraManagement::getCameraCode, cameraCode);
        BaseCameraManagement baseCameraManagement = baseCameraManagementService.getOne(wrapper);
        return AjaxResult.success(baseCameraManagement);
    }

    @PostMapping(value = "/homeGetInfo")
    @Log(title = "相机台账管理", businessType = BusinessType.SELECT)
    public AjaxResult homeGetInfo(@RequestBody BaseCameraManagementHomeVo baseCameraManagementHomeVo) {
        Integer isRelease = baseCameraManagementHomeVo.getIsRelease();
        Long id = baseCameraManagementHomeVo.getId();
        String cameraCode = baseCameraManagementHomeVo.getCameraCode();
        // isRelease  报警是否解除 1已解除2未解除
        if (!StringUtils.isEmpty(isRelease) && isRelease == 1 && !StringUtils.isEmpty(id)) {
            BaseCameraManagement baseCameraManagement = baseCameraManagementService.getById(id);
            LambdaQueryWrapper<BaseRailwayManagement> queryWrapper = new LambdaQueryWrapper<BaseRailwayManagement>();
            if (!ObjectUtils.isEmpty(baseCameraManagement.getRailwayCode())) {
                queryWrapper.eq(BaseRailwayManagement::getRailwayCode, baseCameraManagement.getRailwayCode());
            }
            BaseRailwayManagement baseRailwayManagement = baseRailwayManagementService.getOne(queryWrapper);
//            SysDept sysDept = deptService.selectDeptById(baseCameraManagement.getDeptId());
//            baseCameraManagement.setDeptName(sysDept.getDeptName());
            baseCameraManagement.setRailwayName(baseRailwayManagement.getRailwayName());
            if (!StringUtils.isEmptySunhh(baseCameraManagement.getInstallMile())) {
                String mils = AppendUtils.stringAppend(baseCameraManagement.getInstallMile());
                baseCameraManagement.setInstallMiles(mils);
            }
            if (!StringUtils.isEmptySunhh(baseCameraManagement.getInstallMile())) {
                String end = AppendUtils.stringAppend(baseCameraManagement.getEndMile());
                baseCameraManagement.setEndMiles(end);
            }
            if (!StringUtils.isEmptySunhh(baseCameraManagement.getBeginMile())) {
                String begin = AppendUtils.stringAppend(baseCameraManagement.getBeginMile());
                baseCameraManagement.setBeginMiles(begin);
            }
            return AjaxResult.success(baseCameraManagement);
        } else if (!StringUtils.isEmpty(isRelease) && isRelease == 2 && !StringUtils.isEmpty(cameraCode)) {
            MsgAlarm msgAlarm = msgAlarmService.selectByCameraCode(cameraCode);
//            LambdaQueryWrapper<BaseCameraManagement> lw = new LambdaQueryWrapper<BaseCameraManagement>();
//            if (!ObjectUtils.isEmpty(msgAlarm.getCameraCode())) {
//                lw.eq(BaseCameraManagement::getCameraCode, msgAlarm.getCameraCode());
//            }
//            BaseCameraManagement baseCameraManagement = baseCameraManagementService.getOne(lw);
//            LambdaQueryWrapper<BaseRailwayManagement> wrapper = new LambdaQueryWrapper<BaseRailwayManagement>();
//            if (!ObjectUtils.isEmpty(baseCameraManagement.getRailwayCode())) {
//                wrapper.eq(BaseRailwayManagement::getRailwayCode, baseCameraManagement.getRailwayCode());
//            }
//            BaseRailwayManagement baseRailwayManagement = baseRailwayManagementService.getOne(wrapper);
            MsgAlarmResp msgAlarmResp = new MsgAlarmResp();
//            BeanUtils.copyProperties(msgAlarm, msgAlarmResp);
//            msgAlarmResp.setRailwayName(baseRailwayManagement.getRailwayName());
//            msgAlarmResp.setDeptId(baseCameraManagement.getDeptId());
//            String begin = AppendUtils.stringAppend(baseCameraManagement.getBeginMile());
//            String end = AppendUtils.stringAppend(baseCameraManagement.getEndMile());
//            String endMile = begin + "-" + end;
//            msgAlarmResp.setBeginMile(endMile);
//            String mile = AppendUtils.stringAppend(baseCameraManagement.getInstallMile());
//            msgAlarmResp.setAlarmMile(mile);
//            msgAlarmResp.setInstallLongitude(baseCameraManagement.getInstallLongitude() + "," + baseCameraManagement.getInstallLatitude());
//            String[] split = msgAlarm.getImageUrl().split(";");
//            ArrayList<String> objects = new ArrayList<>(Arrays.asList(split));
//            msgAlarmResp.setImageUrls(objects);
            return AjaxResult.success(msgAlarmResp);
        }
        return null;
    }

    /**
     * 相机台账管理分页
     *
     * @param baseCameraManagementVo
     * @return
     */
    @PostMapping("/list")
    @Log(title = "相机台账管理", businessType = BusinessType.SELECT)
    public AjaxResult selectBaseAccountManagement(@RequestBody BaseCameraManagementVo baseCameraManagementVo) {
        baseCameraManagementVo = (BaseCameraManagementVo) dataScoreUtil.setDataScore(getUserId(), baseCameraManagementVo);
        if (!ObjectUtils.isEmpty(baseCameraManagementVo.getBeginMileBD())) {
            if (baseCameraManagementVo.getBeginMileBD().toString().matches(PATTERN)) {
                baseCameraManagementVo.setBeginMile(baseCameraManagementVo.getBeginMileBD().multiply(new BigDecimal("1000")).intValue());
            }
        }
        if (!ObjectUtils.isEmpty(baseCameraManagementVo.getEndMileBD())) {
            if (baseCameraManagementVo.getEndMileBD().toString().matches(PATTERN)) {
                baseCameraManagementVo.setEndMile(baseCameraManagementVo.getEndMileBD().multiply(new BigDecimal("1000")).intValue());
            }
        }
        IPage<BaseCameraManagement> page = baseCameraManagementService.queryPage(baseCameraManagementVo);
        page.setTotal(page.getTotal());
        page.setCurrent(page.getCurrent());
        page.setPages(page.getPages());
        List<String> roleKey = baseUserService.getRoleName(getUserId());
        BaseUser baseUser = baseUserService.getUser(getUserId());
        if (!ObjectUtils.isEmpty(page) && page.getRecords().size() > 0) {
            List<BaseCameraManagement> dto1 = page.getRecords().stream().map(o -> {
                LambdaQueryWrapper<BaseRailwayManagement> queryWrapper = new LambdaQueryWrapper<BaseRailwayManagement>();
                if (!ObjectUtils.isEmpty(o.getRailwayCode())) {
                    queryWrapper.eq(BaseRailwayManagement::getRailwayCode, o.getRailwayCode());
                }
                if (!ObjectUtils.isEmpty(o.getOnline())) {
                    o.setOnlineName(o.getOnline() == 2 ? "在线" : "离线");
                }
                if (!ObjectUtils.isEmpty(o.getEnableOrNot())) {
                    o.setEnableOrNotName(o.getEnableOrNot() == 1 ? "启用" : "弃用");
                }
                BaseRailwayManagement baseRailwayManagement = baseRailwayManagementService.getOne(queryWrapper);
//                SysDept sysDept = deptService.selectDeptById(o.getDeptId());
//                o.setDeptName(sysDept.getDeptName());
                o.setRailwayName(baseRailwayManagement.getRailwayName());
                String mils = AppendUtils.stringAppend(o.getInstallMile());
                o.setInstallMiles(mils);
                o.setInstallMileBD(new BigDecimal(o.getInstallMile()).divide(new BigDecimal(1000)).setScale(3, RoundingMode.HALF_UP));
                String end = "";
                if (!StringUtils.isEmptySunhh(o.getEndMile())) {
                    end = AppendUtils.stringAppend(o.getEndMile());
                    o.setEndMiles(end);
                    o.setEndMileBD(new BigDecimal(o.getEndMile()).divide(new BigDecimal(1000)).setScale(3, RoundingMode.HALF_UP));
                }
                String begin = "";
                if (!StringUtils.isEmptySunhh(o.getBeginMile())) {
                    begin = AppendUtils.stringAppend(o.getBeginMile());
                    o.setBeginMiles(begin);
                    o.setBeginMileBD(new BigDecimal(o.getBeginMile()).divide(new BigDecimal(1000)).setScale(3, RoundingMode.HALF_UP));
                }
                o.setLineDirStr(o.getLineDir() == 1 ? "上行" : "下行");
                o.setMilesRange(begin + "~" + end);
                o.setLongitudeAndLatitude(o.getInstallLongitude() + "," + o.getInstallLongitude());
                if (roleKey.size() > 0 || "admin".equals(baseUser.getUserName())) {
                    o.setIsStartRecording(1);
                    for (String s : roleKey) {
                        if ("admin".equals(s) || "admin".equals(baseUser.getUserName())) {
                            o.setIsStartRecording(1);
                            break;
                        } else {
                            o.setIsStartRecording(2);
                        }
                    }
                }
                return o;
            }).collect(Collectors.toList());
            page.setRecords(dto1);
        }
        return AjaxResult.success(page);
    }

    /**
     * 删除相机台账管理信息
     *
     * @param accountManagementIds
     * @return
     */
    @RequestMapping("/remove/{accountManagementIds}")
    @Log(title = "相机台账管理", businessType = BusinessType.DELETE)
    @Transactional
    public AjaxResult removeAccountManagement(@PathVariable List<Long> accountManagementIds) {
        for (Long accountManagementId : accountManagementIds) {
            LambdaQueryWrapper<BaseDeviceDynamicManagement> queryWrapper = new LambdaQueryWrapper<BaseDeviceDynamicManagement>();
            BaseCameraManagement baseCameraManagement = baseCameraManagementService.getById(accountManagementId);
            if (!ObjectUtils.isEmpty(baseCameraManagement.getCameraCode())) {
                queryWrapper.eq(BaseDeviceDynamicManagement::getCameraCode, baseCameraManagement.getCameraCode());
            }
            baseDeviceDynamicManagementService.remove(queryWrapper);
            baseCameraManagementService.removeById(accountManagementId);
        }
        return AjaxResult.success();
    }


    /**
     * HTTP流转RTSP流
     *
     * @param
     * @return
     */
    @GetMapping("/streamConversion")
    @Transactional
    @Log(title = "相机台账管理", businessType = BusinessType.INSERT)
    public AjaxResult streamConversion(String code) {
        cameraUtil.streamConversion(code);
        return AjaxResult.success();
    }

    /**
     * 新增相机台账管理信息
     *
     * @param baseCameraManagement
     * @return
     */
    @PostMapping("/saveAccountManagement")
    @Transactional
    @Log(title = "相机台账管理", businessType = BusinessType.INSERT)
    public AjaxResult saveAccountManagement(@RequestBody BaseCameraManagement baseCameraManagement) {
        String idempotence = idempotenceUtils.getIdempotence(baseCameraManagement.getCameraCode());
        if (StringUtils.isNotEmpty(idempotence)) {
            return error("你的网络卡顿,请不要一直添加!!!");
        }
        idempotenceUtils.createIdempotence(baseCameraManagement.getCameraCode());
        LambdaQueryWrapper<BaseCameraManagement> lw = new LambdaQueryWrapper<>();
        if (!ObjectUtils.isEmpty(baseCameraManagement.getCameraCode())) {
            lw.eq(BaseCameraManagement::getCameraCode, baseCameraManagement.getCameraCode());
        }
        BaseCameraManagement cameraManagement = baseCameraManagementService.getOne(lw);
        if (!ObjectUtils.isEmpty(cameraManagement)) {
            idempotenceUtils.deleteIdempotence(baseCameraManagement.getCameraCode());
            return error("相机台账管理信息相机编码已存在,不能重复添加");
        }
        LambdaQueryWrapper<BaseDeviceDynamicManagement> queryWrapper = new LambdaQueryWrapper<>();
        if (!ObjectUtils.isEmpty(baseCameraManagement.getCameraCode())) {
            queryWrapper.eq(BaseDeviceDynamicManagement::getCameraCode, baseCameraManagement.getCameraCode());
        }
        BaseDeviceDynamicManagement one = baseDeviceDynamicManagementService.getOne(queryWrapper);
        if (!ObjectUtils.isEmpty(one)) {
            idempotenceUtils.deleteIdempotence(baseCameraManagement.getCameraCode());
            return error("设备动态管理表该相机编码已存在,不能重复添加");
        }
        if (!StringUtils.isEmptySunhh(baseCameraManagement.getBeginMileBD())) {
            if (!baseCameraManagement.getBeginMileBD().toString().matches(PATTERN)) {
                return error("监控范围开始里程位置填写格式不正确");
            } else {
                BigDecimal begin = baseCameraManagement.getBeginMileBD().setScale(3, RoundingMode.HALF_UP);
                // BigDecimal begin = BigDecimal.parseDouble(baseCameraManagement.getBeginMile().toString());
                baseCameraManagement.setBeginMile(begin.multiply(new BigDecimal("1000")).intValue());
            }
        }
        if (!StringUtils.isEmptySunhh(baseCameraManagement.getInstallMileBD())) {
            if (!baseCameraManagement.getInstallMileBD().toString().matches(PATTERN)) {
                return error("监控相机安装里程位置填写格式不正确");
            } else {
                BigDecimal install = baseCameraManagement.getInstallMileBD().setScale(3, RoundingMode.HALF_UP);
                // double install = Double.parseDouble(baseCameraManagement.getInstallMile().toString());
                baseCameraManagement.setInstallMile(install.multiply(new BigDecimal("1000")).intValue());
            }
        }
        if (!StringUtils.isEmptySunhh(baseCameraManagement.getEndMileBD())) {
            if (!baseCameraManagement.getEndMileBD().toString().matches(PATTERN)) {
                return error("监控范围结束里程位置填写格式不正确");
            } else {
                BigDecimal end = baseCameraManagement.getEndMileBD().setScale(3, RoundingMode.HALF_UP);
                // double end = Double.parseDouble(baseCameraManagement.getEndMile().toString());
                baseCameraManagement.setEndMile(end.multiply(new BigDecimal("1000")).intValue());
            }
        }
//        Integer beginMile = 0;
//        Integer endMile = 0;
//        if (!StringUtils.isEmptySunhh(baseCameraManagement.getBeginMile())){
//            beginMile = baseCameraManagement.getBeginMile();
//        }
//        if (!StringUtils.isEmptySunhh(baseCameraManagement.getEndMile())){
//            endMile = baseCameraManagement.getEndMile();
//        }
//        if (beginMile > endMile) {
//            return error("监控范围开始里程位置不能大于监控范围结束里程位置");
//        }
        baseCameraManagement.setCreateBy(getUserId());
        baseCameraManagement.setUpdateBy(getUserId());
        BaseDeviceDynamicManagement baseDynamicManagement = new BaseDeviceDynamicManagement();
        baseDynamicManagement.setCameraCode(baseCameraManagement.getCameraCode());
        baseDynamicManagement.setUpdateBy(getUserId());
        baseDynamicManagement.setCreateBy(getUserId());
//        String start = HttpUtils.sendGet(CameraUtil.startRecording(baseCameraManagement.getCameraCode(), baseCameraManagement.getChannel()));
//        if (start.startsWith(baseCameraManagement.getCameraCode() + "/" + baseCameraManagement.getChannel())) {
//            baseCameraManagement.setStartRecording(1);
//            baseCameraManagement.setTaskId(start);
//        } else {
//            baseCameraManagement.setStartRecording(2);
//        }
        if (baseCameraManagementService.save(baseCameraManagement) && baseDeviceDynamicManagementService.save(baseDynamicManagement)) {
            idempotenceUtils.deleteIdempotence(baseCameraManagement.getCameraCode());
            return AjaxResult.success();
        }
        idempotenceUtils.deleteIdempotence(baseCameraManagement.getCameraCode());
        return AjaxResult.error();
    }

    /**
     * 修改相机台账管理信息
     *
     * @param baseCameraManagement
     * @return
     */
    @PostMapping("/editAccountManagement")
    @Log(title = "相机台账管理", businessType = BusinessType.UPDATE)
    public AjaxResult editAccountManagement(@RequestBody BaseCameraManagement baseCameraManagement) {
        LambdaQueryWrapper<BaseCameraManagement> lw = new LambdaQueryWrapper<BaseCameraManagement>();
        if (!ObjectUtils.isEmpty(baseCameraManagement.getCameraCode())) {
            lw.eq(BaseCameraManagement::getCameraCode, baseCameraManagement.getCameraCode());
        }
        BaseCameraManagement cameraManagement = baseCameraManagementService.getOne(lw);
        if (!ObjectUtils.isEmpty(cameraManagement) && !cameraManagement.getId().equals(baseCameraManagement.getId())) {
            return error("相机编码已存在,不能进行修改操作");
        }
        if (!StringUtils.isEmptySunhh(baseCameraManagement.getBeginMileBD())) {
            if (!baseCameraManagement.getBeginMileBD().toString().matches(PATTERN)) {
                return error("监控范围开始里程位置填写格式不正确");
            } else {
                BigDecimal begin = baseCameraManagement.getBeginMileBD().setScale(3, RoundingMode.HALF_UP);
                // BigDecimal begin = BigDecimal.parseDouble(baseCameraManagement.getBeginMile().toString());
                baseCameraManagement.setBeginMile(begin.multiply(new BigDecimal("1000")).intValue());
            }
        } else {
            baseCameraManagement.setBeginMile(0);
        }
        if (!StringUtils.isEmptySunhh(baseCameraManagement.getInstallMileBD())) {
            if (!baseCameraManagement.getInstallMileBD().toString().matches(PATTERN)) {
                return error("监控相机安装里程位置填写格式不正确");
            } else {
                BigDecimal install = baseCameraManagement.getInstallMileBD().setScale(3, RoundingMode.HALF_UP);
                // double install = Double.parseDouble(baseCameraManagement.getInstallMile().toString());
                baseCameraManagement.setInstallMile(install.multiply(new BigDecimal("1000")).intValue());
            }
        } else {
            baseCameraManagement.setInstallMile(0);
        }
        if (!StringUtils.isEmptySunhh(baseCameraManagement.getEndMileBD())) {
            if (!baseCameraManagement.getEndMileBD().toString().matches(PATTERN)) {
                return error("监控范围结束里程位置填写格式不正确");
            } else {
                BigDecimal end = baseCameraManagement.getEndMileBD().setScale(3, RoundingMode.HALF_UP);
                // double end = Double.parseDouble(baseCameraManagement.getEndMile().toString());
                baseCameraManagement.setEndMile(end.multiply(new BigDecimal("1000")).intValue());
            }
        } else {
            baseCameraManagement.setEndMile(0);
        }
//        Integer beginMile = 0;
//        Integer endMile = 0;
//        if (!StringUtils.isEmptySunhh(baseCameraManagement.getBeginMile())){
//            beginMile = baseCameraManagement.getBeginMile();
//        }
//        if (!StringUtils.isEmptySunhh(baseCameraManagement.getEndMile())){
//            endMile = baseCameraManagement.getEndMile();
//        }
//        if (beginMile > endMile) {
//            return error("监控范围开始里程位置不能大于监控范围结束里程位置");
//        }
        baseCameraManagement.setUpdateBy(getUserId());
        LambdaQueryWrapper<BaseDeviceDynamicManagement> queryWrapper = new LambdaQueryWrapper<BaseDeviceDynamicManagement>();
        BaseCameraManagement management = baseCameraManagementService.getById(baseCameraManagement.getId());
        if (!ObjectUtils.isEmpty(management.getCameraCode())) {
            queryWrapper.eq(BaseDeviceDynamicManagement::getCameraCode, management.getCameraCode());
        }
        BaseDeviceDynamicManagement one = baseDeviceDynamicManagementService.getOne(queryWrapper);
        if (ObjectUtils.isEmpty(one)) {
            return error("设备动态管理表没有该相机编码");
        }
        one.setCameraCode(baseCameraManagement.getCameraCode());
        if (baseCameraManagementService.updateById(baseCameraManagement) && baseDeviceDynamicManagementService.updateById(one)) {
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }

    @GetMapping(value = "/{id}")
    @Log(title = "相机台账管理", businessType = BusinessType.MESSAGE)
    public AjaxResult getInfo(@PathVariable Long id) throws InterruptedException {
        BaseCameraManagement baseCameraManagement = baseCameraManagementService.getById(id);
        LambdaQueryWrapper<BaseRailwayManagement> queryWrapper = new LambdaQueryWrapper<BaseRailwayManagement>();
        if (!ObjectUtils.isEmpty(baseCameraManagement.getRailwayCode())) {
            queryWrapper.eq(BaseRailwayManagement::getRailwayCode, baseCameraManagement.getRailwayCode());
        }
        BaseRailwayManagement baseRailwayManagement = baseRailwayManagementService.getOne(queryWrapper);
//        SysDept sysDept = deptService.selectDeptById(baseCameraManagement.getDeptId());
//        baseCameraManagement.setDeptName(sysDept.getDeptName());
        baseCameraManagement.setRailwayName(baseRailwayManagement.getRailwayName());
        if (!StringUtils.isEmptySunhh(baseCameraManagement.getInstallMile())) {
            String mils = AppendUtils.stringAppend(baseCameraManagement.getInstallMile());
            baseCameraManagement.setInstallMiles(mils);
        }
        String end = "";
        if (!StringUtils.isEmptySunhh(baseCameraManagement.getEndMile())) {
            end = AppendUtils.stringAppend(baseCameraManagement.getEndMile());
            baseCameraManagement.setEndMiles(end);
        }
        String begin = "";
        if (!StringUtils.isEmptySunhh(baseCameraManagement.getBeginMile())) {
            begin = AppendUtils.stringAppend(baseCameraManagement.getBeginMile());
            baseCameraManagement.setBeginMiles(begin);
        }
        if (!StringUtils.isEmptySunhh(baseCameraManagement.getInstallMile())) {
            baseCameraManagement.setInstallMileBD(new BigDecimal(baseCameraManagement.getInstallMile()).divide(new BigDecimal(1000)).setScale(3, RoundingMode.HALF_UP));
        }
        if (!StringUtils.isEmptySunhh(baseCameraManagement.getBeginMile())) {
            baseCameraManagement.setBeginMileBD(new BigDecimal(baseCameraManagement.getBeginMile()).divide(new BigDecimal(1000)).setScale(3, RoundingMode.HALF_UP));
        }
        if (!StringUtils.isEmptySunhh(baseCameraManagement.getEndMile())) {
            baseCameraManagement.setEndMileBD(new BigDecimal(baseCameraManagement.getEndMile()).divide(new BigDecimal(1000)).setScale(3, RoundingMode.HALF_UP));
        }
        baseCameraManagement.setLineDirStr(baseCameraManagement.getLineDir() == 1 ? "上行" : "下行");
        baseCameraManagement.setMilesRange(begin + "-" + end);
        baseCameraManagement.setLongitudeAndLatitude(baseCameraManagement.getInstallLongitude() + "," + baseCameraManagement.getInstallLongitude());
        return AjaxResult.success(baseCameraManagement);
//        String cameraPreviewURL = GetCameraPreviewURL.getPreviewURLs();
//        log.info("-------------------------------->>>>>" + cameraPreviewURL);
//        JSONObject outJson = JSONObject.parse(cameraPreviewURL);
//        log.info("-------------------------------->>>>>outJson------" + outJson);
//        JSONObject data = outJson.getJSONObject("data");
//        log.info("-------------------------------->>>>>data------" + data);
//        String urls = data.getString("url");
//        log.info("-------------------------------->>>>>urls------" + urls);
//        TimeUnit.SECONDS.sleep(5);
//        String msg = HttpUtils.sendGet("http://10.48.36.47:9080/rtsp/api/pull?target=" + urls + "&streamPath=01ea43e6676f4e47bd6c5cd9e02aa006/01ea43e6676f4e47bd6c5cd9e02aa006&save=0");
////        String msg = HttpUtils.sendGet("http://10.48.36.47:9080/api/gateway/stop?stream=01ea43e6676f4e47bd6c5cd9e02aa006/01ea43e6676f4e47bd6c5cd9e02aa006");
//        return AjaxResult.success(msg);
    }

    /**
     * ***********************   弃用   ***********************
     *
     * @param cameraCode
     * @return
     */
    @GetMapping("/getDate/{cameraCode}")
    @Log(title = "相机台账管理", businessType = BusinessType.OTHER)
    public AjaxResult getDate(@PathVariable String cameraCode) {
        LambdaQueryWrapper<BaseCameraManagement> lw = new LambdaQueryWrapper<BaseCameraManagement>();
        if (!ObjectUtils.isEmpty(cameraCode)) {
            lw.eq(BaseCameraManagement::getCameraCode, cameraCode);
        }
        BaseCameraManagement baseCameraManagement = baseCameraManagementService.getOne(lw);
        LambdaQueryWrapper<BaseRailwayManagement> wrapper = new LambdaQueryWrapper<BaseRailwayManagement>();
        if (!ObjectUtils.isEmpty(baseCameraManagement.getRailwayCode())) {
            wrapper.eq(BaseRailwayManagement::getRailwayCode, baseCameraManagement.getRailwayCode());
        }
        BaseRailwayManagement baseRailwayManagement = baseRailwayManagementService.getOne(wrapper);
        if (ObjectUtils.isEmpty(baseRailwayManagement)) {
            return error("线路表中没有该线路编码:" + baseCameraManagement.getRailwayCode() + "的数据");
        }
        LambdaQueryWrapper<BaseDeviceDynamicManagement> queryWrapper = new LambdaQueryWrapper<BaseDeviceDynamicManagement>();
        if (!ObjectUtils.isEmpty(baseCameraManagement.getCameraCode())) {
            queryWrapper.eq(BaseDeviceDynamicManagement::getCameraCode, baseCameraManagement.getCameraCode());
        }
        BaseDeviceDynamicManagement baseDeviceDynamicManagement = baseDeviceDynamicManagementService.getOne(queryWrapper);
        if (ObjectUtils.isEmpty(baseDeviceDynamicManagement)) {
            return error("设备动态管理表中没有该相机编码:" + baseCameraManagement.getCameraCode() + "的数据");
        }
        LambdaQueryWrapper<MsgAlarm> wrapper1 = new LambdaQueryWrapper<MsgAlarm>();
        if (!ObjectUtils.isEmpty(baseCameraManagement.getCameraCode())) {
//            wrapper1.eq(MsgAlarm::getCameraCode, baseCameraManagement.getCameraCode());
            wrapper1.orderByDesc(MsgAlarm::getAlarmTime);
        }
        List<MsgAlarm> list1 = msgAlarmService.list(wrapper1);
        List<Object> list = new ArrayList<>();
        list.add(baseRailwayManagement.getRailwayName());
        list.add(AppendUtils.stringAppend(baseCameraManagement.getInstallMile()));
        list.add(baseCameraManagement.getLineDir());
        list.add(baseCameraManagement.getCameraCode());
        list.add(baseDeviceDynamicManagement.getElectricity());
        if (list1.size() <= 0) {
            list.add(1);
        } else {
            MsgAlarm msgAlarm = list1.get(0);
            list.add(msgAlarm.getIsRelease());
        }
        return AjaxResult.success(list);
    }

    /**
     * 台账管理导入
     *
     * @param file
     * @param updateSupport
     * @return
     * @throws Exception
     */
    @PostMapping("/importBaseAccountManagement")
    @Log(title = "相机台账管理", businessType = BusinessType.IMPORT)
    public AjaxResult importBaseAccountManagement(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<BaseCameraManagementVos> util = new ExcelUtil<BaseCameraManagementVos>(BaseCameraManagementVos.class);
        List<BaseCameraManagementVos> accountManageList = util.importExcel(file.getInputStream());
        String message = baseCameraManagementService.importBaseAccountManagement(accountManageList, updateSupport, getUserId());
        return AjaxResult.success(message);
    }

    /**
     * 导出台账管理
     *
     * @param response
     */
    @PostMapping("/exportBaseAccountManagement")
    @Log(title = "相机台账管理", businessType = BusinessType.EXPORT)
    public void exportBaseAccountManagement(HttpServletResponse response, @RequestBody BaseCameraManagementVo baseCameraManagementVo) {
        baseCameraManagementVo = (BaseCameraManagementVo) dataScoreUtil.setDataScore(getUserId(), baseCameraManagementVo);
        if (!ObjectUtils.isEmpty(baseCameraManagementVo.getBeginMile())) {
            baseCameraManagementVo.setBeginMile(baseCameraManagementVo.getBeginMile() * 1000);
        }
        if (!ObjectUtils.isEmpty(baseCameraManagementVo.getEndMile())) {
            baseCameraManagementVo.setEndMile(baseCameraManagementVo.getEndMile() * 1000);
        }
        List<BaseCameraManagement> baseCameraManagementList = baseCameraManagementService.baseCameraManagementList(baseCameraManagementVo);
        for (BaseCameraManagement baseCameraManagement : baseCameraManagementList) {
//            SysDept sysDept = deptService.selectDeptById(baseCameraManagement.getDeptId());
//            baseCameraManagement.setDeptName(sysDept.getDeptName());
            LambdaQueryWrapper<BaseRailwayManagement> queryWrapper = new LambdaQueryWrapper<BaseRailwayManagement>();
            if (!ObjectUtils.isEmpty(baseCameraManagement.getRailwayCode())) {
                queryWrapper.eq(BaseRailwayManagement::getRailwayCode, baseCameraManagement.getRailwayCode());
            }
            BaseRailwayManagement baseRailwayManagement = baseRailwayManagementService.getOne(queryWrapper);
            baseCameraManagement.setRailwayName(baseRailwayManagement.getRailwayName());
            if (!StringUtils.isEmptySunhh(baseCameraManagement.getInstallMile())) {
                String mils = AppendUtils.stringAppend(baseCameraManagement.getInstallMile());
                baseCameraManagement.setInstallMiles(mils);
            }
            String end = "";
            if (!StringUtils.isEmptySunhh(baseCameraManagement.getEndMile())) {
                end = AppendUtils.stringAppend(baseCameraManagement.getEndMile());
                baseCameraManagement.setEndMiles(end);
            }
            String begin = "";
            if (!StringUtils.isEmptySunhh(baseCameraManagement.getBeginMile())) {
                begin = AppendUtils.stringAppend(baseCameraManagement.getBeginMile());
                baseCameraManagement.setBeginMiles(begin);
            }
            if (!ObjectUtils.isEmpty(baseCameraManagement.getEnableOrNot())) {
                baseCameraManagement.setEnableOrNotName(baseCameraManagement.getEnableOrNot() == 1 ? "启用" : "弃用");
            }
            if (!StringUtils.isEmpty(baseCameraManagement.getMonitoringDirection())) {
                List<SysDictData> data = dictTypeService.selectDictDataByType("monitoring_direction");
                for (SysDictData datum : data) {
                    if (datum.getDictValue().equals(baseCameraManagement.getMonitoringDirection().toString())) {
                        baseCameraManagement.setMonitoringDirectionName(datum.getDictLabel());
                    }
                }
            }
        }
        ExcelUtil<BaseCameraManagement> util = new ExcelUtil<>(BaseCameraManagement.class);
        util.exportExcel(response, baseCameraManagementList, "台账管理相机数据");
    }


    @GetMapping("/downloaExcel")
    @Log(title = "相机台账管理", businessType = BusinessType.OTHER)
    public void downloadZip(HttpServletResponse response) {
        try {
            InputStream resourceAsStream = this.getClass().getResourceAsStream("/template/baseCameraManagement.xlsx");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, "相机台账管理信息模板.xlsx");
            FileUtils.writeBytesByInput(resourceAsStream, response.getOutputStream());
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

    @GetMapping("/api/records/{cameraCode}")
    @Log(title = "相机台账管理", businessType = BusinessType.OTHER)
    public AjaxResult apiRecords(@PathVariable @NotNull(message = "相机编码不能为空") String cameraCode) {
        LambdaQueryWrapper<BaseCameraManagement> lw = new LambdaQueryWrapper<BaseCameraManagement>();
        lw.eq(BaseCameraManagement::getCameraCode, cameraCode);
        BaseCameraManagement one = baseCameraManagementService.getOne(lw);
        if (ObjectUtils.isEmpty(one)) {
            throw new BaseException("相机编号【" + cameraCode + "】不存在");
        }
        return new AjaxResult(200, "ok", CameraUtil.getPlayFlv(cameraCode, one.getChannel()));
    }

    @GetMapping("/api/invite/{cameraCode}")
    @Log(title = "相机台账管理", businessType = BusinessType.OTHER)
    public AjaxResult invite(@PathVariable @NotNull(message = "相机编码不能为空") String cameraCode) {
        LambdaQueryWrapper<BaseCameraManagement> lw = new LambdaQueryWrapper<BaseCameraManagement>();
        lw.eq(BaseCameraManagement::getCameraCode, cameraCode);
        BaseCameraManagement one = baseCameraManagementService.getOne(lw);
        if (ObjectUtils.isEmpty(one)) {
            throw new BaseException("相机编号【" + cameraCode + "】不存在");
        }
        return new AjaxResult(200, "ok", CameraUtil.invite(cameraCode, one.getChannel()));
    }


    @GetMapping("/api/records/{cameraCode}/{flay}")
    @Log(title = "相机台账管理", businessType = BusinessType.OTHER)
    public AjaxResult apiRecords(@PathVariable @NotNull(message = "相机编码不能为空") String cameraCode,
                                 @PathVariable @NotNull(message = "条件不能为空") boolean flay) {
        LambdaQueryWrapper<BaseCameraManagement> lw = new LambdaQueryWrapper<BaseCameraManagement>();
        lw.eq(BaseCameraManagement::getCameraCode, cameraCode);
        BaseCameraManagement one = baseCameraManagementService.getOne(lw);
        if (ObjectUtils.isEmpty(one)) {
            throw new BaseException("相机编号【" + cameraCode + "】不存在");
        }
        return new AjaxResult(200, "ok", CameraUtil.getPlayFlv(cameraCode, one.getChannel(), flay));
    }

    @GetMapping("/api/getRecordByAlarmId")
    @Log(title = "相机台账管理", businessType = BusinessType.OTHER)
    public AjaxResult getRecordByAlarmId(@RequestParam("alarmId") String alarmId) {
        LambdaQueryWrapper<MsgAlarm> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MsgAlarm::getAlarmId, alarmId);
        MsgAlarm msgAlarm = msgAlarmService.getOne(wrapper);
        LambdaQueryWrapper<BaseRailwayManagement> wrapperRailway = new LambdaQueryWrapper<>();
        if (!ObjectUtils.isEmpty(msgAlarm.getRailwayCode())) {
            wrapperRailway.eq(BaseRailwayManagement::getRailwayCode, msgAlarm.getRailwayCode());
        }
        BaseRailwayManagement baseRailwayManagement = baseRailwayManagementService.getOne(wrapperRailway);
        if (StringUtils.isEmptySunhh(baseRailwayManagement)) {
            return AjaxResult.error("报警线路编码：" + msgAlarm.getRailwayCode() + "不存在！");
        }
        // 查询里程位置最近的相机
        LambdaQueryWrapper<BaseCameraManagement> lw = new LambdaQueryWrapper<>();
        if (!StringUtils.isEmptySunhh(msgAlarm.getRailwayCode())) {
            lw.eq(BaseCameraManagement::getRailwayCode, msgAlarm.getRailwayCode());
        }
        if (!StringUtils.isEmptySunhh(msgAlarm.getAlarmMile())) {
            lw.le(BaseCameraManagement::getBeginMile, msgAlarm.getAlarmMile());
            lw.gt(BaseCameraManagement::getEndMile, msgAlarm.getAlarmMile());
        }
        lw.eq(BaseCameraManagement::getLineDir, msgAlarm.getLineDir());
//        lw.eq(BaseCameraManagement::getOnline, 2);
        lw.eq(BaseCameraManagement::getEnableOrNot, 1);
        List<BaseCameraManagement> baseCameraManagementList = baseCameraManagementService.list(lw);
        BaseCameraManagement baseCameraManagement = new BaseCameraManagement();
        if (!StringUtils.isEmptySunhh(baseCameraManagementList) && baseCameraManagementList.size() > 0) {
            baseCameraManagement = baseCameraManagementList.get(0);
            return new AjaxResult(200, "ok", baseCameraManagement.getUrl());
        } else {
            return AjaxResult.error("报警里程范围内：" + msgAlarm.getAlarmMile() + "没有可查看的相机！");
        }
    }

    @PostMapping("/api/record")
    @Log(title = "相机台账管理", businessType = BusinessType.OTHER)
    public AjaxResult record(@Validated @RequestBody BaseCameraResVo vo) {
        LambdaQueryWrapper<BaseCameraManagement> lw = new LambdaQueryWrapper<BaseCameraManagement>();
        lw.eq(BaseCameraManagement::getCameraCode, vo.getCameraCode());
        BaseCameraManagement one = baseCameraManagementService.getOne(lw);
        if (ObjectUtils.isEmpty(one)) {
            throw new BaseException("相机编号【" + vo.getCameraCode() + "】不存在");
        }
        return new AjaxResult(200, "ok", CameraUtil.getRecordList(one.getCameraCode(), vo.getStartTime(), vo.getEntTime()));
    }

    @GetMapping("/api/recordsList")
    @Log(title = "相机台账管理", businessType = BusinessType.OTHER)
    public AjaxResult apiRecordsList(@RequestBody
                                     @NotNull(message = "相机编码不能为空")
                                             List<String> cameraCodes) {
        List<String> list = new ArrayList<>();
        for (String cameraCode : cameraCodes) {
            LambdaQueryWrapper<BaseCameraManagement> lw = new LambdaQueryWrapper<BaseCameraManagement>();
            lw.eq(BaseCameraManagement::getCameraCode, cameraCode);
            BaseCameraManagement one = baseCameraManagementService.getOne(lw);
            if (ObjectUtils.isEmpty(one)) {
                throw new BaseException("相机编号【" + cameraCode + "】不存在");
            }
            String playFlv = null;
            if (list.size() > 5) {
                playFlv = CameraUtil.getPlayFlv(cameraCode, one.getChannel(), false);
            } else {
                playFlv = CameraUtil.getPlayFlv(cameraCode, one.getChannel());
            }
            list.add(playFlv);
        }

        return new AjaxResult(200, "ok", list);
    }


    @PostMapping("/api/invite")
    public AjaxResult apiInvite(@Validated @RequestBody BaseCameraResVo vo) {
        LambdaQueryWrapper<BaseCameraManagement> lw = new LambdaQueryWrapper<BaseCameraManagement>();
        lw.eq(BaseCameraManagement::getCameraCode, vo.getCameraCode());
        BaseCameraManagement one = baseCameraManagementService.getOne(lw);
        if (ObjectUtils.isEmpty(one)) {
            throw new BaseException("相机编号【" + vo.getCameraCode() + "】不存在");
        }
        // CameraUtil.historyPlayList(one.getChannel(), vo.getStartTime(), vo.getEntTime(), caneraConfig.getMappingUrl())
        return success();
    }

//    @PostMapping("/api/play")
//    @Log(title = "相机台账管理", businessType = BusinessType.OTHER)
//    public AjaxResult play(@Validated @RequestBody BaseCameraResVo vo) {
//        LambdaQueryWrapper<BaseCameraManagement> lw = new LambdaQueryWrapper<BaseCameraManagement>();
//        lw.eq(BaseCameraManagement::getCameraCode, vo.getCameraCode());
//        BaseCameraManagement one = baseCameraManagementService.getOne(lw);
//        if (ObjectUtils.isEmpty(one)) {
//            throw new BaseException("相机编号【" + vo.getCameraCode() + "】不存在");
//        }
//        String path = CameraUtil.historyPlayListStr(one.getChannel(), vo.getStartTime(), vo.getEntTime());
//        if (org.apache.commons.lang3.StringUtils.isBlank(path)) {
//            throw new BaseException("当前相机无视频录像");
//        }
//        return new AjaxResult(200, "ok", serverConfig.getUrl() + path);
////        return success(CameraUtil.historyPlayList(one.getChannel(), vo.getStartTime(), vo.getEntTime()));
//    }

    @GetMapping("/totalNumberOfDevices")
    @Log(title = "相机台账管理", businessType = BusinessType.OTHER)
    public AjaxResult totalNumberOfDevices() {
        long count = baseCameraManagementService.count();
        return success(count);
    }

    /**
     * 视频服务树形结构
     *
     * @param
     * @param
     * @param
     * @return
     */
    @PostMapping("/cameraTree")
    @Log(title = "相机台账管理", businessType = BusinessType.OTHER)
    public AjaxResult cameraTree(@RequestBody CameraTreeVo cameraTreeVo) {
        //cameraTreeVo = (CameraTreeVo) dataScoreUtil.setDataScore(getUserId(), cameraTreeVo);
        int count = 0;
        if (!ObjectUtils.isEmpty(cameraTreeVo.getMils())) {
            cameraTreeVo.setMils(new BigDecimal(cameraTreeVo.getMils()).multiply(new BigDecimal(1000)).setScale(0, BigDecimal.ROUND_DOWN).toString());
        }
        CameraTree cameraTree = baseDeviceDynamicManagementService.cameraTree(cameraTreeVo);
        List<CameraTree> children = cameraTree.getChildren();
        children.sort(new Comparator<CameraTree>() {
            @Override
            public int compare(CameraTree o1, CameraTree o2) {
                String name1 = ChineseToPingyin.convertHanziToPinyin(o1.getName());
                String substring1 = name1.substring(0, 1);
                String name2 = ChineseToPingyin.convertHanziToPinyin(o2.getName());
                String substring2 = name2.substring(0, 1);
                return substring1.compareTo(substring2);
            }
        });


        for (CameraTree child : children) {
            List<CameraTree> children1 = child.getChildren();
            children1.sort(new Comparator<CameraTree>() {
                @Override
                public int compare(CameraTree o1, CameraTree o2) {
                    int i = o1.getMileage() - o2.getMileage();
                    if (i == 0) {
                        String[] split = o1.getName().split("-");
                        return "上行".equals(split[1]) ? -1 : 1;
                    } else {
                        return i;
                    }
                }
            });
            for (CameraTree tree : children1) {
                List<CameraTree> children2 = tree.getChildren();
                if (children2.size() < 2) {
                    String code = children2.get(0).getCode();
                    tree.setCode(code);
                    children2.remove(0);
                } else {
                    for (CameraTree cameraTree1 : children2) {
                        count = count + 1;
                        cameraTree1.setName("相机" + count);
                    }
                    count = 0;
                }
            }
        }
        return success(cameraTree);
    }

    @GetMapping("/endRecording/{id}")
    @Log(title = "相机台账管理", businessType = BusinessType.OTHER)
    public AjaxResult endRecording(@PathVariable Long id) {
        BaseCameraManagement baseCameraManagement = baseCameraManagementService.getById(id);
        if (ObjectUtils.isEmpty(baseCameraManagement)) {
            return error("查不到该ID的相机台账数据!!!");
        }
        log.info("endRecording------------" + baseCameraManagement.getTaskId());
        String start = HttpUtils.sendGet(CameraUtil.endRecording(baseCameraManagement.getTaskId()));
        log.info("endRecording------------" + start);
        if ("success".equals(start)) {
            baseCameraManagement.setStartRecording(2);
            baseCameraManagement.setTaskId("");
            baseCameraManagement.setUpdateBy(getUserId());
        } else {
            baseCameraManagement.setStartRecording(2);
            baseCameraManagement.setTaskId("");
            baseCameraManagement.setUpdateBy(getUserId());
            log.error("关闭视频录制异常日志如下:" + start);
        }
        if (baseCameraManagementService.updateById(baseCameraManagement)) {
            return success();
        }
        return error();
    }

    @GetMapping("/startRecording/{id}")
    @Log(title = "相机台账管理", businessType = BusinessType.OTHER)
    public AjaxResult startRecording(@PathVariable Long id) {
        BaseCameraManagement baseCameraManagement = baseCameraManagementService.getById(id);
        log.info("startRecording------CameraCode------" + baseCameraManagement.getCameraCode());
        log.info("startRecording------Channel------" + baseCameraManagement.getChannel());
        String start = HttpUtils.sendGet(CameraUtil.startRecording(baseCameraManagement.getCameraCode(), baseCameraManagement.getChannel()));
        log.info("startRecording------------" + start);
        if (start.startsWith(baseCameraManagement.getCameraCode() + "/" + baseCameraManagement.getChannel())) {
            log.info("startRecording 返回成功！！1");
            baseCameraManagement.setStartRecording(1);
            baseCameraManagement.setTaskId(start);
            baseCameraManagement.setUpdateBy(getUserId());
        } else {
            return success("视频录制失败:请确认流是否存在或流是否开视频启开启");
        }
        if (baseCameraManagementService.updateById(baseCameraManagement)) {
            return success();
        } else {
            return error("开启视频录制失败");
        }
    }

    @GetMapping(value = "/getAlarm/{cameraCode}")
    @Log(title = "相机台账管理", businessType = BusinessType.MESSAGE)
    public AjaxResult getAlarm(@PathVariable String cameraCode) {
        LambdaQueryWrapper<BaseCameraManagement> queryWrapper = new LambdaQueryWrapper<BaseCameraManagement>();
        if (!ObjectUtils.isEmpty(cameraCode)) {
            queryWrapper.eq(BaseCameraManagement::getCameraCode, cameraCode);
        }
        BaseCameraManagement baseCameraManagement = baseCameraManagementService.getOne(queryWrapper);
        if (!ObjectUtils.isEmpty(baseCameraManagement)) {
            LambdaQueryWrapper<BaseRailwayManagement> wrapper = new LambdaQueryWrapper<BaseRailwayManagement>();
            if (!ObjectUtils.isEmpty(baseCameraManagement.getRailwayCode())) {
                wrapper.eq(BaseRailwayManagement::getRailwayCode, baseCameraManagement.getRailwayCode());
            }
            BaseRailwayManagement baseRailwayManagement = baseRailwayManagementService.getOne(wrapper);
            MsgAlarmResp msgAlarmResp = new MsgAlarmResp();
            LambdaQueryWrapper<MsgAlarm> wrapper1 = new LambdaQueryWrapper<MsgAlarm>();
            if (!ObjectUtils.isEmpty(baseCameraManagement.getCameraCode())) {
//                wrapper1.eq(MsgAlarm::getCameraCode, baseCameraManagement.getCameraCode());
                wrapper1.orderByDesc(MsgAlarm::getCreateTime);
            }
            List<MsgAlarm> list = msgAlarmService.list(wrapper1);
            if (list.size() > 0) {
                MsgAlarm msgAlarm = list.get(0);
                if (StringUtils.isNotEmpty(msgAlarm.getReleasedBy())) {
//                    BaseUser user = baseUserService.getUser(msgAlarm.getReleasedBy());
//                    if (!StringUtils.isEmptySunhh(user) && !StringUtils.isEmptySunhh(user.getNickName())) {
//                        msgAlarm.setReleasedByName(user.getNickName());
//                    }
                    msgAlarm.setReleasedByName(msgAlarm.getReleasedBy());
                }
                msgAlarmResp.setAlarmType(msgAlarm.getAlarmType());
                msgAlarmResp.setIsRelease(msgAlarm.getIsRelease());
                msgAlarmResp.setReleasedTime(msgAlarm.getReleasedTime());
                msgAlarmResp.setAlarmTime(msgAlarm.getAlarmTime());
                msgAlarmResp.setContent(msgAlarm.getContent());
                msgAlarmResp.setReleasedByName(msgAlarm.getReleasedByName());
//                if (!StringUtils.isEmpty(msgAlarm.getImageUrl())) {
//                    String[] split = msgAlarm.getImageUrl().split(";");
//                    ArrayList<String> objects = new ArrayList<>(Arrays.asList(split));
//                    log.info("publish--------" + objects);
//                    msgAlarmResp.setImageUrls(objects);
//                }
            }
            BeanUtils.copyProperties(baseCameraManagement, msgAlarmResp);
            msgAlarmResp.setRailwayName(baseRailwayManagement.getRailwayName());
            msgAlarmResp.setDeptId(baseCameraManagement.getDeptId());
            String begin = "";
            if (!StringUtils.isEmptySunhh(baseCameraManagement.getBeginMile())) {
                begin = AppendUtils.stringAppend(baseCameraManagement.getBeginMile());
            }
            String end = "";
            if (!StringUtils.isEmptySunhh(baseCameraManagement.getEndMile())) {
                end = AppendUtils.stringAppend(baseCameraManagement.getEndMile());
            }
            String endMile = "[" + begin + "]-[" + end + "]";
            msgAlarmResp.setBeginMile(endMile);
            String mile = AppendUtils.stringAppend(baseCameraManagement.getInstallMile());
            msgAlarmResp.setAlarmMile(mile);
            msgAlarmResp.setInstallLongitude(baseCameraManagement.getInstallLongitude() + "," + baseCameraManagement.getInstallLatitude());
            msgAlarmResp.setLineDir(baseCameraManagement.getLineDir());
            SysDept sysDept = deptService.selectDeptById(baseCameraManagement.getDeptId());
            msgAlarmResp.setDeptName(sysDept.getDeptName());
            if (!ObjectUtils.isEmpty(baseCameraManagement.getOnline())) {
                msgAlarmResp.setOnlineName(baseCameraManagement.getOnline() == 2 ? "在线" : "离线");
            }
            if (!ObjectUtils.isEmpty(baseCameraManagement.getEnableOrNot())) {
                msgAlarmResp.setEnableOrNotName(baseCameraManagement.getEnableOrNot() == 1 ? "启用" : "弃用");
            }
            return AjaxResult.success(msgAlarmResp);
        } else {
            return error("该相机编码在相机台账表中不存在");
        }
    }

    @GetMapping(value = "/getCameraPreviewURL")
    @Log(title = "相机台账管理", businessType = BusinessType.MESSAGE)
    public AjaxResult getCameraPreviewURL() {
        String cameraPreviewURL = GetCameraPreviewURL.getCameraPreviewURL();
        return AjaxResult.success(cameraPreviewURL);
    }

    @GetMapping(value = "/testURL")
    @Log(title = "相机台账管理", businessType = BusinessType.MESSAGE)
    public AjaxResult testURL() {
        return AjaxResult.success(CameraUtil.getPlayFlv("live", "42010001541320000025"));
    }

    @GetMapping(value = "/getAlarmRecord")
    @Log(title = "相机台账管理", businessType = BusinessType.MESSAGE)
    public AjaxResult getAlarmRecord() {
        List<BaseCameraManagement> list = baseCameraManagementService.list(new QueryWrapper<BaseCameraManagement>().eq("line_dir", 2));
        List<String> collect = list.stream().map(BaseCameraManagement::getCameraCode).collect(Collectors.toList());
        CompletableFuture.runAsync(() -> cameraUtil.playbackURLs(collect, "5"));
        return AjaxResult.success("ok");
    }


    @GetMapping(value = "/stop")
    public AjaxResult stop(String id) {
        return cameraUtil.stop(id);
    }


    @GetMapping(value = "/videoCompression")
    public AjaxResult videoCompression(String code) {
        cameraUtil.videoCompression(code);
        return AjaxResult.success();
    }

    @GetMapping(value = "/terminalHeartbeatLog")
    public AjaxResult terminalHeartbeatLog() {
        TerminalHeartbeatLog terminalHeartbeatLog = new TerminalHeartbeatLog();
        terminalHeartbeatLog.setId(terminalHeartbeatLogService.count() + 1);
        terminalHeartbeatLog.setCameraCode("111");
        terminalHeartbeatLog.setCreateTime(new Date());
        boolean save = terminalHeartbeatLogService.save(terminalHeartbeatLog);
        return AjaxResult.success(save);
    }

    /**
     * 流媒体页面接口
     *
     * @param list
     * @return
     */
    @RequestMapping("/getCameraManagementList")
    public AjaxResult getCameraManagementList(@RequestBody List<String> list) {
        List<BaseCameraManagementResponse> responseList = new ArrayList<>();
        for (String name : list) {
            // 寻找第一个斜杠的位置
            int slashIndex = name.indexOf("/");
            if (slashIndex != -1) {
                BaseCameraManagementResponse response = new BaseCameraManagementResponse();
                String result = name.substring(0, slashIndex);
                BaseCameraManagement cameraManagement = baseCameraManagementService.getOne(new LambdaQueryWrapper<BaseCameraManagement>()
                        .eq(BaseCameraManagement::getCameraCode, result));
                response.setCameraCode(cameraManagement.getCameraCode());
                response.setInstallMile(cameraManagement.getInstallMile());
                response.setStreamPath(name);
                responseList.add(response);
            } else {
                return AjaxResult.error("未找到斜杠符号");
            }
        }
        return AjaxResult.success(responseList);
    }


    /**
     * 流媒体页面接口
     *
     * @param
     * @return
     */
    @GetMapping("/getCameraManagementList")
    public AjaxResult getCameraManagementList() {
        int count = cameraUtil.urlCount();
        return AjaxResult.success(count);
    }
}

