package com.huimv.receiver.cloud.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.huimv.receiver.cloud.dao.entity.EnvDayEntity;
import com.huimv.receiver.cloud.dao.entity.EnvHourEntity;
import com.huimv.receiver.cloud.dao.entity.SysThresholdEntity;
import com.huimv.receiver.cloud.dao.repo.EnvDayRepo;
import com.huimv.receiver.cloud.dao.repo.EnvHourRepo;
import com.huimv.receiver.cloud.dao.repo.SysThresholdEntityRepo;
import com.huimv.receiver.cloud.service.IEnviron;
import com.huimv.receiver.cloud.service.IWarningInfo;
import com.huimv.receiver.farm.service.IAlarm;
import com.huimv.receiver.utils.Const;
import com.huimv.receiver.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * @Project : huimv.shiwan
 * @Package : com.huimv.biosafety.uface.controller
 * @Description : TODO
 * @Version : 1.0
 * @Author : ZhuoNing
 * @Create : 2020-12-25
 **/
@Service
@Slf4j
public class EnvironImpl implements IEnviron {
    @Autowired
    private EnvHourRepo envHourRepo;
    @Autowired
    private EnvDayRepo envDayRepo;
    @Autowired
    private IWarningInfo warningInfo;
    @Autowired
    private DateUtil dateUtil;
    @Autowired
    private com.huimv.receiver.cloud.dao.repo.SysThresholdEntityRepo thresholdRepo;
    @Autowired
    private IAlarm iAlarm;

    @Override
    public void handleEnvironJSONArray(String data) {
        //JSON数组转化对象
        List<EnvHourEntity> envHourEntityList = JSON.parseArray(data, EnvHourEntity.class);
        int a = 0;
        for (EnvHourEntity envHourEntity : envHourEntityList) {
            envHourRepo.save(envHourEntity);
//            System.out.println(""+(++a));
        }
    }

    /**
     * @Method : handleEnvironJSONObject
     * @Description :
     * @Params : [data]
     * @Return : void
     * @Author : ZhuoNing
     * @Date : 2021/12/2
     * @Time : 23:46
     */
    @Override
    public void handleEnvironJSONObject(String data) throws ParseException {
        System.out.println("接收数据>>"+data);
//        JSONObject deviceJo = JSON.parseObject(data);
        EnvHourEntity envHourEntity = JSON.parseObject(data, EnvHourEntity.class);
        envHourRepo.save(envHourEntity);

        Integer farmId = envHourEntity.getFarmId();
//        String todayDateText = dateUtil.formatTimestampToDate(envHourEntity.getAddTime());
//        String todayDateTimeText = dateUtil.formatTimestampToDatetime(envHourEntity.getDatetime());
//        System.out.println(">>>>>>>>>>> 采样时间 todayDateTimeText>>"+todayDateTimeText);
        String todayDateText = dateUtil.formatTimestampToDate(envHourEntity.getDatetime());
//        System.out.println(">>>>>>>>>>> 采样日期 todayDateText>>"+todayDateText);

        //计算每天平均数据
        countDayAvgEnviron2(farmId, todayDateText);
    }

