package com.hzjt.controller;
import cn.hutool.core.codec.Base64Encoder;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.util.concurrent.RateLimiter;
import com.hzjt.config.MQTTSubsribe;
import com.hzjt.domain.*;
import com.hzjt.handler.FileTransferManager;
import com.hzjt.handler.WebSocket;
import com.hzjt.mapper.SbtdspsrMapper;
import com.hzjt.mapper.TraffAlarmRecordMapper;
import com.hzjt.redis.RedisDao;
import com.hzjt.service.*;
import com.hzjt.util.*;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.annotation.PostConstruct;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import sun.net.www.protocol.ftp.FtpURLConnection;

@RestController
public class TraffController {
    private static final Logger log = LoggerFactory.getLogger(TraffController.class);

    @Autowired
    ImportService importService;

    @Autowired
    WebSocket webSocket;

    private Map<String, RateLimiter> rateLimiterMap;
    private String port;
    private String dept;
    private Integer rate = Integer.valueOf(10);

    private SbtdspsrMapper sbtdspsrMapper;

    @Autowired
    TraffFlowService traffFlowService;

    @Value("${flv.resisvalue}")
    private String resisvalue;

    @Value("${json.resisurl}")
    private String resisjsonvalue;

    @Value("${ftppath}")
    private String ftppath;

    @Value("${ftpServiceUrl}")
    private String ftpServiceUrl;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    RedisDao redisDao;

    @Autowired
    private TraffAlarmRecordMapper traffAlarmRecordMapper;

    @Autowired
    FtpService ftpService;
    @Autowired
    EventWriteService eventWriteService;
    @Value("ftpIp")
    String ftpIp;
    @Value("ftpPort")
    private String ftpPort;
    @Value("ftpUsername")
    private String ftpUsername;
    @Value("ftpPassword")
    private String ftpPassword;
    @Value("${alarmrecord.check.enable}")
    private String checkEnable;
    Long ldir = new Long(180L);

    @Autowired
    FLVCacheService flvCacheService;
    Long eightHour = Long.valueOf(25200000L);



    @Autowired
    MQTTSubsribe mQTTSubsribe;


    String manualStatus = "0";

    private static final String TYPE = "TRAFFIC_INCIDENT_ALARM";
    ScheduledExecutorService schedulepool = Executors.newScheduledThreadPool(5);

    @Autowired
    public TraffController(@Value("${port}") String port,
                           @Value("${message.dept}") String dept,
                           @Value("${message.rate}") Integer rate,
                           SbtdspsrMapper sbtdspsrMapper) {
        this.port = port;
        this.rate = rate;
        this.dept = dept.substring(0, 5);
        this.sbtdspsrMapper = sbtdspsrMapper;
        this.rateLimiterMap = new ConcurrentHashMap<>(16);
    }







    @PostConstruct
    public void init() {
        List<String> sbbhlist = this.sbtdspsrMapper.selectAllWbbh();
        //消息结果处理返回topic
        sbbhlist.add("notice/66211/videoEventConfirm");
        this.mQTTSubsribe.subscribe(sbbhlist);
    }

