package com.ruoyi.web.controller.system;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.unit.DataUnit;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.controller.chenyanlogin.haikang.CameraInfo;
import com.ruoyi.web.controller.chenyanlogin.haikang.CameraResponse;
import com.ruoyi.web.controller.chenyanlogin.haikang.CameraStatusResponse;
import com.ruoyi.web.controller.chenyanlogin.timer.GetCameraPreviewURL;
import com.ruoyi.web.domain.dto.lotVideo.LotVideoAddRequest;
import com.ruoyi.web.domain.dto.lotVideo.LotVideoEditRequest;
import com.ruoyi.web.domain.dto.lotVideo.LotVideoQueryRequest;
import com.ruoyi.web.domain.entity.LotVideo;
import com.ruoyi.web.domain.vo.LotVideoVO;
import com.ruoyi.web.service.LotVideoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;

import javax.xml.crypto.Data;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import static com.ruoyi.common.core.domain.AjaxResult.error;
import static com.ruoyi.common.core.domain.AjaxResult.success;

@Api(tags = "物联网实时数据视频监控")
@RestController
@RequestMapping("/system/lot/video")
public class LotVideoController {

    @Autowired
    private LotVideoService lotVideoService;

    private  String camerList =  "/api/resource/v1/camera/advance/cameraList";
    private  String previewURLs =  "/api/video/v2/cameras/previewURLs";
    private  String  cameras =  "/api/resource/v1/cameras/indexCode";
    private  String  pictureInfos =  "/api/video/v1/pictureInfos";
    private  String  manualCapture =  "/api/video/v1/manualCapture";
    private  String  search =  "/api/pems/v1/monitor/search";
    private  String  events =  "/api/els/v1/events/search";
    /**
     * 同步列表
     * @return
     */
    @ApiOperation("添加物联网实时数据视频监控")
    @PostMapping("/syncVideoList")
    public AjaxResult syncVideoList() throws Exception {
        JSONObject jsonBody = new JSONObject();
        jsonBody.put("pageNo", 1);
        jsonBody.put("pageSize", 100);
        jsonBody.put("isCascade", 0);

        String body = jsonBody.toJSONString();

        String getCameraPreviewURL = GetCameraPreviewURL.GetCameraPreviewURL(camerList, body);
        CameraResponse cameraResponse = JSON.parseObject(getCameraPreviewURL, CameraResponse.class);

        if (ObjectUtil.isNotEmpty(cameraResponse) && "0".equals(cameraResponse.getCode())){
            List<CameraInfo> list = cameraResponse.getData().getList();
            System.out.println(list.toString());
            for (CameraInfo cameraInfo : list) {
                LotVideo video = lotVideoService.getOne(new QueryWrapper<LotVideo>().eq("camera_index_code", cameraInfo.getCameraIndexCode()));
                if (ObjectUtil.isEmpty(video)){
                    video = new LotVideo();
                    video.setCreateTime(cameraInfo.getCreateTime());
                    video.setName(cameraInfo.getCameraName());
                    video.setLocation(cameraInfo.getCameraName());
                    video.setUpdateTime(cameraInfo.getUpdateTime());
                    video.setRegionIndexCode(cameraInfo.getRegionIndexCode());
                    video.setCameraIndexCode(cameraInfo.getCameraIndexCode());
                    video.setCapabilitySetName(cameraInfo.getCapabilitySetName());
                    video.setEncodeDevIndexCode(cameraInfo.getEncodeDevIndexCode());
                    lotVideoService.save(video);
                }else {
                    video.setCreateTime(cameraInfo.getCreateTime());
                    video.setName(cameraInfo.getCameraName());
                    video.setLocation(cameraInfo.getCameraName());
                    video.setUpdateTime(cameraInfo.getUpdateTime());
                    video.setRegionIndexCode(cameraInfo.getRegionIndexCode());
                    video.setCameraIndexCode(cameraInfo.getCameraIndexCode());
                    video.setCapabilitySetName(cameraInfo.getCapabilitySetName());
                    video.setEncodeDevIndexCode(cameraInfo.getEncodeDevIndexCode());
                    lotVideoService.updateById(video);
                }

            }
        }
        return success("同步成功");

    }
    /**
     * 获取流地址
     */
    @ApiOperation("获取缩略图")
    @GetMapping("/pictureInfos")
    public Object pictureInfos( @RequestParam (value = "cameraIndexCode")String cameraIndexCode) throws Exception {
        JSONObject jsonBody = new JSONObject();
        jsonBody.put("cameraIndexCode", cameraIndexCode);
        String body = jsonBody.toJSONString();
        System.out.println(body);
        String getCameraPreviewURL = GetCameraPreviewURL.GetCameraPreviewURL(manualCapture, body);
        Map<String,Object> cameraResponse = JSON.parseObject(getCameraPreviewURL, Map.class);
        System.out.println("--->"+cameraResponse);
        return cameraResponse;
    }
    private  static  String getTime(DateTime dateTime ){
        TimeZone timeZone = TimeZone.getTimeZone("GMT+8");
        // 2. 设置为东八区时区
        dateTime.setTimeZone(timeZone);

        // 3. 格式化为目标字符串（手动拼接毫秒和时区）
        String isoFormat = dateTime.toString("yyyy-MM-dd'T'HH:mm:ss.SSS")
                + dateTime.toString("Z").replaceFirst("(\\d{2})(\\d{2})$", "$1:$2");
        return isoFormat;

    }

