package org.jeecg.modules.newWarning.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.checkerframework.checker.units.qual.K;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.newWarning.entity.TabQi;
import org.jeecg.modules.newWarning.entity.NewWarnHistory;
import org.jeecg.modules.newWarning.entity.WarningJh;
import org.jeecg.modules.newWarning.entity.WorkCondition;
import org.jeecg.modules.newWarning.service.NewWarnHistoryService;
import org.jeecg.modules.newWarning.service.WarningJhService;
import org.jeecg.modules.newWarning.service.WorkConditionService;
import org.jeecg.modules.newWarning.service.impl.TabQiServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;


@Component
@Slf4j
public class AutomaticOperationPostConstruct implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private NewWarnHistoryService warnHistoryService;
    @Autowired
    private WarningJhService warningJhService;
    @Autowired
    private TabQiServiceImpl tabQiService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private WorkConditionService workConditionService;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        try {
            System.out.println("任务已经启动...");
           // initnew();
         //  init();
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            e.printStackTrace();
        }
    }
    /**
     * 程序启动自动运行的方法
     */
   // @PostConstruct
    public void init(){
        System.out.println("程序启动运行");
        TabQi tabQi=new TabQi();
        /**
         * 获取工况参数
         */

        List<WarningJh> list = warningJhService.list();
        System.out.println("程序启动清除之前的缓存数据");
        for (WarningJh model : list) {
            redisUtil.del(model.getJhTableName());
            redisUtil.del(model.getJhTableName()+"_time");
        }
        do {
            try {
                List<WorkCondition> workConditionList = workConditionService.list();
                if(workConditionList.size()<=0){
                    tabQi.setBitdepth(500.00F);
                    tabQi.setColumnWeight(10.0);
                    tabQi.setWarningValue(50.0);
                    tabQi.setHkhRang(1.0);
                    tabQi.setLoopDrillingpump(5.00);
                    tabQi.setLoopDrillingSpp(10.00);
                }else{
                    tabQi.setBitdepth(workConditionList.get(0).getBitdepth());
                    tabQi.setColumnWeight(BigDecimal.valueOf(workConditionList.get(0).getColumnWeight()).doubleValue());
                    tabQi.setWarningValue(BigDecimal.valueOf(workConditionList.get(0).getWarnValue()).doubleValue());
                    tabQi.setHkhRang( BigDecimal.valueOf(workConditionList.get(0).getHkhRang()).doubleValue());
                    tabQi.setLoopDrillingpump( BigDecimal.valueOf(workConditionList.get(0).getLoopDrillingPump()).doubleValue());
                    tabQi.setLoopDrillingSpp( BigDecimal.valueOf(workConditionList.get(0).getLoopDrillingSpp()).doubleValue());
                }
                judgeWarn(tabQi);
                Thread.sleep(5000L);
                System.out.println("循环监听表数据");
            } catch (InterruptedException e) {
                log.error(e.getMessage(),e);
                e.printStackTrace();
            }

            System.out.println("循环监听表数据----");
        } while (true);
    }

    private void judgeWarn(TabQi tabQi){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<WarningJh> list = warningJhService.list();
        try {
            for (WarningJh model : list) {
                tabQi.setJhTableName(model.getJhTableName());
                TabQi nowTabQi1 = tabQiService.selectOneOrcale(model.getJhTableName());
                System.out.println("井号"+nowTabQi1.getJh()+";时间:"+ sdf.format(nowTabQi1.getTime())+";大钩负荷:"+nowTabQi1.getTime()+";大钩位置:"+nowTabQi1.getHkh());
                boolean isHave = redisUtil.hasKey(tabQi.getJhTableName() + "_time");
                tabQi.setTime(nowTabQi1.getTime());
                if(isHave){
                    Object catchDate = redisUtil.get(tabQi.getJhTableName() + "_time");
                    String catchDataTabQi =String.valueOf(catchDate);
                    System.out.println("缓存时间:"+sdf.parse(catchDataTabQi));
                    System.out.println("当前时间:"+sdf.parse(sdf.format(nowTabQi1.getTime())));
                    long l = tabQiService.timeDifference(sdf.parse(catchDataTabQi), sdf.parse(sdf.format(nowTabQi1.getTime())));
                    if( l>1){
                        JSONObject smoothInterval = tabQiService.getSmoothInterval(tabQi);
                        System.out.println("判断结果="+smoothInterval.getBoolean("isStartMonitor"));
                        redisUtil.del(model.getJhTableName()+"_time");
                        redisUtil.set(model.getJhTableName()+"_time",sdf.format(nowTabQi1.getTime()));
                        if(smoothInterval.getBoolean("isStartMonitor")){
                            //判断当前点是否为正常点
                            if(!smoothInterval.getBoolean("isNormal")){
                                System.out.println("插入报警数据");
                                redisUtil.set(tabQi.getJhTableName() + "_time",nowTabQi1.getTime());
                                NewWarnHistory history=new NewWarnHistory();

                                history.setJh(model.getJh());
                                history.setWarnTime((Date) smoothInterval.getTimestamp("nowPointTime"));
                                history.setWarnCondition(smoothInterval.getString("nowCondition"));
                                history.setWarnHkh(smoothInterval.getFloat("nowHkh"));
                                history.setWarnBitdepth(smoothInterval.getFloat("nowBitdepth"));
                                history.setWarnWoh(smoothInterval.getFloat("nowWoh"));
                                history.setWholeCondition(smoothInterval.getString("nowWholeWorking"));
                                history.setNormalStarttime((Date) smoothInterval.getTimestamp("nowStart"));
                                history.setNormalEndtime((Date) smoothInterval.getTimestamp("nowEnd"));
                                history.setNormalWoh(smoothInterval.getFloat("frontColumn"));
                                history.setNormalNum(smoothInterval.getInteger("normaNum"));
                                warnHistoryService.save(history);
                            }
                        }
                    }else {
                        System.out.println("当前点已计算,不在计算该点");
                    }
                }else{
                    JSONObject smoothInterval = tabQiService.getSmoothInterval(tabQi);
                    System.out.println("判断结果="+smoothInterval);
                    redisUtil.set(model.getJhTableName()+"_time",sdf.format(nowTabQi1.getTime()));
                    if(smoothInterval.getBoolean("isStartMonitor")){
                        //判断当前点是否为正常点
                        if(!smoothInterval.getBoolean("isNormal")){
                            redisUtil.set(tabQi.getJhTableName() + "_time",nowTabQi1.getTime());
                            NewWarnHistory history=new NewWarnHistory();
                            history.setJh(model.getJh());
                            history.setWarnTime((Date) smoothInterval.getTimestamp("nowPointTime"));
                            history.setWarnCondition(smoothInterval.getString("nowCondition"));
                            history.setWarnHkh(smoothInterval.getFloat("nowHkh"));
                            history.setWarnBitdepth(smoothInterval.getFloat("nowBitdepth"));
                            history.setWarnWoh(smoothInterval.getFloat("nowWoh"));
                            history.setWholeCondition(smoothInterval.getString("nowWholeWorking"));
                            history.setNormalStarttime((Date) smoothInterval.getTimestamp("nowStart"));
                            history.setNormalEndtime((Date) smoothInterval.getTimestamp("nowEnd"));
                            history.setNormalWoh(smoothInterval.getFloat("frontColumn"));
                            history.setNormalNum(smoothInterval.getInteger("normaNum"));
                            warnHistoryService.save(history);
                        }
                    }
                }
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }

    }

//    @PostConstruct
    public void initnew(){
        TabQi tabQi=new TabQi();
        tabQi.setBitdepth(500.00F);
        tabQi.setColumnWeight(10.0);
        tabQi.setWarningValue(50.0);
        tabQi.setHkhRang(1.0);
        tabQi.setJhTableName("tab_cbx397");
        QueryWrapper<TabQi> wrapper=new QueryWrapper<>();
        wrapper.orderByAsc("time");
        List<TabQi> tab_ny13803hf = tabQiService.selectList(tabQi.getJhTableName(), wrapper);
        tabQiService.delRedisJh(tabQi.getJhTableName());
        for (TabQi model:tab_ny13803hf) {
           // tabQi.setJhTableName("tab_ny13803hf");
            tabQi.setTime(model.getTime());
            JSONObject smoothInterval = tabQiService.getSmoothInterval(tabQi);
            if(smoothInterval.getBoolean("isStartMonitor")){
                //判断当前点是否为正常点
                if(!smoothInterval.getBoolean("isNormal")){
                    NewWarnHistory history=new NewWarnHistory();
                    history.setJh(model.getJh());
                    history.setWarnTime((Date) smoothInterval.getTimestamp("nowPointTime"));
                    history.setWarnCondition(smoothInterval.getString("nowCondition"));
                    history.setWarnHkh(smoothInterval.getFloat("nowHkh"));
                    history.setWarnBitdepth(smoothInterval.getFloat("nowBitdepth"));
                    history.setWarnWoh(smoothInterval.getFloat("nowWoh"));
                    history.setWholeCondition(smoothInterval.getString("nowWholeWorking"));
                    history.setNormalStarttime((Date) smoothInterval.getTimestamp("nowStart"));
                    history.setNormalEndtime((Date) smoothInterval.getTimestamp("nowEnd"));
                    history.setNormalWoh(smoothInterval.getFloat("frontColumn"));
                    history.setNormalNum(smoothInterval.getInteger("normaNum"));
                    warnHistoryService.save(history);
                }
            }
        }
    }
}
