/*
package com.guwan.face.rtsp;

import cn.hutool.core.collection.CollectionUtil;
import com.arcsoft.face.FaceInfo;
import com.arcsoft.face.enums.ExtractType;
import com.arcsoft.face.toolkit.ImageFactory;
import com.arcsoft.face.toolkit.ImageInfo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.guwan.face.dto.FaceVideoVo;
import io.minio.MinioClient;
import io.minio.PutObjectOptions;
import lombok.extern.slf4j.Slf4j;
import net.shapelight.common.config.GlobalValue;
import net.shapelight.common.config.MinioConfig;
import net.shapelight.common.utils.Constant;
import net.shapelight.common.utils.UUIDUtil;
import net.shapelight.modules.face.entity.UserCompareInfo;
import net.shapelight.modules.face.service.FaceEngineService;
import net.shapelight.modules.face.util.UserInfo;
import net.shapelight.modules.face.util.UserRamGroup;
import net.shapelight.modules.feignClient.CxFeignClient;

import net.shapelight.modules.ten.dao.TenCellDao;
import net.shapelight.modules.ten.entity.TenCellEntity;
import net.shapelight.modules.ten.entity.TenPersonEntity;
import net.shapelight.modules.ten.service.TenPersonService;
import net.shapelight.modules.ten.service.impl.TenPersonServiceImpl;
import org.bytedeco.javacpp.avutil;
import org.bytedeco.javacv.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import static org.bytedeco.javacpp.avutil.AV_LOG_ERROR;

@Component
@Slf4j
public class RtspFrameGrabber {

   */
/* @Autowired
    private FaceEngineService faceEngineService;

    @Autowired
    private TenPersonService personService;

    @Autowired
    private GlobalValue globalValue;

    @Autowired
    private CxFeignClient feignClient;
    @Autowired
    private TenPersonServiceImpl tenPersonService;

    @Autowired
    private TenCellDao tenCellDao;

    @Autowired
    private MinioConfig minioConfig;
    @Autowired
    private  MinioClient minioClient;


    *//*

    */
/**
     * 用于记录人脸识别相关状态
     *//*

    public ConcurrentHashMap<Integer, Integer> requestFeatureStatusMap = new ConcurrentHashMap<>();
    */
/**
     * rtsp视频流url
     *//*

    @Value("${global.Url.rtspUrl}")
    private String rtspUrl;
    */
/**
     * 帧抓取器
     *//*

    private FFmpegFrameGrabber grabber;
    */
/**
     * 视频帧率
     *//*

    private int frameRate = 25;
    */
/**
     * 视频码率
     *//*

//    private int bitRate = 2000000;
    private int bitRate = 128000;
    */
/**
     * 视频宽度
     *//*

    private int frameWidth = 480;
    */
/**
     * 视频高度
     *//*

    private int frameHeight = 270;



    private void createGrabber() {
        try {

            grabber = FFmpegFrameGrabber.createDefault(rtspUrl);
            grabber.setOption("rtsp_transport", "tcp");

//            grabber.setOption("reconnect", "1");
//            grabber.setOption("reconnect_at_eof", "1");
//            grabber.setOption("reconnect_streamed", "1");
//            grabber.setOption("reconnect_delay_max", "2");
//            grabber.setOption("preset", "veryfast");
//            grabber.setOption("probesize", "192");
//            grabber.setOption("tune", "zerolatency");
//            grabber.setFrameRate(30.0);
//            grabber.setOption("buffer_size", "" + this.bufferSize);
//            grabber.setOption("max_delay", "500000");
//            grabber.setOption("stimeout", String.valueOf(20000));
//            grabber.setOption("loglevel", "quiet");


//            grabber.setOption("appkey", "****");//海康视频 appkey
//            grabber.setOption("secret", byte2Base64);//海康视频 secret
//            grabber.setOption("port", "446");//默认443
//            grabber.setOption("enableHTTPS", "1"); //是否启用HTTPS协议，这里总是填1
//            grabber.setOption("rtsp_flags", "prefer_tcp");
            grabber.setOption("stimeout", "5000000");//5秒


            //设置帧率
            grabber.setFrameRate(frameRate);
            //设置获取的视频宽度
            grabber.setImageWidth(frameWidth);
            //设置获取的视频高度
            grabber.setImageHeight(frameHeight);
            //设置视频bit率
            grabber.setVideoBitrate(bitRate);
            grabber.start();
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }
    public List<FaceVideoVo> startGrabber(String cellId) {

        List<FaceVideoVo>  faceVideoVos = new ArrayList<>();

        avutil.av_log_set_level(AV_LOG_ERROR);
        Java2DFrameConverter java2DFrameConverter = new Java2DFrameConverter();
        if (grabber == null) {
            //log.info("连接rtsp：" + rstp + "，开始创建grabber");
            createGrabber();
        }
        try {
            Frame frame = grabber.grabImage();
            if (frame != null) {
//                    logger.info("处理帧.............................................");
                BufferedImage bi = java2DFrameConverter.getBufferedImage(frame);

                byte[] bytes = imageToBytes(bi, "jpg");

               */