    @PostMapping({"/alarmevent"})
    public ResultObj rece(@RequestBody Alarm trffClientMessage) {
//        log.info("trffClientMessage:{}" ,JsonUtil.beanToString(trffClientMessage));

        if (!TYPE.equals(trffClientMessage.getType())) {
            return ResultObj.error(Integer.valueOf(ResponseEnum.E_1002.getCode()), "type类型不正确");
        }

        if (trffClientMessage.getImg_urls().isEmpty()) {
            return ResultObj.error(Integer.valueOf(ResponseEnum.E_1004.getCode()), "img_urls值不能为空");
        }
        if (StringUtils.isBlank(trffClientMessage.getIncident_type())) {
            log.info("incident_type值不能为空" + trffClientMessage.toString());
            return ResultObj.error(Integer.valueOf(ResponseEnum.E_1004.getCode()), "incident_type值不能为空");
        }

        Long current = Long.valueOf((new Date()).getTime() - Long.valueOf(trffClientMessage.getTs()).longValue());
        log.info("current.longValue()>=eightHour.longValue()======" + ((current.longValue() >= this.eightHour.longValue()) ? 1 : 0));
        if (current.longValue() >= this.eightHour.longValue()) {

            Long lontime = Long.valueOf(Long.valueOf(trffClientMessage.getTs()).longValue() + 28800000L);
            log.info("trffClientMessage lontime=====" + lontime);
            trffClientMessage.setTs(String.valueOf(lontime));
        }

        String videoId = trffClientMessage.getVideo_id();

        if (StringUtils.isBlank(videoId)) {
            log.info("video_id值异常 值为:" + videoId);
            return ResultObj.error(Integer.valueOf(ResponseEnum.E_1002.getCode()), "video_id值异常 值为:" + videoId);
        }
        String sbbh = videoId;
        int tdbh = 0;
        List<Sbtdspsr> sbtdspsrs = this.sbtdspsrMapper.selectBySbbh(sbbh, Integer.valueOf(tdbh));
        if (sbtdspsrs.isEmpty()) {
            log.info("设备为:" + sbbh + ",通道为:" + tdbh + "未录入(备案)");
            return ResultObj.error(Integer.valueOf(ResponseEnum.E_1002.getCode()), "设备为:" + sbbh + ",通道为:" + tdbh + "未录入(备案)");
        }
        String xzbh = ((Sbtdspsr)sbtdspsrs.get(0)).getXzbh();
        if (xzbh.length() != 12) {
            log.info("设备为:" + sbbh + ",通道为:" + tdbh + "配置的行政区划" + xzbh + "不合规");
            return ResultObj.error(Integer.valueOf(ResponseEnum.E_1002.getCode()), "设备为:" + sbbh + ",通道为:" + tdbh + "配置的行政区划不合规");
        }
        trffClientMessage.setDept(xzbh);

        try {
            sendevent(trffClientMessage, (Sbtdspsr)sbtdspsrs.get(0));
        } catch (Exception e) {
            log.error("MessageController receive putData error：{}", e.toString());
        }
        return ResultObj.ok(trffClientMessage);
    }