    // 计算每天都平均数据
    public void countDayAvgEnviron2(Integer farmId, String todayDateText) throws ParseException {
        System.out.println("计算每天的环保数据");
        System.out.println("farmId="+farmId);
        System.out.println("todayDateText="+todayDateText);
        //计算平均数
        List<Object[]> envHourEntityList = envHourRepo.findByFarmIdAndDate(farmId, todayDateText);
        System.out.println("每天小时采集数envHourEntityList.size>>"+envHourEntityList.size());

        if (envHourEntityList.size() > 0) {
            //更新新数据
            JSONArray dataJa = new JSONArray();
            for (int a = 0; a < envHourEntityList.size(); a++) {
                JSONObject dataJo = new JSONObject();
                dataJa.add(dataJo);
                Object[] avgObj = (Object[]) envHourEntityList.get(a);
                dataJo.put("cod", avgObj[2]);
                dataJo.put("ad", avgObj[3]);
                dataJo.put("ph", avgObj[4]);
                dataJo.put("ws", avgObj[5]);
            }
            BigDecimal codBd = new BigDecimal(0);
            BigDecimal adBd = new BigDecimal(0);
            BigDecimal phBd = new BigDecimal(0);
            BigDecimal wsBd = new BigDecimal(0);

            for (int a = 0; a < dataJa.size(); a++) {
                JSONObject dataJo = dataJa.getJSONObject(a);
                codBd = new BigDecimal(dataJo.getString("cod")).add(codBd);
                adBd = new BigDecimal(dataJo.getString("ad")).add(adBd);
                phBd = new BigDecimal(dataJo.getString("ph")).add(phBd);
                wsBd = new BigDecimal(dataJo.getString("ws")).add(wsBd);
            }
            //精度位数
            int bit = 3;
            double codDouble = codBd.divide(new BigDecimal(dataJa.size()), 3, BigDecimal.ROUND_HALF_UP).setScale(bit, BigDecimal.ROUND_HALF_UP).doubleValue();
            double adDouble = adBd.divide(new BigDecimal(dataJa.size()), 3, BigDecimal.ROUND_HALF_UP).setScale(bit, BigDecimal.ROUND_HALF_UP).doubleValue();
            double phDouble = phBd.divide(new BigDecimal(dataJa.size()), 3, BigDecimal.ROUND_HALF_UP).setScale(bit, BigDecimal.ROUND_HALF_UP).doubleValue();
            double wsDouble = wsBd.divide(new BigDecimal(dataJa.size()), 3, BigDecimal.ROUND_HALF_UP).setScale(bit, BigDecimal.ROUND_HALF_UP).doubleValue();
            Optional<EnvDayEntity> option = envDayRepo.findByFarmIdAndDate(farmId, todayDateText);
            if(option.isPresent()){
                System.out.println("更新数据");
                //更新数据
                EnvDayEntity envDayEntity = option.get();
                envDayEntity.setAd(String.valueOf(adDouble));
                envDayEntity.setCod(String.valueOf(codDouble));
                envDayEntity.setPh(String.valueOf(phDouble));
                envDayEntity.setWs(String.valueOf(wsDouble));
                envDayEntity.setFarmId(farmId);
                envDayEntity.setAddDate(dateUtil.parseDate(todayDateText));
                //保存
                envDayRepo.saveAndFlush(envDayEntity);
            }else{
                System.out.println("增加新数据");
                //增加新数据
                EnvDayEntity envDayEntity = new EnvDayEntity();
                envDayEntity.setAd(String.valueOf(adDouble));
                envDayEntity.setCod(String.valueOf(codDouble));
                envDayEntity.setPh(String.valueOf(phDouble));
                envDayEntity.setWs(String.valueOf(wsDouble));
                envDayEntity.setFarmId(farmId);
                envDayEntity.setAddDate(dateUtil.parseDate(todayDateText));
                //保存
                envDayRepo.saveAndFlush(envDayEntity);
            }
        }
    }

    @Override
    public void countDayAvgEnviron(Integer farmId, String todayDateText) throws ParseException {
        System.out.println("计算每天的环保数据");
        System.out.println("farmId="+farmId);
        System.out.println("todayDateText="+todayDateText);
        //计算平均数
        List<Object[]> envHourEntityList = envHourRepo.findByFarmIdAndDate(farmId, todayDateText);
        System.out.println("每天小时采集数envHourEntityList.size>>"+envHourEntityList.size());

        if (envHourEntityList.size() > 0) {
            //删除旧数据
//            envHourRepo.removeByFarmIdAndDate(farmId, todayDateText);
            envDayRepo.removeByFarmIdAndDate(farmId, todayDateText);

            JSONArray dataJa = new JSONArray();
            for (int a = 0; a < envHourEntityList.size(); a++) {
                JSONObject dataJo = new JSONObject();
                dataJa.add(dataJo);
                Object[] avgObj = (Object[]) envHourEntityList.get(a);
                dataJo.put("cod", avgObj[2]);
                dataJo.put("ad", avgObj[3]);
                dataJo.put("ph", avgObj[4]);
                dataJo.put("ws", avgObj[5]);
            }
            BigDecimal codBd = new BigDecimal(0);
            BigDecimal adBd = new BigDecimal(0);
            BigDecimal phBd = new BigDecimal(0);
            BigDecimal wsBd = new BigDecimal(0);

            for (int a = 0; a < dataJa.size(); a++) {
                JSONObject dataJo = dataJa.getJSONObject(a);
                codBd = new BigDecimal(dataJo.getString("cod")).add(codBd);
                adBd = new BigDecimal(dataJo.getString("ad")).add(adBd);
                phBd = new BigDecimal(dataJo.getString("ph")).add(phBd);
                wsBd = new BigDecimal(dataJo.getString("ws")).add(wsBd);
            }
            //精度位数
            int bit = 3;
            double codDouble = codBd.divide(new BigDecimal(dataJa.size()), 3, BigDecimal.ROUND_HALF_UP).setScale(bit, BigDecimal.ROUND_HALF_UP).doubleValue();
            double adDouble = adBd.divide(new BigDecimal(dataJa.size()), 3, BigDecimal.ROUND_HALF_UP).setScale(bit, BigDecimal.ROUND_HALF_UP).doubleValue();
            double phDouble = phBd.divide(new BigDecimal(dataJa.size()), 3, BigDecimal.ROUND_HALF_UP).setScale(bit, BigDecimal.ROUND_HALF_UP).doubleValue();
            double wsDouble = wsBd.divide(new BigDecimal(dataJa.size()), 3, BigDecimal.ROUND_HALF_UP).setScale(bit, BigDecimal.ROUND_HALF_UP).doubleValue();
            EnvDayEntity envDayEntity = new EnvDayEntity();
            envDayEntity.setAd(String.valueOf(adDouble));
            envDayEntity.setCod(String.valueOf(codDouble));
            envDayEntity.setPh(String.valueOf(phDouble));
            envDayEntity.setWs(String.valueOf(wsDouble));
            envDayEntity.setFarmId(farmId);
            envDayEntity.setAddDate(dateUtil.parseDate(todayDateText));
            //保存
            envDayRepo.saveAndFlush(envDayEntity);
        }
    }

