package com.huimv.environ.eco.schedule;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.huimv.common.utils.Result;
import com.huimv.environ.eco.entity.EcoDevice;
import com.huimv.environ.eco.entity.EcoDeviceFlow;
import com.huimv.environ.eco.mapper.EcoDeviceFlowMapper;
import com.huimv.environ.eco.service.EcoDeviceFlowService;
import com.huimv.environ.eco.service.EcoDeviceService;
import com.huimv.environ.eco.service.EcoDryListService;
import com.huimv.environ.eco.service.SysConfigService;
import com.huimv.environ.env.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.lang.reflect.Array;
import java.text.ParseException;
import java.util.*;

/**
 * @Project : huimv-farm-datacenter
 * @Package : ${}
 * @Description : TODO
 * @Version : 1.0
 * @Author : ZhuoNing
 * @Create : 2022/11/9
 **/
@Component
@Slf4j
public class ScheduleTask {
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private com.huimv.environ.eco.service.EcoDeviceFlowService ecoDeviceFlowService;
    @Autowired
    private EcoDeviceService ecoDeviceService;
    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private EcoDryListService ecoDryListService;
    @Value("${url.threshold.service}")
    private String URL_THRESHOLD_SERVICE;
    @Value("${url.environ.device.service}")
    private String URL_ENVIRON_DEVICE_SERVICE;
//    private static String URL = "http://www.0531yun.com/app/GetDeviceData";

//        @Scheduled(cron = "0 0/5 * * * ?")  //每5分钟执行一次
        @Scheduled(cron = "0 0/1 * * * ?")  //每1分钟执行一次
//    @Scheduled(cron = "*/10 * * * * ?")  //每10秒钟执行一次
    public void autoRunDryList() throws ParseException {
        DateUtil dateUtil = new DateUtil();
        System.out.println("开始取数:" + dateUtil.fromLongToDate(new Date().getTime(), "yyyy-MM-dd HH:mm:ss.SSS"));
        //查询所有设备
//        List<Map> ecoDeviceList = ecoDeviceService.getDeviceList2();
        List<Map> ecoDeviceList = ecoDeviceService.getDryDeviceByDeviceType();
        System.out.println("ecoDeviceList = " + ecoDeviceList);
        System.out.println("ecoDeviceList.size=" + ecoDeviceList.size());
        if (ecoDeviceList.size() == 0) {
            System.out.println("设备记录为空.");
        } else {
            for (int a = 0; a < ecoDeviceList.size(); a++) {
                System.out.println("a========================================================================================================" + a);
                Map deviceMap = ecoDeviceList.get(a);
                Integer farmId = Integer.parseInt(deviceMap.get("farm_id") + "");
                String dryDeviceCode = deviceMap.get("device_code") + "";
                System.out.println("dryDeviceCode=" + dryDeviceCode);
                System.out.println("id=" + deviceMap.get("id"));
                //读取高温阈值数据
                JSONObject thresholdJo = getThresholdURL(farmId);
//                JSONObject thresholdJo = getThresholdURL2(farmId);
                System.out.println("调取牧场[" + farmId + "]服务获取阈值接口：" + thresholdJo);
                if (thresholdJo == null) {
                    log.error("thresholdJo======" + thresholdJo);
                    log.error("牧场[" + farmId + "]暂时没有洗消烘干温度阈值设置.");
                    continue;
                }
                Date todayTime = dateUtil.getTodayDateTime();
                //读取最新一条烘干记录
                System.out.println("最近一条烘干记录 dryDeviceCode=" + dryDeviceCode);
                System.out.println("最近一条烘干记录 todayTime=" + todayTime);
                String datetime = dateUtil.formatDateTime(todayTime);
                System.out.println("最近一条烘干记录 datetime=" + datetime);
                EcoDeviceFlow ecoDeviceFlow = ecoDeviceFlowService.getLastDryDeviceFlow(dryDeviceCode, datetime);
                if (ecoDeviceFlow == null) {
                    log.error("牧场[" + farmId + "]暂时没有取到洗消烘干温度任何数据.");
                    continue;
                }
                //新建烘干记录
                String currentTemp = ecoDeviceFlow.getId1Value();
                System.out.println("当前的烘干温度currentTemp=" + currentTemp);
                ecoDryListService.saveDryList(deviceMap, currentTemp, thresholdJo, todayTime);
            }
        }
        System.out.println("完成取数:" + dateUtil.fromLongToDate(new Date().getTime(), "yyyy-MM-dd HH:mm:ss.SSS"));
    }