/* InputStream frameInputStream = new ByteArrayInputStream(bytes);
                String frameFileName = "temp/" + "frame_" + UUIDUtil.uuid()
                        + ".jpg";

                PutObjectOptions framePutObjectOptions = new PutObjectOptions(bytes.length, -1);
                framePutObjectOptions.setContentType("image/jpeg");

                minioClient.putObject(
                        minioConfig.getBucketName(), frameFileName, frameInputStream, framePutObjectOptions);

                System.out.println("文件名 = " + globalValue.getMinioEndpoint() + "/" +
                        globalValue.getMinioBucketName() + "/" + frameFileName);*//*

              */
/*  // 读取图片
                BufferedImage image = ImageIO.read(new File("C:\\Users\\zhangbo\\OneDrive\\图片\\Camera Roll\\1寸相片.jpg"));

                // 创建字节输出流
                ByteArrayOutputStream baos = new ByteArrayOutputStream();

                // 使用ImageIO将BufferedImage编码为byte[]
                ImageIO.write(image, "jpg", baos);

                // 转换为byte数组
                byte[] imageBytes = baos.toByteArray();*//*

                faceVideoVos = imageRecognition(bytes, cellId);
                System.out.println("faceVideoVos = " + faceVideoVos);

            } else {
                log.error("解码失败");
                if (grabber != null) {
                    try {
                        grabber.stop();
                    } catch (FrameGrabber.Exception ex) {
                        log.error("grabber stop exception: " + ex.getMessage());
                    } finally {
                        grabber = null;
                    }
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage());

            if (grabber != null) {
                try {
                    grabber.stop();
                } catch (FrameGrabber.Exception ex) {
                    log.error("grabber stop exception: " + ex.getMessage());
                } finally {
                    grabber = null;
                }
            }

        } finally {
            grabber = null;
        }
//            try {
//                Thread.sleep(100);
//            } catch (InterruptedException e) {
//                logger.error(e.getMessage());
//            }

        return  faceVideoVos;
    }

    public List<FaceVideoVo> recognition(MultipartFile file,String cellId) {
        try {
            byte[] bytes = file.getBytes();
            return imageRecognition(bytes, cellId);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private List<FaceVideoVo> imageRecognition(byte[] bytes,String cellId) {
        List<FaceVideoVo> temp = new ArrayList<>();
        if (bytes != null && bytes.length > 0) {
            ImageInfo imageInfo = ImageFactory.getRGBData(bytes);
            List<FaceInfo> faceInfoList = faceEngineService.detectFaces(imageInfo);


          */
/*  for (FaceInfo faceInfo : faceInfoList) {
                System.out.println(faceInfo.getFace3DAngle());
                //Yaw上下 Pitch左右
                if (faceInfo.getFace3DAngle().getYaw() > 20 || faceInfo.getFace3DAngle().getYaw() < -20) {
                    System.out.println("没在好好看！！！");
                  //  faceInfoList.remove(faceInfo);
                }
                if (faceInfo.getFace3DAngle().getPitch() > 20 || faceInfo.getFace3DAngle().getPitch() < -20) {
                    System.out.println("没在好好看！！！");
                }
            }*//*



            if (CollectionUtil.isNotEmpty(faceInfoList)) {
                faceInfoList.forEach(faceInfo -> {
                   */