    public void sendevent(Alarm trffClientMessage,Sbtdspsr spr) {
        String   wbbh=spr.getWbbh();
        Traffalarmrecord traffAlarmRecord = new Traffalarmrecord();
        traffAlarmRecord.setAreaid(Long.valueOf(trffClientMessage.getDept()));
        traffAlarmRecord.setRecordtype(trffClientMessage.getIncident_type().toLowerCase());
        traffAlarmRecord.setRecordtime(DateUtils.getDateString(new Date(Long.valueOf(trffClientMessage.getTs()).longValue())));
        traffAlarmRecord.setFdid(trffClientMessage.getVideo_id());
        traffAlarmRecord.setChannelid(Integer.valueOf(0));
        traffAlarmRecord.setVideourlfrom(trffClientMessage.getVideo_record_url());
        traffAlarmRecord.setCreatetime(DateUtils.getDateString(new Date()));
        traffAlarmRecord.setObjlable(trffClientMessage.getObjLabel());
        traffAlarmRecord.setPushstatus(Integer.valueOf(9));
        traffAlarmRecord.setChannelname(spr.getBz());
        List<String> imgBase64List = trffClientMessage.getImg_base64();
        String imgEnumHead = "IMG";
        Ftp ftp = this.ftpService.reloadFtp();
        for (int i = 0; i < imgBase64List.size(); i++) {
            String path = trffClientMessage.getVideo_id() + "/" + DateUtils.formatCurrDayNoSign();
            String fileName = UUIDUtils.createuuid() + ".jpg";
            if (FTPUtil.uploadFile(ftp, path, fileName, imgBase64List.get(i))) {
                TraffAlarmRecordImgEnum.valueOf(imgEnumHead + i).setImg(traffAlarmRecord, FTPUtil.getFtpUrl(ftp) + path + "/" + fileName);
            }
        }
        List<String> imgUrls = trffClientMessage.getImg_urls();
        for (int j = 0; j < imgUrls.size(); j++) {
            TraffAlarmRecordFromImgEnum.valueOf(imgEnumHead + j).setImg(traffAlarmRecord, imgUrls.get(j));
        }

        if (StringEnum.ONE.getValue().equals(this.checkEnable))
        {
            traffAlarmRecord.setCheckstatus(Integer.valueOf(9));
        }
        Map<Object, Object> map = new HashMap<>();
        if (this.manualStatus.equalsIgnoreCase("1")) {
            map.put("type", "recordalarm");
            traffAlarmRecord.setManualstatus(Integer.valueOf(0));
        } else {

            map.put("type", "alarm");
            traffAlarmRecord.setManualstatus(Integer.valueOf(1));
        }
        //为了适配mqtt返回的处理状态，将状态设置为mqtt的事件主键
        traffAlarmRecord.setEventid("66211"+UUIDUtils.createuuid());
        this.traffAlarmRecordMapper.inserTraffAlarmRecord(traffAlarmRecord);
        map.put("data", trffClientMessage);
        map.put("recordid", traffAlarmRecord.getRecordid());
        this.webSocket.GroupSending(JsonUtil.beanToString(map));
        try {
            String basepath = "gstraff/" + traffAlarmRecord.getFdid() + ((traffAlarmRecord.getChannelid().intValue() < 10) ? ("0" + traffAlarmRecord.getChannelid()) : traffAlarmRecord.getChannelid()) + "/" + DateUtils.formatCurrDayNoSign();
            Map<String, Object> transferRecordMap = new HashMap<>();
            FileTransferManager.fetchUrlsFromRecord(traffAlarmRecord, transferRecordMap);
            List<TransferResult> results = FileTransferManager.transferFile(transferRecordMap, ftp, basepath);
            Traffalarmrecord recordBak = FileTransferManager.traffAlarmRecordUrlUpdate(results);
            traffAlarmRecord.setImg2path(recordBak.getImg2path());
            traffAlarmRecord.setImg3path(recordBak.getImg3path());
            traffAlarmRecord.setImg4path(recordBak.getImg4path());
            traffAlarmRecord.setImg5path(recordBak.getImg5path());
            traffAlarmRecord.setVideopath(recordBak.getVideopath());

            if (traffAlarmRecord != null && traffAlarmRecord.getRecordid() != null) {
                this.traffAlarmRecordMapper.updateTraffAlarmRecordUrl(traffAlarmRecord);
            }

            if (null != transferRecordMap.get("videopath") &&
                    !"".equals(transferRecordMap.get("videopath").toString()) && (null == recordBak
                    .getVideopath() || "".equalsIgnoreCase(recordBak.getVideopath()))) {

                String pname = DateUtils.formatCurrDayNoSign() + traffAlarmRecord.getRecordid() + "_video";
                String fileName = pname + ".mp4";
                String ftputl = FTPUtil.getFtpUrl(ftp) + basepath + "/" + fileName;
                log.info("send to mqtt  video is not  empty");
                 schedulepool.schedule(() -> {
                        String url = transferRecordMap.get("videopath").toString();

                        try {
                            HttpURLConnection connection = (HttpURLConnection) (new URL(url)).openConnection();
                            connection.setReadTimeout(2000);
                            connection.setConnectTimeout(3000);
                            connection.setRequestMethod("GET");
                            if (connection.getResponseCode() == 200) {
                                InputStream inputStream = connection.getInputStream();
                                log.info("url:", url);
                                boolean r = FTPUtil.uploadFile(ftp, basepath, fileName, inputStream);
                                if (r) {
                                    log.info("video:{} upload success:", ftputl);
                                    traffAlarmRecord.setVideopath(ftputl);
                                    if (traffAlarmRecord != null && traffAlarmRecord.getRecordid() != null) {
                                        this.traffAlarmRecordMapper.updateTraffAlarmRecordUrl(traffAlarmRecord);
                                    }
                                }
                            } else {
                                log.info("video:{} upload fail:", ftputl);
                            }
                            sendtomqtt(trffClientMessage, wbbh, traffAlarmRecord);
                        } catch (IOException e) {
                            log.error(e.toString());

                            sendtomqtt(trffClientMessage, wbbh, traffAlarmRecord);
                            return Integer.valueOf(0);
                        }
                        return Integer.valueOf(1);
                    }, 50, TimeUnit.SECONDS); //等待50秒钟执行
                }
            traffAlarmRecord.setPushdesc("success");
            traffAlarmRecord.setPushstatus(Integer.valueOf(0));
            this.traffAlarmRecordMapper.updatePushEvent(traffAlarmRecord);
        } catch (Exception e) {
            log.error("alarmevent  error :{}" , e.toString());
        }
    }


