package cn.iocoder.yudao.module.pms.controller.admin.yanfan.sip.record;

import cn.iocoder.yudao.framework.common.exception.ErrorCode;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.module.pms.controller.admin.yanfan.utils.BaseResult;
import cn.iocoder.yudao.module.pms.controller.admin.yanfan.enums.CodeEnum;
import cn.iocoder.yudao.module.pms.controller.admin.yanfan.utils.DataResult;
import cn.iocoder.yudao.module.pms.controller.admin.yanfan.utils.MessageUtils;
import cn.iocoder.yudao.module.pms.controller.admin.yanfan.utils.WebAsyncUtil;
import cn.iocoder.yudao.module.pms.service.yanfan.play.model.Stream;
import cn.iocoder.yudao.module.pms.service.yanfan.sip.model.RecordItem;
import cn.iocoder.yudao.module.pms.service.yanfan.sip.model.RecordList;
import cn.iocoder.yudao.module.pms.service.yanfan.sip.record.IRecordService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.swagger.v3.oas.annotations.Operation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.async.WebAsyncTask;

import java.util.List;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.error;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

@Slf4j
@RestController
@RequestMapping("rq/sip/record")
public class RecordController {

    @Autowired
    private IRecordService recordService;

//    @Qualifier("taskExecutor")
    @Qualifier("PMS_THREAD_POOL_TASK_EXECUTOR")
    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;

    @Operation(summary="设备录像查询")
    //@PreAuthorize("@ss.hasPermi('iot:video:list')")
    @GetMapping("/devquery/{deviceId}/{channelId}")
    public WebAsyncTask<Object> devquery(@PathVariable String deviceId, @PathVariable String channelId, String start, String end) {
        return WebAsyncUtil.init(taskExecutor, () -> {
            try {
                RecordList result = recordService.listDevRecord(deviceId, channelId, start, end);
                return DataResult.out(CodeEnum.SUCCESS, result);
            } catch (Exception e) {
                log.error("", e);
                return BaseResult.out(CodeEnum.FAIL, e.getMessage());
            }
        });
    }

    @Operation(summary="设备录像缓存查询")
    //@PreAuthorize("@ss.hasPermi('iot:video:list')")
    @GetMapping("/query/{channelId}/{sn}")
    public CommonResult<List<RecordItem>> list(@PathVariable String channelId, @PathVariable String sn) {
        return success(recordService.listRecord(channelId, sn));
    }

    @Operation(summary="指定流ID开始录像")
    //@PreAuthorize("@ss.hasPermi('iot:video:list')")
    @GetMapping("/start/{stream}")
    public CommonResult<String> startRecord(@PathVariable String stream) {
        boolean result = recordService.startRecord(stream);
        if (result) {
            return success("success");
        } else {
            return error(new ErrorCode(1,"error!"));
        }
    }

    @Operation(summary="指定流ID停止录像")
    //@PreAuthorize("@ss.hasPermi('iot:video:list')")
    @GetMapping("/stop/{stream}")
    public CommonResult<String> stopRecord(@PathVariable String stream) {
        boolean result = recordService.stopRecord(stream);
        if (result) {
            return success(MessageUtils.message("success"));
        } else {
            return error(new ErrorCode(1,"error!"));
        }
    }

    @Operation(summary="获取流对应的录像文件列表")
    //@PreAuthorize("@ss.hasPermi('iot:video:list')")
    @GetMapping("/file/{stream}/{period}")
    public CommonResult<JSONObject> getMp4RecordFile(@PathVariable String stream, @PathVariable String period) {
        return success(recordService.getMp4RecordFile(stream, period));
    }

    @Operation(summary="直播录像")
    @GetMapping("/play/{deviceId}/{channelId}")
    public CommonResult<Stream> playRecord(@PathVariable String deviceId, @PathVariable String channelId) {
        log.debug("直播录像 API调用，deviceId：{}，channelId：{}", deviceId, channelId);
        return success(recordService.playRecord(deviceId, channelId));
    }

    //@PreAuthorize("@ss.hasPermi('iot:sip:record:download')")
    @Operation(summary="设备录像下载")
    @GetMapping("/download/{deviceId}/{channelId}")
    public CommonResult<Stream> download(@PathVariable String deviceId, @PathVariable String channelId, String startTime, String endTime, String speed) {
        log.debug("设备录像下载 API调用，deviceId：{}，channelId：{}，downloadSpeed：{}", deviceId, channelId, speed);
        return success(recordService.download(deviceId, channelId, startTime, endTime, Integer.parseInt(speed)));
    }

