package com.gyee.alarm.service;

import com.gyee.alarm.init.CacheContext;
import com.gyee.alarm.model.auto.*;
import com.gyee.alarm.model.vo.*;
import com.gyee.alarm.service.auto.IAlarmTsService;
import com.gyee.alarm.service.auto.IProEconAlarmInfoService;
import com.gyee.alarm.service.auto.IProEconAlarmRuleService;
import com.gyee.alarm.util.DateUtils;
import com.gyee.alarm.util.StringUtils;
import com.gyee.alarm.websocket.PushParams;
import com.gyee.alarm.websocket.WebSocket;
import org.apache.juli.logging.Log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.websocket.EncodeException;
import java.io.IOException;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Service

public class AlarmCtService {

    private static Logger logger = LoggerFactory.getLogger(AlarmCtService.class);
    @Resource
    private IAlarmTsService alarmTsService;

    @Resource
    private IProEconAlarmInfoService proEconAlarmInfoService;
    @Value("${initialcode}")
    private String initialcode;

    @Value("${pushinterval}")
    private Double pushinterval;
    @Resource
    private WebSocket webSocket;
    @Resource
    private PushDataSevice pushDataSevice;
    public void dropSuperTable() {
        alarmTsService.dropSuperTable(AlarmSuperTalbeType.CT.getCode());
    }

    public void createSuperTable() {

        alarmTsService.createSuperTable(AlarmSuperTalbeType.CT.getCode());
    }

    public void initalCtAlarm() throws SQLException {


        List<AlarmVo> alarmVoList = CacheContext.alarmCtList;
//        List<AlarmTag> alarmTags = new ArrayList<>();




        if (!alarmVoList.isEmpty()) {
            for (AlarmVo vo : alarmVoList) {


                alarmTsService.createTable(vo.getTbName(), vo.getAlarmid(), vo.getAlarmtype(),
                        vo.getCharacteristic(), vo.getComponents(),
                        vo.getDescription(),
                        vo.getDeviceid(), vo.getDevicename(),
                        vo.getDevicetype(), vo.getEnabled(),
                        vo.getLineid(), vo.getLinename(),
                        vo.getModelId(), vo.getProjectid(),
                        vo.getProjectname(), vo.getRank(),
                        vo.getResettable(), vo.getStationid(),
                        vo.getStationname(), vo.getSubcomponents(),
                        vo.getSuffix(), vo.getTagid(),
                        vo.getTriggertype(), vo.getUniformcode(), vo.getSuperTableName(),
                        vo.getName(),
                        vo.getNemCode(), vo.getFaultCause(), vo.getResolvent(), vo.getFaultType(), vo.getAname());
//                alarmTsService.createTable(vo.getTbName(), vo.getAlarmid(), vo.getAlarmtype(),
//                        vo.getCharacteristic(), vo.getComponents(),
//                        vo.getDescription(),
//                        vo.getDeviceid(), vo.getDevicename(),
//                        vo.getDevicetype(), vo.getEnabled(),
//                        vo.getLineid(), vo.getLinename(),
//                        vo.getModelId(), vo.getProjectid(),
//                        vo.getProjectname(), vo.getRank(),
//                        vo.getResettable(), vo.getStationid(),
//                        vo.getStationname(), vo.getSubcomponents(),
//                        vo.getSuffix(), vo.getTagid(),
//                        vo.getTriggertype(), vo.getUniformcode(),
//                        vo.getSuperTableName(),vo.getName(),
//                        vo.getNemCode(),vo.getFaultCause(),vo.getResolvent(),vo.getFaultType(),vo.getAname());
//                alarmTsService.updateTable(vo.getTbName(), vo.getAlarmid(), vo.getAlarmtype(),
//                        vo.getCharacteristic(), vo.getComponents(),
//                        vo.getDescription(),
//                        vo.getDeviceid(), vo.getDevicename(),
//                        vo.getDevicetype(), vo.getEnabled(),
//                        vo.getLineid(), vo.getLinename(),
//                        vo.getModelId(), vo.getProjectid(),
//                        vo.getProjectname(), vo.getRank(),
//                        vo.getResettable(), vo.getStationid(),
//                        vo.getStationname(), vo.getSubcomponents(),
//                        vo.getSuffix(), vo.getTagid(),
//                        vo.getTriggertype(), vo.getUniformcode(), vo.getSuperTableName(),
//                        vo.getName(),
//                        vo.getNemCode(),vo.getFaultCause(),vo.getResolvent(),vo.getFaultType(),vo.getAname());
//                AlarmTag po = new AlarmTag();
//                po.setId(vo.getTbName());
//                po.setVal(0.0);
//                po.setTriggerType(vo.getTriggertype());
//                po.setTagId(vo.getTagid());
//                po.setVal(0.0);
//                po.setRank(vo.getRank());
//                po.setTs(new Date().getTime());
//                alarmTags.add(po);
            }
        }


//        alarmTsService.insertList(alarmTags);
    }