    private void sendtomqtt(Alarm trffClientMessage, String wbbh, Traffalarmrecord traffAlarmRecord) {
        log.info("sendtomqtt");
        if (null == wbbh || "".equals(wbbh)) {
            log.info("设备为:{}wbbh is empty",traffAlarmRecord.getFdid());
        } else {
            MqttAlarm mqttalarm = new MqttAlarm();
            String mqttbh = this.traffAlarmRecordMapper.seletmqttbh(trffClientMessage.getIncident_type());
            mqttalarm.setAlarmTime(traffAlarmRecord.getRecordtime());
            mqttalarm.setCompanyId("66211");
            mqttalarm.setEventid(traffAlarmRecord.getEventid());
            mqttalarm.setImagePath((traffAlarmRecord.getImg1path() == null) ? "" : (this.ftpServiceUrl + "?location=" + traffAlarmRecord.getImg1path().replace("ftp://" + this.ftppath + "/", "")));
            mqttalarm.setVideoPath((traffAlarmRecord.getVideopath() == null) ? "" : (this.ftpServiceUrl + "?location=" + traffAlarmRecord.getVideopath().replace("ftp://" + this.ftppath + "/", "")));
            mqttalarm.setDeviceId(wbbh);
            log.info("mqtt data1：{}",JsonUtil.beanToString(mqttalarm));
            //查询部门是否包含隧道
            mqttalarm.setLocation(traffAlarmRecord.getChannelname()!=null&&traffAlarmRecord.getChannelname().contains("隧道")?2:1);
            if (null != trffClientMessage.getObj_location()) {
                mqttalarm.setX(trffClientMessage.getObj_location().get("x") == null? null : (trffClientMessage.getObj_location().get("x")).toString());
                mqttalarm.setY(trffClientMessage.getObj_location().get("y") == null ? null : (trffClientMessage.getObj_location().get("y")).toString());
                mqttalarm.setWidth(trffClientMessage.getObj_location().get("width") == null ? null : (trffClientMessage.getObj_location().get("width")).toString());
                mqttalarm.setHeight(trffClientMessage.getObj_location().get("height") == null ? null : (trffClientMessage.getObj_location().get("height")).toString());
            }
            mqttalarm.setEventTypeId(mqttbh);
            log.info("mqtt data：{}",JsonUtil.beanToString(mqttalarm));
            this.mQTTSubsribe.publishMessage("event/" + wbbh + "/videoEvent", JSON.toJSONString(mqttalarm));
        }
    }


    private RateLimiter getRateLimiter(String videoId) {
        RateLimiter rateLimiter;
        if (this.rateLimiterMap.containsKey(videoId)) {
            rateLimiter = this.rateLimiterMap.get(videoId);
        } else {
            RateLimiter value = RateLimiter.create(this.rate.intValue());
            rateLimiter = this.rateLimiterMap.putIfAbsent(videoId, value);
            if (rateLimiter == null) {
                rateLimiter = value;
            }
        }
        return rateLimiter;
    }

    @GetMapping({"/getflv/{videoid}"})
    public String getflv(@PathVariable("videoid") String videoid) {
        String rtsp = this.traffFlowService.selectSbtddspsrRtspByVideoid(videoid);


        if (null != rtsp) {
            if (null == this.stringRedisTemplate.opsForValue().get(videoid))
            {
                this.flvCacheService.getvalue(videoid, rtsp);
            }

            JSONObject jsonObject = JSONObject.parseObject((String)this.stringRedisTemplate.opsForValue().get(videoid));

            if (null != jsonObject.getJSONArray("play_list") && jsonObject.getJSONArray("play_list").size() > 0) {
                return String.valueOf(jsonObject.getJSONArray("play_list").get(0));
            }
        }

        return "";
    }



