package com.gyee.alarm.service;

import com.gyee.alarm.init.CacheContext;
import com.gyee.alarm.model.auto.*;
import com.gyee.alarm.model.vo.AlarmSuperTalbeType;
import com.gyee.alarm.model.vo.AlarmTag;
import com.gyee.alarm.model.vo.AlarmVo;
import com.gyee.alarm.model.vo.DeviceTypeValue;
import com.gyee.alarm.service.auto.IAlarmTsService;
import com.gyee.alarm.service.auto.IProEconAlarmInfoService;
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 AlarmWtService {
    @Resource
    private IAlarmTsService alarmTsService;
    @Resource
    private IProEconAlarmInfoService proEconAlarmInfoService;
    @Value("${initialcode}")
    private String initialcode;

    public void dropSuperTable()
    {
        alarmTsService.dropSuperTable(AlarmSuperTalbeType.WT.getCode());
    }
    public void createSuperTable()
    {

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

    public void initalWtAlarm() throws SQLException {



        List<AlarmVo> alarmVoList=CacheContext.alarmWtList;
        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<ProEconAlarmConfiguration>> wtAlarmMap = CacheContext.wtAlarmMap;
        Map<String, Map<String, ProBasicEquipmentPoint>> wtpAimap = CacheContext.wtpAimap;
        for (ProBasicEquipment wt : CacheContext.wtls) {
            if (wtpAimap.containsKey(wt.getId())) {
                Map<String, ProBasicEquipmentPoint> pointMap = wtpAimap.get(wt.getId());

                StringBuilder sb = new StringBuilder();
                sb.append(wt.getWindpowerstationId() + wt.getModelId());
                if (StringUtils.notEmp(pointMap) && wtAlarmMap.containsKey(String.valueOf(sb))) {
                    List<ProEconAlarmConfiguration> alarmls = wtAlarmMap.get(String.valueOf(sb));

                    if (!alarmls.isEmpty()) {
                        for (ProEconAlarmConfiguration alarm : alarmls) {
                            if (pointMap.containsKey(alarm.getUniformCode())) {
                                ProBasicEquipmentPoint equipmentPoint = pointMap.get(alarm.getUniformCode());

                                if(StringUtils.notEmp(initialcode) &&
                                        StringUtils.notEmp(equipmentPoint.getNemCode()) &&
                                        !equipmentPoint.getNemCode().equals(initialcode))
                                {
                                    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(equipmentPoint.getNemCode());
                                    vo.setAlarmtype(alarm.getAlarmType());
                                    vo.setCharacteristic(alarm.getCharacteristic());
                                    vo.setComponents(alarm.getComponents());
                                    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(alarm.getResetTable());
                                    vo.setStationid(wt.getWindpowerstationId());
                                    if(CacheContext.wpmap.containsKey(wt.getWindpowerstationId()))
                                    {
                                        ProBasicPowerstation wp=CacheContext.wpmap.get(wt.getWindpowerstationId());
                                        vo.setStationname(wp.getName());
                                    }
                                    vo.setSubcomponents(alarm.getSubcomponents());
                                    vo.setSuffix(alarm.getSuffix());
                                    vo.setTriggertype(alarm.getTriggerType());
                                    vo.setUniformcode(alarm.getUniformCode());
                                    vo.setSuperTableName(AlarmSuperTalbeType.WT.getCode());
                                    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.alarmWtList;
            if(!vos.isEmpty())
            {
                for(AlarmVo vo:vos)
                {
                    AlarmTag po=new AlarmTag();
                    po.setId(vo.getTbName());

                    po.setTriggerType(vo.getTriggertype());
                    po.setTagId(vo.getTagid());

                    po.setRank(vo.getRank());

                    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.alarmWtMap.containsKey(alarm.getId()))
                    {
                        AlarmVo vo=CacheContext.alarmWtMap.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 if(alarm.getVal()==0)
                        {
                            po.setIsOpen(0);
                        }

                        valuels.add(po);
                    }
                }

//                List<ProEconAlarmInfo> templs=new ArrayList<>();
//                for(ProEconAlarmInfo vo:valuels)
//                {
//                    templs.add(vo);
//                    if(templs.size()==200)
//                    {
//                        proEconAlarmInfoService.saveOrUpdateBatch(templs);
//                        templs=new ArrayList<>();
//                    }
//                }
//
//                if(!templs.isEmpty())
//                {
//                    proEconAlarmInfoService.saveOrUpdateBatch(templs);
//                }

//分类，相同的报警放在一个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);
                }

            }
        }

    }

}
