package com.gyee.alarm.task.thread;

import com.gyee.alarm.controller.feigns.IAlarmService;
import com.gyee.alarm.model.vo.AlarmTag;
import com.gyee.alarm.service.auto.IAlarmTsService;
import com.gyee.alarm.util.realtimesource.IEdosUtil;
import com.gyee.common.model.PointData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

public class AlarmThread implements Runnable {

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    private Executor executor;

    private IEdosUtil edosUtil;


    private IAlarmService alarmService;

    private List<AlarmTag> alarmVoList;
    private String str;

    private Integer interval;
    private Integer readRows;
    private String alarmType;
    private boolean serverStarted=true;

    private IAlarmTsService alarmTsService;
    private CountDownLatch countDownLatch;

    private Map<String, Integer> historymap;
    public AlarmThread(Executor executor, IEdosUtil edosUtil, IAlarmService alarmService, List<AlarmTag> alarmVoList, Integer interval, String str,Integer readRows,String alarmType,CountDownLatch countDownLatch,IAlarmTsService alarmTsService,Map<String, Integer> historymap) {
        this.executor = executor;
        this.edosUtil = edosUtil;
        this.alarmService = alarmService;
        this.alarmVoList = alarmVoList;
        this.interval = interval;
        this.str = str;
        this.readRows = readRows;
        this.alarmType=alarmType;
        this.countDownLatch=countDownLatch;
        this.alarmTsService = alarmTsService;
        this.historymap = historymap;

    }


