package com.huimv.environ.eco.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huimv.common.utils.Result;
import com.huimv.common.utils.ResultCode;
import com.huimv.environ.eco.entity.EcoDeviceFlow;
import com.huimv.environ.eco.entity.EcoDryList;
import com.huimv.environ.eco.mapper.EcoDryListMapper;
import com.huimv.environ.eco.service.EcoDryListService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huimv.environ.env.utils.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zn
 * @since 2022-11-11
 */
@Service
public class EcoDryListServiceImpl extends ServiceImpl<EcoDryListMapper, EcoDryList> implements EcoDryListService {
    @Autowired
    private EcoDryListMapper ecoDryListMapper;
    @Autowired
    private RestTemplate restTemplate;
    @Value("${url.warning.service}")
    private String URL_WARNING_SERVICE;

    @Override
    public void saveDryList(Map deviceMap, String currentDryTemp, JSONObject thresholdJo, Date todayTime) throws ParseException {
        System.out.println("开始保存saveDryList()");
        if (StringUtils.isBlank(currentDryTemp)) {
            currentDryTemp = "0";
        }
        System.out.println("当前的烘干温度currentDryTemp=" + currentDryTemp);
        //默认烘干温度（分钟）
        String thresholdDryTem = "0";
        //烘干时间过短报警时长（分钟）
        String dryMin = "0";
        //一次烘干持续时间（分钟）
        String dryDuration = "0";
        //常温阈值
        String dryNormalTemp = "0";
        //烘干高温阈值温度
        thresholdDryTem = thresholdJo.getString("dryTem");
        System.out.println("++ 烘干高温阈值温度 thresholdDryTem="+thresholdDryTem);
        dryMin = thresholdJo.getString("dryMin");
        //持续时间
        dryDuration = thresholdJo.getString("dryDuration");
        System.out.println("++ 烘干高温持续时间阈值 dryDuration="+dryDuration);
        //烘干动作温度
        dryNormalTemp = thresholdJo.getString("dryNormalTemp");
        System.out.println("++ 烘干动作温度 dryNormalTemp="+dryNormalTemp);
        String farmId = thresholdJo.getString("farmId");
        DateUtil dateUtil = new DateUtil();
        int deviceType = (int) deviceMap.get("device_type");
        String deviceCode = deviceMap.get("device_code") + "";
        System.out.println("deviceType=" + deviceType);
        String location = deviceMap.get("pigpen_name") + "";
        //保存烘干设备记录列表
        if (deviceType == 2) {
            System.out.println("1.");
            //判断上次间隔时间(读取该设备上次添加时间),超过一次洗消烘干的标准周期时间
            if (isOverdue(deviceCode, farmId, todayTime, dryDuration)) {
                System.out.println("1.1");
                System.out.println("currentDryTemp=" + currentDryTemp);
                System.out.println("thresholdDryTem=" + thresholdDryTem);
                //超过2次烘干之间的规定间隔时间，判断是否高温（高温且超过一次烘干持续时间需要进行烘干高温记录）
//                if (new BigDecimal(temp).compareTo(new BigDecimal(dryTem)) != -1) {
                if (Float.parseFloat(currentDryTemp) >= Float.parseFloat(thresholdDryTem)) {
                    //
                    System.out.println("1.2");
                    EcoDryList ecoDryList = new EcoDryList();
                    ecoDryList.setDeviceCode(deviceCode);
                    ecoDryList.setLocation(location);
                    ecoDryList.setStandardStatus(1);
                    ecoDryList.setAddTime(todayTime);
                    ecoDryList.setFarmId(Integer.parseInt(farmId));
                    ecoDryListMapper.insert(ecoDryList);
                    System.out.println("保存");
                } else {
                    System.out.println("1.3");
                    EcoDryList ecoDryList = new EcoDryList();
                    ecoDryList.setDeviceCode(deviceCode);
                    ecoDryList.setLocation(location);
                    ecoDryList.setStandardStatus(0);
                    ecoDryList.setAddTime(todayTime);
                    ecoDryList.setFarmId(Integer.parseInt(farmId));
                    ecoDryListMapper.insert(ecoDryList);
                    System.out.println("处理温度不达标。");
                    newLowDryTempWarningInfo(currentDryTemp, dryNormalTemp, thresholdDryTem, dateUtil.formatDateTime(todayTime), farmId, location);
                }
            } else {
                System.out.println("2.");
                //未超过2次烘干之间的规定间隔时间,判断当前温度是否介于烘干温度阈值和常温阈值之间，即可报警
                newLowDryTempWarningInfo(currentDryTemp, dryNormalTemp, thresholdDryTem, dateUtil.formatDateTime(todayTime), farmId, location);
            }
        }
    }

//    @Override
//    public void saveDryList(Map deviceMap, JSONObject deviceFlowDataJo, JSONObject thresholdJo, Date todayTime) throws ParseException {
//        System.out.println("开始保存saveDryList()");
//        JSONArray realTimeDataJa = deviceFlowDataJo.getJSONArray("realTimeData");
//        String flowId = deviceFlowDataJo.getString("id");
//        System.out.println("flowId >>>>>>>>>>>>>>>>>>" + flowId);
//        JSONObject tempDataJo = realTimeDataJa.getJSONObject(0);
//        String temp = tempDataJo.getString("dataValue");
//        if (StringUtils.isBlank(temp)) {
//            temp = "0";
//        }
//        //Debug:temp
//        temp = "40";
//        System.out.println(">> temp=" + temp);
//        //烘干温度（分钟）
//        String dryTem = "0";
//        System.out.println(">> dryTem=" + dryTem);
//        //烘干时间过短报警时长（分钟）
//        String dryMin = "0";
//        //一次烘干持续时间（分钟）
//        String dryDuration = "0";
//        //常温阈值
//        String dryNormalTemp = "0";
//        System.out.println("thresholdJo>>>>>>>>>>>>>>>>>>>>>>>" + thresholdJo);
//        if (thresholdJo != null) {
//            dryTem = thresholdJo.getString("dryTem");
//            dryMin = thresholdJo.getString("dryMin");
//            dryDuration = thresholdJo.getString("dryDuration");
//            dryNormalTemp = thresholdJo.getString("dryNormalTemp");
//        }
//        String farmId = thresholdJo.getString("farmId");
//        DateUtil dateUtil = new DateUtil();
//        int deviceType = (int) deviceMap.get("device_type");
//        String deviceCode = deviceMap.get("device_code") + "";
//        System.out.println("deviceType=" + deviceType);
//        String location = deviceMap.get("pigpen_name") + "";
//        //保存烘干设备记录列表
//        if (deviceType == 2) {
//            System.out.println("1.");
//            //判断上次间隔时间(读取该设备上次添加时间),超过一次洗消烘干的标准周期时间
//            if (isOverdue(deviceCode, farmId, todayTime, dryDuration)) {
//                System.out.println("1.1");
//                System.out.println("temp=" + temp);
//                System.out.println("dryTem=" + dryTem);
//                //超过2次烘干之间的规定间隔时间，判断是否高温（高温且超过一次烘干持续时间需要进行烘干高温记录）
////                if (new BigDecimal(temp).compareTo(new BigDecimal(dryTem)) != -1) {
//                if (Float.parseFloat(temp) >= Float.parseFloat(dryTem)) {
//                    System.out.println("1.2");
//                    EcoDryList ecoDryList = new EcoDryList();
//                    ecoDryList.setDeviceCode(deviceCode);
//                    ecoDryList.setLocation(location);
//                    ecoDryList.setStandardStatus(1);
//                    ecoDryList.setAddTime(todayTime);
//                    ecoDryList.setFarmId(Integer.parseInt(farmId));
//                    ecoDryListMapper.insert(ecoDryList);
//                    System.out.println("保存");
//                } else {
//                    System.out.println("1.3");
//                    EcoDryList ecoDryList = new EcoDryList();
//                    ecoDryList.setDeviceCode(deviceCode);
//                    ecoDryList.setLocation(location);
//                    ecoDryList.setStandardStatus(0);
//                    ecoDryList.setAddTime(todayTime);
//                    ecoDryList.setFarmId(Integer.parseInt(farmId));
//                    ecoDryListMapper.insert(ecoDryList);
//                    System.out.println("处理温度不达标。");
//                    newLowDryTempWarningInfo(temp, dryNormalTemp, dryTem, dateUtil.formatDateTime(todayTime), farmId, location);
//                }
//            } else {
//                System.out.println("2.");
//                //未超过2次烘干之间的规定间隔时间,判断当前温度是否介于烘干温度阈值和常温阈值之间，即可报警
//                newLowDryTempWarningInfo(temp, dryNormalTemp, dryTem, dateUtil.formatDateTime(todayTime), farmId, location);
//            }
//        }
//    }