    /**
     * 获取流地址
     */
    @ApiOperation("获取事件列表")
    @GetMapping("/events")
    public Object events() throws Exception {
        JSONObject jsonBody = new JSONObject();
        jsonBody.put("startTime", getTime(DateUtil.beginOfDay(new Date())));
        jsonBody.put("endTime",  getTime(DateUtil.endOfDay(new Date())));
        jsonBody.put("pageSize", 1);
        jsonBody.put("pageNo", 1000);
        String body = jsonBody.toJSONString();
        System.out.println(body);
        String getCameraPreviewURL = GetCameraPreviewURL.GetCameraPreviewURL(events, body);
        Map<String,Object> cameraResponse = JSON.parseObject(getCameraPreviewURL, Map.class);
        System.out.println("--->"+cameraResponse);
        return cameraResponse;
    }

    public static void main(String[] args) throws Exception {

        JSONObject jsonBody = new JSONObject();
        jsonBody.put("startTime", getTime(DateUtil.beginOfYear(new Date())));
        jsonBody.put("endTime",  getTime(DateUtil.endOfDay(new Date())));
        jsonBody.put("pageSize", 1000);
        jsonBody.put("pageNo", 1);
//        jsonBody.put("ability", "frs");
        String body = jsonBody.toJSONString();
        System.out.println(body);
        String getCameraPreviewURL = GetCameraPreviewURL.GetCameraPreviewURL("/api/els/v1/events/search", body);
        Map<String,Object> cameraResponse = JSON.parseObject(getCameraPreviewURL, Map.class);
        System.out.println("--->"+cameraResponse);

    }



    /**
     * 获取流地址
     */
    @ApiOperation("获取流地址")
    @GetMapping("/getUrl")
    public AjaxResult getUrl( @RequestParam (value = "cameraIndexCode")String cameraIndexCode,
                              @RequestParam (value = "protocol")String protocol) throws Exception {
        JSONObject jsonBody = new JSONObject();
        jsonBody.put("cameraIndexCode", cameraIndexCode);
        jsonBody.put("streamType", 0);
        jsonBody.put("protocol", "hls");
        jsonBody.put("transmode", 0);
        jsonBody.put("streamform", "ps");
        if (StringUtils.isNotEmpty(protocol)){
            jsonBody.put("protocol", protocol);
        }

        String body = jsonBody.toJSONString();
//        try {
            String getCameraPreviewURL = GetCameraPreviewURL.GetCameraPreviewURL(previewURLs, body);
            Map<String,Object> cameraResponse = JSON.parseObject(getCameraPreviewURL, Map.class);
            return success(cameraResponse.get("data"));
//        }catch (Exception e){
//            return success("失败");
//        }


    }

    @ApiOperation("获取传感器")
    @GetMapping("/search")
    public  CameraStatusResponse search() throws Exception {
        JSONObject jsonBody = new JSONObject();
        jsonBody.put("pageNo",  1);
        jsonBody.put("pageSize",  10000);
        String body = jsonBody.toJSONString();
        String getCameraPreviewURL = GetCameraPreviewURL.GetCameraPreviewURL(search, body);
        CameraStatusResponse cameraResponse = JSON.parseObject(getCameraPreviewURL, CameraStatusResponse.class);
        return cameraResponse;
    }