    @Override
    public synchronized  void run() {


        String task = "task@ " + str;
        logger.info("创建任务并提交到线程池中：" + task);
        String result = "";


//			while (true)
//			{
        List<String> ls = new ArrayList<>();
        List<PointData> values = new ArrayList<>();


        int times = 0;

        for (AlarmTag vo : alarmVoList) {

            ls.add(vo.getTagId());
            times++;
            if (times == readRows) {
                List<PointData> templs = null;
                try {
                    templs = edosUtil.getRealData(ls);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                values.addAll(templs);
                ls = new ArrayList<>();
                times=0;
            }
        }

        if (!ls.isEmpty()) {
            List<PointData> templs = null;
            try {
                templs = edosUtil.getRealData(ls);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            values.addAll(templs);
        }


//				System.out.println(values.size()+"____"+ alarmVoList.size());
        int alarmNumber = 0;
        if (values.size() == alarmVoList.size()) {
            List<AlarmTag> saveAlarmTags = new ArrayList<>();

            List<AlarmTag> updateAlarmTags = new ArrayList<>();

            for (int i = 0; i < alarmVoList.size(); i++) {

                AlarmTag vo = alarmVoList.get(i);

//                    if(vo.getTagId().equals("FD-DJY-YuanDong.140623F0221MDQ02GS006DB0111SW09RAW00"))
//                    {
//                        System.out.println("");
//                    }

                PointData value = values.get(i);

//                    if (vo.getTagId().equals("FD-PYZK-Taizhong1.140728F0111MDY01GS002DB0111SW01RAW00")) {
//                        System.out.println("");
//                    }
                if (vo.updateAndCheck(value)) {
                    if (vo.getVal() == 1) {
                        AlarmTag po = new AlarmTag();

                        po.setId(vo.getId());
                        po.setTs(vo.getTs());
//                        po.setEndts(po.getEndts());
                        po.setVal(vo.getVal());
                        po.setOval(vo.getOval());
                        po.setTriggerType(vo.getTriggerType());
                        po.setTagId(vo.getTagId());
                        po.setRank(vo.getRank());
                        po.setTimeLong(0.0);
                        saveAlarmTags.add(po);
                        alarmNumber++;

                        historymap.put(vo.getId().toLowerCase(),0);


                    } else if (vo.getVal() == 2) {

                        if (historymap.containsKey(vo.getId().toLowerCase())) {
                            //有结束时间，创建新的报警
                            if (historymap.get(vo.getId().toLowerCase()) == 0) {
                                //没有有结束时间，结束报警
                                AlarmTag po = new AlarmTag();

                                po.setId(vo.getId());
                                po.setTs(vo.getTs());
                                po.setEndts(vo.getEndts());
                                po.setVal(vo.getVal());
                                po.setOval(vo.getOval());
                                po.setTriggerType(vo.getTriggerType());
                                po.setTagId(vo.getTagId());
                                po.setRank(vo.getRank());
                                po.setTimeLong(0.0);
                                updateAlarmTags.add(po);
                                historymap.put(vo.getId().toLowerCase(),1);
                            }
                        }

                    } else {
                        AlarmTag po = new AlarmTag();

                        po.setId(vo.getId());
                        po.setTs(vo.getTs());
                        po.setEndts(vo.getEndts());
                        po.setVal(vo.getVal());
                        po.setOval(vo.getOval());
                        po.setTriggerType(vo.getTriggerType());
                        po.setTagId(vo.getTagId());
                        po.setRank(vo.getRank());
                        po.setTimeLong(0.0);
                        updateAlarmTags.add(po);
                        alarmNumber++;
                        historymap.put(vo.getId().toLowerCase(),1);
                    }
                }
//                else  if (!historymap.containsKey(vo.getId().toLowerCase())) {
//                    if (vo.updateAndCheckNoInfo(value)) {
//                        if (vo.getVal() == 1) {
//                            AlarmTag po = new AlarmTag();
//
//                            po.setId(vo.getId());
//                            po.setTs(vo.getTs());
//                            po.setEndts(po.getEndts());
//                            po.setVal(vo.getVal());
//                            po.setOval(vo.getOval());
//                            po.setTriggerType(vo.getTriggerType());
//                            po.setTagId(vo.getTagId());
//                            po.setRank(vo.getRank());
//                            po.setTimeLong(0.0);
//                            saveAlarmTags.add(po);
//                            alarmNumber++;
//                            historymap.put(vo.getId().toLowerCase(),0);
//                        }
//                    }
//                }
            }

            switch (alarmType) {
                case "in_alarms":
                    if (!saveAlarmTags.isEmpty()) {
                        alarmService.saveInTags(saveAlarmTags);
                    }
                    if (!updateAlarmTags.isEmpty()) {
                        alarmService.updateInTags(updateAlarmTags);
                    }
                    break;
                case "wt_alarms":
                    if (!saveAlarmTags.isEmpty()) {
                        alarmService.saveWtTags(saveAlarmTags);
                    }
                    if (!updateAlarmTags.isEmpty()) {
                        alarmService.updateWtTags(updateAlarmTags);
                    }
                    break;
                case "bt_alarms":
                    if (!saveAlarmTags.isEmpty()) {

//                        for(AlarmTag tag:saveAlarmTags)
//                        {
//                            logger.info("tagId_"+tag.getTagId()+"_wpId_"+tag.getWpId()+"_ts_"+tag.getTs()+"_val_"+tag.getVal());
//                        }

                        alarmService.saveBtTags(saveAlarmTags);
                    }
                    if (!updateAlarmTags.isEmpty()) {
//                        for(AlarmTag tag:updateAlarmTags)
//                        {
//                            logger.info("tagId_"+tag.getTagId()+"_wpId_"+tag.getWpId()+"_ts_"+tag.getTs()+"_val_"+tag.getVal());
//                        }
                        alarmService.updateBtTags(updateAlarmTags);
                    }

                    break;

            }


            logger.info("开始报警数量：" + saveAlarmTags.size());
            logger.info( "结束报警数量：" + updateAlarmTags.size());
        }

        try {
            Thread.sleep(interval * 500);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {

            countDownLatch.countDown();
            logger.info("完成任务并提交到线程池中：" + task);
        }
    }
}