    public List<AlarmVo> initalAlarmVo() {

        List<AlarmVo> alarmVoList = new ArrayList<>();
        Map<String, List<ProEconAlarmRule>> alarmRulesMap = CacheContext.alarmRulesMap;

        //风机自定义报警
        wtCustomAlarm(alarmVoList, alarmRulesMap);
        //逆变器自定义报警
        lnCustomAlarm(alarmVoList, alarmRulesMap);
//        //场站自定义报警
//        wpCustomAlarm(alarmVoList, alarmRulesMap);
        //升压站自定义报警
        btCustomAlarm(alarmVoList, alarmRulesMap);
        return alarmVoList;
    }

    private void wtCustomAlarm(List<AlarmVo> alarmVoList, Map<String, List<ProEconAlarmRule>> alarmRulesMap) {

        Map<String, List<ProEconAlarmRule>> armap = new HashMap<>();
        //将多有的自定义报警通过场站编号和型号进行分类
        if (alarmRulesMap.containsKey(DeviceTypeValue.WT.getCode())) {
            List<ProEconAlarmRule> arls = alarmRulesMap.get(DeviceTypeValue.WT.getCode());
            if (!arls.isEmpty()) {
                for (ProEconAlarmRule ar : arls) {
                    StringBuilder sb = new StringBuilder();
                    sb.append(ar.getStationId() + ar.getModelId());
                    if (armap.containsKey(String.valueOf(sb))) {
                        List<ProEconAlarmRule> ls = armap.get(String.valueOf(sb));
                        ls.add(ar);
                    } else {
                        List<ProEconAlarmRule> ls = new ArrayList<>();
                        ls.add(ar);
                        armap.put(String.valueOf(sb), ls);
                    }
                }
            }
        }
        //将pg数据库中配置的自定义报警信息转化为报警对象，方便进行自定义报警的判定功能
        for (ProBasicEquipment wt : CacheContext.wtls) {
            StringBuilder sb = new StringBuilder();
            sb.append(wt.getWindpowerstationId() + wt.getModelId());

            if (armap.containsKey(String.valueOf(sb))) {
                List<ProEconAlarmRule> alarmls = armap.get(String.valueOf(sb));

                if (!alarmls.isEmpty()) {
                    for (ProEconAlarmRule alarm : alarmls) {
                        AlarmVo vo = new AlarmVo();
                        StringBuilder tbName = new StringBuilder();
                        tbName.append(wt.getId()).append("_").append(alarm.getId());
                        vo.setTbName(String.valueOf(tbName));
                        vo.setAlarmid(alarm.getId());
                        vo.setTagid(alarm.getExpression());
                        vo.setAlarmtype(AlarmTypeValue.CT.getCode());
                        vo.setCharacteristic(alarm.getName());
                        vo.setComponents(alarm.getRelatedParts());
                        vo.setDescription(alarm.getDescription());
                        vo.setDeviceid(wt.getId());
                        vo.setDevicename(wt.getName());
                        vo.setDevicetype(DeviceTypeValue.WT.getCode());
                        vo.setEnabled(alarm.getEnable());
                        vo.setLineid(wt.getLineId());
                        if (CacheContext.lnmap.containsKey(wt.getLineId())) {
                            ProBasicLine ln = CacheContext.lnmap.get(wt.getLineId());
                            vo.setLinename(ln.getName());
                        }
                        vo.setModelId(wt.getModelId());
                        vo.setProjectid(wt.getProjectId());
                        if (CacheContext.pjmap.containsKey(wt.getProjectId())) {
                            ProBasicProject pj = CacheContext.pjmap.get(wt.getProjectId());
                            vo.setProjectname(pj.getName());
                        }
                        vo.setRank(alarm.getRank());
                        vo.setResettable(false);
                        vo.setStationid(wt.getWindpowerstationId());
                        if (CacheContext.wpmap.containsKey(wt.getWindpowerstationId())) {
                            ProBasicPowerstation wp = CacheContext.wpmap.get(wt.getWindpowerstationId());
                            vo.setStationname(wp.getName());
                        }
                        vo.setSubcomponents("");
                        vo.setSuffix("");
                        vo.setTriggertype(1);
                        vo.setUniformcode("");
                        vo.setSuperTableName(AlarmSuperTalbeType.CT.getCode());
                        vo.setVal(0);

                        vo.setCharacteristic(alarm.getName());
                        vo.setFaultCause(alarm.getDescription());
                        vo.setResolvent(alarm.getExpression());
                        alarmVoList.add(vo);
                    }
                }
            }
        }
    }

