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.util.DateUtils;
import com.gyee.alarm.util.StringUtils;
import com.gyee.alarm.util.realtimesource.IEdosUtil;
import com.gyee.alarm.websocket.PushParams;
import com.gyee.alarm.websocket.WebSocket;

import com.gyee.common.model.PointData;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.TextMessage;

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 AlarmBtService {
    @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;
    @Value("${read-rows}")
    private Integer readRows;
    @Resource
    private IEdosUtil edosUtil;
    public void dropSuperTable() {
        alarmTsService.dropSuperTable(AlarmSuperTalbeType.BT.getCode());
    }

    public void createSuperTable() {

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

    public void initalBtAlarm() throws Exception {


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

        List<AlarmVo> alarmVoList = CacheContext.alarmBtList;

        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.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());

            }
        }


//        alarmTsService.insertList(alarmTags);
    }


    public List<AlarmVo> initalAlarmVo() throws Exception {

        List<ProEconAlarmConfiguration> btalarmls = CacheContext.btalarmls;


        List<AlarmVo> alarmVoList = new ArrayList<>();
        if (!btalarmls.isEmpty()) {
            for (ProEconAlarmConfiguration alarm : btalarmls) {
                if (StringUtils.notEmp(alarm.getTagId()) &&
                        (alarm.getAlarmType().equals(AlarmTypeValue.BT.getCode()) || alarm.getAlarmType().equals(AlarmTypeValue.BTE.getCode()))) {
                    AlarmVo vo = new AlarmVo();
                    StringBuilder tbName = new StringBuilder();
                    tbName.append(alarm.getStationId()).append("_").append(alarm.getId());
                    vo.setTbName(String.valueOf(tbName));
                    vo.setAlarmid(alarm.getId());
                    vo.setTagid(alarm.getTagId());
                    vo.setAlarmtype(alarm.getAlarmType());
                    vo.setCharacteristic(alarm.getCharacteristic());
                    vo.setComponents(alarm.getComponents());
                    vo.setDescription(alarm.getDescription());
                    vo.setDeviceid("");
                    vo.setDevicename("");
                    vo.setDevicetype(DeviceTypeValue.BT.getCode());
                    vo.setEnabled(alarm.getEnable());
                    vo.setLineid("");
                    vo.setLinename("");
                    vo.setModelId(alarm.getModelId());
                    vo.setProjectid("");
                    vo.setProjectname("");
                    vo.setRank(alarm.getRank());
                    vo.setResettable(alarm.getResetTable());
                    vo.setStationid(alarm.getStationId());
                    if (CacheContext.subwpmap.containsKey(alarm.getStationId())) {
                        ProBasicSubStation wp = CacheContext.subwpmap.get(alarm.getStationId());
                        vo.setStationname(wp.getName());
                    }
                    vo.setSubcomponents(alarm.getSubcomponents());
                    vo.setSuffix(alarm.getSuffix());
                    vo.setTriggertype(alarm.getTriggerType());
                    vo.setUniformcode(alarm.getUniformCode());
                    vo.setSuperTableName(AlarmSuperTalbeType.BT.getCode());
                    //                                    PointData temp=edosUtil.getRealData(equipmentPoint.getNemCode());
//                                    vo.setVal((int)temp.getPointValueInDouble());
//                                    vo.setOval((int)temp.getPointValueInDouble());

                    vo.setVal(null);
                    vo.setOval(null);
                    vo.setFaultType(alarm.getDeviceId());
                    vo.setAname(alarm.getSuffix());
                    vo.setName(alarm.getName());
                    vo.setNemCode(alarm.getNemCode());
                    vo.setFaultCause(alarm.getFaultCause());
                    vo.setResolvent(alarm.getResolvent());
                    alarmVoList.add(vo);
                }
            }
        }

        return alarmVoList;
    }


    public List<AlarmTag> findTags(String stbaleName) {
        List<AlarmTag> ls = new ArrayList<>();
        if (StringUtils.notEmp(stbaleName)) {
            // List<AlarmVo> vos= alarmTsService.findTags(stbaleName);

            List<AlarmVo> vos = CacheContext.alarmBtList;
            if (!vos.isEmpty()) {
                for (AlarmVo vo : vos) {
                    AlarmTag po=new AlarmTag();
                    po.setId(vo.getTbName());
                    po.setOval(null);
                    po.setTriggerType(vo.getTriggertype());
                    po.setTagId(vo.getTagid());
                    po.setVal(null);
                    po.setRank(vo.getRank());
                    po.setAlarmType(vo.getAlarmtype());
                    po.setWpId(vo.getStationid());
                    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.alarmBtMap.containsKey(alarm.getId())) {
                        AlarmVo vo = CacheContext.alarmBtMap.get(alarm.getId());
                        ProEconAlarmInfo po = new ProEconAlarmInfo();
                        po.setTbname(vo.getTbName());
                        po.setUpdateTime(new Date(alarm.getTs()));
                        po.setLastUpdateTime(new Date(alarm.getTs()));
                        po.setTagId(alarm.getTagId());
                        po.setTriggerType(alarm.getTriggerType());

                        if(alarm.getTriggerType()==-1)
                        {
                            if(alarm.getOval()==0)
                            {
                                po.setDescription(vo.getDescription()+"_分位");
                            }else   if(alarm.getOval()==1)
                            {
                                po.setDescription(vo.getDescription()+"_合位");
                            }
                        }else
                        {
                            po.setDescription(vo.getDescription());
                        }
                        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.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(CacheContext.subwpmap.containsKey(vo.getStationid()))
                        {
                            alarm.setWpName(CacheContext.subwpmap.get(vo.getStationid()).getName());
                        }
                        alarm.setWpId(vo.getStationid());

//                        try {
//                            pushDataSevice.pushBtData(alarm);
//                        }catch (Exception e)
//                        {
//                            System.out.println(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.alarmBtMap.containsKey(alarm.getId())) {
                        AlarmVo vo = CacheContext.alarmBtMap.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(CacheContext.subwpmap.containsKey(vo.getStationid()))
                        {
                            alarm.setWpName(CacheContext.subwpmap.get(vo.getStationid()).getName());
                        }
                        alarm.setWpId(vo.getStationid());

                        pushDataSevice.pushBtData(alarm);
                    }
                }

                Thread.sleep(pushinterval.intValue());


            }
        }

    }


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

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

            StringBuilder sb=new StringBuilder();
            Map<String,AlarmSimpleVo> map=new HashMap<>();
            for (AlarmTag alarm : ls) {
                if (CacheContext.alarmBtMap.containsKey(alarm.getId())) {
                    AlarmVo vo = CacheContext.alarmBtMap.get(alarm.getId());
                    if(vo.getAlarmtype().equals(AlarmTypeValue.BT.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.BT.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.BT.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.alarmBtMap.containsKey(alarm.getId())) {
                        AlarmVo vo = CacheContext.alarmBtMap.get(alarm.getId());
                        ProEconAlarmInfo po = new ProEconAlarmInfo();
                        po.setTbname(vo.getTbName());
                        po.setUpdateTime(new Date(alarm.getTs()));
                        po.setLastUpdateTime(new Date(alarm.getEndts()));

                        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());
                        if(StringUtils.notEmp(alarm.getEndts()))
                        {
                            po.setCloseTime(new Date(alarm.getEndts()));
                        }else
                        {
                            po.setCloseTime(new Date());
                        }

                        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(CacheContext.subwpmap.containsKey(vo.getStationid()))
                        {
                            alarm.setWpName(CacheContext.subwpmap.get(vo.getStationid()).getName());
                        }
                        alarm.setWpId(vo.getStationid());
//                        try {
//                            pushDataSevice.pushBtData(alarm);
//                        }catch (Exception e)
//                        {
//                            System.out.println(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.alarmBtMap.containsKey(alarm.getId())) {
                        AlarmVo vo = CacheContext.alarmBtMap.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(CacheContext.subwpmap.containsKey(vo.getStationid()))
                        {
                            alarm.setWpName(CacheContext.subwpmap.get(vo.getStationid()).getName());
                        }
                        alarm.setWpId(vo.getStationid());

                        pushDataSevice.pushBtData(alarm);
                    }
                }

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

    }

//    public synchronized 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)
//                    {
//
//                        webSocket.sendMessageByUserId(key,po);
//                        pp.setStartTime(new Date(po.getTs()));
//
//                    }
//                }else
//                {
//                    webSocket.sendMessageByUserId(key,po);
//                    PushParams pp=new PushParams();
//                    pp.setStartTime(new Date());
//                    webSocketPushParamsMap.put(po.getId(),pp);
//
//                }
//            }
//        }
//
//    }
}