    //新建洗消烘干温度不足报警记录
    private void newLowDryTempWarningInfo(String currentTemp, String dryNormalTemp, String thresholdDryTem, String todayTime, String farmId, String location) {
        System.out.println("# 开始处理烘干温度不足的场景 #");
        System.out.println("44 currentTemp=" + currentTemp);
        System.out.println("44 dryNormalTemp=" + dryNormalTemp);
        System.out.println("44 thresholdDryTem=" + thresholdDryTem);
        if (Float.parseFloat(currentTemp) > Float.parseFloat(dryNormalTemp) && Float.parseFloat(currentTemp) < Float.parseFloat(thresholdDryTem)) {
            System.out.println("烘干温度未达到烘干温度阈值");
            //烘干温度未达标，发送烘干警报
            String alarmInfo = todayTime + " " + location + "当前温度" + currentTemp + "°,未达到烘干阈值温度" + thresholdDryTem + "°";
            System.out.println("alarmInfo=" + alarmInfo);
            System.out.println("farmId=" + farmId);
            System.out.println("todayTime=" + todayTime);
            System.out.println("todayTime=" + todayTime);
            //发送低烘干温度报警
            sendLowDryTempAlarm(alarmInfo, farmId, todayTime, todayTime);
        } else if (Float.parseFloat(currentTemp) >= Float.parseFloat(thresholdDryTem)) {
//            System.out.println("烘干温度已达到烘干温度阈值");
        } else {
//            System.out.println("当前温度小于常温阈值");
        }
    }