    private void lnCustomAlarm(List<AlarmVo> alarmVoList, Map<String, List<ProEconAlarmRule>> alarmRulesMap) {

        Map<String, List<ProEconAlarmRule>> armap = new HashMap<>();

        if (alarmRulesMap.containsKey(DeviceTypeValue.IN.getCode())) {
            List<ProEconAlarmRule> arls = alarmRulesMap.get(DeviceTypeValue.IN.getCode());
            if (!arls.isEmpty()) {
                for (ProEconAlarmRule ar : arls) {
                    StringBuilder sb = new StringBuilder();
                    sb.append(ar.getStationId() + ar.getModelId());
                    if (armap.containsKey(String.valueOf(sb))) {
                        List<ProEconAlarmRule> ls = armap.get(String.valueOf(sb));
                        ls.add(ar);
                    } else {
                        List<ProEconAlarmRule> ls = new ArrayList<>();
                        ls.add(ar);
                        armap.put(String.valueOf(sb), ls);
                    }
                }
            }
        }
        for (ProBasicEquipment wt : CacheContext.wtls) {
            StringBuilder sb = new StringBuilder();
            sb.append(wt.getWindpowerstationId() + wt.getModelId());

            if (armap.containsKey(String.valueOf(sb))) {
                List<ProEconAlarmRule> alarmls = armap.get(String.valueOf(sb));

                if (!alarmls.isEmpty()) {
                    for (ProEconAlarmRule alarm : alarmls) {
                        AlarmVo vo = new AlarmVo();
                        StringBuilder tbName = new StringBuilder();
                        tbName.append(wt.getId()).append("_").append(alarm.getId());
                        vo.setTbName(String.valueOf(tbName));
                        vo.setAlarmid(alarm.getId());
                        vo.setTagid(alarm.getExpression());
                        vo.setAlarmtype(AlarmTypeValue.CT.getCode());
                        vo.setCharacteristic(alarm.getName());
                        vo.setComponents(alarm.getRelatedParts());
                        vo.setDescription(alarm.getDescription());
                        vo.setDeviceid(wt.getId());
                        vo.setDevicename(wt.getName());
                        vo.setDevicetype(DeviceTypeValue.IN.getCode());
                        vo.setEnabled(alarm.getEnable());
                        vo.setLineid(wt.getLineId());
                        if (CacheContext.lnmap.containsKey(wt.getLineId())) {
                            ProBasicLine ln = CacheContext.lnmap.get(wt.getLineId());
                            vo.setLinename(ln.getName());
                        }
                        vo.setModelId(wt.getModelId());
                        vo.setProjectid(wt.getProjectId());
                        if (CacheContext.pjmap.containsKey(wt.getProjectId())) {
                            ProBasicProject pj = CacheContext.pjmap.get(wt.getProjectId());
                            vo.setProjectname(pj.getName());
                        }
                        vo.setRank(alarm.getRank());
                        vo.setResettable(false);
                        vo.setStationid(wt.getWindpowerstationId());
                        if (CacheContext.wpmap.containsKey(wt.getWindpowerstationId())) {
                            ProBasicPowerstation wp = CacheContext.wpmap.get(wt.getWindpowerstationId());
                            vo.setStationname(wp.getName());
                        }
                        vo.setSubcomponents("");
                        vo.setSuffix("");
                        vo.setTriggertype(1);
                        vo.setUniformcode("");
                        vo.setSuperTableName(AlarmSuperTalbeType.CT.getCode());
                        vo.setVal(0);

                        vo.setCharacteristic(alarm.getName());
                        vo.setFaultCause(alarm.getDescription());
                        vo.setResolvent(alarm.getExpression());
                        alarmVoList.add(vo);
                    }
                }
            }
        }
    }

