package im.zhaojun.system.controller;

import com.github.pagehelper.PageInfo;
import im.zhaojun.common.annotation.OperationLog;
import im.zhaojun.common.util.*;
import im.zhaojun.system.model.*;
import im.zhaojun.system.service.TrafficStatisticsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import sun.net.www.protocol.ftp.FtpURLConnection;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.server.PathParam;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Slf4j
@Controller
@RequestMapping("/TrafficStatistics")
public class TrafficStatisticsController {
    @Resource
    private TrafficStatisticsService trafficStatisticsService;

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

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

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


    @OperationLog("获取车流量列表,从当天凌晨开始")
    @GetMapping("/list/vehicles")
    @ResponseBody
    public ResultBean vehicles(@RequestParam("starttime") String time,
                               @RequestParam("deptid") String deptid) {

        //开始时间
        String starttime = DateUtils.getEndTimestamp(0, time);
        List<Map> deptList = trafficStatisticsService.selectVehicles(starttime, time, deptid);
        //
        return ResultBean.success(deptList);
    }

    @OperationLog("统计流量中车辆类型,从当天凌晨开始")
    @GetMapping("/list/vehiclesTypes")
    @ResponseBody
    public ResultBean vehiclesTypes(@RequestParam("starttime") String time,
                                    @RequestParam("deptid") String deptid) {

        String starttime = DateUtils.getEndTimestamp(0, time);
        List<Map> deptList = trafficStatisticsService.selectVehiclesTypes(starttime, time, deptid);
        return ResultBean.success(deptList);
    }

    @OperationLog("车流量畅通等级数据,从当天凌晨开始")
    @GetMapping("/list/flowStatus")
    @ResponseBody
    public ResultBean flowList(@RequestParam("starttime") String time,
                               @RequestParam("deptid") String deptid) {

        String starttime = DateUtils.getEndTimestamp(0, time);
        return ResultBean.success(trafficStatisticsService.selectFlowStatus(starttime, time, deptid));
    }

    @OperationLog("统计异常时间段事件数,从当天凌晨开始")
    @GetMapping("/list/alarm")
    @ResponseBody
    public ResultBean alarm(@RequestParam("starttime") String time,
                            @RequestParam("deptid") String deptid) {

        String starttime = DateUtils.getEndTimestamp(0, time);
        List<Map> deptList = trafficStatisticsService.selectAlarms(starttime, time, deptid);
        return ResultBean.success(deptList);
    }

