package com.inspect.patrol.controller;

import com.alibaba.fastjson.JSONObject;
import com.inspect.base.core.constant.Constants;
import com.inspect.base.core.sftp.SftpClient;
import com.inspect.base.core.utils.HttpClientUtils;
import com.inspect.base.core.web.controller.BaseController;
import com.inspect.base.core.web.domain.AjaxResult;
import com.inspect.base.redis.service.RedisService;
import com.inspect.patrol.contants.AccessApiConstant;
import com.inspect.patrol.linkage.util.JsonUtil;
import com.inspect.patrol.model.PtzFiModel;
import com.inspect.patrol.model.PtzModel;
import com.inspect.patrol.model.RecordListModel;
import com.inspect.patrol.model.RecordModel;
import com.inspect.patrol.model.ReviewControlModel;
import com.inspect.patrol.model.VideoReviewStartModel;
import com.inspect.patrol.service.IPatrolPresetPosService;
import com.inspect.patrol.service.IPatrolVideotapeService;
import com.inspect.patrol.service.PatrolTaskService;
import com.inspect.patrol.service.impl.DeviceIntoService;
import com.inspect.patrol.service.impl.Video2NvrComponent;

import java.util.Date;
import java.util.Objects;
import javax.servlet.http.HttpServletRequest;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

@Slf4j
@ApiIgnore
@RestController
@RequestMapping({"/videotape"})
public class PatrolVideotapeController extends BaseController {
    @Autowired
    private IPatrolVideotapeService patrolVideotapeService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private HttpServletRequest httpServletRequest;
    @Autowired
    private PatrolTaskService patrolTaskService;
    @Autowired
    private IPatrolPresetPosService patrolPresetPosService;
    @Autowired
    private DeviceIntoService deviceIntoService;
    private final String REDIS_KEY_RECORD = "PATROL_RECORD";
    @Autowired
    private SftpClient sftpClient;
    @Autowired
    private Video2NvrComponent video2NvrComponent;
    @Value("${gwb.url}")
    private String deviceUrl;

    @GetMapping({"/record"})
    public AjaxResult record(RecordModel recordModel) throws Exception {
        log.info("record start param: {}", recordModel);
        String action = recordModel.getAction();
        switch (action) {
            case "0":
                this.redisService.redisTemplate.opsForHash().put(REDIS_KEY_RECORD, recordModel.getStreamid(), new Date());
                String params = JsonUtil.json2Str(JSONObject.parseObject(JSONObject.toJSONString(recordModel)));
                String result = HttpClientUtils.get(this.deviceUrl + AccessApiConstant.RECORD_START, params);
                return AjaxResult.success(result);
            case "1":
                return AjaxResult.success(this.stopRecord(recordModel));
            default:
                return AjaxResult.error("录屏失败，状态识别异常！");
        }
    }

    @GetMapping({"/heartbeat"})
    public AjaxResult heartbeat(String streamId) throws Exception {
        this.redisService.redisTemplate.opsForHash().put(REDIS_KEY_RECORD, streamId, new Date());
        return AjaxResult.success();
    }

    @GetMapping({"stop"})
    private JSONObject stopRecord(RecordModel recordModel) throws Exception {
        String params = JsonUtil.json2Str(JSONObject.parseObject(JSONObject.toJSONString(recordModel)));
        if (this.redisService.redisTemplate.opsForHash().hasKey(REDIS_KEY_RECORD, recordModel.getStreamid()).booleanValue()) {
            this.redisService.redisTemplate.opsForHash().delete(REDIS_KEY_RECORD, recordModel.getStreamid());
            String result = HttpClientUtils.get(this.deviceUrl + AccessApiConstant.RECORD_STOP, params);
            return JSONObject.parseObject(result);
        } else {
            return JSONObject.parseObject(HttpClientUtils.get(this.deviceUrl + AccessApiConstant.RECORD_SCAN, params));
        }
    }

    @GetMapping({"/ptz"})
    public AjaxResult ptz(PtzModel ptzModel) throws Exception {
        ptzModel.setSerial(this.video2NvrComponent.toNvrCode(ptzModel.getPatrolDeviceCode()));
        boolean manualControlPTZ = this.patrolTaskService.isManualControlPTZ(ptzModel.getPatrolDeviceCode(), this.httpServletRequest);
        if (!manualControlPTZ) {
            return AjaxResult.error("控制失败，正在执行任务，您的权限不足！");
        } else {
            String params = JsonUtil.json2Str(JSONObject.parseObject(JSONObject.toJSONString(ptzModel)));
            String result = HttpClientUtils.get(this.deviceUrl + AccessApiConstant.PTZ_CONTROL, params);
            JSONObject jsonObject = JSONObject.parseObject(result);
            if (Objects.equals(jsonObject.getInteger("code"), Constants.SUCCESS)) {
                return AjaxResult.success();
            } else {
                return AjaxResult.error(jsonObject.getString("msg"));
            }
        }
    }