    private void wpCustomAlarm(List<AlarmVo> alarmVoList, Map<String, List<ProEconAlarmRule>> alarmRulesMap) {
        List<ProEconAlarmRule> alarmls = new ArrayList<>();
        if (alarmRulesMap.containsKey(DeviceTypeValue.WP.getCode())) {
            alarmls = alarmRulesMap.get(DeviceTypeValue.WP.getCode());

        }

        for (ProBasicPowerstation wp : CacheContext.wpls) {
            if (!alarmls.isEmpty()) {
                for (ProEconAlarmRule alarm : alarmls) {
                    AlarmVo vo = new AlarmVo();
                    StringBuilder tbName = new StringBuilder();
                    tbName.append(wp.getId()).append("_").append(alarm.getId());
                    vo.setTbName(String.valueOf(tbName));
                    vo.setAlarmid(alarm.getId());
                    vo.setTagid(alarm.getExpression());
                    vo.setAlarmtype(AlarmTypeValue.CT.getCode());
                    vo.setCharacteristic(alarm.getName());
                    vo.setComponents(alarm.getRelatedParts());
                    vo.setDescription(alarm.getDescription());
                    vo.setDeviceid("");
                    vo.setDevicename("");
                    vo.setDevicetype(DeviceTypeValue.WP.getCode());
                    vo.setEnabled(alarm.getEnable());
                    vo.setLineid("");
                    vo.setLinename("");
                    vo.setModelId("");
                    vo.setProjectid("");
                    vo.setProjectname("");
                    vo.setRank(alarm.getRank());
                    vo.setResettable(false);
                    vo.setStationid(wp.getId());
                    vo.setStationname(wp.getName());
                    vo.setSubcomponents("");
                    vo.setSuffix("");
                    vo.setTriggertype(1);
                    vo.setUniformcode("");
                    vo.setSuperTableName(AlarmSuperTalbeType.CT.getCode());
                    vo.setVal(0);
                    alarmVoList.add(vo);
                }
            }
        }
    }

    private void btCustomAlarm(List<AlarmVo> alarmVoList, Map<String, List<ProEconAlarmRule>> alarmRulesMap) {


        Map<String,List<ProEconAlarmRule>> alarmMap=new HashMap<>();

        if (alarmRulesMap.containsKey(DeviceTypeValue.BT.getCode())) {

            List<ProEconAlarmRule>  alarmls = alarmRulesMap.get(DeviceTypeValue.BT.getCode());

            if(!alarmls.isEmpty())
            {
                for(ProEconAlarmRule alarm:alarmls)
                {
                    if (StringUtils.notEmp(alarm) && StringUtils.notEmp(alarm.getElectricalId()))
                    {
                        String [] ids=alarm.getElectricalId().split(",");
                        if(ids.length>0)
                        {
                            for(int i=0;i<ids.length;i++)
                            {
                                if(alarmMap.containsKey(ids[i]))
                                {
                                    List<ProEconAlarmRule> arls=alarmMap.get(ids[i]);
                                    arls.add(alarm);

                                }else
                                {
                                    List<ProEconAlarmRule> arls=new ArrayList<>();
                                    arls.add(alarm);
                                    alarmMap.put(ids[i],arls);
                                }

                            }
                        }
                    }

                }
            }
        }

        for (ProBasicSubStation wp : CacheContext.subwpls) {

            if (!alarmMap.isEmpty() && alarmMap.containsKey(wp.getId())) {

                List<ProEconAlarmRule> alarmls = alarmMap.get(wp.getId());
                for (ProEconAlarmRule alarm : alarmls) {
                    AlarmVo vo = new AlarmVo();
                    StringBuilder tbName = new StringBuilder();

                    tbName.append(wp.getId()).append("_").append(alarm.getId());
                    vo.setTbName(String.valueOf(tbName));
                    vo.setAlarmid(alarm.getId());
                    vo.setTagid(alarm.getExpression());
                    vo.setAlarmtype(AlarmTypeValue.CT.getCode());
                    vo.setCharacteristic(alarm.getName());
                    vo.setComponents(alarm.getRelatedParts());
                    vo.setDescription(alarm.getDescription());
                    vo.setDeviceid("");
                    vo.setDevicename("");
                    vo.setDevicetype(DeviceTypeValue.BT.getCode());
                    vo.setEnabled(alarm.getEnable());
                    vo.setLineid("");
                    vo.setLinename("");
                    vo.setModelId("");
                    vo.setProjectid("");
                    vo.setProjectname("");
                    vo.setRank(alarm.getRank());
                    vo.setResettable(false);
                    vo.setStationid(wp.getId());
                    vo.setStationname(wp.getName());
                    vo.setSubcomponents("");
                    vo.setSuffix("");
                    vo.setTriggertype(1);
                    vo.setUniformcode("");
                    vo.setSuperTableName(AlarmSuperTalbeType.CT.getCode());
                    vo.setVal(0);
                    vo.setOval(0);

                    vo.setCharacteristic(alarm.getName());
                    vo.setFaultCause(alarm.getDescription());
                    vo.setResolvent(alarm.getExpression());
                    alarmVoList.add(vo);
                }
            }
        }
    }

    public List<AlarmCustomTag> findTags(String stbaleName) {
        List<AlarmCustomTag> ls = new ArrayList<>();
        if (StringUtils.notEmp(stbaleName)) {
            // List<AlarmVo> vos= alarmTsService.findTags(stbaleName);
            List<AlarmVo> vos = CacheContext.alarmCtList;
            if (!vos.isEmpty()) {
                for (AlarmVo vo : vos) {
                    AlarmCustomTag po = new AlarmCustomTag();
                    po.setId(vo.getTbName());
                    po.setDescription(vo.getDescription());
                    po.setTagId(vo.getTagid());
                    po.setDeviceid(vo.getDeviceid());
                    po.setDevicetype(vo.getDevicetype());
                    po.setModelId(vo.getModelId());
                    po.setAlarmtype(vo.getAlarmtype());
                    po.setStationid(vo.getStationid());

                    po.setVal(null);

                    ls.add(po);
                }
            }
        }
        return ls;
    }