    @Override
    public void sendLowDryTempAlarm(String alarmInfo, String farmId, String warningTime, String uploadTime) {
        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);
        map.put("level", 1);
        map.put("msg", alarmInfo);
        map.put("levelName", "一级警报");
        map.put("warningName", "洗消监测");
        map.put("warningTime", warningTime);
        map.put("uploadTime", uploadTime);
        map.put("alarmType", "0");
        HttpEntity<Map<String, Object>> objectHttpEntity = new HttpEntity<>(map, httpHeaders);
        System.out.println("URL_WARNING_SERVICE=" + URL_WARNING_SERVICE);
        System.out.println("map>>>>>>>>>>>>>>>>>" + map);
        ResponseEntity<String> entity = restTemplate.postForEntity(URL_WARNING_SERVICE, objectHttpEntity, String.class);
        JSONObject thresholdJo = JSONObject.parseObject(entity.getBody());
//        if (thresholdJo.getInteger("code") != 10000) {
//            return null;
//        }
//        return thresholdJo.getJSONObject("data");

    }

    //判断是否过期
    private boolean isOverdue(String deviceCode, String farmId, Date todayTime, String dryDuration) {
        QueryWrapper<EcoDryList> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("farm_id", farmId);
        queryWrapper.eq("device_code", deviceCode);
        queryWrapper.orderByDesc("add_time");
        queryWrapper.last("LIMIT 1");
        EcoDryList lastEcoDryList = ecoDryListMapper.selectOne(queryWrapper);
        if (lastEcoDryList == null) {
            return true;
        }
        System.out.println("1==" + (todayTime.getTime() - lastEcoDryList.getAddTime().getTime()));
        System.out.println("2==" + (todayTime.getTime() - lastEcoDryList.getAddTime().getTime()) / (1000 * 60));
        System.out.println("3==" + dryDuration);
        //当前时间比较最后一次上次时间（分钟）
        if ((todayTime.getTime() - lastEcoDryList.getAddTime().getTime()) / (1000 * 60) >= Integer.parseInt(dryDuration)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * @Method : listDayEvent
     * @Description : 查看烘干时间
     * @Params : [request, paramsMap]
     * @Return : com.huimv.common.utils.Result
     * @Author : ZhuoNing
     * @Date : 2022/11/14
     * @Time : 9:24
     */
    @Override
    public Result listDayEvent(HttpServletRequest request, Map<String, String> paramsMap) throws ParseException {
        //pageNo
        String pageNo = paramsMap.get("pageNo") + "";
        if (StringUtils.isBlank(pageNo)) {
            pageNo = "1";
        }
        //pageSize
        String pageSize = paramsMap.get("pageSize") + "";
        if (StringUtils.isBlank(pageSize)) {
            pageSize = "10";
        }
        String startDate = paramsMap.get("startDate") + " 00:00:00";
        String endDate = paramsMap.get("endDate") + " 23:59:59";

        DateUtil dateUtil = new DateUtil();
        //farmId
        String farmId = paramsMap.get("farmId");
        QueryWrapper<EcoDryList> queryWrapper = new QueryWrapper();
        queryWrapper.eq("farm_id", farmId);
        queryWrapper.ge("add_time", startDate).le("add_time", endDate);
        queryWrapper.orderByDesc("add_time");
        Page<EcoDryList> page = new Page<>(Integer.parseInt(pageNo), Integer.parseInt(pageSize));
        Page<EcoDryList> pageEcoDryList = ecoDryListMapper.selectPage(page, queryWrapper);
        List<EcoDryList> ecoDryListList = pageEcoDryList.getRecords();
        List dataList = new ArrayList();
        for (EcoDryList ecoDryList : ecoDryListList) {
            JSONObject ecoDryJo = JSONObject.parseObject(JSONObject.toJSONString(ecoDryList));
            ecoDryJo.put("addTime", dateUtil.formatDateTime(ecoDryList.getAddTime()));
            dataList.add(ecoDryJo);
        }
        pageEcoDryList.setRecords(dataList);
        return new Result(ResultCode.SUCCESS, pageEcoDryList);
    }


}