    @GetMapping({"/sendtouser/{recordid}"})
    @ResponseBody
    public Integer sendtouser(@PathVariable("recordid") String recordid) {
        Traffalarmrecord traffalarmrecord = (Traffalarmrecord)this.traffAlarmRecordMapper.selectByPrimaryKey(recordid);
        if (traffalarmrecord == null) return Integer.valueOf(0);
        Alarm alarm = new Alarm();
        Base64Encoder base64Encoder = new Base64Encoder();
        alarm.setTs(Long.toString((traffalarmrecord.getRecordtime() == null) ? (new Date()).getTime() : DateUtils.Parsedate(traffalarmrecord.getRecordtime()).getTime()));
        alarm.setDept((traffalarmrecord.getAreaid() == null) ? null : Long.toString(traffalarmrecord.getAreaid().longValue()));
        alarm.setVideo_id(traffalarmrecord.getFdid() + "_" + traffalarmrecord.getChannelid());
        alarm.setIncident_type(traffalarmrecord.getRecordtype());
        List<String> strImgs = new ArrayList<>();
        if (traffalarmrecord.getImg1path() != null) {
            byte[] Img = FTPUtil.getFtpPicBytes(traffalarmrecord.getImg1path());
            strImgs.add((Img != null) ? Base64Encoder.encode(Img) : null);
        }

        if (traffalarmrecord.getImg2path() != null) {
            byte[] Img = FTPUtil.getFtpPicBytes(traffalarmrecord.getImg2path());
            strImgs.add((Img != null) ? Base64Encoder.encode(Img) : null);
        }
        if (traffalarmrecord.getImg3path() != null) {
            byte[] Img = FTPUtil.getFtpPicBytes(traffalarmrecord.getImg3path());
            strImgs.add((Img != null) ? Base64Encoder.encode(Img) : null);
        }

        if (traffalarmrecord.getImg4path() != null) {
            byte[] Img = FTPUtil.getFtpPicBytes(traffalarmrecord.getImg4path());
            strImgs.add((Img != null) ? Base64Encoder.encode(Img) : null);
        }
        if (traffalarmrecord.getImg5path() != null) {
            byte[] Img = FTPUtil.getFtpPicBytes(traffalarmrecord.getImg5path());
            strImgs.add((Img != null) ? Base64Encoder.encode(Img) : null);
        }

        alarm.setImg_base64(strImgs);
        Map<Object, Object> map = new HashMap<>();

        map.put("type", "alarm");
        map.put("data", alarm);
        map.put("recordid", recordid);
        this.webSocket.GroupSending(JsonUtil.beanToString(map));


        try {
            ResultObj obj = this.eventWriteService.updateAndAutoSendEvent(traffalarmrecord);
            log.info("send to guangda novideopath --->response message" + obj.toString());

            if (obj.getStatus().intValue() == 200) {
                return Integer.valueOf(1);
            }
            return Integer.valueOf(0);


        }
        catch (Exception ex) {
            log.info("send to guangda novideopath --->response error" + ex.toString());

            return Integer.valueOf(1);
        }
    }