    public synchronized void saveAlarms(List<AlarmTag> ls) throws EncodeException, IOException, InterruptedException {

        if (StringUtils.notEmp(ls) && !ls.isEmpty()) {

            alarmTsService.insertList(ls);

            Map<String,ProEconAlarmInfo> tempmap=new HashMap<>();
            if (StringUtils.notEmp(ls) && !ls.isEmpty()) {

                List<ProEconAlarmInfo> valuels = new ArrayList<>();
                for (AlarmTag alarm : ls) {
                    if (CacheContext.alarmCtMap.containsKey(alarm.getId())) {
                        AlarmVo vo = CacheContext.alarmCtMap.get(alarm.getId());
                        ProEconAlarmInfo po = new ProEconAlarmInfo();
                        po.setTbname(vo.getTbName());
                        po.setLastUpdateTime(new Date(alarm.getTs()));
                        po.setUpdateTime(new Date(alarm.getTs()));
                        po.setTagId(alarm.getTagId());
                        po.setTriggerType(alarm.getTriggerType());
                        po.setAlarmId(vo.getAlarmid());
                        po.setDeviceId(vo.getDeviceid());
                        po.setSubcomponents(vo.getSuffix());
                        po.setRank(vo.getRank());
                        po.setConfirmed(false);
                        po.setUniformCode(vo.getUniformcode());
                        po.setAlarmType(vo.getAlarmtype());
                        po.setDeviceType(vo.getDevicetype());
                        po.setComponents(vo.getComponents());
                        po.setSubcomponents(vo.getSubcomponents());
                        po.setDescription(vo.getDescription());
                        po.setModelId(vo.getModelId());
                        po.setResetTable(vo.getResettable());
                        po.setEnable(vo.getEnabled());
                        po.setCharacteristic(vo.getCharacteristic());
                        po.setStationId(vo.getStationid());
                        po.setProjectId(vo.getProjectid());
                        po.setLineId(vo.getLineid());
                        po.setStationName(vo.getStationname());
                        po.setProjectiName(vo.getProjectname());
                        po.setLineidName(vo.getLinename());
                        po.setDeviceName(vo.getDevicename());
                        po.setOval(alarm.getOval().intValue());

                        po.setVal(alarm.getVal().intValue());
                        po.setIsOpen(1);

                        alarm.setRank(vo.getRank());
                        alarm.setDescription(vo.getDescription());
                        alarm.setAlarmType(vo.getAlarmtype());
                        alarm.setDeviceType(vo.getDevicetype());

                        alarm.setCharacteristic(vo.getCharacteristic());
                        alarm.setFaultCause(vo.getFaultCause());
                        alarm.setResolvent(vo.getResolvent());
                        alarm.setIsClose(false);
                        alarm.setDeviceId(vo.getDeviceid());
                        alarm.setAlarmId(vo.getAlarmid());
                        if(StringUtils.notEmp(vo.getDeviceid()) && CacheContext.wtmap.containsKey(vo.getDeviceid()))
                        {
                            alarm.setCode(CacheContext.wtmap.get(vo.getDeviceid()).getNemCode());
                        }
                        if(CacheContext.wpmap.containsKey(vo.getStationid()))
                        {
                            alarm.setWpName(CacheContext.wpmap.get(vo.getStationid()).getName());
                        }

//                        if(po.getDeviceType().equals(DeviceTypeValue.IN.getCode()) || po.getDeviceType().equals(DeviceTypeValue.WT.getCode()))
//                        {
//                            try {
//                                pushDataSevice.pushWtData(alarm);
//                            }catch (Exception e)
//                            {
//                                logger.info(e.getMessage());
//                            }
//                        }else  if(po.getDeviceType().equals(DeviceTypeValue.BT.getCode()))
//                        {
//                            try {
//                                pushDataSevice.pushBtData(alarm);
//                            }catch (Exception e)
//                            {
//                                logger.info(e.getMessage());
//                            }
//                        }


                        tempmap.put(po.getTbname(),po);
                    }
                }

                for (Map.Entry<String, ProEconAlarmInfo> entry : tempmap.entrySet()) {
                    valuels.add(entry.getValue());
                }
                List<String> idls = new ArrayList<>();
                for (ProEconAlarmInfo vo : valuels) {
                    idls.add(vo.getTbname());
                }
//                Map<String,ProEconAlarmInfo> infoMap=new HashMap<>();
                if (!idls.isEmpty()) {

//                    List<ProEconAlarmInfo> templs= proEconAlarmInfoService.listByIds(idls);
//                    if(!templs.isEmpty())
//                    {
//                        for(ProEconAlarmInfo info:templs)
//                        {
//                            infoMap.put(info.getTbname().toLowerCase(),info);
//                        }
//                    }
                    proEconAlarmInfoService.removeByIds(idls);
                }


                List<ProEconAlarmInfo> templs = new ArrayList<>();
                for (ProEconAlarmInfo vo : valuels) {

//                    if(infoMap.containsKey(vo.getTbname().toLowerCase()))
//                    {
//                        ProEconAlarmInfo in=infoMap.get(vo.getTbname().toLowerCase());
//                        vo.setUpdateTime(in.getLastUpdateTime());
//                    }
                    templs.add(vo);
                    if (templs.size() == 900) {
                        proEconAlarmInfoService.saveBatch(templs);
                        templs = new ArrayList<>();
                    }
                }

                if (!templs.isEmpty()) {
                    proEconAlarmInfoService.saveBatch(templs);
                }

            }


            if (StringUtils.notEmp(ls) && !ls.isEmpty()) {


                for (AlarmTag alarm : ls) {
                    if (CacheContext.alarmCtMap.containsKey(alarm.getId())) {
                        AlarmVo vo = CacheContext.alarmCtMap.get(alarm.getId());

                        alarm.setRank(vo.getRank());
                        alarm.setDescription(vo.getDescription());
                        alarm.setAlarmType(vo.getAlarmtype());
                        alarm.setDeviceType(vo.getDevicetype());
                        alarm.setCharacteristic(vo.getCharacteristic());
                        alarm.setFaultCause(vo.getFaultCause());
                        alarm.setResolvent(vo.getResolvent());
                        alarm.setIsClose(false);
                        alarm.setDeviceId(vo.getDeviceid());
                        alarm.setAlarmId(vo.getAlarmid());
                        if(StringUtils.notEmp(vo.getDeviceid()) && CacheContext.wtmap.containsKey(vo.getDeviceid()))
                        {
                            alarm.setCode(CacheContext.wtmap.get(vo.getDeviceid()).getNemCode());
                        }
                        if(CacheContext.wpmap.containsKey(vo.getStationid()))
                        {
                            alarm.setWpName(CacheContext.wpmap.get(vo.getStationid()).getName());
                        }

                        if(vo.getDevicetype().equals(DeviceTypeValue.IN.getCode()) || vo.getDevicetype().equals(DeviceTypeValue.WT.getCode()))
                        {
                            pushDataSevice.pushWtData(alarm);
                        }else  if(vo.getDevicetype().equals(DeviceTypeValue.BT.getCode()))
                        {
                            pushDataSevice.pushBtData(alarm);
                        }

                    }
                }

            }

//            Thread.sleep(300);
            Thread.sleep(pushinterval.intValue());
        }

    }