    //以下是旧的代码
//    @Scheduled(cron = "0 0/5 * * * ?")  //每5分钟执行一次
//    @Scheduled(cron = "*/5 * * * * ?")  //每10秒钟执行一次
//    public void getDeviceFlow() throws ParseException {
//        DateUtil dateUtil = new DateUtil();
//        System.out.println("开始取数:" + dateUtil.fromLongToDate(new Date().getTime(), "yyyy-MM-dd HH:mm:ss.SSS"));
//        //查询所有设备
//        List<Map> ecoDeviceList = ecoDeviceService.getDeviceList2();
//        System.out.println("ecoDeviceList.size=" + ecoDeviceList.size());
//        if (ecoDeviceList.size() == 0) {
//            System.out.println("设备记录为空.");
//        } else {
//            for (int a = 0; a < ecoDeviceList.size(); a++) {
//                System.out.println("a========================================================================================================" + a);
//                Map deviceMap = ecoDeviceList.get(a);
//                Integer farmId = Integer.parseInt(deviceMap.get("farm_id") + "");
//                String deviceGroupCode = deviceMap.get("device_code") + "";
//                System.out.println("id=" + deviceMap.get("id"));
//                //读取高温阈值数据
//                JSONObject thresholdJo = getThresholdURL(farmId);
//                System.out.println("调取牧场[" + farmId + "]服务获取阈值接口：" + thresholdJo);
//                if (thresholdJo == null) {
//                    log.error("thresholdJo======" + thresholdJo);
//                    log.error("牧场[" + farmId + "]暂时没有洗消烘干温度设置.");
//                    continue;
//                }
//                String cfgName = "userId";
//                // 查询用户userId
//                String userId = sysConfigService.getUserId(farmId, cfgName);
//                if (userId == null) {
//                    System.out.println("牧场[" + farmId + "]的userId不存在.");
//                    continue;
//                }
//                //调用远程设备上传流水接口，查询远程数据
//                JSONObject resultJo = JSONObject.parseObject(getDeviceFlowFromRemoteURL(userId, deviceGroupCode));
//                if (resultJo.getInteger("code") != 1000) {
//                    System.out.println("牧场[" + farmId + "]设备组编号(" + deviceGroupCode + ")调用远程接口返回结果出错.");
//                } else {
//                    JSONArray dataJa = resultJo.getJSONArray("data");
//                    System.out.println("dataJa.size=" + dataJa.size());
//                    JSONObject dataJo = dataJa.getJSONObject(0);
//                    Date todayTime = dateUtil.getTodayDateTime();
//                    //保存温度流水记录
//                    ecoDeviceFlowService.save(dataJo, todayTime);
//                    System.out.println("22 dataJo=" + dataJo);
//                    System.out.println("33 thresholdJo=" + thresholdJo);
//                    //新建烘干记录
//                    ecoDryListService.saveDryList(deviceMap, dataJo, thresholdJo, todayTime);
//                    //新建洗消烘干温度时长不足报警记录
//                    //dryMin = thresholdJo.getString("dryMin");
////                    newShortDryingtime();
//                }
//            }
//        }
//        System.out.println("完成取数:" + dateUtil.fromLongToDate(new Date().getTime(), "yyyy-MM-dd HH:mm:ss.SSS"));
//    }

    //获取阈值
    private JSONObject getThresholdURL(Integer farmId) {
        HttpHeaders httpHeaders = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json;charset=UTF-8");
        httpHeaders.setContentType(type);
        HashMap<String, Object> map = new HashMap<>();
        map.put("farmId", farmId);
        HttpEntity<Map<String, Object>> objectHttpEntity = new HttpEntity<>(map, httpHeaders);
        //读取真实数据
//        String remoteUrl = "http://192.168.1.67:8010/produce/threshold/getThresholdByFarmId";
        System.out.println("URL_THRESHOLD_SERVICE=" + URL_THRESHOLD_SERVICE);
        ResponseEntity<String> entity = restTemplate.postForEntity(URL_THRESHOLD_SERVICE, objectHttpEntity, String.class);
        JSONObject thresholdJo = JSONObject.parseObject(entity.getBody());
        if (thresholdJo.getInteger("code") != 10000) {
            return null;
        }
        return thresholdJo.getJSONObject("data");
    }