    @Override
    public void handleMinuteJSONObject(String data) throws ParseException {
        System.out.println("data>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+data);
        JSONObject environJo = JSON.parseObject(data);
        System.out.println("environJo="+environJo);
        String farmId = environJo.getString("farmId");
        System.out.println("farmId="+farmId);
        //读取阈值
        String thresholdData = getThreshold(farmId);
        if(thresholdData == null) {
            log.info("阈值记录为空.");
        }else{
            JSONObject thresholdJo = JSON.parseObject(thresholdData);
            System.out.println("阈值="+thresholdJo);
            //环保氨氮数据>=阈值氨氮数据
            if(new BigDecimal(environJo.getString("adPj")).compareTo(new BigDecimal(thresholdJo.getString("ammonia"))) > -1){
                String alarmInfo = "当前氨氮数据为"+environJo.getString("adPj")+"高于或等于阈值"+thresholdJo.getString("ammonia")+".";
                //报警数据直接入库
                iAlarm.handleEnvironAlarm(alarmInfo,Const.TYPE_ALARM_AD,farmId);
            }

            //环保COD数据>=阈值COD数据
            if(new BigDecimal(environJo.getString("hxxylPj")).compareTo(new BigDecimal(thresholdJo.getString("cOD"))) > -1){
                String alarmInfo = "当前化学需氧量数据为"+environJo.getString("hxxylPj")+"高于或等于阈值"+thresholdJo.getString("cOD")+".";
                //报警数据直接入库
                iAlarm.handleEnvironAlarm(alarmInfo,Const.TYPE_ALARM_COD,farmId);
            }
            //环保PH数据>=阈值PH数据
            if(new BigDecimal(environJo.getString("phPj")).compareTo(new BigDecimal(thresholdJo.getString("ph"))) > -1){
                String alarmInfo = "当前PH值数据为"+environJo.getString("phPj")+"高于或等于阈值"+thresholdJo.getString("ph")+".";
                //报警数据直接入库
                iAlarm.handleEnvironAlarm(alarmInfo,Const.TYPE_ALARM_PH,farmId);
            }
            //环保污水浓度数据>=阈值污水浓度数据
            if(new BigDecimal(environJo.getString("wsPj")).compareTo(new BigDecimal(thresholdJo.getString("flow"))) > -1){
                String alarmInfo = "当前污水浓度数据为"+environJo.getString("wsPj")+"高于或等于阈值"+thresholdJo.getString("flow")+".";
                //报警数据直接入库
                iAlarm.handleEnvironAlarm(alarmInfo,Const.TYPE_ALARM_WS,farmId);
            }
        }


//        EnvHourEntity envHourEntity = JSON.parseObject(data, EnvHourEntity.class);
//        envHourRepo.save(envHourEntity);

//        Integer farmId = envHourEntity.getFarmId();
//        String todayDateText = dateUtil.formatTimestampToDate(envHourEntity.getDatetime());
//        System.out.println(">>>>>>>>>>> 采样日期 todayDateText>>"+todayDateText);

        //计算每天平均数据
//        countDayAvgEnviron2(farmId, todayDateText);
    }

    //读取阈值
    private String getThreshold(String farmId) {
        //
        Optional<SysThresholdEntity> option = thresholdRepo.findByFarmId(farmId);
        if(option.isPresent()){
            return JSON.toJSON(option.get()).toString();
        }else{
            return null;
        }
    }

    public void countDayAvgEnviron_old1(Integer farmId, String todayDateText) {
        System.out.println("farmId=" + farmId);
        System.out.println("todayDateText=" + todayDateText);
        //计算平均数
        List<Object[]> avgList = envHourRepo.findByFarmIdAndDate_old1(farmId, todayDateText);
        if (avgList.size() > 0) {
            JSONObject dataJo = new JSONObject();
            for (int a = 0; a < avgList.size(); a++) {
                Object[] avgObj = (Object[]) avgList.get(a);
                dataJo.put("farm_id", farmId);
                dataJo.put("add_time", new Timestamp(new Date().getTime()));
                dataJo.put("cod", avgObj[0]);
                dataJo.put("ad", avgObj[1]);
                dataJo.put("ph", avgObj[2]);
                dataJo.put("ws", avgObj[3]);
            }
            System.out.println("dataJo>>" + dataJo);
            EnvDayEntity envDayEntity = JSON.toJavaObject(dataJo, EnvDayEntity.class);
            //保存
            envDayRepo.save(envDayEntity);
        }
    }


}
