package com.jisco.dynamicweight.dynamicbasecamera.controller;

import cn.hutool.core.lang.Assert;
import com.jisco.dynamicweight.dynamicbasebatchstation.model.DynamicBaseBatchStation;
import com.jisco.dynamicweight.dynamicbasecamera.model.DynamicBaseCamera;
import com.jisco.dynamicweight.dynamicbasecamera.service.IDynamicBaseCameraService;
import com.jisco.dynamicweight.dynamicbasecamera.service.IFLVService;
import com.jisco.dynamicweight.util.ExcelUtil;
import com.jisco.dynamicweight.util.UserUtil;
import com.jisco.dynamicweight.util.VideoUtil;
import com.steerinfo.framework.controller.BaseRESTfulController;
import com.steerinfo.framework.controller.RESTfulResult;
import com.steerinfo.framework.service.pagehelper.PageList;
import com.steerinfo.framework.utils.collection.ListUtils;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.bytedeco.javacv.*;
import org.bytedeco.opencv.opencv_core.IplImage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.Buffer;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * DynamicBaseCamera RESTful接口：
 *
 * @author generator
 * @version 1.0-SNAPSHORT 2022-02-15 09:14
 * 类描述
 * 修订历史：
 * 日期：2022-02-15
 * 作者：generator
 * 参考：
 * 描述：DynamicBaseCamera RESTful接口
 * @Copyright 湖南视拓信息技术股份有限公司. All rights reserved.
 * @see null
 */
@RestController
@RequestMapping("/${api.version}/dynamicbasecameras")
public class DynamicBaseCameraController extends BaseRESTfulController {

    @Autowired
    IDynamicBaseCameraService dynamicBaseCameraService;

    @Autowired
    IFLVService flvService;

    @ApiOperation(value = "获取列表", notes = "分页查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    //@RequiresPermissions("dynamicbasecamera:view")
    @GetMapping(value = "/")
    public RESTfulResult list(@RequestParam HashMap parmas, Integer pageNum, Integer pageSize) {
        PageList<DynamicBaseCamera> list = dynamicBaseCameraService.queryForPage(parmas, pageNum, pageSize);
        return success(list);
    }

    @ApiOperation(value = "获取列表", notes = "分页模糊查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    //@RequiresPermissions("dynamicbasecamera:view")
    @GetMapping(value = "/like/")
    public RESTfulResult listLike(@RequestParam HashMap parmas, Integer pageNum, Integer pageSize) {
        PageList<DynamicBaseCamera> list = dynamicBaseCameraService.queryLikeForPage(parmas, pageNum, pageSize);
        return success(list);
    }

    @ApiOperation(value = "创建", notes = "根据DynamicBaseCamera对象创建")
    @ApiImplicitParam(name = "dynamicBaseCamera", value = "详细实体dynamicBaseCamera", required = true, dataType = "DynamicBaseCamera")
    //@RequiresPermissions("dynamicbasecamera:create")
    @PostMapping(value = "/")
    public RESTfulResult add(@RequestBody DynamicBaseCamera model) {
        model.setCreateManNo(UserUtil.getCurrentUserId());
        model.setCreateManName(UserUtil.getCurrentUserName());
        model.setCreateTime(new Date());
        DynamicBaseCamera dynamicBaseCamera = dynamicBaseCameraService.add(model);
        return success(dynamicBaseCamera);
    }

    @ApiOperation(value = "导出Excel", notes = "导出Excel")
    @PostMapping(value = "/exportExcel")//String
    public void exportExcel(HttpServletResponse response) throws IOException {
        List<DynamicBaseCamera> list = dynamicBaseCameraService.query(null);
        ExcelUtil.exportExcel(response, list, DynamicBaseCamera.class, "动态秤站点视频配置");
    }

    @ApiOperation(value = "获取详细信息", notes = "根据url的id来获取详细信息")
    @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")
    //@RequiresPermissions("dynamicbasecamera:view")
    @GetMapping(value = "/{id}")
    public RESTfulResult get(@PathVariable String id) {
        DynamicBaseCamera dynamicBaseCamera = dynamicBaseCameraService.getById(id);
        return success(dynamicBaseCamera);
    }

    @ApiOperation(value = "更新详细信息", notes = "根据url的id来指定更新对象，并根据传过来的dynamicBaseCamera信息来更新详细信息")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String"),
            @ApiImplicitParam(name = "dynamicBaseCamera", value = "详细实体dynamicBaseCamera", required = true, dataType = "DynamicBaseCamera")
    })
    //@RequiresPermissions("dynamicbasecamera:update")
    @PutMapping(value = "/{id}", produces = "application/json;charset=UTF-8")
    public RESTfulResult update(@PathVariable String id, @RequestBody DynamicBaseCamera model) {
        model.setId(id);
        model.setUpdateManNo(UserUtil.getCurrentUserId());
        model.setUpdateManName(UserUtil.getCurrentUserName());
        model.setUpdateTime(new Date());
        DynamicBaseCamera dynamicBaseCamera = dynamicBaseCameraService.modify(model);
        return success(dynamicBaseCamera);
    }