    @GetMapping({"/test"})
    @ResponseBody
    public void test() {
        String manualStatus = this.traffAlarmRecordMapper.seletManualStatus();
        Alarm alarm = new Alarm();
        alarm.setVideo_id("33_65_230_156_554_fbXdTkVe98u_ecvs_0");
        alarm.setIncident_type("NO_MOTOR_BAN");
        String str = "iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAB1UlEQVRIS5WVjTEEQRBG30WACBABGSACLgJEgAicCBABIkAEiIAMkAERUG9remtua2Z3rquuam935nvTPf0zY9y2gENgH/B5Ny3/AL6AV+A5PReVZhV9xS6Bk/RdEUVzE7qXXtwDVyVQCaDoNeC3m/T7qRxkHThPvz9gnrzqlw8Bi3RyTyyoJjzkCTJcO8ApoEed5QAF74CHLDRDofwOShA9PgYOwpMAGPN34A04Grl3T6kZ/5KFJ5vAthEIgC4pLGgsLFMAoWp8pktfCFh6MZG2LQAlPLDpvS3ALDBrNhoutRUQh54LcJNhGYt9ONYKcH1XiAJ80CVTdMpWATwB6wIsEKswALpnupZsLE1dfwsorKl3WAP0hTKgCDcFTeeSWQc5YF+APcaXLSGKSq/1sBzah6h7GCmefNMqgP6SV0nTVsBSmq5SaK2A6AxdFi1V3kSxtQDMNPtal5l5s/Oy7SF2wlo/EmBIvbOS+f4ldQVBfbNzsR3Sj7p3UYG4yZBGKuaQELeLqtVNwGG6xUzwo9PJTGgxwY/p5HpYHDghJN0TrqVxaXXWQAqfpQH1nfrZ0uyuFUw+awUJcGNsVjjC9Ts2u6cqMgowhpH/IwGE2fxK99GH9R91mncY+HKoHAAAAABJRU5ErkJggg==";
        List<String> arrlist = new ArrayList();
        arrlist.add(str);
        arrlist.add(str);
        arrlist.add(str);
        arrlist.add(str);
        arrlist.add(str);
        alarm.setImg_base64(arrlist);
        alarm.setTs("1345677777");
        alarm.setType("TRAFFIC_INCIDENT_ALARM");
        Map<Object, Object> map = new HashMap<>();
        map.put("type", "alarm");
        map.put("data", alarm);
        map.put("recordid", "33448");
        this.webSocket.GroupSending(JsonUtil.beanToString(map));
        Traffalarmrecord traffAlarmRecord = new Traffalarmrecord();
        traffAlarmRecord.setRecordid(Long.valueOf(Long.parseLong("33448")));
        traffAlarmRecord.setChannelid(new Integer(1));
        traffAlarmRecord.setFdid("20200305112042989");
        traffAlarmRecord.setRecordtype("NO_MOTOR_BAN");



        map.put("recordid", "33449");
        this.webSocket.GroupSending(JsonUtil.beanToString(map));
        Traffalarmrecord traffAlarmRecord2 = new Traffalarmrecord();
        traffAlarmRecord2.setRecordid(Long.valueOf(Long.parseLong("33449")));
        traffAlarmRecord2.setChannelid(new Integer(1));
        traffAlarmRecord2.setFdid("20200305112042989");
        traffAlarmRecord2.setRecordtype("WRONG_DIRECTION");
    }