    @OperationLog("根据时间和监控id统计不同类别异常事件数,从当天凌晨开始")
    @GetMapping("/list/alarmTypes")
    @ResponseBody
    public ResultBean alarmtypes(@RequestParam("starttime") String time,
                                 @RequestParam("deptid") String deptid) {

        String starttime = DateUtils.getEndTimestamp(0, time);
        List<Map> alarmList = trafficStatisticsService.selectAlarmsTypes(starttime, time, deptid);
        //查询昨天的数据
        String yesendtime = DateUtils.getYestodayTimestamp(-1, time);
        String yestarttime = DateUtils.getYestodayTimestamp(-1, yesendtime);
        List<Map> yesalarmList = trafficStatisticsService.selectAlarmsTypes(yestarttime, yesendtime, deptid);
        List<Map> newmaplist = new ArrayList<>();
        boolean isfind = false;


        //遍历今天和昨天的数据
        for (Map m : alarmList) {
            for (Map yem : yesalarmList) {
                if (null != m.get("type") && null != yem.get("type") && m.get("type").equals(yem.get("type"))) {
                    isfind = true;
                    m.put("yesdata", yem.get("data"));
                }
            }
            if (!isfind) {
                m.put("yesdata", 0);
            }
            newmaplist.add(m);
        }
        //遍历今天和昨天的数据
        for (Map m : yesalarmList) {
            for (Map yem : alarmList) {
                if (null != m.get("type") && null != yem.get("type") && m.get("type").equals(yem.get("type"))) {
                    isfind = true;
                }
            }
            if (!isfind) {
                m.put("data", 0);
                newmaplist.add(m);
            }

        }

        return ResultBean.success(newmaplist);
    }


//    @OperationLog("按照监控推送事件总量排序取前10,从当天凌晨开始")
//    @GetMapping("/list/alarmsByVideoName")
//    @ResponseBody
//    public ResultBean alarmsByVideoName(@RequestParam("videoname") String videoname,@RequestParam("starttime") String time,@RequestParam("topnum") String topnum ) {
//            String starttime=DateUtils.getEndTimestamp(0,time);
//            List<Map> deptList = trafficStatisticsService.selectAlarmsByVideoName(videoname,starttime,time ,Integer.parseInt(topnum));
//            return ResultBean.success(deptList);
//    }

//
//    @OperationLog("分页按照监控点位分组进行各种车辆同比环比流量数据")
//    @GetMapping("/list/vehiclesByVideoIdAndType")
//    @ResponseBody
//    public ResultBean vehiclesByVideoIdAndType(@RequestParam("videoname") String videoname,
//                                               @RequestParam("starttime") String starttime,
//                                               @RequestParam("endtime") String endtime,
//                                               @RequestParam("pageNum") int pageNum,
//                                               @RequestParam("pageSize") int pageSize) {
//            //当前时间
//            List<Map> carList = trafficStatisticsService.selectVehiclesByVideoIdAndType(videoname,starttime,endtime, DateUtils.getLastMinTime(endtime,-5,"",0),pageNum,pageSize);
//
//
//        //同比时间
//            List<Map> tbcarList = trafficStatisticsService.selectVehiclesByVideoIdAndType(videoname,
//                    DateUtils.getlastYearTime(starttime,-1),DateUtils.getlastYearTime(endtime,-1)
//                    , DateUtils.getLastMinTime(endtime,-5,"year",-1),pageNum,pageSize);
//
//            //环比时间
//            List<Map> hbcarList = trafficStatisticsService.selectVehiclesByVideoIdAndType(videoname,
//                    DateUtils.getlastMonthTime(starttime,-1),DateUtils.getlastMonthTime(endtime,-1)
//                    , DateUtils.getLastMinTime(endtime,-5,"month",-1),pageNum,pageSize);
//
//
//            DecimalFormat format = new DecimalFormat("0.00");
//            //遍历总数，环比，同比
//            Double data,tbdata,hbdata;
//            Boolean isfind=false;
//            List<Map> maplist=getMapList(carList);
//            List<Map> lastyear_maplist=getMapList(tbcarList);
//            List<Map> lastmonth_maplist=getMapList(hbcarList);
//            //遍歷map  主鍵
//
//        for (Map mp:maplist) {
//               //遍歷所有主鍵，獲得對應的值
//                data=Double.parseDouble(String.valueOf(mp.get("data")));
//                for (Map tbmp:lastyear_maplist) {
//                    if(null!=mp.get("videoid")&& null!=tbmp.get("videoid")&& mp.get("videoid").equals(tbmp.get("videoid")) )
//                    {
//                      tbdata=Double.parseDouble(String.valueOf(tbmp.get("total")));
//                        if(tbmp.get("data").equals("0"))
//                            mp.put("tb","100.00%");
//                         else {
//                            mp.put("tb", format.format((data - tbdata) / tbdata * 100)+ '%');
//                        }
//                    }
//                }
//
//                for (Map hbmp:hbcarList) {
//                    if(null!=mp.get("videoid")&& null!=hbmp.get("videoid") && mp.get("videoid").equals(hbmp.get("videoid")) )
//                    {
//                        hbdata=Double.parseDouble(String.valueOf(hbmp.get("data")));
//                        if(hbmp.get("data").equals("0"))
//                            mp.put("hb","100.00%");
//                        else {
//                            mp.put("hb", format.format((data - hbdata) / hbdata * 100)+ '%');
//                        }
//                    }
//                }
//            }
//
//            //查詢該用戶下所有點位信息
//
//
//            //Map 整合
//        String videoid=null;
//        Map  nmap=null;
//        for (Map mp:carList) {
//            for (Map inmp:carList) {
//                if (null != mp.get("videoid") && videoid.equals(mp.get("videoid"))) {
//                    nmap.put("videoid", mp.get("videoid"));
//                    nmap.put("videoname", mp.get("videoname"));
//                    nmap.put(mp.get("name"), mp.get("data"));
//                } else if (null != mp.get("videoid")) {
//                    nmap = new HashMap();
//                    videoid = mp.get("videoid").toString();
//                }
//
//            }
//
//        }
//
//
//
//            return  ResultBean.success(carList);
//    }


    @OperationLog("按照监控推送事件总量排序取前10,从当天凌晨开始")
    @GetMapping("/list/alarmsByVideoName")
    @ResponseBody
    public ResultBean alarmsByVideoName(@RequestParam("videoname") String videoname,
                                        @RequestParam("starttime") String time,
                                        @RequestParam("topnum") String topnum) {
        String starttime = DateUtils.getEndTimestamp(0, time);
        List<Map> list = trafficStatisticsService.selectAlarmsByVideoName(videoname, starttime, time, Integer.parseInt(topnum));
        List<Map> lastdaylist = trafficStatisticsService.selectAlarmsByVideoName(videoname,
                DateUtils.getlastDayTime(DateUtils.parseDate(starttime), -1),
                DateUtils.getlastDayTime(DateUtils.parseDate(time), -1),
                Integer.parseInt(topnum));
        for (Map mp : list) {
            mp.put("lastdata", 0);
            for (Map lstmp : lastdaylist) {
                if (null != mp.get("videoid") && null != lstmp.get("videoid") && mp.get("videoid").equals(lstmp.get("videoid"))) {
                    mp.put("lastdata", lstmp.get("data"));
                }
            }

        }

        return ResultBean.success(list);
    }


