package com.fastbee.iot.timer;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.fastbee.deviceData.api.devlink.service.ZhanLianMetDataService;
import com.fastbee.deviceData.api.devlink.service.ZhanLianMiaoQingDataService;
import com.fastbee.deviceData.api.devlink.service.ZhanLianMoistureDataService;
import com.fastbee.deviceData.api.devlink.service.ZhanLianPhotovoltaicDataService;
import com.fastbee.deviceData.api.renke.service.RenkeTargetpestsDeviceDataService;
import com.fastbee.deviceData.api.renke.service.RenkeWormDeviceDataService;
import com.fastbee.deviceData.domain.*;

import com.fastbee.deviceData.mapper.*;
import com.fastbee.deviceData.service.IDeviceRealtimedataWormsService;
import com.fastbee.deviceData.service.impl.DeviceRealtimedataMeteorologyServiceImpl;
import com.fastbee.deviceData.service.impl.DeviceRealtimedataMoistureServiceImpl;
import com.fastbee.deviceData.service.impl.DeviceRealtimedataWormsServiceImpl;
import com.fastbee.deviceInfo.domain.DeviceInformationMeteorology;
import com.fastbee.deviceInfo.domain.DeviceInformationMoisture;
import com.fastbee.deviceInfo.domain.DeviceInformationTargetpests;
import com.fastbee.deviceInfo.domain.DeviceInformationWorms;
import com.fastbee.deviceInfo.mapper.*;
import com.fastbee.iot.mapper.DeviceMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author mijiupro
 */
@Component("agricultureDeviceDateTask")
@Slf4j
public class DeviceDateTask {
//

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

//    @Autowired
//    private ThreadPoolTaskExecutor taskExecutor;

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private DeviceRealtimedataWormsServiceImpl wormsSaveDataService;//虫情

    @Autowired
    private DeviceRealtimedataMeteorologyServiceImpl meteorologySaveDataService;

    @Autowired
    private DeviceRealtimedataMoistureServiceImpl moistureSaveDataService;

    @Autowired
    private DeviceRealtimedataPhotovoltaicMapper deviceRealtimedataPhotovoltaicMapper;

    @Autowired
    private DeviceRealtimedataMiaoqingMapper deviceRealtimedataMiaoqingMapper;

    @Autowired
    private RenkeWormDeviceDataService wormsService; //虫情设备数据获取

    @Autowired
    private ZhanLianMetDataService metDataService; //气象设备数据获取

    @Autowired
    private ZhanLianMoistureDataService moistureDataService; //墒情设备数据获取

    @Autowired
    private ZhanLianPhotovoltaicDataService photovoltaicDataService; //光伏设备数据获取

    @Autowired
    private ZhanLianMiaoQingDataService miaoQingDataService; //苗情设备数据获取

    @Autowired
    private RenkeTargetpestsDeviceDataService targetpestsDeviceDataService;


    @Autowired
    private DeviceInformationWormsMapper wormsMapper;

    @Autowired
    private DeviceInformationMeteorologyMapper meteorologyMapper;

    @Autowired
    private DeviceInformationMoistureMapper moistureMapper;

    @Autowired
    private DeviceInformationMonitorMapper monitorMapper;

    @Autowired
    private DeviceInformationTargetpestsMapper targetpestsMapper;




    /**
     * 获取虫情设备实时数据并保存
     */
    public void getWormsDeviceRealtimeData() {
        List<DeviceInformationWorms> list = new LambdaQueryChainWrapper<>(wormsMapper).select(DeviceInformationWorms::getDeviceEncoding).list();
        List<String> deviceEncodingList = list.stream().map(DeviceInformationWorms::getDeviceEncoding).collect(Collectors.toList());
        StringBuilder deviceAddrsStringBuilder= new StringBuilder("");
        //离线设备列表
        List<String> offlineDeviceList = new ArrayList<>();
        //在线设备列表
        List<String> onlineDeviceList = new ArrayList<>();
        for (String deviceEncoding : deviceEncodingList) {
            deviceAddrsStringBuilder.append(deviceEncoding);
            deviceAddrsStringBuilder.append(",");
        }
        try{
            //去除最后，
            StringBuilder stringBuilder = deviceAddrsStringBuilder.deleteCharAt(deviceAddrsStringBuilder.length() - 1);
            String deviceAddrs = stringBuilder.toString();
            List<DeviceRealtimedataWorms> deviceRealtimedataWorms = wormsService.setData(deviceAddrs);
            new LambdaUpdateChainWrapper<>(wormsMapper).in(DeviceInformationWorms::getDeviceEncoding,"1017240042").set(DeviceInformationWorms::getStatus, 1).update();
            boolean saved = wormsSaveDataService.saveBatch(deviceRealtimedataWorms);
            if (!saved){
                System.out.println("插入数据失败!");
            }
        }
        catch (Exception e){
            log.error("获取虫情设备实时数据失败",e);
            new LambdaUpdateChainWrapper<>(wormsMapper).in(DeviceInformationWorms::getDeviceEncoding,"1017240042").set(DeviceInformationWorms::getStatus, 0).update();
        }

    }