    public synchronized void updateAlarms(List<AlarmTag> ls) throws EncodeException, IOException, InterruptedException {

        if (StringUtils.notEmp(ls) && !ls.isEmpty()) {

            if (StringUtils.notEmp(ls) && !ls.isEmpty()) {

                StringBuilder sb = new StringBuilder();
                Map<String, AlarmSimpleVo> map = new HashMap<>();
                for (AlarmTag alarm : ls) {
                    if (CacheContext.alarmCtMap.containsKey(alarm.getId())) {
                        AlarmVo vo = CacheContext.alarmCtMap.get(alarm.getId());
                        if(vo.getAlarmtype().equals(AlarmTypeValue.CT.getCode())  )
                        {
                            sb.append("'").append(alarm.getId().toLowerCase()).append("',");
                        }
                    }

                }
                String ids=null;

                if(sb.length()>0)
                {
                    ids=sb.substring(0,sb.length()-1);
                }
                List<AlarmSimpleVo> alarmls=new ArrayList<>();
                if( null !=ids)
                {
                    alarmls=alarmTsService.selectLastRowByTbname(AlarmSuperTalbeType.CT.getCode(),ids);
                }

                if(!alarmls.isEmpty())
                {
                    for(AlarmSimpleVo vo:alarmls)
                    {
                        map.put(vo.getTbName().toLowerCase(),vo);
                    }
                }
                List<AlarmTag> alarmTagls=new ArrayList<>();
                for (AlarmTag alarm : ls) {
                    if(map.containsKey(alarm.getId().toLowerCase()))
                    {
                        AlarmSimpleVo tag=map.get(alarm.getId().toLowerCase());
                        if(StringUtils.notEmp(tag.getTs()))
                        {
                            alarm.setTs(tag.getTs());
                            Date begin = new Date(alarm.getEndts());
                            Date end = new Date(alarm.getTs());

                            double value= DateUtils.secondsDiff(begin,end);
                            alarm.setTimeLong(value);
                            alarm.setConfirmed(tag.getConfirmed());
                            alarm.setSuperTalbe(AlarmSuperTalbeType.CT.getCode());

                            alarmTagls.add(alarm);
                        }
                    }
//                    else
//                    {
//                        alarm.setSuperTalbe(AlarmSuperTalbeType.BT.getCode());
//                        alarmTagls.add(alarm);
//                    }
                }
                if (StringUtils.notEmp(alarmTagls) && !alarmTagls.isEmpty()) {
                    alarmTsService.insertList(alarmTagls);
                }

                Map<String,ProEconAlarmInfo> tempmap=new HashMap<>();

                if (StringUtils.notEmp(alarmTagls) && !alarmTagls.isEmpty()) {

                    List<ProEconAlarmInfo> valuels = new ArrayList<>();
                    for (AlarmTag alarm : alarmTagls) {
                        if (CacheContext.alarmCtMap.containsKey(alarm.getId())) {
                            AlarmVo vo = CacheContext.alarmCtMap.get(alarm.getId());
                            ProEconAlarmInfo po = new ProEconAlarmInfo();
                            po.setTbname(vo.getTbName());
                            po.setLastUpdateTime(new Date(alarm.getEndts()));
                            po.setUpdateTime(new Date(alarm.getTs()));
                            po.setTagId(alarm.getTagId());
                            po.setTriggerType(alarm.getTriggerType());
                            po.setAlarmId(vo.getAlarmid());
                            po.setDeviceId(vo.getDeviceid());
                            po.setSubcomponents(vo.getSuffix());
                            po.setRank(vo.getRank());
                            po.setConfirmed(alarm.getConfirmed());
                            po.setUniformCode(vo.getUniformcode());
                            po.setAlarmType(vo.getAlarmtype());
                            po.setDeviceType(vo.getDevicetype());
                            po.setComponents(vo.getComponents());
                            po.setSubcomponents(vo.getSubcomponents());
                            po.setDescription(vo.getDescription());
                            po.setModelId(vo.getModelId());
                            po.setResetTable(vo.getResettable());
                            po.setEnable(vo.getEnabled());
                            po.setCharacteristic(vo.getCharacteristic());
                            po.setStationId(vo.getStationid());
                            po.setProjectId(vo.getProjectid());
                            po.setLineId(vo.getLineid());
                            po.setStationName(vo.getStationname());
                            po.setProjectiName(vo.getProjectname());
                            po.setLineidName(vo.getLinename());
                            po.setDeviceName(vo.getDevicename());
                            po.setOval(alarm.getOval().intValue());

                            po.setVal(alarm.getVal().intValue());
                            po.setCloseTime(new Date(alarm.getEndts()));
                            po.setIsOpen(0);

                            alarm.setRank(vo.getRank());
                            alarm.setDescription(vo.getDescription());
                            alarm.setAlarmType(vo.getAlarmtype());
                            alarm.setDeviceType(vo.getDevicetype());

                            alarm.setCharacteristic(vo.getCharacteristic());
                            alarm.setFaultCause(vo.getFaultCause());
                            alarm.setResolvent(vo.getResolvent());

                            alarm.setDeviceId(vo.getDeviceid());
                            alarm.setAlarmId(vo.getAlarmid());
                            alarm.setIsClose(true);
                            if(StringUtils.notEmp(vo.getDeviceid()) && CacheContext.wtmap.containsKey(vo.getDeviceid()))
                            {
                                alarm.setCode(CacheContext.wtmap.get(vo.getDeviceid()).getNemCode());
                            }
                            if(CacheContext.wpmap.containsKey(vo.getStationid()))
                            {
                                alarm.setWpName(CacheContext.wpmap.get(vo.getStationid()).getName());
                            }

//                            if(po.getDeviceType().equals(DeviceTypeValue.IN.getCode()) || po.getDeviceType().equals(DeviceTypeValue.WT.getCode()))
//                            {
//                                try {
//                                    pushDataSevice.pushWtData(alarm);
//                                }catch (Exception e)
//                                {
//                                    logger.info(e.getMessage());
//                                }
//                            }else  if(po.getDeviceType().equals(DeviceTypeValue.BT.getCode()))
//                            {
//                                try {
//                                    pushDataSevice.pushBtData(alarm);
//                                }catch (Exception e)
//                                {
//                                    logger.info(e.getMessage());
//                                }
//                            }
                            tempmap.put(po.getTbname(),po);
                        }
                    }

                    for (Map.Entry<String, ProEconAlarmInfo> entry : tempmap.entrySet()) {
                        valuels.add(entry.getValue());
                    }
                    List<String> idls = new ArrayList<>();
                    for (ProEconAlarmInfo vo : valuels) {
                        idls.add(vo.getTbname());
                    }
//                    Map<String,ProEconAlarmInfo> infoMap=new HashMap<>();
                    if (!idls.isEmpty()) {

//                        List<ProEconAlarmInfo> templs= proEconAlarmInfoService.listByIds(idls);
//                        if(!templs.isEmpty())
//                        {
//                            for(ProEconAlarmInfo info:templs)
//                            {
//                                infoMap.put(info.getTbname().toLowerCase(),info);
//                            }
//                        }
                        proEconAlarmInfoService.removeByIds(idls);
                    }


                    List<ProEconAlarmInfo> templs = new ArrayList<>();
                    for (ProEconAlarmInfo vo : valuels) {

//                        if(infoMap.containsKey(vo.getTbname().toLowerCase()))
//                        {
//                            ProEconAlarmInfo in=infoMap.get(vo.getTbname().toLowerCase());
//                            vo.setUpdateTime(in.getLastUpdateTime());
//                        }
                        templs.add(vo);
                        if (templs.size() == 900) {
                            proEconAlarmInfoService.saveBatch(templs);
                            templs = new ArrayList<>();
                        }
                    }

                    if (!templs.isEmpty()) {
                        proEconAlarmInfoService.saveBatch(templs);
                    }

                }

                if (StringUtils.notEmp(ls) && !ls.isEmpty()) {


                    for (AlarmTag alarm : ls) {
                        if (CacheContext.alarmCtMap.containsKey(alarm.getId())) {
                            AlarmVo vo = CacheContext.alarmCtMap.get(alarm.getId());

                            alarm.setRank(vo.getRank());
                            alarm.setDescription(vo.getDescription());
                            alarm.setAlarmType(vo.getAlarmtype());
                            alarm.setDeviceType(vo.getDevicetype());
                            alarm.setCharacteristic(vo.getCharacteristic());
                            alarm.setFaultCause(vo.getFaultCause());
                            alarm.setResolvent(vo.getResolvent());
                            alarm.setIsClose(false);
                            alarm.setDeviceId(vo.getDeviceid());
                            alarm.setAlarmId(vo.getAlarmid());
                            if(StringUtils.notEmp(vo.getDeviceid()) && CacheContext.wtmap.containsKey(vo.getDeviceid()))
                            {
                                alarm.setCode(CacheContext.wtmap.get(vo.getDeviceid()).getNemCode());
                            }
                            if(CacheContext.wpmap.containsKey(vo.getStationid()))
                            {
                                alarm.setWpName(CacheContext.wpmap.get(vo.getStationid()).getName());
                            }

                            if(vo.getDevicetype().equals(DeviceTypeValue.IN.getCode()) || vo.getDevicetype().equals(DeviceTypeValue.WT.getCode()))
                            {
                                pushDataSevice.pushWtData(alarm);
                            }else  if(vo.getDevicetype().equals(DeviceTypeValue.BT.getCode()))
                            {
                                pushDataSevice.pushBtData(alarm);
                            }
                        }


                    }
                }
                //            Thread.sleep(300);
                Thread.sleep(pushinterval.intValue());
            }
        }
    }

//    public void pushData(AlarmTag po) throws EncodeException, IOException {
//        ConcurrentHashMap<String, WebSocket> webSocketPushMap = WebSocket.webSocketMap;
//        ConcurrentHashMap<String, PushParams> webSocketPushParamsMap = WebSocket.webSocketParamsMap;
//        if(!webSocketPushMap.isEmpty()){
//            for(String key : webSocketPushMap.keySet()){
//                // 根据ws连接用户ID获取推送参数
//                PushParams pushParams = webSocketPushParamsMap.get(key);
//
//                if(webSocketPushParamsMap.contains(po.getId()))
//                {
//                    PushParams pp=webSocketPushParamsMap.get(po.getId());
//
//                    double hours=DateUtils.hoursDiff(pp.getStartTime(),new Date());
//                    if(hours>pushinterval)
//                    {
//
//                        synchronized (key)
//                        {
//                            webSocket.sendMessageByUserId(key,po);
//                            pp.setStartTime(new Date(po.getTs()));
//                        }
//
//
//                    }
//                }else
//                {
//                    synchronized (key)
//                    {
//                        webSocket.sendMessageByUserId(key,po);
//                        PushParams pp=new PushParams();
//                        pp.setStartTime(new Date());
//                        webSocketPushParamsMap.put(po.getId(),pp);
//                    }
//
//                }
//            }
//        }
//
//    }
}