    @OperationLog("分页按照监控点位分组进行各种车辆同比环比流量数据")
    @GetMapping("/list/vehiclesByVideoIdAndType2")
    @ResponseBody
    public ResultBean vehiclesByVideoIdAndType2(@RequestParam("videoname") String videoname,
                                                @RequestParam("starttime") String starttime,
                                                @RequestParam("endtime") String endtime,
                                                @RequestParam("pageNum") int pageNum,
                                                @RequestParam("deptid") String deptid,
                                                @RequestParam("pageSize") int pageSize) {
        //当前时间
        Map map = new HashMap();
        map.put("starttime", starttime);
        map.put("endtime", endtime);
        map.put("dept_id", deptid);
        Date enddate = DateUtils.parseDate(endtime);
        Date startdate = DateUtils.parseDate(starttime);

        map.put("fivetime", DateUtils.getLastMinTime(enddate, -5, "", 0));
        map.put("lastyearstarttime", DateUtils.getlastYearTime(startdate, -1));
        map.put("lastyearendtime", DateUtils.getlastYearTime(enddate, -1));
        map.put("lastyearfivetime", DateUtils.getLastMinTime(enddate, -5, "year", -1));
        map.put("lastmonthstarttime", DateUtils.getlastMonthTime(startdate, -1));
        map.put("lastmonthendtime", DateUtils.getlastMonthTime(enddate, -1));
        map.put("lastmonthfivetime", DateUtils.getLastMinTime(enddate, -5, "month", -1));
        map.put("videoname", videoname);
        List<VehiclesStatistic> carList = trafficStatisticsService.selectVehiclesByVideoIdAndType(map, pageNum, pageSize);
        return ResultBean.success(getMapList(carList));
    }

    @OperationLog("分页按照监控点位分组进行各种车辆同比环比流量数据 按照总量排序查询，同比环比按照上个月，上周的时间来计算")
    @GetMapping("/list/vehiclesByVideoIdAndType")
    @ResponseBody
    public PageResultBean<VehiclesStatisticResult> vehiclesByVideoIdAndType(@RequestParam("videoname") String videoname,
                                                                            @RequestParam("starttime") String starttime,
                                                                            @RequestParam("endtime") String endtime,
                                                                            @RequestParam("ruletag") String ruletag,
                                                                            @RequestParam("pageNum") int pageNum,
                                                                            @RequestParam("deptid") String deptid,
                                                                            @RequestParam("videoid") String videoid,
                                                                            @RequestParam("pageSize") int pageSize) {
        //判断当前查询时间是否大于1天

        Date entdate = DateUtils.parseDate(endtime);
        Date startdate = DateUtils.parseDate(starttime);
        boolean day = DateUtils.TheSameDay(entdate, startdate);
        //当前时间
        Map map = new HashMap();
        map.put("starttime", starttime);
        map.put("endtime", endtime);
        map.put("deptId", deptid);
        map.put("videoname", videoname);
        map.put("ruletag", ruletag);
        List<VehiclesStatisticResult> carList = new ArrayList<>();
        List<VehiclesStatisticResult> tbList = new ArrayList<>();
        List<VehiclesStatisticResult> hbList = new ArrayList<>();
        map.put("videoids",StringUtils.isEmpty(videoid)?new ArrayList():Arrays.asList(videoid.split(",")));
        map.put("statis", 1);
        //查询原始表当天数据与统计表合并数据
        carList = trafficStatisticsService.selectStatisVehiclesByVideoIdAndType(map, pageNum, pageSize);
        if (day) {//时间跨度为1天查询同比环比
            if (carList.size() > 0) {
                //获得carlist videoids
                List<String> videoids = new ArrayList<>();
                for (VehiclesStatisticResult item : carList) {
                    videoids.add(item.getVideoid());
                }
                map.put("deptId", null);
                map.put("videoids", videoids);
                //计算同比环比，
                if (endtime.substring(0, 10).equals(DateUtils.getDate())) {
                    //如果时间为当前时间，需要查询一个月前本表的记录                    //上个月
                    map.put("starttime", DateUtils.getlastMonthTime(startdate, -1));
                    map.put("endtime", DateUtils.getlastMonthTime(entdate, -1));
                    tbList = trafficStatisticsService.selectStatisVehiclesByVideoIdAndType(map);
                    //上周
                    map.put("starttime", DateUtils.getlastDayTime(startdate, -7));
                    map.put("endtime", DateUtils.getlastDayTime(entdate, -7));
                    hbList = trafficStatisticsService.selectStatisVehiclesByVideoIdAndType(map);

                } else {//不是当前时间，而是历史时间，查询统计表中的数据
                    //上个月
                    map.put("starttime", DateUtils.getlastMonthTimeY_M_D(startdate, -1));
                    map.put("endtime", DateUtils.getlastMonthTime(entdate, -1));
                    tbList = trafficStatisticsService.selectVehiclesStatisByVideoIdAndType(map);
                    //上周
                    map.put("starttime", DateUtils.getlastDayTimeY_M_D(startdate, -7));
                    map.put("endtime", DateUtils.getlastDayTime(entdate, -7));
                    hbList = trafficStatisticsService.selectVehiclesStatisByVideoIdAndType(map);

                }
                for (VehiclesStatisticResult item : carList) {

                    for (VehiclesStatisticResult tbitem : tbList) {

                        if (item.getVideoid().equalsIgnoreCase(tbitem.getVideoid())) {
                            item.setTbsedan(tbitem.getSedan());
                            item.setTbgoodsvan(tbitem.getGoodsvan());
                            item.setTbcoach(tbitem.getCoach());
                            item.setTbtotal(tbitem.getTotal());
                            item.setTbfiveflow(tbitem.getFiveflow());
                            item.setTbother(tbitem.getOther());
                            break;
                        }
                    }

                    for (VehiclesStatisticResult hbitem : hbList) {
                        if (item.getVideoid().equalsIgnoreCase(hbitem.getVideoid())) {
                            item.setHbsedan(hbitem.getSedan());
                            item.setHbgoodsvan(hbitem.getGoodsvan());
                            item.setHbcoach(hbitem.getCoach());
                            item.setHbtotal(hbitem.getTotal());
                            item.setHbfiveflow(hbitem.getFiveflow());
                            item.setHbother(hbitem.getOther());
                            break;
                        }

                    }

                }
            }
        }
        PageInfo<VehiclesStatisticResult> rolePageInfo = new PageInfo<>(carList);
        return new PageResultBean<VehiclesStatisticResult>(rolePageInfo.getTotal(), rolePageInfo.getList());
    }