    /**
     * 添加物联网实时数据视频监控
     *
     * @param lotVideoAddRequest
     * @return
     */
    @ApiOperation("添加物联网实时数据视频监控")
    @PostMapping("/add")
    public AjaxResult addLotVideo(@RequestBody LotVideoAddRequest lotVideoAddRequest) {
        if (lotVideoAddRequest == null) {
            return error("请求参数为空");
        }
        Integer id = lotVideoService.addLotVideo(lotVideoAddRequest);
        return success(id);
    }

    /**
     * 删除物联网实时数据视频监控
     *
     * @param paramsMap
     * @return
     */
    @ApiOperation("删除物联网实时数据视频监控")
    @PostMapping("/delete")
    public AjaxResult deleteLotVideo(@RequestBody Map<String, String> paramsMap) {
        String ids = paramsMap.get("ids");
        if (StrUtil.isBlank(ids)) {
            return error("请求参数为空");
        }
        boolean b = lotVideoService.deleteLotVideo(ids);
        if (b) {
            return success("删除成功");
        }
        return error("删除失败");
    }


    /**
     * 编辑物联网实时数据视频监控
     *
     * @param lotVideoEditRequest
     * @return
     */
    @ApiOperation("编辑物联网实时数据视频监控")
    @PostMapping("/edit")
    public AjaxResult editLotVideo(@RequestBody LotVideoEditRequest lotVideoEditRequest) {
        if (lotVideoEditRequest == null) {
            return error("请求参数为空");
        }
        lotVideoService.editLotVideo(lotVideoEditRequest);
        return AjaxResult.success();
    }


    /**
     * 根据id获取物联网实时数据视频监控
     *
     * @param id
     * @return
     */
    @ApiOperation("根据id获取物联网实时数据视频监控")
    @GetMapping("/get")
    public AjaxResult getLotVideoById(@RequestParam int id) {
        if (ObjectUtil.isEmpty(id)) {
            return error("请求参数为空");
        }
        LotVideoVO lotVideoVO = lotVideoService.getLotVideoById(id);
        return success(lotVideoVO);
    }

    /**
     * 分页获取物联网实时数据视频监控列表
     *
     * @param lotVideoQueryRequest
     * @return
     */
    @ApiOperation("分页获取物联网实时数据视频监控列表")
    @PostMapping("/list/page")
    public AjaxResult listLotVideoByPage(@RequestBody LotVideoQueryRequest lotVideoQueryRequest) {
        if (lotVideoQueryRequest == null) {
            return error("请求参数为空");
        }
        Page<LotVideoVO> listLotVideoVOByPage = lotVideoService.getListLotVideoByPage(lotVideoQueryRequest);
        return success(listLotVideoVOByPage);
    }

    @ApiOperation("获取物联网实时数据视频监控列表")
    @PostMapping("/list/list")
    public AjaxResult listLotVideo(@RequestBody LotVideoQueryRequest lotVideoQueryRequest) {
        if (lotVideoQueryRequest == null) {
            return error("请求参数为空");
        }
        List<LotVideo> listLotVideoVOByPage = lotVideoService.listLotVideo(lotVideoQueryRequest);
        return success(listLotVideoVOByPage);
    }

    @ApiOperation("更新监控摄像头的经纬度接口")
    @PutMapping("/put")
    public AjaxResult put(@RequestBody Map<String , Object> map) {
        int id = (int)map.get("id");
        String longitude = (String)map.get("longitude");
        String latitude = (String)map.get("latitude");
        LotVideo lotVideo = new LotVideo();
        lotVideo.setId(id);
        lotVideo.setLongitude(longitude);
        lotVideo.setLatitude(latitude);
        lotVideoService.updateById(lotVideo);

        return success();
    }
    @ApiOperation("获取摄像头详情接口")
    @PostMapping("/getById")
    public AjaxResult getById(@RequestBody Map<String , Integer> map) {
        return success(lotVideoService.getById( map.get("id")));
    }
}
