package com.keystar.plane.inspection.service.impl;

import cn.hutool.core.util.IdUtil;
import com.drew.imaging.jpeg.JpegProcessingException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.keystar.mqtt.bo.MqttMessageBo;
import com.keystar.plane.inspection.bo.NewFileBo;
import com.keystar.plane.inspection.bo.PhotoMqttMessageBo;
import com.keystar.plane.inspection.dao.PlanePhotoVo;
import com.keystar.plane.inspection.entity.PlanePhotoEntity;
import com.keystar.plane.inspection.service.MqttService;
import com.keystar.plane.inspection.service.PhotoService;
import com.keystar.plane.inspection.service.PlanePhotoService;
import com.keystar.plane.inspection.utils.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttAsyncClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Service
public class MqttServiceImpl implements MqttService {

    @Autowired
    MqttAsyncClient mqttAsyncClient;

    @Autowired
    PhotoService photoService;

    @Autowired
    PlanePhotoService planePhotoService;

    @Autowired
    MqttService mqttService;



    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    @Override
    public void sendMqtt(List<PhotoMqttMessageBo> messageBos) throws JsonProcessingException {
        MqttMessage mqttMessage = new MqttMessage();
        Map<String, Object> map = new HashMap<>();
        map.put("data", messageBos);
        byte[] bytes = OBJECT_MAPPER.writeValueAsBytes(map);
        mqttMessage.setPayload(bytes);
        try {
            mqttAsyncClient.publish("LightSpot_recognize",mqttMessage);
        } catch (MqttException e) {

        }
    }

    /**
     *  发送最新任务图片目录给图像识别
     **/
    @Override
    public void sendPhotos(String path, String type) throws JsonProcessingException {
        // 获取新图片的minio地址
//        List<String> newPhoto = FileUtil.getNewPhoto(path);
//        MqttMessage mqttMessage = new MqttMessage();
//        for (String photoPath : newPhoto){
//            // 先初步判断
//
//
//            // 每张图片单独发一个MQ
//            PhotoMqttMessageBo mqttMessageBo = new PhotoMqttMessageBo();
//            mqttMessageBo.setFuncIndex(type);
//            mqttMessageBo.setInfraredImagePath(photoPath);
//            byte[] bytes = OBJECT_MAPPER.writeValueAsBytes(mqttMessageBo);
//            mqttMessage.setPayload(bytes);
//            try {
//                mqttAsyncClient.publish("LightSpot_recognize",mqttMessage);
//            } catch (MqttException e) {
//
//            }
//        }
    }

    /**
     *  发送最新图片目录mqtt给图像
     **/
    @Override
    public void sendPhotoFile(String path, String type) throws JsonProcessingException {
        // 获取最新修改的目录地址
//        String newFilePath = FileUtil.getNewFilePath();
//
//        PhotoMqttMessageBo photoMqttMessageBo = new PhotoMqttMessageBo();
//        Map<String, List<PhotoMqttMessageBo>> map = new HashMap<>();
//        photoMqttMessageBo.setFunc_index("0");
//        photoMqttMessageBo.setInfrared_image_path(path);
//        MqttMessage mqttMessage = new MqttMessage();
//        List<PhotoMqttMessageBo> messageBoList = new ArrayList<>();
//        messageBoList.add(photoMqttMessageBo);
//        map.put("data", messageBoList);
//        byte[] bytes = OBJECT_MAPPER.writeValueAsBytes(map);
//        mqttMessage.setPayload(bytes);
//        try {
//            mqttAsyncClient.publish("sunboard_recognize_result",mqttMessage);
//        } catch (MqttException e) {
//
//        }
    }

    @Override
    public void sendPhotoMqtt() throws IOException, JpegProcessingException, ParseException, InterruptedException {
//        NewFileBo newFile = FileUtil.getNewFilePath();
        NewFileBo newFile = new NewFileBo();
        newFile.setMissionId(2418);
        newFile.setRecordId(1869);
        newFile.setPath("/data/autoUpload/photo/"+ "2418" + "/" + "1869");
        log.info("=====返回的最新的图片文件目录：" + newFile.toString());
        File path = new File(newFile.getPath());
        log.info("=====图片目录：" + path.getPath());
        File[] files = path.listFiles();
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (files != null){
            log.info("======目录里面的文件数：" + files.length);
            // 取出红外图片
            List <PlanePhotoEntity> photoEntityList = new ArrayList<>();
            for ( File file : files){
                log.info("========图片名：" + file.getPath());
                if (file.getName().contains("THRM.jpg") || file.getName().contains("T.jpg") || file.getName().contains("T.JPG") || file.getName().contains("THRM.JPG")){
                    log.info("=======红外图片地址：" + file.getPath());
                    // 且图片是在光伏区内
                    PlanePhotoVo planePhotoVo = photoService.queryPhoto(file.getPath());
                    log.info("======图片算法判断结果："+ planePhotoVo.toString());
                    if (planePhotoVo.getPZName() != null){
                        // 将图片入库
                        PlanePhotoEntity planePhotoEntity = new PlanePhotoEntity();
                        planePhotoEntity.setId(IdUtil.getSnowflake().nextId());
                        // minio地址
                        String minioPath = "nest/autoUpload/photo/"+newFile.getMissionId()+"/"+newFile.getRecordId()+"/"+file.getName();
                        planePhotoEntity.setPath(minioPath);
                        planePhotoEntity.setPzName(planePhotoVo.getPZName());
                        String joined = String.join(",", planePhotoVo.getPVNames());
                        planePhotoEntity.setPvName(joined);
                        planePhotoEntity.setTime(sd.parse(sd.format(new Date(file.lastModified()))));
                        planePhotoEntity.setMissionId(newFile.getMissionId());
                        planePhotoEntity.setRecordId(newFile.getRecordId());
                        photoEntityList.add(planePhotoEntity);
//                        planePhotoService.save(planePhotoEntity);
//                        log.info("======将图片入库：" + planePhotoEntity.toString());

//                        // 发送mqtt给图像识别
//                        Thread.sleep(3000);
//                        PhotoMqttMessageBo photoMqttMessageBo = new PhotoMqttMessageBo();
//                        photoMqttMessageBo.setId(planePhotoEntity.getId());
//                        photoMqttMessageBo.setFunc_index("0");
//                        photoMqttMessageBo.setInfrared_image_path(minioPath);
//                        mqttService.sendMqtt(photoMqttMessageBo);
//                        log.info("======将图片发送mqtt给图像识别：" + photoMqttMessageBo.toString());

                    }

                }
            }
            // 遍历完图片后，一起入库和发给图像识别
            planePhotoService.saveBatch(photoEntityList);
            log.info("======遍历完成，将图像信息入库======");
            List<String> funcIndex = new ArrayList<>();
            // 二极管故障
            funcIndex.add("1");
            // 遮挡
            funcIndex.add("1");
            // 掉串
            funcIndex.add("0");
            List<PhotoMqttMessageBo> messageBoList = new ArrayList<>();
            for ( PlanePhotoEntity photoEntity : photoEntityList){
                PhotoMqttMessageBo photoMqttMessageBo = new PhotoMqttMessageBo();
                photoMqttMessageBo.setId(photoEntity.getId());
                photoMqttMessageBo.setFuncIndex(funcIndex);
                photoMqttMessageBo.setVisibleImagePath("");
                photoMqttMessageBo.setInfraredImagePath(photoEntity.getPath());
                messageBoList.add(photoMqttMessageBo);
            }
            mqttService.sendMqtt(messageBoList);

        }else {
            log.info("======文件夹是空的======");
        }
    }


}