/* FaceRecognitionResDTO faceRecognitionResDTO = new FaceRecognitionResDTO();
                    faceRecognitionResDTO.setRect(faceInfo.getRect());*//*


                    byte[] featureBytes = faceEngineService.extractFaceFeature(imageInfo,
                            faceInfo, ExtractType.REGISTER);
                    if (featureBytes != null) {
                        //底库
                        List<UserInfo> userInfoList = UserRamGroup.getUserList(cellId);
                        //人脸对比  这里长度永远为1
                        List<UserCompareInfo> userCompareInfoList = faceEngineService
                                .faceRecognition(featureBytes, userInfoList, Float.parseFloat(globalValue.getRecFaceThd()));

                        for (UserCompareInfo userCompareInfo : userCompareInfoList) {
                            FaceVideoVo faceVideoVo = new FaceVideoVo();
                            if (faceInfo.getFace3DAngle().getYaw() > 20 || faceInfo.getFace3DAngle().getYaw() < -20) {
                                faceVideoVo.setIsHeadOnView(0);
                            }else if (faceInfo.getFace3DAngle().getPitch() > 20 || faceInfo.getFace3DAngle().getPitch() < -20) {
                                faceVideoVo.setIsHeadOnView(0);
                            }else {
                                faceVideoVo.setIsHeadOnView(1);
                            }

                            faceVideoVo.setPersonId(userCompareInfo.getFaceId()).setName(userCompareInfo.getName());



                            InputStream frameInputStream = new ByteArrayInputStream(bytes);
                            String frameFileName = "temp/" + "frame_" + UUIDUtil.uuid()
                                    + ".jpg";

                            PutObjectOptions framePutObjectOptions = new PutObjectOptions(bytes.length, -1);
                            framePutObjectOptions.setContentType("image/jpeg");

                            try {
                                frameInputStream.close();
                            } catch (IOException e) {
                                throw new RuntimeException(e);
                            }

                            try {
                                minioClient.putObject(
                                        minioConfig.getBucketName(), frameFileName, frameInputStream, framePutObjectOptions);
                            } catch (Exception e) {
                                throw new RuntimeException(e);
                            }

                            System.out.println("文件名 = " + globalValue.getMinioEndpoint() + "/" +
                                    globalValue.getMinioBucketName() + "/" + frameFileName);



                            faceVideoVo.setImageUrl(frameFileName);

                            temp.add(faceVideoVo);
                        }
                        if (!userCompareInfoList.isEmpty()) {

                            for (UserCompareInfo userCompareInfo : userCompareInfoList) {
                                TenPersonEntity tenPerson = personService.getOne(new LambdaQueryWrapper<TenPersonEntity>()
                                        .eq(TenPersonEntity::getPersonId, userCompareInfo.getFaceId()));
                                Map<Integer, String> personnelTypeMap = new HashMap<>();
                                personnelTypeMap.put(Constant.PERSON_TYPE_OWNER, "2");//内部人员
                                personnelTypeMap.put(Constant.PERSON_TYPE_MEMBER, "1");//承包商
                                personnelTypeMap.put(Constant.PERSON_TYPE_TENANT, "3");//长期供应商
                                personnelTypeMap.put(Constant.PERSON_TYPE_GUEST, "4");//访客

                                //
                                Map<String, Object> params = new HashMap<>();
                                params.put("pmWatchVideoRecordId", "");
                                params.put("orgId", tenPerson.getOrgId());
                                params.put("orgName", tenCellDao.selectOne(new QueryWrapper<TenCellEntity>().eq("cell_id", tenPerson.getCellId())));
                                params.put("personnelName", tenPerson.getName());
                                params.put("personnelId", tenPerson.getOpenId());
                                params.put("personnelCardId", tenPerson.getIdCard());
                                params.put("personnelType", personnelTypeMap.get(tenPerson.getPersonType()));
                                params.put("dictSex", tenPerson.getGender() == 0 ? "女" : "男");
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                                params.put("watchVideoTime", sdf.format(System.currentTimeMillis()));
                                tenPerson.setIsWatchSafeVideo(1);
                                tenPersonService.updateById(tenPerson);

                                System.out.println("params = " + params);

                          */
/*  JSONObject jsonObject = feignClient.savePmWatchVideoRecord(params);
                            if (jsonObject.getBool("success") != null && jsonObject.getBool("success")) {
                                personService.update(new LambdaUpdateWrapper<TenPersonEntity>()
                                        .set(TenPersonEntity::getIsWatchSafeVideo, 1)
                                        .eq(TenPersonEntity::getPersonId, userCompareInfo.getFaceId()));
                            }*//*

                            }


                        }
                    } else {
                        log.error("图片不合格,未检测到人脸");
                    }
                });

            } else {
                log.error("图片不合格,未检测到人脸");
            }

        } else {
        }
        return temp;
    }

    */
/**
     * 图片转字节数组
     *
     * @param _bi 图片数据
     * @return 图片字节码
     *//*

    private byte[] imageToBytes(BufferedImage _bi, String _format) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            ImageIO.write(_bi, _format, baos);
        } catch (IOException e) {
            log.error(e.getMessage());
            return null;
        }
        return baos.toByteArray();
    }

}
*/
