package com.usky.iot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.usky.common.core.bean.CommonPage;
import com.usky.common.core.exception.BusinessException;
import com.usky.common.security.utils.SecurityUtils;
import com.usky.iot.domain.VcDevice;
import com.usky.iot.mapper.VcDeviceMapper;
import com.usky.iot.service.VcDeviceService;
import com.usky.common.mybatis.core.AbstractCrudService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 视频配置信息表 服务实现类
 * </p>
 *
 * @author han
 * @since 2024-10-22
 */
@Slf4j
@Service
public class VcDeviceServiceImpl extends AbstractCrudService<VcDeviceMapper, VcDevice> implements VcDeviceService {

    @Value("${vc.rtmp-ip}")
    private String rtmpIp;

    Process process = null;

    @Override
    public List<VcDevice> VcDeviceList(Integer groupId){
        LambdaQueryWrapper<VcDevice> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(VcDevice::getGroupId,groupId);
        List<VcDevice> list = this.list(queryWrapper);
        return list;
    }

    @Override
    public CommonPage<VcDevice> pageList(String videoNumber, String videoName, Integer groupId , Integer pageNum,
                                  Integer pageSize){
        IPage<VcDevice> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<VcDevice> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery.like(StringUtils.isNotBlank(videoName),VcDevice::getVideoName,videoName)
                .eq(StringUtils.isNotBlank(videoNumber),VcDevice::getVideoNumber,videoNumber)
                .eq(null != groupId,VcDevice::getGroupId,groupId)
                .eq(VcDevice::getDelFlag,0)
                .orderByDesc(VcDevice::getId);
        page = this.page(page,lambdaQuery);
        return new CommonPage<>(page.getRecords(),page.getTotal(),page.getCurrent(),page.getSize());
    }

    @Override
    public String getVcDeviceVideo(String deviceUuid){
        LambdaQueryWrapper<VcDevice> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery.like(StringUtils.isNotBlank(deviceUuid),VcDevice::getVideoNumber,deviceUuid)
                .eq(VcDevice::getDelFlag,0);
        VcDevice one = this.getOne(lambdaQuery);
        if(one==null){
            throw new BusinessException("未查询到设备信息");
        }
        String accountNumber = one.getAccountNumber();
        String videoPassword = one.getVideoPassword();
        String videoIp = one.getVideoIp();
        String videoPort = one.getVideoPort().toString();
        String command = "ffmpeg -i rtsp://"+accountNumber+":"+videoPassword+"@"+videoIp+":"+videoPort+" -vcodec copy -acodec aac -ar 44100 -c:v libx264 -preset ultrafast -tune zerolatency -strict -2 -ac 1 -r 30 -s 1280x720 -q 10 -f flv -hls_time 1 -hls_list_size 3 -hls_flags delete_segments rtmp://"+rtmpIp+":1935/hls/"+deviceUuid;
        System.out.println(command);

        try {
            log.info("【begin】实时拉取摄像头数据流 "+command);
            // 创建 ProcessBuilder 实例
            ProcessBuilder processBuilder = new ProcessBuilder(command.split(" "));
            // 启动进程
            process = processBuilder.start();

            new Thread(() -> {
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getErrorStream()))) {
                    String line;
                    while ((line = reader.readLine()) != null) {
                        System.out.println(line);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();

            String repDeviceVideo = rtmpIp+":80/hls/"+deviceUuid+".m3u8";
            return repDeviceVideo;


        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

    }

    @Override
    public void stopDeviceVideo() {
        if (process != null && process.isAlive()) {
            process.destroy();
            try {
                process.waitFor();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public boolean add(VcDevice vcDevice){
        vcDevice.setCreateBy(SecurityUtils.getUsername());
        vcDevice.setCreateTime(LocalDateTime.now());
//        vcDevice.setDeptId(SecurityUtils.getLoginUser().getSysUser().getDeptId());
//        vcDevice.setTenantId(SecurityUtils.getTenantId());
        return this.save(vcDevice);
    }

    @Override
    public void update(VcDevice vcDevice){
        vcDevice.setUpdateBy(SecurityUtils.getUsername());
        vcDevice.setUpdateTime(LocalDateTime.now());
        this.updateById(vcDevice);
    }

    @Override
    public boolean remove(Integer id) {
        VcDevice vcDevice = this.getById(id);
        vcDevice.setDelFlag(1);
        return this.updateById(vcDevice);
    }
}