    /**
     * 获取气象设备实时数据并保存
     */
    public void getDevLinkMetDeviceRealtimeData(){
        List<DeviceInformationMeteorology> list = new LambdaQueryChainWrapper<>(meteorologyMapper).select(DeviceInformationMeteorology::getDeviceEncoding).list();
        List<String> deviceEncodingList = list.stream().map(DeviceInformationMeteorology::getDeviceEncoding).collect(Collectors.toList());
        //离线设备列表
        List<String> offlineDeviceList = new ArrayList<>();
        //在线设备列表
        List<String> onlineDeviceList = new ArrayList<>();
        try{
            deviceEncodingList.forEach(deviceEncoding->{
                Map<String, String> deviceRealTimeData = new HashMap<>();
                try{
                    deviceRealTimeData = metDataService.getDeviceRealTimeData(deviceEncoding);
                    onlineDeviceList.add(deviceEncoding);
                }
                catch (Exception e){
                    offlineDeviceList.add(deviceEncoding);
                }
                DeviceRealtimedataMeteorology deviceRealtimedataMeteorology = metDataService.setData(deviceRealTimeData);
                boolean save = meteorologySaveDataService.save(deviceRealtimedataMeteorology);
                if (!save){
                    System.out.println("插入数据失败!");
                }
            });
            if(!onlineDeviceList.isEmpty()){
                new LambdaUpdateChainWrapper<>(meteorologyMapper).in(DeviceInformationMeteorology::getDeviceEncoding,onlineDeviceList).set(DeviceInformationMeteorology::getStatus, 1).update();
            }

        }
        catch (Exception e){
            log.error("获取气象设备实时数据失败",e);
            if(!offlineDeviceList.isEmpty()){
                new LambdaUpdateChainWrapper<>(meteorologyMapper).in(DeviceInformationMeteorology::getDeviceEncoding,offlineDeviceList).set(DeviceInformationMeteorology::getStatus, 0).update();
            }
        }
    }
    /**
     * 获取墒情设备实时数据并保存
     */
    public void getDevLinkMoistureDeviceRealtimeData() {
        List<DeviceInformationMoisture> list = new LambdaQueryChainWrapper<>(moistureMapper).select(DeviceInformationMoisture::getDeviceEncoding).list();
        List<String> deviceEncodingList = list.stream().map(DeviceInformationMoisture::getDeviceEncoding).collect(Collectors.toList());
        //离线设备列表
        List<String> offlineDeviceList = new ArrayList<>();
        //在线设备列表
        List<String> onlineDeviceList = new ArrayList<>();
        try{
                deviceEncodingList.forEach(deviceEncoding->{
                    Map<String, String> deviceRealTimeData = new HashMap<>();
                    try {
                         deviceRealTimeData = moistureDataService.getDeviceRealTimeData(deviceEncoding);
                         onlineDeviceList.add(deviceEncoding);
                    }catch (Exception e){
                        offlineDeviceList.add(deviceEncoding);
                    }
                    DeviceRealtimedataMoisture deviceRealtimedataMoisture = moistureDataService.setData(deviceRealTimeData);
                boolean save = moistureSaveDataService.save(deviceRealtimedataMoisture);
                if (!save){
                    log.error("墒情设备"+deviceEncoding+"实时数据插入数据失败!");
                }
            });
            if(!onlineDeviceList.isEmpty()){
                    new LambdaUpdateChainWrapper<>(moistureMapper).in(DeviceInformationMoisture::getDeviceEncoding,onlineDeviceList).set(DeviceInformationMoisture::getStatus, 1).update();
            }
        }
        catch (Exception e){
            log.error("获取墒情设备实时数据失败:{}",e.getMessage());
            if(!offlineDeviceList.isEmpty()){
                new LambdaUpdateChainWrapper<>(moistureMapper).in(DeviceInformationMoisture::getDeviceEncoding,offlineDeviceList).set(DeviceInformationMoisture::getStatus, 0).update();
            }
        }
    }
    /**
     * 获取杀虫灯设备实时数据并保存
     */
    public void getDevLinkTargetpestsDeviceRealtimeData() {
        try{
            //查询杀虫灯设备列表
            StringBuilder deviceAddrsStringBuilder= new StringBuilder("");
            List<DeviceInformationTargetpests> list = new LambdaQueryChainWrapper<>(targetpestsMapper).select(DeviceInformationTargetpests::getDeviceEncoding).list();
            for(DeviceInformationTargetpests targetpests:list){
                deviceAddrsStringBuilder.append(targetpests.getDeviceEncoding());
                deviceAddrsStringBuilder.append(",");
            }
            //去除最后，
            StringBuilder stringBuilder = deviceAddrsStringBuilder.deleteCharAt(deviceAddrsStringBuilder.length() - 1);
            String deviceAddrs = stringBuilder.toString();
            //拼接设备编码
            System.err.println("拼接后设备地址参数编码："+deviceAddrs);
            targetpestsDeviceDataService.setData(deviceAddrs);
        }
        catch (Exception e){
            log.error("获取杀虫灯设备实时数据失败",e);
        }
    }

    /**
     * 获取光伏设备实时数据并保存
     */
    public void getDevLinkPhotovoltaicDeviceRealtimeData() throws Exception{
        DeviceRealtimedataPhotovoltaic deviceRealtimedataPhotovoltaic = photovoltaicDataService.setData(photovoltaicDataService.getDeviceRealTimeData("3276"));
        int i = deviceRealtimedataPhotovoltaicMapper.insert(deviceRealtimedataPhotovoltaic);
        if (i<1)
            System.out.println("插入数据失败!");
    }

    /**
     * 获取苗情设备实时数据并保存
     */
    public void getDevLinkMiaoqingDeviceRealtimeData() throws Exception{
        DeviceRealtimedataMiaoqing deviceRealtimedataMiaoqing = miaoQingDataService.setData(miaoQingDataService.getDeviceRealTimeData("3275"));
        int i = deviceRealtimedataMiaoqingMapper.insert(deviceRealtimedataMiaoqing);
        if (i<1)
            System.out.println("插入数据失败!");
    }

}