    public List<Map> getMapList(List<VehiclesStatistic> carList) {
        List<Map> maplist = new ArrayList<>();
        for (VehiclesStatistic mp : carList) {
            if (mp.getData() == null) continue;
            String[] totallist = mp.getData().toString().split(",");
            String[] namelist = mp.getName().toString().split(",");

            String[] tblist = mp.getTbdata().toString().split(",");
            String[] hblist = mp.getHbdata().toString().split(",");
            Map map = new HashMap();
            map.put("videoid", mp.getVideoid());
            map.put("videoname", mp.getVideoname());
            for (int i = 0; i < namelist.length; i++) {
                map.put(namelist[i], totallist[i]);
                map.put(namelist[i] + "_tbdata", tblist[i]);
                map.put(namelist[i] + "_hbdata", hblist[i]);
            }
            maplist.add(map);
        }
        return maplist;

    }

    @OperationLog("查询字典表")
    @GetMapping("/listcode")
    @ResponseBody
    public ResultBean listcode(@RequestParam("codeid") String codeid,
                               @RequestParam("alarmlevel") String level
                               ) {
        List<CodeData> deptList = trafficStatisticsService.selectCodeByCodeId(codeid, level);
        return ResultBean.success(deptList);
    }


    @OperationLog("查询")
    @GetMapping("/list/alarmsByTime")
    @ResponseBody
    public PageResultBean<Alarm> alarmsByTime(@RequestParam("deptId") String deptId,
                                              @RequestParam("starttime") String starttime,
                                              @RequestParam("endtime") String endtime,
                                              @RequestParam("pageNum") int pageNum,
                                              @RequestParam("pageSize") int pageSize,
                                              @RequestParam("type") String type,
                                              @RequestParam("videoname") String videoname
    ) {
        Map map = new HashMap();
        map.put("deptId", deptId);
        map.put("starttime", starttime);
        map.put("endtime", endtime);
        map.put("type", type);
        map.put("videoname", videoname);

        List<Alarm> deptList = trafficStatisticsService.selectAlarmsByTime(map, pageNum, pageSize);
        PageInfo<Alarm> userPageInfo = new PageInfo<>(deptList);
        return new PageResultBean<Alarm>(userPageInfo.getTotal(), userPageInfo.getList());
    }