    @GetMapping({"/testevent"})
    @ResponseBody
    public void testevent() {
        String json = "{            \"type\": \"TRAFFIC_INCIDENT_ALARM\",                \"id\": \"d9a2b0f0-f0cf-49b9-9b64-3da86a122afa\",                \"video_id\": \"201809180950119121_0\",                \"ts\": \"1544602970458\",                \"incident_type\": \"WRONG_DIRECTION\",                \"img_urls\": [            \"http://192.168.1.3:8001/api/alg/files/1535740000-test\",\n                    \"http://192.168.1.3:8001/api/alg/files/1535740000-test2\",                    \"http://192.168.1.3:8001/api/alg/files/1535740000-test3\",                    \"http://192.168.1.3:8001/api/alg/files/1535740000-test4\",                    \"http://192.168.1.3:8001/api/alg/files/1535740000-test5\"    ],            \"video_record_url\": \"http://192.168.1.3:8001/api/alg/files/1576459828-test\",                \"obj_location\": {            \"x\": 0.1,\n                    \"y\": 0.2,                    \"width\": 0.4,                    \"height\": 0.7        },            \"img_base64\": [\"d0xEMHcFAESwdwaUjWDqB6/1Qw4LapAiSICVTOFWsGT0sgt\"]\n        }";






















        MqttAlarm alarm = new MqttAlarm();

        alarm.setHeight("0.7");
        alarm.setWidth("0.7");
        this.mQTTSubsribe.publishMessage("event/1111/videoEvent", JSONUtil.toJsonStr(alarm));
    }
    @GetMapping({"/api/alg/files"})
    protected void fielagent(@RequestParam("location") String location, HttpServletRequest request, HttpServletResponse response) {
        ServletOutputStream servletOutputStream;
        long startTime = System.currentTimeMillis();


        String ftpPath = "ftp://" + this.ftppath + "/" + location;
        FileInputStream hFile = null;
        OutputStream toClient = null;
        InputStream inputStream = null;
        BufferedInputStream bis = null;

        try { response.reset();
            response.setHeader("Expires", "Sat, 10 May 2059 12:00:00 GMT");
            response.setHeader("Cache-Control", "max-age=315360000");

            if (StringUtils.isNotBlank(ftpPath)) {
                if (ftpPath.endsWith(".jpg") || ftpPath.endsWith(".JPG") || ftpPath.endsWith(".png") || ftpPath.endsWith(".PNG") || ftpPath.endsWith(".gif") || ftpPath.endsWith(".GIF")) {
                    response.setContentType("image/" + ftpPath.substring(ftpPath.lastIndexOf(".") + 1) + "; charset=utf-8");
                } else if (ftpPath.endsWith(".mp4") || ftpPath.endsWith(".MP4")) {
                    response.setContentType("video/mpeg4; charset=utf-8");
                    String mp4file = ftpPath.substring(ftpPath.lastIndexOf("/") + 1);
                    response.setHeader("Content-Disposition", "attachment;fileName=" + mp4file);
                }

                String destUrl = ftpPath;
                destUrl = new String(destUrl.getBytes("ISO8859-1"), "GBK");
                String[] arr = destUrl.split(";");
                FtpURLConnection ftpUrl = null;
                HttpURLConnection httpUrl = null;
                for (int i = 0; i < arr.length; i++) {

                    try { URL url = new URL(arr[i]);
                        if (arr[i].toUpperCase().indexOf("FTP") != -1) {
                            ftpUrl = (FtpURLConnection)url.openConnection();
                            ftpUrl.setConnectTimeout(30000);
                            ftpUrl.setReadTimeout(30000);
                            bis = new BufferedInputStream(ftpUrl.getInputStream());
                            response.setContentLength(ftpUrl.getContentLength());
                        } else {
                            httpUrl = (HttpURLConnection)url.openConnection();
                            httpUrl.setConnectTimeout(30000);
                            httpUrl.setReadTimeout(30000);
                            bis = new BufferedInputStream(httpUrl.getInputStream());
                            response.setContentLength(httpUrl.getContentLength());
                        }
                        servletOutputStream = response.getOutputStream();
                        IOUtils.copy(bis, (OutputStream)servletOutputStream);
                        if (bis != null) {
                            bis.close();
                        }
                        if (httpUrl != null) {
                            httpUrl.disconnect();
                        }
                        if (ftpUrl != null) {
                            ftpUrl.close();
                        }
                        if (servletOutputStream != null)
                            servletOutputStream.close();  }
                            catch (Exception e) {
                        response.setContentType("text/html;charset=GBK");
                        response.setCharacterEncoding("GBK");
                        PrintWriter out = response.getWriter();
                        out.write("无法打开图片!");
                        out.flush(); log.info("ftpagent error " + ftpUrl + e.toString()); }
                        finally {
                        if (bis != null) {
                            bis.close();
                        }
                        if (httpUrl != null) {
                            httpUrl.disconnect();
                        }
                        if (ftpUrl != null) {
                            ftpUrl.close();
                        }
                        if (toClient != null) {
                            toClient.close();
                        }
                    }

                }

                return;
            }  }
        catch (Exception exception) {  }
        finally
        { IOUtils.closeQuietly(bis);
            IOUtils.closeQuietly(toClient);
            IOUtils.closeQuietly(hFile);
            IOUtils.closeQuietly(inputStream); }

    }


    @GetMapping({"/testmqtt"})
    public String testmqtt() {
        String json="{\"alarmTime\":\"2021-11-26 10:40:38\",\"companyId\":\"66211\",\"deviceId\":\"401150076\",\"eventTypeId\":\"66003\",\"eventid\":\"662115a9fb682b4324f3cb1a69943bcaf845b\",\"height\":\"0.2665441036224365\",\"imagePath\":\"http://33.65.219.103:8089/api/alg/files?location=20210521001321054002_1/20211126/e1491a815a744f47bed58f2c83d520a5.jpg\",\"location\":1,\"videoPath\":\"http://33.65.219.103:8089/api/alg/files?location=gstraff/20210521001321054002_100/20211126/20211126143488_video.mp4\",\"width\":\"0.14374999701976776\",\"x\":\"0.4677083194255829\",\"y\":\"0.6158088445663452\"}";
        this.mQTTSubsribe.publishMessage("event/" + 401150294 + "/videoEvent", json);
        return "";
    }
}
