package com.bootdo.datasend.dianxin.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.Feature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bootdo.datasend.dianxin.cache.DeviceCache;
import com.bootdo.datasend.dianxin.domain.BaseUserRecord;
import com.bootdo.datasend.dianxin.domain.BaseVehicleRecord;
import com.bootdo.datasend.dianxin.domain.DevopsDeviceInfo;
import com.bootdo.datasend.dianxin.domain.dto.*;
import com.bootdo.datasend.dianxin.service.BaseUserRecordService;
import com.bootdo.datasend.dianxin.service.BaseVehicleRecordService;
import com.bootdo.util.Base64Util;
import com.bootdo.util.StringKit;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

@Component
@RequiredArgsConstructor
public class StandardTask {
    private static final Logger logger = LoggerFactory.getLogger(StandardTask.class);
    private final BaseVehicleRecordService vehicleRecordService;
    private final RestTemplate restTemplate;
    private final BaseUserRecordService userRecordService;
    private final RabbitTemplate rabbitTemplate;

    //    @Scheduled(cron = "0/5 * * * * ? ")
    @Scheduled(cron = "0/30 * * * * ? ")
    public void sendVehicleRecord() {

        List<BaseVehicleRecord> lists = vehicleRecordService.list(new QueryWrapper<BaseVehicleRecord>()
                .eq("is_send", "0")
                .last("limit 100")
                .orderByAsc("id")
        );

        for (BaseVehicleRecord h : lists) {


            String deviceId = h.getDeviceIp();
            String deviceCacheStr = DeviceCache.get(deviceId);
            String passDirection = "";
            DevopsDeviceInfo deviceInfo = null;
            if ("".equals(StringKit.toString(deviceCacheStr))) {
                logger.info("当前设备缓存中不存在:" + deviceId);
            } else {
                logger.info("当前设备获取到缓存:" + deviceId);
                deviceInfo = JSON.parseObject(deviceCacheStr, DevopsDeviceInfo.class, Feature.IgnoreNotMatch);
            }


            VehicleRecordDto dto = new VehicleRecordDto();

            VehicleRequestDataDTO dataDTO = new VehicleRequestDataDTO();
            dataDTO.setRequestFlag("1");

            VehicleRequestDataListDTO requestDataListDTO = new VehicleRequestDataListDTO();
            if (deviceInfo != null) {
                requestDataListDTO.setGatewaySN(deviceInfo.getGeminiSn());
            }
            requestDataListDTO.setPassTime(StringKit.toString(h.getPassTime()));
            if (h.getPlatePic() != null) {
                requestDataListDTO.setPlatePicBase64(Base64Util.getBase64ByUrl(h.getPlatePic()));
            }
            if (h.getGlobalPic() != null) {
                requestDataListDTO.setGlobalPicBase64(Base64Util.getBase64ByUrl(h.getGlobalPic()));
            }
            requestDataListDTO.setPlateNo(h.getPlateNo());
            requestDataListDTO.setDeviceSN(h.getGbsChannelNo());
            requestDataListDTO.setGlobalPic(h.getGlobalPic());
            requestDataListDTO.setUserName(h.getOwnerName());
            requestDataListDTO.setPassDirection(StringKit.toString(deviceInfo.getDirection()));
            List<VehicleRequestDataListDTO> list = new ArrayList<>();
            list.add(requestDataListDTO);
            dataDTO.setRequestDataList(list);
            dto.setRequestData(dataDTO);
            boolean b = sendVehicleMq(dto);
            logger.info("车辆数据发送成功：" + JSON.toJSONString(dto));
            if (b) {
                h.setIsSend(1);
                vehicleRecordService.saveOrUpdate(h);
                logger.info("车辆数据发送成功：" + h.getId());
            }

        }
    }


    @Scheduled(cron = "0/30 * * * * ? ")
    public void sendUserRecord() {

        List<BaseUserRecord> lists = userRecordService.list(new QueryWrapper<BaseUserRecord>()
                .eq("is_send", "0")
                .ne("pass_time", 0L)
                .last("limit 100")
                .orderByAsc("id")
        );

        for (BaseUserRecord h : lists) {

            String deviceId = h.getDeviceIp();
            String deviceCacheStr = DeviceCache.get(deviceId);
            DevopsDeviceInfo deviceInfo = null;
            if ("".equals(StringKit.toString(deviceCacheStr))) {
                logger.info("当前设备缓存中不存在:" + deviceId);
            } else {
                logger.info("当前设备获取到缓存:" + deviceId);
                deviceInfo = JSON.parseObject(deviceCacheStr, DevopsDeviceInfo.class, Feature.IgnoreNotMatch);
            }

            UserRecordDto dto = new UserRecordDto();

            UserRequestDataDTO dataDTO = new UserRequestDataDTO();
            dataDTO.setRequestFlag("1");

            UserRequestDataListDTO requestDataListDTO = new UserRequestDataListDTO();


            if (deviceInfo != null) {
                requestDataListDTO.setGatewaySN(deviceInfo.getGeminiSn());
            }
            requestDataListDTO.setPassTime(StringKit.toString(h.getPassTime()));
            requestDataListDTO.setPersonPicBase64(Base64Util.getBase64ByUrl(h.getPersonPic()));
            requestDataListDTO.setGlobalPicBase64(Base64Util.getBase64ByUrl(h.getGlobalPic()));
            requestDataListDTO.setPassDirection(StringKit.toString(deviceInfo.getDirection()));
            requestDataListDTO.setDeviceSN(h.getGbsChannelNo());
            List<UserRequestDataListDTO> list = new ArrayList<>();
            list.add(requestDataListDTO);
            dataDTO.setRequestDataList(list);
            dto.setRequestData(dataDTO);

            boolean result = sendUserMq(dto);
            logger.info("人脸数据发送成功：" + JSON.toJSONString(dto));
            if (result) {
                h.setIsSend(1);
                userRecordService.saveOrUpdate(h);
                logger.info("人脸数据发送成功：" + h.getId());
            }
        }
    }

    public boolean sendVehicleMq(VehicleRecordDto bean) {
        try {
            rabbitTemplate.convertAndSend("warnrecord", "routing.key.vehiclerecord", JSON.toJSONString(bean));
            logger.info("车辆数据发送成功：" + JSON.toJSONString(bean));
        } catch (Exception e) {
            return false;
        }
        return true;
    }


    public boolean sendUserMq(UserRecordDto bean) {
        try {
            rabbitTemplate.convertAndSend("warnrecord", "routing.key.userrecord", JSON.toJSONString(bean));
            logger.info("人脸数据发送成功：" + JSON.toJSONString(bean));
        } catch (Exception e) {
            return false;
        }
        return true;
    }
}