    /**
     * @Method : getThresholdURL2
     * @Description :
     * @Params : [farmId]
     * @Return : com.alibaba.fastjson.JSONObject
     * @Author : ZhuoNing
     * @Date : 2022/12/6
     * @Time : 20:12
     */
    private JSONObject getThresholdURL2(Integer farmId) {
        //        设置请求头，请求类型为json
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
//        设置请求参数
        HashMap<String, Object> map = new HashMap<>();
        map.put("farmId", farmId);
        //用HttpEntity封装整个请求报文
        HttpEntity<HashMap<String, Object>> request = new HttpEntity<>(map, headers);
        //读取真实数据
//        String remoteUrl = "http://192.168.1.67:8010/produce/threshold/getThresholdByFarmId";
        String url = "http://localhost:10052/threshold/getThresholdByFarmId";
        System.out.println("url=" + url);
        JSONObject resultJo = restTemplate.postForObject(url, request, JSONObject.class);
        System.out.println("resultJo=" + resultJo);
        if (resultJo.getInteger("code") != 10000) {
            return null;
        }
        return resultJo.getJSONObject("data");
    }

    //获取远程数据
    private String getDeviceFlowFromRemoteURL(String userId, String groupId) {
        //请求头
        HttpHeaders headers = new HttpHeaders();
        headers.add("userId", userId);
        //Body参数
        MultiValueMap<String, Object> paramsMap = new LinkedMultiValueMap<String, Object>();
        HttpEntity<MultiValueMap> objectHttpEntity = new HttpEntity<MultiValueMap>(paramsMap, headers);
        System.out.println("URL_ENVIRON_DEVICE_SERVICE=" + URL_ENVIRON_DEVICE_SERVICE);
        ResponseEntity<String> result = restTemplate.exchange(URL_ENVIRON_DEVICE_SERVICE + "?groupId=" + groupId, HttpMethod.GET, objectHttpEntity, String.class);
        return result.getBody();
    }

    // ################################# 以下部分是可以优化提炼的代码 #################################

//        List headerList = new ArrayList();
//        List getParamsList = new ArrayList();
//        List postParamsList = new ArrayList();
//        //获取远程数据
//        String remoteData = getBodyFromRemoteURL(headerList, getParamsList);
////        System.out.println("result = " + result.getBody(remoteData));
//        JSONObject resultJo = JSONObject.parseObject(remoteData);
//        if (resultJo.getInteger("code") != 1000) {
//            System.out.println("返回出错.");
//        } else {
//            JSONArray dataJa = resultJo.getJSONArray("data");
//            for (int a = 0; a < dataJa.size(); a++) {
//                JSONObject dataJo = dataJa.getJSONObject(a);
//                ecoDeviceFlowService.save(dataJo);
//            }
//        }

    // String remoteData = getBodyFromRemoteURL(headerList, getParamsList);
    //做成通用远程接口
//    private String getBodyFromRemoteURL(List headerList, List getParamsList) {
//        //请求头
//        HttpHeaders headers = new HttpHeaders();
//        headers.add("userId", "-1618620464");
//        //Body参数
//        MultiValueMap<String, Object> paramsMap = new LinkedMultiValueMap<String, Object>();
////        paramsMap.add("groupId", "24234390");
//        //封装请求头
////        HttpEntity<Map<String, Object>> objectHttpEntity = new HttpEntity<Map<String,Object>>(paramsMap, headers);
//        HttpEntity<MultiValueMap> objectHttpEntity = new HttpEntity<MultiValueMap>(paramsMap, headers);
//        ResponseEntity<String> result = restTemplate.exchange(URL + "?groupId=24234390", HttpMethod.GET, objectHttpEntity, String.class);
//        return result.getBody();
//    }
}