    //    @OperationLog("统计点位机动车总量与点位事件量并计算同比与环比")
//    @GetMapping("/list/alarmsStatis")
//    @ResponseBody
//    public ResultBean alarmsStatis(@RequestParam("videoid") String videoid,@RequestParam("starttime") String starttime,@RequestParam("endtime") String endtime) {
//        List<Map> deptList = trafficStatisticsService.selectAlarmsStatis(videoid,starttime,endtime);
//        return ResultBean.success(deptList);
//    }
    @OperationLog("查询点位高发排行榜")
    @GetMapping("/list/videoVehiclesOrAlarm")
    @ResponseBody
    public ResultBean videoVehiclesOrAlarms(@RequestParam("deptId") String deptId,
                                            @RequestParam("starttime") String starttime,
                                            @RequestParam("endtime") String endtime) {
        Map map = new HashMap();
        map.put("deptId", deptId);
        map.put("starttime", starttime);
        map.put("endtime", endtime);
        return ResultBean.success(trafficStatisticsService.selectvideoVehiclesOrAlarms(map));
    }

//
//    @PostMapping("/queryTraffalarmrecordByPage1")
//    public PageResultBean<TraffalarmrecordResult>  queryTraffalarmrecordByPage(@RequestParam(value = "videoids[]") List<String> videoid,
//                                                       @RequestParam(value = "page", defaultValue = "1") int page,
//                                                       @RequestParam(value = "limit", defaultValue = "10") int limit,
//                                                       @RequestParam(value = "recordtype")   String recordtype,
//                                                       @RequestParam(value = "checkstatus") Integer checkstatus,
//                                                       @RequestParam (value = "starttime") String starttime,
//                                                       @RequestParam (value = "endtime") String endtime) {
//        List<TraffalarmrecordResult> traffalarmrecordResults =
//                trafficStatisticsService.queryTraffalarmrecordByPage(videoid,recordtype,checkstatus,starttime,endtime,page,limit);
//
//        PageInfo<TraffalarmrecordResult> rolePageInfo = new PageInfo<>(traffalarmrecordResults);
//        return new PageResultBean<Tra月ffalarmrecordResult>(rolePageInfo.getTotal(), rolePageInfo.getList());
//    }

    @PostMapping("/queryTraffalarmrecordByPage/{sendOrNot}")
    @ResponseBody
    public PageResultBean<TraffalarmrecordResult> queryTraffalarmrecordByPage(@PathVariable("sendOrNot")String  sendOrNot,@RequestBody TraffalarmrecordParams params) {

        String[] arry = {};
        Map parammap = new HashMap();
        parammap.put("videoids", Arrays.asList(params.getVideoids() == "" ? arry : params.getVideoids().split(",")));
        parammap.put("starttime", params.getStarttime());
        parammap.put("endtime", params.getEndtime());
        parammap.put("recordtype", params.getRecordtype());
        parammap.put("checkstatus", params.getCheckstatus());
        parammap.put("deptid", params.getDeptid());
        parammap.put("construction", params.getConstruction());
        parammap.put("objlables", Arrays.asList(params.getObjlabel() == "" ? arry : params.getObjlabel().split(",")));
        parammap.put("processstatus", Arrays.asList(params.getProcessstatus() == "" ? arry : params.getProcessstatus().split(",")));
        parammap.put("rectificationtype",params.getRectificationtype());
        parammap.put("pushstatus",sendOrNot);
        List<TraffalarmrecordResult> traffalarmrecordResults =
                trafficStatisticsService.queryTraffalarmrecordByPage(parammap, params.getPage()
                        , params.getLimit());

        PageInfo<TraffalarmrecordResult> rolePageInfo = new PageInfo<>(traffalarmrecordResults);
        return new PageResultBean<TraffalarmrecordResult>(rolePageInfo.getTotal(), rolePageInfo.getList());
    }

    //更新告警状态
    @PostMapping("/updateTraffalarmrecordById")
    @ResponseBody
    public ResultBean updateTraffalarmrecordById(@RequestBody List<Traffalarmrecord> recrdlist) {
      //支持对某一点位某一事件类型标注正检后，该事件类型之前的MANUALCHECKTIME 重复事件类型自动标注为正检.
        int result = trafficStatisticsService.updateTraffalarmrecordById(recrdlist);
        //记录该次正检的时间
        int result2 = trafficStatisticsService.updateVideochecktime(recrdlist);
        return ResultBean.success();
    }


