package cn.iocoder.yudao.module.pms.controller.admin.alarm;

import cn.iocoder.yudao.module.pms.controller.admin.alarm.vo.IotVideoAlarmPageReqVO;
import cn.iocoder.yudao.module.pms.controller.admin.alarm.vo.IotVideoAlarmRespVO;
import cn.iocoder.yudao.module.pms.controller.admin.alarm.vo.IotVideoAlarmSaveReqVO;
import cn.iocoder.yudao.module.pms.dal.dataobject.alarm.IotVideoAlarmDO;
import cn.iocoder.yudao.module.pms.dal.dataobject.yanfan.device.YfIotDeviceDO;
import cn.iocoder.yudao.module.pms.dal.dataobject.yanfan.sip.device.channel.YfSipDeviceChannelDO;
import cn.iocoder.yudao.module.pms.dal.mysql.yanfan.device.YfIotDeviceMapper;
import cn.iocoder.yudao.module.pms.dal.mysql.yanfan.sip.device.channel.YfSipDeviceChannelMapper;
import cn.iocoder.yudao.module.pms.hik.HikIsapiService;
import cn.iocoder.yudao.module.pms.service.alarm.IotVideoAlarmService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import java.util.*;
import java.io.IOException;
import java.util.stream.Collectors;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.*;


@Tag(name = "管理后台 - 资料")
@RestController
@RequestMapping("/rq/iot-video-alarm")
@Validated
public class IotVideoAlarmController {

    @Resource
    private IotVideoAlarmService iotVideoAlarmService;
    @Resource
    private YfSipDeviceChannelMapper yfsipDeviceChannelMapper;
    @Resource
    private HikIsapiService hikIsapiService;
    @Resource
    private YfIotDeviceMapper yfIotDeviceMapper;

    @PostMapping("/create")
    @Operation(summary = "创建资料")
    @PreAuthorize("@ss.hasPermission('rq:iot-video-alarm:create')")
    public CommonResult<Long> createIotVideoAlarm(@Valid @RequestBody IotVideoAlarmSaveReqVO createReqVO) {
        return success(iotVideoAlarmService.createIotVideoAlarm(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新资料")
    @PreAuthorize("@ss.hasPermission('rq:iot-video-alarm:update')")
    public CommonResult<Boolean> updateIotVideoAlarm(@Valid @RequestBody IotVideoAlarmSaveReqVO updateReqVO) {
        iotVideoAlarmService.updateIotVideoAlarm(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除资料")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('rq:iot-video-alarm:delete')")
    public CommonResult<Boolean> deleteIotVideoAlarm(@RequestParam("id") Long id) {
        iotVideoAlarmService.deleteIotVideoAlarm(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得资料")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('rq:iot-video-alarm:query')")
    public CommonResult<IotVideoAlarmRespVO> getIotVideoAlarm(@RequestParam("id") Long id) {
        IotVideoAlarmDO iotVideoAlarm = iotVideoAlarmService.getIotVideoAlarm(id);
        return success(BeanUtils.toBean(iotVideoAlarm, IotVideoAlarmRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得视频告警分页")
    @PreAuthorize("@ss.hasPermission('rq:iot-video-alarm:query')")
    public CommonResult<PageResult<IotVideoAlarmRespVO>> getIotVideoAlarmPage(@Valid IotVideoAlarmPageReqVO pageReqVO) {
        PageResult<IotVideoAlarmDO> pageResult = iotVideoAlarmService.getIotVideoAlarmPage(pageReqVO);
        List<IotVideoAlarmRespVO> collect = pageResult.getList().stream().map(e -> {
            IotVideoAlarmRespVO iotVideoAlarmRespVO = new IotVideoAlarmRespVO();
            BeanUtils.copyProperties(e, iotVideoAlarmRespVO);
            if (StringUtils.isNotBlank(e.getBusinessChannel())) {
                YfSipDeviceChannelDO yfSipDeviceChannelDO = yfsipDeviceChannelMapper.selectSipDeviceChannelByChannelSipId(e.getBusinessChannel());
                if (yfSipDeviceChannelDO != null) {
                    if (Objects.nonNull(yfSipDeviceChannelDO.getDeviceSipId())&&StringUtils.isNotBlank(yfSipDeviceChannelDO.getDeviceSipId())) {
                        YfIotDeviceDO yfIotDeviceDO = yfIotDeviceMapper.selectDeviceBySerialNumber(yfSipDeviceChannelDO.getDeviceSipId());
                        iotVideoAlarmRespVO.setDeviceName(yfIotDeviceDO.getDeviceName());
                    }
                    iotVideoAlarmRespVO.setChannelName(yfSipDeviceChannelDO.getChannelName());
                }
            }
            return iotVideoAlarmRespVO;
        }).collect(Collectors.toList());
        return success(new PageResult<>(collect, pageResult.getTotal()));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出资料 Excel")
    @PreAuthorize("@ss.hasPermission('rq:iot-video-alarm:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportIotVideoAlarmExcel(@Valid IotVideoAlarmPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<IotVideoAlarmDO> list = iotVideoAlarmService.getIotVideoAlarmPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "资料.xls", "数据", IotVideoAlarmRespVO.class,
                        BeanUtils.toBean(list, IotVideoAlarmRespVO.class));
    }


    @GetMapping("/pic/{id}")
    @Operation(summary = "获得视频告警图片")
    @PreAuthorize("@ss.hasPermission('rq:iot-video-alarm:query')")
    public ResponseEntity<byte[]> getAlarmPic(@PathVariable Long id) throws IOException {
        IotVideoAlarmDO iotVideoAlarm = iotVideoAlarmService.getIotVideoAlarm(id);
        String url = "";
        if (iotVideoAlarm != null) {
            if (StringUtils.isNotBlank(iotVideoAlarm.getUrl())) {
                url = iotVideoAlarm.getUrl();
            } else if (StringUtils.isNotBlank(iotVideoAlarm.getImageUrl())){
                url = iotVideoAlarm.getImageUrl();
            }
        }
        byte[] picInfo = new byte[0];
        if (StringUtils.isNotBlank(url)) {
            picInfo = hikIsapiService.getPicInfo("nvr-001", url);
        }
        // 2. 设置响应头，告诉前端这是图片流
//        HttpHeaders headers = new HttpHeaders();
//        // 根据实际图片格式调整（海康通常返回jpeg）
//        headers.setContentType(MediaType.IMAGE_JPEG);
//        // 设置内容长度，提升传输效率
//        headers.setContentLength(picInfo.length);
//        // 禁止缓存（可选，根据业务需求）
//        headers.setCacheControl("no-cache, no-store, must-revalidate");
//
//        // 3. 返回二进制流和响应头
//        return success(new ByteArrayInputStream(picInfo));
//        return success(picInfo);



        // 4. 设置响应头，返回纯图片流
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.IMAGE_JPEG); // 海康默认jpeg，可根据实际调整
        headers.setContentLength(picInfo.length);
        headers.setCacheControl("no-cache, no-store, must-revalidate");

        return new ResponseEntity<>(picInfo, headers, HttpStatus.OK);
    }
}