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.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.SQLException;
import java.util.*;

@Service

public class AlarmCtService {
    @Resource
    private IAlarmTsService alarmTsService;

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

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

                AlarmTag po = new AlarmTag();
                po.setId(vo.getTbName());
                po.setVal(Double.valueOf(String.valueOf(vo.getTriggertype())));
                po.setTriggerType(vo.getTriggertype());
                po.setTagId(vo.getTagid());
                po.setOval(po.getVal());
                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);
        //场站自定义报警
        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);
                    }
                }
            }
        }
        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());
                        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());
                    alarmVoList.add(vo);
                }
            }
        }
    }

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

        }

        for (ProBasicSubStation wp : CacheContext.subwpls) {
            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.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());
                    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());

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


    public synchronized void saveAlarms(List<AlarmTag> ls) {

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

            alarmTsService.insertList(ls);


            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.setTs(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.setConfirmed(vo.getConfirmed());
                        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());

                        if(alarm.getVal()==1)
                        {
                            po.setIsOpen(1);
                        }else
                        {
                            po.setIsOpen(0);
                        }
                        valuels.add(po);
                    }
                }

//分类，相同的报警放在一个map中的list中
                Map<String, List<ProEconAlarmInfo>> tempmap = new HashMap<>();
                for (ProEconAlarmInfo vo : valuels) {
                    if (tempmap.containsKey(vo.getTbname())) {
                        List<ProEconAlarmInfo> templs = tempmap.get(vo.getTbname());
                        templs.add(vo);
                    } else {
                        List<ProEconAlarmInfo> templs = new ArrayList<>();
                        templs.add(vo);
                        tempmap.put(vo.getTbname(), templs);
                    }
                }
//删除，相同的报警
                List<String> idls = new ArrayList<>();
                for (Map.Entry<String, List<ProEconAlarmInfo>> entry : tempmap.entrySet()) {
                    idls.add(entry.getKey());
                }

                if (!idls.isEmpty()) {

                    proEconAlarmInfoService.removeByIds(idls);
                }

                List<ProEconAlarmInfo> pols = new ArrayList<>();
//保存，取项目集合中的最后一个记录进行保存
                for (Map.Entry<String, List<ProEconAlarmInfo>> entry : tempmap.entrySet()) {
                    List<ProEconAlarmInfo> resultls = entry.getValue();
                    if(!resultls.isEmpty())
                    {
                        Collections.sort(resultls, new Comparator<ProEconAlarmInfo>() {
                            public int compare(ProEconAlarmInfo arg0, ProEconAlarmInfo arg1) {
                                return arg0.getTs().compareTo(arg1.getTs());

                            }
                        });
                        pols.add(resultls.get(resultls.size() - 1));
                    }

                }

                List<ProEconAlarmInfo> templs = new ArrayList<>();
                for (ProEconAlarmInfo vo : pols) {
                    templs.add(vo);
                    if (templs.size() == 100) {
                        proEconAlarmInfoService.saveBatch(templs);
                        templs = new ArrayList<>();
                    }
                }

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

            }
        }

    }

}
