package im.zksy.yjmqserver.system.mqtt;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import im.zksy.yjmqserver.common.util.CommonUtil;
import im.zksy.yjmqserver.common.util.DateUtil;
import im.zksy.yjmqserver.common.util.FTPUtils;
import im.zksy.yjmqserver.system.model.Alarm;
import im.zksy.yjmqserver.system.model.AlarmInfo;
import im.zksy.yjmqserver.system.model.Data;
import im.zksy.yjmqserver.system.model.Picture;
import im.zksy.yjmqserver.system.service.AlarmService;
import im.zksy.yjmqserver.system.service.PictureService;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.util.Date;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.stream.Collectors;

@Configuration

public class PushCallback implements MqttCallback,IMQTTPublisher {
    private static Logger log = LoggerFactory.getLogger(PushCallback.class);
    @Autowired
    private MQTTSubsribe mqttSubsribe;

    @Autowired
    private PictureService pictureService;

    @Autowired
    private AlarmService alarmService;


    @Override
    public void connectionLost(Throwable throwable) {
        // 连接丢失后，一般在这里面进行重连
        log.info("连接断开，重连");
        this.mqttSubsribe.startReconnect();
    }


    @Override

    public void messageArrived(String topic, MqttMessage message) throws Exception {
//        String str =new String(message.getPayload(),"GB2312");
        Alarm alarm = new Alarm();
        JSONObject  alarmjson=null;
        Integer checkvalue = 1;
        try {
            alarmjson = new ObjectMapper().readValue(message.getPayload(), JSONObject.class);
        } catch (Exception ex) {
        }
        if (null!=alarmjson && alarmjson.getString("type").equals("0"))//type 指令类型：0：告警事件 1：边缘设备运行状态
        {
            JSONObject   alarmdata = alarmjson.getJSONObject("data");
            if ((alarmdata.getInteger("label03")!= null && alarmdata.getInteger("label03").equals(checkvalue))  //边界入侵
                    || (alarmdata.getInteger("label13")!= null && alarmdata.getInteger("label13").equals(checkvalue))//人脸考勤
                    || (alarmdata.getInteger("label14") != null && alarmdata.getInteger("label14").equals(checkvalue))//陌生人
                    || (alarmdata.getInteger("label18") != null && alarmdata.getInteger("label18") .equals(checkvalue))//行人跟踪
                    || (alarmdata.getInteger("label19") != null && alarmdata.getInteger("label19").equals(checkvalue))//倒地检测
                    || (alarmdata.getInteger("label20")!= null && alarmdata.getInteger("label20").equals(checkvalue))//行人检测
                    || (alarmdata.getInteger( "label49")!= null && alarmdata.getInteger( "label49").equals(checkvalue))//人员离岗
                    || (alarmdata.getInteger( "label50") != null && alarmdata.getInteger( "label50").equals(checkvalue))//人员聚集
                    || (alarmdata.getInteger( "label51")!= null && alarmdata.getInteger( "label51").equals(checkvalue))//攀高检测
            ) {
                String checkJpg = alarmdata.getString("checkJpg");
                String path = DateUtil.getDateStringNoSign(new Date());
                String picid = CommonUtil.getUUID() + ".jpg";
                alarm.setCheckJpg(path + "/" + picid);
                alarm.setUuid(alarmdata.getString("uuid"));
                alarm.setDataType(alarmjson.getString("dataType"));
                alarm.setType(alarmjson.getString("type"));
                alarm.setIdentity(alarmjson.getString("identity"));
                alarm.setCheckName(alarmdata.getString("checkName"));
                alarm.setCollector_output_file(alarmdata.getString("collector_output_file"));
                alarm.setDevice_model(alarmdata.getString("device_model"));
                alarm.setDevice_sn(alarmdata.getString("device_model"));
                alarm.setDevice_name(alarmdata.getString("device_sn"));
                alarm.setFactory_name(alarmdata.getString("factory_name"));
                alarm.setImageType(alarmdata.getString("imageType"));
                alarm.setIp_addr(alarmdata.getString("ip_addr"));
                alarm.setTime_norm(alarmdata.getString("time_norm"));
                alarm.setVideoPath(alarmdata.getString("videoPath"));
                alarm.setVideoState(alarmdata.getString("videoState"));
                //labeltext
                List<String> list = JSONObject.parseArray(alarmdata.getJSONArray("label_text").toString(),String.class);
                List<String> list_normal = list.stream()
                        .filter(b -> b.indexOf("人脸考勤") < 0 && b.indexOf("陌生人") < 0 && b.indexOf("行人跟踪") < 0 && b.indexOf("行人检测") < 0)
                        .collect(Collectors.toList());
                //过滤人员进行人员靠近数据替换
                List<String> list_rykj = list.stream()
                        .filter(b -> b.indexOf("人脸考勤") >= 0 || b.indexOf("陌生人") >= 0 || b.indexOf("行人跟踪") >= 0 || b.indexOf("行人检测") >= 0)
                        .collect(Collectors.toList());
                if (list_rykj.size() > 0) {
                    list_normal.add("人员靠近");
                }
                list_normal= list_normal.stream().distinct().collect(Collectors.toList());
                alarm.setLabel_text(list_normal);
                int alarmid = alarmService.insert(alarm); //入表
                //异步上传ftpconnectServer
                if(null!=checkJpg && !checkJpg.equals("")){
                    FTPUtils util = new FTPUtils();
                    try {
                        Picture pic = new Picture();
                        //                        pic.setId(alarm.getId());
                        pic.setImgpath(path + "/" + picid);
                        if (util.uploadFile(path, picid, checkJpg)) {
                            pic.setImg("");
                            pic.setStatus("1");//成功
                        } else {
                            //记录入表.失败保留图片base64？
                            pic.setImg(checkJpg);
                            pic.setStatus("0");
                        }
                        pictureService.insert(pic);

                    } catch (Exception ex) {
                        log.error(ex.toString());
                    }
                }else{
                    log.info("无图片");
                }
            }
        }
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {
        log.info("deliveryComplete---------" + token.isComplete());
    }

    @Override
    public void publishMessage(String topic, String message) {

    }

    @Override
    public void disconnect() {
        log.info("disconnect---------" );
    }

}