    @GetMapping({"/ptz/fi"})
    public AjaxResult ptzFi(PtzFiModel ptzModel) throws Exception {
        ptzModel.setSerial(this.video2NvrComponent.toNvrCode(ptzModel.getPatrolDeviceCode()));
        String params = JsonUtil.json2Str(JSONObject.parseObject(JSONObject.toJSONString(ptzModel)));
        HttpClientUtils.get(this.deviceUrl + AccessApiConstant.PTZ_CONTROL, params);
        return AjaxResult.success();
    }

    @GetMapping({"/review/start"})
    public AjaxResult reviewStart(VideoReviewStartModel videoReviewStartModel) throws Exception {
        videoReviewStartModel.setSerial(this.video2NvrComponent.toNvrCode(videoReviewStartModel.getPatrolDeviceCode()));
        String params = JsonUtil.json2Str(JSONObject.parseObject(JSONObject.toJSONString(videoReviewStartModel)));
        String result = HttpClientUtils.get(this.deviceUrl + AccessApiConstant.PLAYBACK_START, params);
        return AjaxResult.success(JSONObject.parseObject(result));
    }

    @GetMapping({"/review/stop"})
    public AjaxResult reviewStop(String streamid) throws Exception {
        String result = HttpClientUtils.get(this.deviceUrl + AccessApiConstant.PLAYBACK_STOP, "streamid=" + streamid);
        return AjaxResult.success(result);
    }

    @GetMapping({"/review/control"})
    public AjaxResult reviewControl(ReviewControlModel reviewControlModel) throws Exception {
        String result = HttpClientUtils.get(this.deviceUrl + AccessApiConstant.PLAYBACK_CONTROL, JsonUtil.json2Str(JSONObject.parseObject(JSONObject.toJSONString(reviewControlModel))));
        return AjaxResult.success(result);
    }

    @GetMapping({"/record/list"})
    public AjaxResult queryRecordList(RecordListModel recordListModel) {
        recordListModel.setSerial(this.video2NvrComponent.toNvrCode(recordListModel.getPatrolDeviceCode()));
        String params = JsonUtil.json2Str(JSONObject.parseObject(JSONObject.toJSONString(recordListModel)));
        String result = null;

        try {
            result = HttpClientUtils.get(this.deviceUrl + AccessApiConstant.RECORD_LIST, params);
        } catch (Exception var5) {
            return AjaxResult.error("连接接入层失败！");
        }

        return AjaxResult.success(JSONObject.parseObject(result));
    }

    public static void main(String[] args) {
        String str = "{\"msg\":\"操作成功\",\"code\":200,\"data\":{\"SnapURL\":\"\",\"RTMP\":\"rtmp://10.10.18.201:11935/hls/010010000103010001_010010000103010001_1010000002\",\"SourceVideoFrameRate\":0,\"RTPLostCount\":0,\"PlaybackDuration\":26638,\"CDN\":\"\",\"HLS\":\"http://10.10.18.201:20000/sms/34020000002020000001/hls/010010000103010001_010010000103010001_1010000002/010010000103010001_010010000103010001_1010000002_live.m3u8\",\"InBytes\":0,\"FLV\":\"http://10.10.18.201:20000/sms/34020000002020000001/flv/hls/010010000103010001_010010000103010001_1010000002.flv\",\"ChannelCustomName\":\"\",\"SourceAudioSampleRate\":0,\"SourceVideoHeight\":0,\"SourceVideoWidth\":0,\"Ondemand\":true,\"VideoFrameCount\":0,\"NumOutputs\":0,\"InBitRate\":0,\"WS_FLV\":\"ws://10.10.18.201:20000/sms/34020000002020000001/ws-flv/hls/010010000103010001_010010000103010001_1010000002.flv\",\"AudioEnable\":false,\"OutBytes\":0,\"SMSID\":\"34020000002020000001\",\"Progress\":0,\"RTPLostRate\":0,\"StreamID\":\"playback:010010000103010001:010010000103010001:1010000002\",\"DeviceID\":\"010010000103010001\",\"SourceVideoCodecName\":\"\",\"Duration\":0,\"SourceAudioCodecName\":\"\",\"TimestampSec\":0,\"ChannelID\":\"010010000103010001\",\"WEBRTC\":\"\",\"CascadeSize\":0,\"PlaybackFileURL\":\"\",\"RecordStartAt\":\"\",\"RTPCount\":0,\"ChannelName\":\"Camera 01\",\"StartAt\":\"2022-05-06 08:32:49\",\"RTSP\":\"\",\"Transport\":\"UDP\"}}";
        JSONObject jsonObject = JSONObject.parseObject(str);
        System.out.println(jsonObject);
    }
}