    //@PreAuthorize("@ss.hasPermi('iot:sip:record:upload')")
//    @Operation(summary="录像上传OSS")
//    @GetMapping("/upload")
//    public AjaxResult upload(@RequestParam String recordApi, @RequestParam String file) {
//        logger.debug(String.format("录像上传OSS API调用，recordApi：%s，file：%s", recordApi, file));
//        return AjaxResult.success("success!", recordService.upload(recordApi, file));
//    }

    @Operation(summary="查询服务端录像列表")
    //@PreAuthorize("@ss.hasPermi('iot:sip:record:list')")
    @GetMapping("/serverRecord/list")
    public CommonResult<Object> listServerRecord(@RequestParam Integer pageNum, @RequestParam Integer pageSize, @RequestParam String recordApi) {
        try {
            Object data = recordService.listServerRecord(recordApi, pageNum, pageSize);
            return success(data);
        } catch (Exception e) {
            return error(new ErrorCode(2, e.getMessage()));
        }
    }

    @Operation(summary="通过日期查询服务端录像列表")
    //@PreAuthorize("@ss.hasPermi('iot:sip:record:list')")
    @GetMapping("/serverRecord/date/list")
    public CommonResult<JSONArray> listServerRecordByDate(@RequestParam(required = false) Integer year, @RequestParam(required = false) Integer month, @RequestParam String app, @RequestParam String stream, @RequestParam String recordApi) {
        return success(recordService.listServerRecordByDate(recordApi, year, month, app, stream));
    }

    @Operation(summary="通过流ID查询服务端录像列表")
    //@PreAuthorize("@ss.hasPermi('iot:sip:record:list')")
    @GetMapping("/serverRecord/stream/list")
    public CommonResult<JSONObject> listServerRecordByStream(@RequestParam Integer pageNum, @RequestParam Integer pageSize, @RequestParam String app, @RequestParam String recordApi) {
        return success(recordService.listServerRecordByStream(recordApi, pageNum, pageSize, app));
    }

    @Operation(summary="通过应用名查询服务端录像列表")
    //@PreAuthorize("@ss.hasPermi('iot:sip:record:list')")
    @GetMapping("/serverRecord/app/list")
    public CommonResult<JSONObject> listServerRecordByApp(@RequestParam Integer pageNum, @RequestParam Integer pageSize, @RequestParam String recordApi) {
        return success(recordService.listServerRecordByApp(recordApi, pageNum, pageSize));
    }

    @Operation(summary="通过文件名查询服务端录像列表")
    //@PreAuthorize("@ss.hasPermi('iot:sip:record:list')")
    @GetMapping("/serverRecord/file/list")
    public CommonResult<JSONObject> listServerRecordByFile(@RequestParam Integer pageNum, @RequestParam Integer pageSize, @RequestParam String app, @RequestParam String stream, @RequestParam String startTime, @RequestParam String endTime, @RequestParam String recordApi) {
        return success(recordService.listServerRecordByFile(recordApi, pageNum, pageSize, app, stream, startTime, endTime));
    }

    @Operation(summary="通过设备信息查询服务端录像列表")
    //@PreAuthorize("@ss.hasPermi('iot:sip:record:list')")
    @GetMapping("/serverRecord/device/list")
    public CommonResult<JSONObject> getServerRecordByDevice(@RequestParam Integer pageNum, @RequestParam Integer pageSize, @RequestParam String deviceId, @RequestParam String channelId, @RequestParam String startTime, @RequestParam String endTime) {
        return success(recordService.listServerRecordByDevice(pageNum, pageSize, deviceId, channelId, startTime, endTime));
    }

    @Operation(summary="代理视频流rtsp转换hls.m3u8")
    @GetMapping("/addStreamProxy/{deviceId}")
    public CommonResult<JSONObject> addStreamProxy(@PathVariable String deviceId, @RequestParam String url, @RequestParam(required = false, defaultValue = "10") Integer count) {
        return success(recordService.addStreamProxy(deviceId, url, count));
    }
}
