package com.hzjt.redis;

import com.hzjt.domain.*;
import com.hzjt.handler.FileTransferManager;
import com.hzjt.mapper.TraffAlarmRecordMapper;
import com.hzjt.service.EventWriteService;
import com.hzjt.service.FtpService;
import com.hzjt.util.*;
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.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Service
public class Receiver {

    @Autowired
    RedisDao redisDao;

    @Autowired
    private TraffAlarmRecordMapper traffAlarmRecordMapper;

    @Autowired
    FtpService ftpService;

    @Autowired
    EventWriteService eventWriteService;


    ScheduledExecutorService schedulepool = Executors.newScheduledThreadPool(5); //创

    @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;


    private static final Logger log = LoggerFactory.getLogger(Receiver.class);



    /**
     * @Description: 用于接收单个对象，将对象同步至数据库，如果同步失败，则存入redis中
     * @Param: [message] “fastjson”转换后的json字符串
     * @Retrun: void
     */
    public void receiveSingle(String Message) throws InterruptedException {
        // 将json字符串转换成实体对

        Alarm trffClientMessage= JsonUtil.stringToBean(Message,Alarm.class);
        List<String> imgBase64List = trffClientMessage.getImg_base64();

        Traffalarmrecord traffAlarmRecord = new Traffalarmrecord();
        String imgEnumHead = "IMG";
        Ftp ftp = 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 i = 0; i < imgUrls.size(); i++) {
            TraffAlarmRecordFromImgEnum.valueOf(imgEnumHead + i).setImg(traffAlarmRecord, imgUrls.get(i));
        }
        String[] videoIdArr = trffClientMessage.getVideo_id().split("_");
        String fdid = videoIdArr[0];
        traffAlarmRecord.setFdid(fdid);
        Integer channelid = Integer.valueOf(videoIdArr[1]) + 1;
        traffAlarmRecord.setChannelid(channelid);

        if (StringEnum.ONE.getValue().equals(checkEnable)) {
            /* 9:免审 */
            traffAlarmRecord.setCheckstatus(9);
        }
        int recordid = traffAlarmRecordMapper.selectmax();
        traffAlarmRecord.setRecordid((long)(recordid+1));
        traffAlarmRecord.setProcessstatus("0");
        traffAlarmRecord.setAreaid(Long.valueOf(trffClientMessage.getDept()));
        traffAlarmRecord.setRecordtype(trffClientMessage.getIncident_type().toLowerCase());
        traffAlarmRecord.setVideourlfrom(trffClientMessage.getVideo_record_url());
        traffAlarmRecord.setRecordtime(new Date(Long.valueOf(trffClientMessage.getTs())));
        traffAlarmRecord.setCreatetime(new Date());
        traffAlarmRecord.setObjlable(trffClientMessage.getObjLabel());
        traffAlarmRecord.setPushstatus(9);//设置为未推送

        traffAlarmRecordMapper.inserTraffAlarmRecord(traffAlarmRecord);

        try {
            String basepath = "gstraff/" + traffAlarmRecord.getFdid() + (traffAlarmRecord.getChannelid() < 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);
//            log.info("缓存数据上传结果：" + results.toString());
            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) {
                traffAlarmRecordMapper.updateTraffAlarmRecordUrl(traffAlarmRecord);
            }
            //如果监控视频为空，延时加载重新获取
            if(null==recordBak.getVideopath() || "".equalsIgnoreCase(recordBak.getVideopath())) {

                schedulepool.schedule(()->{
                        for (String key : transferRecordMap.keySet()) {
                            if (key.equals("videopath")) {
                                final String url = transferRecordMap.get(key).toString();
                                try {
                                    HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
                                    //延迟连接
                                    connection.setReadTimeout(2000);
                                    connection.setConnectTimeout(3000);
                                    connection.setRequestMethod("GET");
                                    String pname = DateUtils.formatCurrDayNoSign() + "_" + recordid + "_0000_" + key.replace("path", "");
                                    String fileName = pname + ".mp4";
                                    String ftputl = FTPUtil.getFtpUrl(ftp) + basepath + "/" + fileName;
                                    if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                                        InputStream inputStream = connection.getInputStream();
//                                        log.info("url:", url, " --- " + "key:", key);
                                        boolean r = FTPUtil.uploadFile(ftp, basepath, fileName, inputStream);
                                        if (r) traffAlarmRecord.setVideopath(ftputl);
                                        //只更新监控
                                        if (traffAlarmRecord != null && traffAlarmRecord.getRecordid() != null) {
                                            traffAlarmRecordMapper.updateTraffAlarmRecordUrl(traffAlarmRecord);

                                            //推送给第三方
                                            ResultObj obj = eventWriteService.updateAndAutoSendEvent(traffAlarmRecord);
//                                            log.info("调用接口推送给广达返回信息：" + obj.toString());

                                        }
                                    }
                                } catch (IOException e) {
                                    System.out.println(e.toString());
                                    log.error(e.toString());
                                    return 0;
                                }
                            }

                        }
                        return 1;
                },30, TimeUnit.SECONDS); //等待30秒钟执行
            }else {
                //推送给第三方
                ResultObj obj = eventWriteService.updateAndAutoSendEvent(traffAlarmRecord);
//                log.info("调用接口推送给广达返回信息：" + obj.toString());

            }

        } catch (Exception e) {
            log.error("解析事件告警数据异常 :" + e.getMessage());
        }
//
        redisDao.incrOrDecr(Constant.succSizeTempKey, -1);


    }

    /**
     * @Description: 用于接收对象集合，将集合遍历拆分成单个对象并进行发布
     * @Param: [message] “fastjson”转换后的json字符串
     * @Retrun: void
     */
    public void receiveList(String message) throws InterruptedException {

    }
}