    @ApiOperation(value = "删除", notes = "根据url的id来指定删除对象")
    @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")
    //@RequiresPermissions("dynamicbasecamera:delete")
    @DeleteMapping(value = "/{id}")//String
    public RESTfulResult delete(@PathVariable String id) {
        List<String> list = Arrays.asList(id.split(","));
        if (ListUtils.isNotEmpty(list)) {
            List<String> ids = ListUtils.convertList(list);
            dynamicBaseCameraService.delete(ids);
        }
        return success();
    }

    //无需nginx推流服务器，本身服务器够强就行，切可以集群部署
    @GetMapping(value = "/video/flv/live/", produces = {"video/x-flv;charset=UTF-8"})
    public void flvLive(@RequestParam(value = "id") String id, @RequestParam(value = "verificationCode") String verificationCode, HttpServletResponse response,
                        HttpServletRequest request) {
        DynamicBaseCamera camera = dynamicBaseCameraService.getById(id);
        String url = VideoUtil.getRTSPUrl(camera);
        String starttime = request.getParameter("starttime");
        String endtime = request.getParameter("endtime");
        if (!StringUtils.isEmpty(starttime) && !StringUtils.isEmpty(endtime)) {
            //回放
            url = VideoUtil.getRTSPPlayBackUrl(camera);
            starttime = starttime.replaceAll("-", "");
            endtime = endtime.replaceAll("-", "");
            url += "?starttime=" + starttime + "&endtime=" + endtime;
        }

        //非网关时开启这里，flvjs插件播放
        response.setHeader("Access-Control-Allow-Origin", "*");//走网关时去掉这行
        flvService.open(url, id, response, request);
    }

    /**
     * 截图
     *
     * @param id
     * @return java.lang.Object
     * @author jitwxs
     * @date 2022/2/15 11:39
     */
    @GetMapping("shot")
    public RESTfulResult shot(@RequestParam String id) throws IOException, InterruptedException {
//        long start = System.currentTimeMillis();
        DynamicBaseCamera camera = dynamicBaseCameraService.getById(id);
        if (Objects.isNull(camera)) return failed(null, "未查询到摄像头配置信息");
        String url = VideoUtil.getRTSPUrl(camera);
        FFmpegFrameGrabber fFmpegFrameGrabber = new FFmpegFrameGrabber(url);
        fFmpegFrameGrabber.start();
        fFmpegFrameGrabber.getAudioChannels();
        Frame frame = fFmpegFrameGrabber.grabImage();
        Java2DFrameConverter java2DFrameConverter = new Java2DFrameConverter();
        BufferedImage bufferedImage = java2DFrameConverter.convert(frame);
        fFmpegFrameGrabber.stop();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();//io流
        ImageIO.write(bufferedImage, "jpeg", baos);//写入流中
        byte[] bytes = baos.toByteArray();//转换成字节
        BASE64Encoder encoder = new BASE64Encoder();
        String jpg_base64 = encoder.encodeBuffer(bytes).trim();//转换成base64串
        jpg_base64 = jpg_base64.replaceAll("\n", "").replaceAll("\r", "");//删除 \r\n
        return success("data:image/jpeg;base64," + jpg_base64);
    }
}