    @GetMapping("/fielagent")
    protected void fielagent(@RequestParam("ftpPath") String ftpPath, HttpServletRequest request, HttpServletResponse response) {
        long startTime = System.currentTimeMillis();
        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) { // ftp
                            ftpUrl = (FtpURLConnection) url.openConnection();
                            ftpUrl.setConnectTimeout(5000);
                            ftpUrl.setReadTimeout(5000);
                            bis = new BufferedInputStream(ftpUrl.getInputStream());
                            response.setContentLength(ftpUrl.getContentLength());
                        } else { // http
                            httpUrl = (HttpURLConnection) url.openConnection();
                            httpUrl.setConnectTimeout(5000);
                            httpUrl.setReadTimeout(5000);
                            bis = new BufferedInputStream(httpUrl.getInputStream());
                            response.setContentLength(httpUrl.getContentLength());
                        }
                        toClient = response.getOutputStream();
                        IOUtils.copy(bis, toClient);
                    } catch (Exception e) {
                        response.setContentType("text/html;charset=GBK");
                        response.setCharacterEncoding("GBK");
                        PrintWriter out = response.getWriter();
                        out.write("无法打开图片!");
                        out.flush();
                    } finally {
                        if (bis != null) {
                            bis.close();
                        }
                        if (bis != null) {
                            bis.close();
                        }
                        if (httpUrl != null) {
                            httpUrl.disconnect();
                        }
                        if (ftpUrl != null) {
                            ftpUrl.close();
                        }
                        if (toClient != null) {
                            toClient.close();
                        }
                    }
                }
                return;
            }

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

    }

    @OperationLog("查询今天所有车流量,同比环比按照上个月和上周时间")
    @GetMapping("/list/todayvehiclesByVideoId")
    @ResponseBody
    public ResultBean todayvehiclesByVideoId(@RequestParam("videoId") String videoId,
                                             @RequestParam("starttime") String starttime,
                                             @RequestParam("endtime") String endtime) {
        Map map = new HashMap();
        map.put("starttime", starttime);
        map.put("endtime", endtime);
        map.put("videoId", videoId);
        List<VehiclesStatisticResult> carList = trafficStatisticsService.todayvehiclesByVideoId(map);

        Date entdate = DateUtils.parseDate(endtime);
        Date startdate = DateUtils.parseDate(starttime);

        map.put("starttime", DateUtils.getlastMonthTime(startdate, -1));
        map.put("endtime", DateUtils.getlastMonthTime(entdate, -1));
        map.put("videoId", videoId);
        List<VehiclesStatisticResult> tbcarList = trafficStatisticsService.todayvehiclesByVideoId(map);
        //上周
        map.put("starttime", DateUtils.getlastDayTime(startdate, -7));
        map.put("endtime", DateUtils.getlastDayTime(entdate, -7));
        map.put("videoId", videoId);
        List<VehiclesStatisticResult> hbcarList = trafficStatisticsService.todayvehiclesByVideoId(map);
        for (VehiclesStatisticResult item : carList) {
            for (VehiclesStatisticResult tbitem : tbcarList) {
                item.setTbtotal(tbitem.getTotal());
                item.setTbcoach(tbitem.getCoach());
                item.setTbgoodsvan(tbitem.getGoodsvan());
                item.setTbother(tbitem.getOther());
                item.setTbsedan(tbitem.getSedan());
            }

            for (VehiclesStatisticResult hbitem : hbcarList) {
                item.setHbtotal(hbitem.getTotal());
                item.setHbcoach(hbitem.getCoach());
                item.setHbgoodsvan(hbitem.getGoodsvan());
                item.setHbother(hbitem.getOther());
                item.setHbsedan(hbitem.getSedan());
            }
        }
        return ResultBean.success(carList);
    }


    @OperationLog("查询今日实时车辆，间隔为一个小时")
    @GetMapping("/list/todayvehiclesByeveryhour")
    @ResponseBody
    public ResultBean todayvehiclesByeveryhour(@RequestParam("videoId") String videoId,
                                               @RequestParam("starttime") String starttime,
                                               @RequestParam("endtime") String endtime) {
        Map map = new HashMap();
        map.put("starttime", starttime);
        map.put("endtime", endtime);
        map.put("videoId", videoId);
        List<VehiclesStatisticResult> carList = trafficStatisticsService.todayvehiclesByeveryhour(map);
//


        return ResultBean.success(carList);
    }

    @OperationLog("查询今日实时事件，间隔为一个小时")
    @GetMapping("/list/todaytraffRecordByeveryhour")
    @ResponseBody
    public ResultBean todaytraffRecordByeveryhour(@RequestParam("videoId") String videoId,
                                                  @RequestParam("starttime") String starttime,
                                                  @RequestParam("endtime") String endtime) {
        Map map = new HashMap();
        map.put("starttime", starttime);
        map.put("endtime", endtime);
        map.put("videoId", videoId);
        List<RecordResult> carList = trafficStatisticsService.todaytraffRecordByeveryhour(map);
        return ResultBean.success(carList);
    }

    @OperationLog("查询事件本月及各分类数量")
    @GetMapping("/list/todaytraffRecords")
    @ResponseBody
    public ResultBean todaytraffRecords(@RequestParam("videoId") String videoId,
                                        @RequestParam("starttime") String starttime,
                                        @RequestParam("endtime") String endtime) {
        Map map = new HashMap();
        map.put("starttime", starttime);
        map.put("endtime", endtime);
        map.put("videoId", videoId);
        List<RecordResult> carList = trafficStatisticsService.todaytraffRecords(map);

        Date entdate = DateUtils.parseDate(endtime);
        Date startdate = DateUtils.parseDate(starttime);
        map.put("starttime", DateUtils.getlastMonthTime(startdate, -1));
        map.put("endtime", DateUtils.getlastMonthTime(startdate, -1));

        List<Map> tblist = trafficStatisticsService.todaythbtraffRecords(map);

        //上周
        map.put("starttime", DateUtils.getlastDayTime(startdate, -7));
        map.put("endtime", DateUtils.getlastDayTime(entdate, -7));
        List<Map> hblist = trafficStatisticsService.todaythbtraffRecords(map);


        for (RecordResult item : carList) {
            for (Map mp : tblist) {
                if (null != mp.get("total"))
                    item.setTbtotal(String.valueOf(mp.get("total")));
            }

            for (Map mp : hblist) {
                if (null != mp.get("total"))
                    item.setHbtotal(String.valueOf(mp.get("total")));
            }

        }


        return ResultBean.success(carList);
    }


    @OperationLog("查询历史一个月事件及各分类数量")
    @GetMapping("/list/historytraffRecords")
    @ResponseBody
    public ResultBean selecthistorytraffRecords(@RequestParam("videoId") String videoId,
                                                @RequestParam("starttime") String starttime,
                                                @RequestParam("endtime") String endtime) {
        Map map = new HashMap();
        map.put("starttime", starttime);
        map.put("videoId", videoId);
        map.put("endtime", endtime);
        List<VehiclesStatisticResult> carList = trafficStatisticsService.selecthistorytraffRecords(map);
        return ResultBean.success(carList);
    }


    @OperationLog("查询历史一个月流量及各分类数量")
    @GetMapping("/list/historyvehicles")
    @ResponseBody
    public ResultBean selecthistoryvehicles(@RequestParam("videoId") String videoId,
                                            @RequestParam("starttime") String starttime,
                                            @RequestParam("endtime") String endtime) {
        Map map = new HashMap();
        map.put("starttime", starttime);
        map.put("videoId", videoId);
        map.put("endtime", endtime);
        List<VehiclesStatisticResult> carList = trafficStatisticsService.selecthistoryvehicles(map);
        return ResultBean.success(carList);
    }


    @OperationLog("查询推送第三方的记录")
    @GetMapping("/list/pushrecordsBypage")
    @ResponseBody
    public PageResultBean<Traffalarmrecord> selectPushRecordsBypage(@RequestParam("page") Integer page,
                                                                    @RequestParam("limit") Integer limit,
                                                                    @RequestParam("pushstatus") String pushstatus,
                                                                    @RequestParam("deptid") String deptid,
                                                                    @RequestParam("construction") String construction) {
        Map map = new HashMap();
//        map.put("starttime", starttime);
        map.put("pushstatus", pushstatus);
//        map.put("endtime", endtime);
        map.put("deptid", deptid);
        map.put("construction", construction);
        List<Traffalarmrecord> carList = trafficStatisticsService.selectPushRecordsBypage(map, page, limit);
        PageInfo<Traffalarmrecord> rolePageInfo = new PageInfo<>(carList);
        return new PageResultBean<>(rolePageInfo.getTotal(), rolePageInfo.getList());

    }

    @OperationLog("统计事件推送结果")
    @PostMapping("/list/eventresultBypage")
    @ResponseBody
    public PageResultBean<Traffalarmrecordstate> selecteventresultBypage(@RequestBody TraffalarmrecordstatParams traffalarmrecordstatParams) {

        List<Traffalarmrecordstate> carList = trafficStatisticsService.selecteventresultBypage(traffalarmrecordstatParams);
        PageInfo<Traffalarmrecordstate> rolePageInfo = new PageInfo<>(carList);
        return new PageResultBean<>(rolePageInfo.getTotal(), rolePageInfo.getList());

    }


    @OperationLog("导出事件结果")
    @RequestMapping("/expTraffalarmrecord")
    @ResponseBody
    public void expTraffalarmrecordstat(HttpServletResponse response, TraffalarmrecordstatParams traffalarmrecordstatParams) {
        String eventname = traffalarmrecordstatParams.getEventtype();
        List<Traffalarmrecordstate> traffalarmrecordstats = trafficStatisticsService.selecteventresultBypage(traffalarmrecordstatParams);
        List<HashMap> lists = new ArrayList<>();
        for (Traffalarmrecordstate m : traffalarmrecordstats) {
            HashMap<String, Object> listMap = new HashMap<>();
            listMap.put("countdate", m.getCountdate());
            listMap.put("eventname", StringUtils.isBlank(eventname) ? "全部" : m.getEventtypename());
            listMap.put("areaname", m.getAreaname());
            listMap.put("totalcount", m.getTotalcount());
            lists.add(listMap);
        }

        ExcelCol[] cells = new ExcelCol[8];
        cells[0] = new ExcelCol();
        cells[0].setColKey("countdate");
        cells[0].setColName("日期");
        cells[1] = new ExcelCol();
        cells[1].setColKey("eventname");
        cells[1].setColName("事件类型");
        cells[2] = new ExcelCol();
        cells[2].setColKey("areaname");
        cells[2].setColName("支队名称");
        cells[3] = new ExcelCol();
        cells[3].setColKey("totalcount");
        cells[3].setColName("事件数量");
        cells[4] = new ExcelCol();
        cells[4].setColKey("checkstatusms");
        cells[4].setColName("免审");
        Map<String, Object> params = new HashMap<>(4);
        SimpleDateFormat formart = new SimpleDateFormat("yyyy-MM-dd");
        String dateTime = formart.format(new Date());
        params.put("fileName", "推送统计-" + dateTime);
        params.put("sheetName", "推送统计");
        params.put("header", "推送统计");
        new ExportEngine().exportCommData(params, cells, lists, response);

    }

    //删除某一事件
    @OperationLog("取消推送事件信息")
    @GetMapping("/deleteTraffalarmrecordById/{recordid}")
    @ResponseBody
    public ResultBean deleteTraffalarmrecordById(@PathVariable("recordid") String recordid) {
        return ResultBean.success(trafficStatisticsService.deleteTraffalarmrecordById(recordid));
    }

    //发送消息
    @OperationLog("更新推送状态")
    @GetMapping("/updateTraffalarmrecordPushStatusById/{recordid}")
    @ResponseBody
    public ResultBean updateTraffalarmrecordPushStatusById(@PathVariable("recordid") String recordid) {
        trafficStatisticsService.updateTraffalarmrecordPushStatusById(recordid);
        //调用事件推送平台发送服务
        HttpHeaders headers = new HttpHeaders();
        HttpEntity<String> requestEntity = new HttpEntity<>(null, headers);
        RestTemplate client = new RestTemplate();
        try {
            ResponseEntity<String> request = client.exchange("http://" + pushrecordurl + "/" + recordid, HttpMethod.GET, requestEntity, String.class);

            if (request.getBody().equalsIgnoreCase("1")) {
                //推送成功，告知前台
                return ResultBean.success();

            }
        }catch (Exception ex) {

            return ResultBean.error("推送失败");
        }
        return ResultBean.success();

    }

    @OperationLog("导出事件")
    @RequestMapping("/expAllTraffalarmrecord/{sendOrNot}")
    @ResponseBody
    public void  expAllTraffalarmrecord(HttpServletResponse response,@PathVariable("sendOrNot")String  sendOrNot,@RequestBody  TraffalarmrecordParams params) {

        String[] arry = {};
        Map parammap = new HashMap();
        parammap.put("videoids", Arrays.asList(params.getVideoids() == "" ? arry : params.getVideoids().split(",")));
        parammap.put("starttime", params.getStarttime());
        parammap.put("endtime", params.getEndtime());
        parammap.put("recordtype", params.getRecordtype());
        parammap.put("checkstatus", params.getCheckstatus());
        parammap.put("deptid", params.getDeptid());
        parammap.put("construction", params.getConstruction());
        parammap.put("objlables", Arrays.asList(params.getObjlabel() == "" ? arry : params.getObjlabel().split(",")));
        parammap.put("processstatus", Arrays.asList(params.getProcessstatus() == "" ? arry : params.getProcessstatus().split(",")));
        parammap.put("rectificationtype", params.getRectificationtype());
        parammap.put("pushstatus", sendOrNot);
        List<TraffalarmrecordResult> traffalarmrecordResults =
                trafficStatisticsService.expTraffalarmrecord(parammap);
        //新增到excel  中
        List<Map> lists = new ArrayList<>();
        for (TraffalarmrecordResult item : traffalarmrecordResults) {
            HashMap<String, Object> listMap = new HashMap<>();
            listMap.put("sbbh",item.getFdid());
            listMap.put("tdbh",item.getChannelid());
            listMap.put("tdmc",item.getTdmc());
            listMap.put("xzbh",item.getAreaid());
            listMap.put("xzmc", item.getXzmc());
            listMap.put("recordtime", DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss",item.getRecordtime()));
            listMap.put("recordlevel", item.getAlarmlevel());
            listMap.put("recordname", item.getRecordname());
            lists.add(listMap);
        }

        Map<String, Object> param= new HashMap<>(4);
        SimpleDateFormat formart = new SimpleDateFormat("yyyy-MM-dd");
        String dateTime = formart.format(new Date());
        param.put("fileName", "告警事件-" + dateTime);
        param.put("sheetName", "告警事件");
        param.put("header", "告警事件");
//        new ExportEngine().exportCommData(param, cells, lists, response);
        new ExportEngine().exportData("告警事件", exportcolumn,enexportcolumn, lists, response);
    }


}
