package com.gyee.alarm.service;


import cn.hutool.core.bean.BeanUtil;


import com.gyee.alarm.init.CacheContext;
import com.gyee.alarm.mapper.auto.AlarmTsMapper;
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.SnowflakeGenerator;
import com.gyee.common.model.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


@Service

public class AlarmHistoryService   {

    @Resource
    private AlarmTsMapper alarmTsMapper;
    @Resource
    private IAlarmTsService alarmTsService;

    @Resource
    private IProEconAlarmInfoService proEconAlarmInfoService;

    public  void updateAlarms(List<AlarmTag> ls) {

        if (com.gyee.alarm.util.StringUtils.notEmp(ls) && !ls.isEmpty()) {

            StringBuilder wtsb=new StringBuilder();
            StringBuilder ctsb=new StringBuilder();
            StringBuilder btsb=new StringBuilder();
            Map<String, AlarmSimpleVo> map=new HashMap<>();
            for (AlarmTag alarm : ls) {

                if(alarm.getAlarmType().equals(AlarmTypeValue.WT.getCode()) || alarm.getAlarmType().equals(AlarmTypeValue.IN.getCode()) )
                {
                    wtsb.append("'").append(alarm.getId().toLowerCase()).append("',");
                }else    if(alarm.getAlarmType().equals(AlarmTypeValue.BT.getCode()))
                {
                    btsb.append("'").append(alarm.getId().toLowerCase()).append("',");
                }else    if(alarm.getAlarmType().equals(AlarmTypeValue.CT.getCode()))
                {
                    ctsb.append("'").append(alarm.getId().toLowerCase()).append("',");
                }



            }
            String wtids=null;
            String ctids=null;
            String btids=null;

            if(wtsb.length()>0)
            {
                wtids=wtsb.substring(0,wtsb.length()-1);
            }
            if(ctsb.length()>0)
            {
                ctids=ctsb.substring(0,ctsb.length()-1);
            }
            if(btsb.length()>0)
            {
                 btids=btsb.substring(0,btsb.length()-1);
            }

            List<AlarmSimpleVo> alarmWtls=new ArrayList<>();
            List<AlarmSimpleVo> alarmCtls=new ArrayList<>();
            List<AlarmSimpleVo> alarmBtls=new ArrayList<>();

            if(null !=wtids)
            {
                 alarmWtls=alarmTsService.selectLastRowByTbname(AlarmSuperTalbeType.WT.getCode(),wtids);
            }
            if(null !=ctids)
            {
               alarmCtls=alarmTsService.selectLastRowByTbname(AlarmSuperTalbeType.CT.getCode(),ctids);
            }
            if(null !=btids)
            {
                alarmBtls=alarmTsService.selectLastRowByTbname(AlarmSuperTalbeType.BT.getCode(),btids);
            }


            if(!alarmWtls.isEmpty())
            {
                for(AlarmSimpleVo vo:alarmWtls)
                {
                    map.put(vo.getTbName().toLowerCase(),vo);
                }
            }

            if(!alarmCtls.isEmpty())
            {
                for(AlarmSimpleVo vo:alarmCtls)
                {
                    map.put(vo.getTbName().toLowerCase(),vo);
                }
            }

            if(!alarmBtls.isEmpty())
            {
                for(AlarmSimpleVo vo:alarmBtls)
                {
                    map.put(vo.getTbName().toLowerCase(),vo);
                }
            }
            List<AlarmTag> savels=new ArrayList<>();
            for (AlarmTag alarm : ls) {


                if(map.containsKey(alarm.getId().toLowerCase()))
                {
                    AlarmSimpleVo tag=map.get(alarm.getId().toLowerCase());

                    if(null !=tag.getTs())
                    {
//                        alarm.setTs(tag.getTs().getTime());
//                        if(StringUtils.notEmp(tag.getVal()))
//                        {
//                            alarm.setVal(tag.getVal().doubleValue());
//                        }
//
                        alarm.setEndts(null!=tag.getEndts()?tag.getEndts().getTime():null);
                        alarm.setTimeLong(null!=tag.getTimelong()?tag.getTimelong():null);
//                        alarm.setConfirmed(true);
//                        savels.add(alarm);
                    }
                    alarm.setVal(1.0);
                        alarm.setConfirmed(true);
                        savels.add(alarm);
                }
            }

            alarmTsService.insertList(savels);

            Map<String,ProEconAlarmInfo> tempmap=new HashMap<>();
            if (com.gyee.alarm.util.StringUtils.notEmp(savels) && !savels.isEmpty()) {

                List<ProEconAlarmInfo> valuels = new ArrayList<>();
                for (AlarmTag alarm : savels) {
                    AlarmVo vo =null;
                    if (CacheContext.alarmWtMap.containsKey(alarm.getId().toUpperCase())) {
                         vo = CacheContext.alarmWtMap.get(alarm.getId().toUpperCase());
                    }else if (CacheContext.alarmInMap.containsKey(alarm.getId().toUpperCase())) {
                        vo = CacheContext.alarmInMap.get(alarm.getId().toUpperCase());
                    }else if (CacheContext.alarmBtMap.containsKey(alarm.getId().toUpperCase())) {
                        vo = CacheContext.alarmBtMap.get(alarm.getId().toUpperCase());
                    }else if (CacheContext.alarmCtMap.containsKey(alarm.getId().toUpperCase())) {
                        vo = CacheContext.alarmCtMap.get(alarm.getId().toUpperCase());
                    }

                    if(StringUtils.notEmp(vo) && StringUtils.notEmp(vo.getTbName()))
                    {
                        ProEconAlarmInfo po = new ProEconAlarmInfo();


                        po.setTbname(vo.getTbName());
                        po.setLastUpdateTime(new Date());
                        po.setTagId(vo.getTagid());
                        po.setTriggerType(vo.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(0);
                        po.setCloseTime(null!=alarm.getEndts()?new Date(alarm.getEndts()):null);
                        po.setIsOpen(0);
                        po.setVal(alarm.getVal().intValue());


                        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());
                }
                if (!idls.isEmpty()) {

                    proEconAlarmInfoService.removeByIds(idls);
                }

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

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

            }

        }

    }

    @Value("${home_pagep_size}")
    private int home_pagep_size;
    /**
     * 查询报警信息接口
     * @param begin 开始时间
     * @param end 结束时间
     * @param alarmType 报警类型
     * @param stationid 场站
     * @param description 描述
     * @param pageNum 页数
     * @param pageSize 每页多少条
     * @return
     */
    public Map<String,Object> findAlarmlist(String modelId, long begin,long end ,String alarmType,String stationid,String deviceid,String description,String deviceType,String components,String alarmId,Boolean isclose, int pageNum, int pageSize) {

        Map<String,Object> map=new HashMap<>();

        List<AlarmVo> vos =new ArrayList<>();
        String superTableName= null;
        StringBuilder descriptionSql=new StringBuilder();
        if(StringUtils.notEmp(alarmType) && StringUtils.notEmp(begin) && StringUtils.notEmp(end) )
        {

//            whereSql.append(" where  ts>=").append(begin).append("  and ts<= ").append(end);
//
//            whereSql.append(" and alarmtype=CONCAT('',").append(alarmType).append(",'')");

            if(AlarmTypeValue.BT.getCode().equals(alarmType))
            {
                superTableName= AlarmSuperTalbeType.BT.getCode();

            }else if(AlarmTypeValue.WT.getCode().equals(alarmType))
            {
                superTableName= AlarmSuperTalbeType.WT.getCode();

            }
            else if(AlarmTypeValue.IN.getCode().equals(alarmType))
            {
                superTableName= AlarmSuperTalbeType.WT.getCode();

            }else if(AlarmTypeValue.CT.getCode().equals(alarmType))
            {
                superTableName= AlarmSuperTalbeType.CT.getCode();

            }
        }


//
        if(StringUtils.notEmp(description)  )
        {
            descriptionSql.append("%").append(description).append("%");
            description=String.valueOf(descriptionSql);
        }
        if(StringUtils.empty(deviceid)  )
        {
            deviceid=null;
        }

        if(StringUtils.empty(stationid)  )
        {
            stationid=null;
        }
        if(StringUtils.empty(modelId)  )
        {
            modelId=null;
        }
        if(StringUtils.empty(description)  )
        {
            description=null;
        }
        if(StringUtils.empty(deviceType)  )
        {
            deviceType=null;
        }

        if(StringUtils.empty(components)  )
        {
            components=null;
        }else
        {
             StringBuilder componentsList=new StringBuilder();
            String [] componentsStr=components.split(",");
            for(String c:componentsStr)
            {
                componentsList.append("'").append(c).append("',");

            }
            if(componentsList.length()>0)
            {
                components=String.valueOf(componentsList.substring(0,componentsList.length()-1));
            }
        }
        if(StringUtils.empty(alarmId)  )
        {
            alarmId=null;
        }

        if(StringUtils.empty(isclose)  )
        {
            isclose=null;
        }
        vos = alarmTsMapper.selectByWtLimit(begin,end,modelId,superTableName, alarmType, stationid, deviceid, description,deviceType,components, alarmId,isclose,pageNum*pageSize, pageSize);

        for(AlarmVo vo:vos)
        {

            if(com.gyee.alarm.util.StringUtils.notEmp(vo.getDeviceId()) && CacheContext.wtmap.containsKey(vo.getDeviceId()))
            {
                vo.setCode(CacheContext.wtmap.get(vo.getDeviceId()).getAname());
            }

            if(CacheContext.wpmap.containsKey(vo.getStationid()))
            {
                vo.setWpName(CacheContext.wpmap.get(vo.getStationid()).getName());
            }

            if(CacheContext.subwpmap.containsKey(vo.getStationid()))
            {
                vo.setWpName(CacheContext.subwpmap.get(vo.getStationid()).getName());
            }

            if(CacheContext.alarmTypeMap.containsKey(vo.getComponents()))
            {
                vo.setComponents(CacheContext.alarmTypeMap.get(vo.getComponents()).getName());
            }
            if(CacheContext.alarmMap.containsKey(vo.getAlarmId()))
            {
                vo.setComponents(CacheContext.alarmMap.get(vo.getAlarmId()).getDescription());
            }

        }


        map.put("ls",vos);
        List<Integer> total=alarmTsMapper.selectByWtCount(begin,end,modelId,superTableName, alarmType, stationid, deviceid, description,deviceType,components,alarmId,isclose);

        if(!total.isEmpty())
        {
            Integer all= total.get(0);
            map.put("total",all);
        }

        return map;
    }



    public List<AlarmVo> findAlarmByTypelist(String type) {


        List<AlarmVo> vos=new ArrayList<>();


        if(StringUtils.notEmp(type) )
        {
            Date endDate = new Date();
//            Date beginDate = DateUtils.addHours(endDate,-1);
            Date beginDate = DateUtils.truncate(endDate);
            if(type.equals(AlarmTypeValue.BT.getCode()))
            {
                vos = alarmTsMapper.selectByWtLimit(beginDate.getTime(),endDate.getTime(),null,AlarmSuperTalbeType.BT.getCode(), AlarmTypeValue.BT.getCode(), null, null, null,null,null, null,null,1, home_pagep_size);

            }else if(type.equals(AlarmTypeValue.WT.getCode()))
            {
                vos = alarmTsMapper.selectByWtLimit(beginDate.getTime(),endDate.getTime(),null,AlarmSuperTalbeType.WT.getCode(), AlarmTypeValue.WT.getCode(), null, null, null,null, null,null,null,1, home_pagep_size);

            }else if(type.equals(AlarmTypeValue.CT.getCode()))
            {
                vos = alarmTsMapper.selectByWtLimit(beginDate.getTime(),endDate.getTime(),null,AlarmSuperTalbeType.CT.getCode(), AlarmTypeValue.CT.getCode(), null, null, null,null, null,null,null,1, home_pagep_size);

            }

        }

        return vos;
    }


    public List<AlarmStatVo> findWtFeatureStat(String stationId,String modelId, Date startTime, Date endTime,String components,String alarmIds,String alarmType,String timeType) {
        List<AlarmStatVo> resultList = new ArrayList<>();

        StringBuilder alarmIdList=new StringBuilder();
        StringBuilder componentsList=new StringBuilder();

        Map<String,String> alarmIdMap=new HashMap<>();
        Map<String,String> componentsMap=new HashMap();

        if(StringUtils.notEmp(components))
        {
            String [] componentsStr=components.split(",");
            for(String c:componentsStr)
            {
                componentsList.append("'").append(c).append("',");
                componentsMap.put(c,c);
            }

        }
        if(StringUtils.notEmp(alarmIds))
        {
            String [] alarmIdStr=alarmIds.split(",");
            for(String c:alarmIdStr)
            {
                alarmIdList.append("'").append(c).append("',");
                alarmIdMap.put(c,c);
            }

        }
        String alarmId=null;
        String component=null;
        if(alarmIdList.length()>0)
        {
             alarmId=String.valueOf(alarmIdList.substring(0,alarmIdList.length()-1));
        }
        if(componentsList.length()>0)
        {
            component=String.valueOf(componentsList.substring(0,componentsList.length()-1));
        }
        List<ProBasicFeatureStat> fsls = new ArrayList<>();
        if(alarmType.equals(AlarmTypeValue.BT.getCode()))
        {
            fsls = alarmTsMapper.findWtFeatureStat(AlarmSuperTalbeType.BT.getCode(), startTime.getTime(), endTime.getTime(),stationId,modelId,component,alarmId, alarmType);

        }else if(alarmType.equals(AlarmTypeValue.WT.getCode()))
        {
            fsls = alarmTsMapper.findWtFeatureStat(AlarmSuperTalbeType.WT.getCode(),startTime.getTime(), endTime.getTime(),stationId,modelId,component,alarmId, alarmType);
        }else if(alarmType.equals(AlarmTypeValue.IN.getCode()))
        {
            fsls = alarmTsMapper.findWtFeatureStat(AlarmSuperTalbeType.WT.getCode(),startTime.getTime(), endTime.getTime(),stationId,modelId,component,alarmId, alarmType);
        }

        Map<String, ProBasicFeatureStat> map = new HashMap<>();
        Date statDate=DateUtils.truncate(new Date());

        if (!fsls.isEmpty()) {
            for (ProBasicFeatureStat fs : fsls) {
                if (StringUtils.notEmp(fs.getTypeCode()) && CacheContext.alarmTypeMap.containsKey(fs.getTypeCode())) {
                    ProEconAlarmType at = CacheContext.alarmTypeMap.get(fs.getTypeCode());
                    fs.setTypeName(at.getName());
                }
                fs.setStatDate(new Timestamp(statDate.getTime()));
                fs.setId(String.valueOf(SnowflakeGenerator.generateId()));
                StringBuilder sb = new StringBuilder();
                sb.append(fs.getWtId()).append("_").append(fs.getAlarmid());
                map.put(String.valueOf(sb), fs);
            }
        }
        List<ProBasicFeatureStat> vos = new ArrayList<>();

        if(CacheContext.wpwtmap.containsKey(stationId))
        {
            List<ProBasicEquipment> wtls=CacheContext.wpwtmap.get(stationId);
            for (ProBasicEquipment wt : wtls) {

                StringBuilder sb=new StringBuilder();
                sb.append(wt.getWindpowerstationId()).append(wt.getModelId());
                if(CacheContext.wtAlarmMap.containsKey(String.valueOf(sb))) {
                    List<ProEconAlarmConfiguration> ls = CacheContext.wtAlarmMap.get(String.valueOf(sb));
                    for (ProEconAlarmConfiguration at : ls) {
                        if(StringUtils.notEmp(components) )
                        {
                            if(componentsMap.containsKey(at.getComponents()) )
                            {
                                if(StringUtils.notEmp(alarmIdMap) && !alarmIdMap.isEmpty())
                                {
                                    if( alarmIdMap.containsKey(at.getId()))
                                    {
                                        setWtValues(statDate, map, vos, wt, at);
                                    }

                                }else
                                {
                                    setWtValues(statDate, map, vos, wt, at);
                                }
                            }
                        }else
                        {
                            setWtValues(statDate, map, vos, wt, at);
                        }

                    }
                }
            }
        }


        Map<String,List<AlarmStatVo>> vomap=new HashMap<>();
        for(ProBasicFeatureStat fs:vos)
        {
            AlarmStatVo d = new AlarmStatVo();
            d.setRelateParts(fs.getTypeCode());
            d.setRelatePartsText(fs.getTypeName());
            d.setAlertText(fs.getDescription());
            d.setCount(fs.getTotal());

            if(StringUtils.empty(fs.getTotalSeconds()))
            {
                fs.setTotalSeconds(0.0);
            }
            if(StringUtils.empty(fs.getAvgSeconds()))
            {
                fs.setAvgSeconds(0.0);
            }
            if(StringUtils.empty(fs.getMinSeconds()))
            {
                fs.setMinSeconds(0.0);
            }
            if(StringUtils.empty(fs.getMaxSeconds()))
            {
                fs.setMaxSeconds(0.0);
            }
            if(StringUtils.empty(fs.getTotal()))
            {
                fs.setTotal(0L);
            }
            if(StringUtils.notEmp(timeType))
            {
                if(AlarmTime.H.getCode().equals(timeType))
                {
                    double times= new BigDecimal(fs.getTotalSeconds()).divide(new BigDecimal(360), 2, RoundingMode.HALF_EVEN).doubleValue();
                    d.setTime(times);
                }else if(AlarmTime.M.getCode().equals(timeType))
                {
                    double times= new BigDecimal(fs.getTotalSeconds()).divide(new BigDecimal(60), 2, RoundingMode.HALF_EVEN).doubleValue();
                    d.setTime(times);
                }else
                {
                    d.setTime(fs.getTotalSeconds());
                }
            }else
            {
                double times= new BigDecimal(fs.getTotalSeconds()).divide(new BigDecimal(60), 2, RoundingMode.HALF_EVEN).doubleValue();
                d.setTime(times);
            }

            d.setStationId(fs.getStationId());
            d.setSnapId(SnowflakeGenerator.generateId());
            d.setWindturbineId(fs.getWtId());
            d.setAlarmid(fs.getAlarmid());
            if(CacheContext.wtmap.containsKey(fs.getWtId()))
            {
                ProBasicEquipment wt= CacheContext.wtmap.get(fs.getWtId());
                d.setWindturbineCode(wt.getAname());
            }

            StringBuilder sb=new StringBuilder();
            sb.append(fs.getWtId()).append("_").append(fs.getTypeCode()).append("_").append(fs.getAlarmid());

            if(map.containsKey(String.valueOf(sb)))
            {
                List<AlarmStatVo> ls=vomap.get(String.valueOf(sb));
                ls.add(d);
            }else
            {
                List<AlarmStatVo> ls=new ArrayList<>();
                ls.add(d);
                vomap.put(String.valueOf(sb),ls);
            }
            resultList.add(d);
        }




        return resultList;
    }
    private  static void setWtValues(Date statDate,Map<String, ProBasicFeatureStat> map, List<ProBasicFeatureStat> vos, ProBasicEquipment wt, ProEconAlarmConfiguration at) {

        ProBasicFeatureStat fs = new ProBasicFeatureStat();

        StringBuilder sb = new StringBuilder();
        sb.append(wt.getId()).append("_").append(at.getId());
        if (map.containsKey(String.valueOf(sb))) {
            ProBasicFeatureStat old = map.get(String.valueOf(sb));
            BeanUtil.copyProperties(old, fs);
        } else {
            fs.setStatDate(new Timestamp(statDate.getTime()));
            fs.setId(String.valueOf(SnowflakeGenerator.generateId()));
            fs.setWtId(wt.getId());
            fs.setStationId(wt.getWindpowerstationId());
            fs.setTypeCode(at.getComponents());
            if(CacheContext.alarmTypeMap.containsKey(at.getComponents()))
            {
                fs.setTypeName(CacheContext.alarmTypeMap.get(at.getComponents()).getName());
            }
            fs.setAlarmid(at.getId());
            fs.setDescription(at.getDescription());
            fs.setTotal(0l);
            fs.setAvgSeconds(0.0);
            fs.setMaxSeconds(0.0);
            fs.setMinSeconds(0.0);
            fs.setTotalSeconds(0.0);

        }
        vos.add(fs);
    }

    public List<AlarmStatVo> findCtFeatureStat(String stationId,String modelId, Date startTime, Date endTime,String components,String deviceType,String alarmIds,String timeType) {
        List<AlarmStatVo> resultList = new ArrayList<>();


        StringBuilder alarmIdList=new StringBuilder();
        StringBuilder componentsList=new StringBuilder();

        Map<String,String> alarmIdMap=new HashMap<>();
        Map<String,String> componentsMap=new HashMap();

        if(StringUtils.notEmp(components))
        {
            String [] componentsStr=components.split(",");
            for(String c:componentsStr)
            {
                componentsList.append("'").append(c).append("',");
                componentsMap.put(c,c);
            }

        }
        if(StringUtils.notEmp(alarmIds))
        {
            String [] alarmIdStr=alarmIds.split(",");
            for(String c:alarmIdStr)
            {
                alarmIdList.append("'").append(c).append("',");
                alarmIdMap.put(c,c);
            }

        }
        String alarmId=null;
        String component=null;
        if(alarmIdList.length()>0)
        {
            alarmId=String.valueOf(alarmIdList.substring(0,alarmIdList.length()-1));
        }
        if(componentsList.length()>0)
        {
            component=String.valueOf(componentsList.substring(0,componentsList.length()-1));
        }
        List<ProBasicFeatureStat> fsls = alarmTsMapper.findCtFeatureStat(startTime.getTime(), endTime.getTime(),stationId,modelId,component,alarmId,deviceType);


        Map<String, ProBasicFeatureStat> map = new HashMap<>();
        Date statDate=DateUtils.truncate(new Date());

        if (!fsls.isEmpty()) {
            for (ProBasicFeatureStat fs : fsls) {
                if (StringUtils.notEmp(fs.getTypeCode()) && CacheContext.alarmTypeMap.containsKey(fs.getTypeCode())) {
                    ProEconAlarmType at = CacheContext.alarmTypeMap.get(fs.getTypeCode());
                    fs.setTypeName(at.getName());
                }
                fs.setStatDate(new Timestamp(statDate.getTime()));
                fs.setId(String.valueOf(SnowflakeGenerator.generateId()));
                StringBuilder sb = new StringBuilder();
                sb.append(fs.getWtId()).append("_").append(fs.getAlarmid());
                map.put(String.valueOf(sb), fs);
            }
        }
        List<ProBasicFeatureStat> vos = new ArrayList<>();

        if(CacheContext.wpwtmap.containsKey(stationId))
        {
            List<ProBasicEquipment> wtls=CacheContext.wpwtmap.get(stationId);
            for (ProBasicEquipment wt : wtls) {

                StringBuilder sb=new StringBuilder();
                sb.append(wt.getWindpowerstationId()).append(wt.getModelId());

                if(CacheContext.ctAlarmlsMap.containsKey(String.valueOf(sb))) {

                    List<ProEconAlarmRule> wtCustomls=CacheContext.ctAlarmlsMap.get(String.valueOf(sb));

                    for (ProEconAlarmRule at : wtCustomls) {

                        if(StringUtils.notEmp(components) )
                        {
                            if(componentsMap.containsKey(at.getRelatedParts().trim()) )
                            {
                                if(StringUtils.notEmp(alarmIdMap) && !alarmIdMap.isEmpty())
                                {
                                    if( alarmIdMap.containsKey(at.getId()))
                                    {
                                        setCtValues(statDate, map, vos, wt, at);
                                    }

                                }else
                                {
                                    setCtValues(statDate, map, vos, wt, at);
                                }
                            }
                        }else
                        {
                            setCtValues(statDate, map, vos, wt, at);
                        }

                    }

                }
            }
        }


        System.out.println("vos"+vos.size());

//        Map<String,List<AlarmStatVo>> vomap=new HashMap<>();
        for(ProBasicFeatureStat fs:vos)
        {
//            if(fs.getDescription().equals("自定义"))
//            {
//                continue;
//            }
            AlarmStatVo d = new AlarmStatVo();
            d.setRelateParts(fs.getTypeCode());
            d.setRelatePartsText(fs.getTypeName());
            d.setAlertText(fs.getDescription());
            d.setCount(fs.getTotal());
            d.setAlarmid(fs.getAlarmid());

            if(StringUtils.empty(fs.getTotalSeconds()))
            {
                fs.setTotalSeconds(0.0);
            }
            if(StringUtils.empty(fs.getAvgSeconds()))
            {
                fs.setAvgSeconds(0.0);
            }
            if(StringUtils.empty(fs.getMinSeconds()))
            {
                fs.setMinSeconds(0.0);
            }
            if(StringUtils.empty(fs.getMaxSeconds()))
            {
                fs.setMaxSeconds(0.0);
            }
            if(StringUtils.empty(fs.getTotal()))
            {
                fs.setTotal(0L);
            }
            if(CacheContext.ctAlarmMap.containsKey(fs.getAlarmid()))
            {
                ProEconAlarmRule ar=CacheContext.ctAlarmMap.get(fs.getAlarmid());
                d.setAlertText(ar.getName());
            }
            if(StringUtils.notEmp(timeType))
            {
                if(AlarmTime.H.getCode().equals(timeType))
                {
                    double times= new BigDecimal(fs.getTotalSeconds()).divide(new BigDecimal(360), 2, RoundingMode.HALF_EVEN).doubleValue();
                    d.setTime(times);
                }else if(AlarmTime.M.getCode().equals(timeType))
                {
                    double times= new BigDecimal(fs.getTotalSeconds()).divide(new BigDecimal(60), 2, RoundingMode.HALF_EVEN).doubleValue();
                    d.setTime(times);
                }else
                {
                    d.setTime(fs.getTotalSeconds());
                }
            }else
            {
                double times= new BigDecimal(fs.getTotalSeconds()).divide(new BigDecimal(60), 2, RoundingMode.HALF_EVEN).doubleValue();
                d.setTime(times);
            }


            d.setStationId(fs.getStationId());
            d.setSnapId(SnowflakeGenerator.generateId());
            d.setWindturbineId(fs.getWtId());
            if(CacheContext.wtmap.containsKey(fs.getWtId()))
            {
                ProBasicEquipment wt= CacheContext.wtmap.get(fs.getWtId());
                d.setWindturbineCode(wt.getNemCode());
            }

            if(CacheContext.wtmap.containsKey(fs.getWtId()))
            {
                ProBasicEquipment wt= CacheContext.wtmap.get(fs.getWtId());
                d.setCode(wt.getAname());
            }


//            StringBuilder sb=new StringBuilder();
//            sb.append(fs.getWtId()).append("_").append(fs.getTypeCode()).append("_").append(fs.getAlarmid());
//
//            if(map.containsKey(String.valueOf(sb)))
//            {
//                List<AlarmStatVo> ls=vomap.get(String.valueOf(sb));
//                ls.add(d);
//            }else
//            {
//                List<AlarmStatVo> ls=new ArrayList<>();
//                ls.add(d);
//                vomap.put(String.valueOf(sb),ls);
//            }
            resultList.add(d);
        }
        System.out.println("resultList"+vos.size());

        return resultList;
    }


    public List<AlarmStatVo> findCtFeatureStatByWpId(String modelId, Date startTime, Date endTime,String components,String deviceType,String alarmIds,String timeType) {
        List<AlarmStatVo> resultList = new ArrayList<>();


        StringBuilder alarmIdList=new StringBuilder();
        StringBuilder componentsList=new StringBuilder();

        Map<String,String> alarmIdMap=new HashMap<>();
        Map<String,String> componentsMap=new HashMap();

        if(StringUtils.notEmp(components))
        {
            String [] componentsStr=components.split(",");
            for(String c:componentsStr)
            {
                componentsList.append("'").append(c).append("',");
                componentsMap.put(c,c);
            }

        }
        if(StringUtils.notEmp(alarmIds))
        {
            String [] alarmIdStr=alarmIds.split(",");
            for(String c:alarmIdStr)
            {
                alarmIdList.append("'").append(c).append("',");
                alarmIdMap.put(c,c);
            }

        }
        String alarmId=null;
        String component=null;
        if(alarmIdList.length()>0)
        {
            alarmId=String.valueOf(alarmIdList.substring(0,alarmIdList.length()-1));
        }
        if(componentsList.length()>0)
        {
            component=String.valueOf(componentsList.substring(0,componentsList.length()-1));
        }
        List<ProBasicFeatureStat> fsls = alarmTsMapper.findCtFeatureStatByWpId(startTime.getTime(), endTime.getTime(),null,modelId,component,alarmId,deviceType);


        Map<String, ProBasicFeatureStat> map = new HashMap<>();
        Date statDate=DateUtils.truncate(new Date());

        if (!fsls.isEmpty()) {
            for (ProBasicFeatureStat fs : fsls) {
                if (StringUtils.notEmp(fs.getTypeCode()) && CacheContext.alarmTypeMap.containsKey(fs.getTypeCode())) {
                    ProEconAlarmType at = CacheContext.alarmTypeMap.get(fs.getTypeCode());
                    fs.setTypeName(at.getName());
                }
                fs.setStatDate(new Timestamp(statDate.getTime()));
                fs.setId(String.valueOf(SnowflakeGenerator.generateId()));
                StringBuilder sb = new StringBuilder();
                sb.append(fs.getStationId()).append("_").append(fs.getAlarmid());
                map.put(String.valueOf(sb), fs);
            }
        }



        Map<String,List<AlarmStatVo>> vomap=new HashMap<>();
        for(ProBasicFeatureStat fs:fsls)
        {
            AlarmStatVo d = new AlarmStatVo();
            d.setRelateParts(fs.getTypeCode());
            d.setRelatePartsText(fs.getTypeName());
            d.setAlertText(fs.getDescription());
            d.setCount(fs.getTotal());
            d.setAlarmid(fs.getAlarmid());

            if(StringUtils.empty(fs.getTotalSeconds()))
            {
                fs.setTotalSeconds(0.0);
            }
            if(StringUtils.empty(fs.getAvgSeconds()))
            {
                fs.setAvgSeconds(0.0);
            }
            if(StringUtils.empty(fs.getMinSeconds()))
            {
                fs.setMinSeconds(0.0);
            }
            if(StringUtils.empty(fs.getMaxSeconds()))
            {
                fs.setMaxSeconds(0.0);
            }
            if(StringUtils.empty(fs.getTotal()))
            {
                fs.setTotal(0L);
            }
            if(CacheContext.ctAlarmMap.containsKey(fs.getAlarmid()))
            {
                ProEconAlarmRule ar=CacheContext.ctAlarmMap.get(fs.getAlarmid());
                d.setAlertText(ar.getName());
            }
            if(StringUtils.notEmp(timeType))
            {
                if(AlarmTime.H.getCode().equals(timeType))
                {
                    double times= new BigDecimal(fs.getTotalSeconds()).divide(new BigDecimal(360), 2, RoundingMode.HALF_EVEN).doubleValue();
                    d.setTime(times);
                }else if(AlarmTime.M.getCode().equals(timeType))
                {
                    double times= new BigDecimal(fs.getTotalSeconds()).divide(new BigDecimal(60), 2, RoundingMode.HALF_EVEN).doubleValue();
                    d.setTime(times);
                }else
                {
                    d.setTime(fs.getTotalSeconds());
                }
            }else
            {
                double times= new BigDecimal(fs.getTotalSeconds()).divide(new BigDecimal(60), 2, RoundingMode.HALF_EVEN).doubleValue();
                d.setTime(times);
            }
            d.setStationId(fs.getStationId());
            d.setSnapId(SnowflakeGenerator.generateId());
            d.setWindturbineId(fs.getWtId());
            if(CacheContext.wpmap.containsKey(fs.getStationId()))
            {
                ProBasicPowerstation wt= CacheContext.wpmap.get(fs.getStationId());
                d.setWindturbineCode(wt.getAname());
            }

            StringBuilder sb=new StringBuilder();
            sb.append(fs.getStationId()).append("_").append(fs.getAlarmid());

            if(vomap.containsKey(String.valueOf(sb)))
            {
                List<AlarmStatVo> ls=vomap.get(String.valueOf(sb));
                ls.add(d);
            }else
            {
                List<AlarmStatVo> ls=new ArrayList<>();
                ls.add(d);
                vomap.put(String.valueOf(sb),ls);
            }
            resultList.add(d);
        }


        return resultList;
    }


    public List<AlarmStatVo> findCtFeatureStatByLnId(String wpId,String modelId, Date startTime, Date endTime,String components,String deviceType,String alarmIds,String timeType) {
        List<AlarmStatVo> resultList = new ArrayList<>();


        StringBuilder alarmIdList=new StringBuilder();
        StringBuilder componentsList=new StringBuilder();

        Map<String,String> alarmIdMap=new HashMap<>();
        Map<String,String> componentsMap=new HashMap();

        if(StringUtils.notEmp(components))
        {
            String [] componentsStr=components.split(",");
            for(String c:componentsStr)
            {
                componentsList.append("'").append(c).append("',");
                componentsMap.put(c,c);
            }

        }
        if(StringUtils.notEmp(alarmIds))
        {
            String [] alarmIdStr=alarmIds.split(",");
            for(String c:alarmIdStr)
            {
                alarmIdList.append("'").append(c).append("',");
                alarmIdMap.put(c,c);
            }

        }
        String alarmId=null;
        String component=null;
        if(alarmIdList.length()>0)
        {
            alarmId=String.valueOf(alarmIdList.substring(0,alarmIdList.length()-1));
        }
        if(componentsList.length()>0)
        {
            component=String.valueOf(componentsList.substring(0,componentsList.length()-1));
        }
        List<ProBasicFeatureStat> fsls = alarmTsMapper.findCtFeatureStatByLnId(startTime.getTime(), endTime.getTime(),wpId,modelId,component,alarmId,deviceType);


        Map<String, ProBasicFeatureStat> map = new HashMap<>();
        Date statDate=DateUtils.truncate(new Date());

        if (!fsls.isEmpty()) {
            for (ProBasicFeatureStat fs : fsls) {
                if (StringUtils.notEmp(fs.getTypeCode()) && CacheContext.alarmTypeMap.containsKey(fs.getTypeCode())) {
                    ProEconAlarmType at = CacheContext.alarmTypeMap.get(fs.getTypeCode());
                    fs.setTypeName(at.getName());
                }
                fs.setStatDate(new Timestamp(statDate.getTime()));
                fs.setId(String.valueOf(SnowflakeGenerator.generateId()));
                StringBuilder sb = new StringBuilder();
                sb.append(fs.getStationId()).append("_").append(fs.getAlarmid());
                map.put(String.valueOf(sb), fs);
            }
        }



        Map<String,List<AlarmStatVo>> vomap=new HashMap<>();
        for(ProBasicFeatureStat fs:fsls)
        {
            AlarmStatVo d = new AlarmStatVo();
            d.setRelateParts(fs.getTypeCode());
            d.setRelatePartsText(fs.getTypeName());
            d.setAlertText(fs.getDescription());
            d.setCount(fs.getTotal());
            d.setAlarmid(fs.getAlarmid());

            if(StringUtils.empty(fs.getTotalSeconds()))
            {
                fs.setTotalSeconds(0.0);
            }
            if(StringUtils.empty(fs.getAvgSeconds()))
            {
                fs.setAvgSeconds(0.0);
            }
            if(StringUtils.empty(fs.getMinSeconds()))
            {
                fs.setMinSeconds(0.0);
            }
            if(StringUtils.empty(fs.getMaxSeconds()))
            {
                fs.setMaxSeconds(0.0);
            }
            if(StringUtils.empty(fs.getTotal()))
            {
                fs.setTotal(0L);
            }

            if(CacheContext.ctAlarmMap.containsKey(fs.getAlarmid()))
            {
                ProEconAlarmRule ar=CacheContext.ctAlarmMap.get(fs.getAlarmid());
                d.setAlertText(ar.getName());
            }
            if(StringUtils.notEmp(timeType))
            {
                if(AlarmTime.H.getCode().equals(timeType))
                {
                    double times= new BigDecimal(fs.getTotalSeconds()).divide(new BigDecimal(360), 2, RoundingMode.HALF_EVEN).doubleValue();
                    d.setTime(times);
                }else if(AlarmTime.M.getCode().equals(timeType))
                {
                    double times= new BigDecimal(fs.getTotalSeconds()).divide(new BigDecimal(60), 2, RoundingMode.HALF_EVEN).doubleValue();
                    d.setTime(times);
                }else
                {
                    d.setTime(fs.getTotalSeconds());
                }
            }else
            {
                double times= new BigDecimal(fs.getTotalSeconds()).divide(new BigDecimal(60), 2, RoundingMode.HALF_EVEN).doubleValue();
                d.setTime(times);
            }
            d.setStationId(fs.getStationId());
            d.setSnapId(SnowflakeGenerator.generateId());
            d.setWindturbineId(fs.getWtId());
            if(CacheContext.lnmap.containsKey(fs.getStationId()))
            {
                ProBasicLine ln= CacheContext.lnmap.get(fs.getStationId());
                d.setWindturbineCode(ln.getNemCode());
            }

            StringBuilder sb=new StringBuilder();
            sb.append(fs.getStationId()).append("_").append(fs.getAlarmid());

            if(vomap.containsKey(String.valueOf(sb)))
            {
                List<AlarmStatVo> ls=vomap.get(String.valueOf(sb));
                ls.add(d);
            }else
            {
                List<AlarmStatVo> ls=new ArrayList<>();
                ls.add(d);
                vomap.put(String.valueOf(sb),ls);
            }
            resultList.add(d);
        }


        return resultList;
    }



    public List<AlarmStatVo> findCtFeatureStatByWtId(String wtId,String modelId, Date startTime, Date endTime,String components,String deviceType,String alarmIds,String timeType) {
        List<AlarmStatVo> resultList = new ArrayList<>();


        StringBuilder alarmIdList=new StringBuilder();
        StringBuilder componentsList=new StringBuilder();

        Map<String,String> alarmIdMap=new HashMap<>();
        Map<String,String> componentsMap=new HashMap();

        if(StringUtils.notEmp(components))
        {
            String [] componentsStr=components.split(",");
            for(String c:componentsStr)
            {
                componentsList.append("'").append(c).append("',");
                componentsMap.put(c,c);
            }

        }
        if(StringUtils.notEmp(alarmIds))
        {
            String [] alarmIdStr=alarmIds.split(",");
            for(String c:alarmIdStr)
            {
                alarmIdList.append("'").append(c).append("',");
                alarmIdMap.put(c,c);
            }

        }
        String alarmId=null;
        String component=null;
        if(alarmIdList.length()>0)
        {
            alarmId=String.valueOf(alarmIdList.substring(0,alarmIdList.length()-1));
        }
        if(componentsList.length()>0)
        {
            component=String.valueOf(componentsList.substring(0,componentsList.length()-1));
        }
        List<ProBasicFeatureStat> fsls = alarmTsMapper.findCtFeatureStatByWtId(startTime.getTime(), endTime.getTime(),wtId,modelId,component,alarmId,deviceType);


        Map<String, ProBasicFeatureStat> map = new HashMap<>();
        Date statDate=DateUtils.truncate(new Date());

        if (!fsls.isEmpty()) {
            for (ProBasicFeatureStat fs : fsls) {
                if (StringUtils.notEmp(fs.getTypeCode()) && CacheContext.alarmTypeMap.containsKey(fs.getTypeCode())) {
                    ProEconAlarmType at = CacheContext.alarmTypeMap.get(fs.getTypeCode());
                    fs.setTypeName(at.getName());
                }
                fs.setStatDate(new Timestamp(statDate.getTime()));
                fs.setId(String.valueOf(SnowflakeGenerator.generateId()));
                StringBuilder sb = new StringBuilder();
                sb.append(fs.getStationId()).append("_").append(fs.getAlarmid());
                map.put(String.valueOf(sb), fs);
            }
        }



        Map<String,List<AlarmStatVo>> vomap=new HashMap<>();
        for(ProBasicFeatureStat fs:fsls)
        {
            AlarmStatVo d = new AlarmStatVo();
            d.setRelateParts(fs.getTypeCode());
            d.setRelatePartsText(fs.getTypeName());
            d.setAlertText(fs.getDescription());
            d.setCount(fs.getTotal());
            d.setAlarmid(fs.getAlarmid());

            if(StringUtils.empty(fs.getTotalSeconds()))
            {
                fs.setTotalSeconds(0.0);
            }
            if(StringUtils.empty(fs.getAvgSeconds()))
            {
                fs.setAvgSeconds(0.0);
            }
            if(StringUtils.empty(fs.getMinSeconds()))
            {
                fs.setMinSeconds(0.0);
            }
            if(StringUtils.empty(fs.getMaxSeconds()))
            {
                fs.setMaxSeconds(0.0);
            }
            if(StringUtils.empty(fs.getTotal()))
            {
                fs.setTotal(0L);
            }

            if(CacheContext.ctAlarmMap.containsKey(fs.getAlarmid()))
            {
                ProEconAlarmRule ar=CacheContext.ctAlarmMap.get(fs.getAlarmid());
                d.setAlertText(ar.getName());
            }
            if(StringUtils.notEmp(timeType))
            {
                if(AlarmTime.H.getCode().equals(timeType))
                {
                    double times= new BigDecimal(fs.getTotalSeconds()).divide(new BigDecimal(360), 2, RoundingMode.HALF_EVEN).doubleValue();
                    d.setTime(times);
                }else if(AlarmTime.M.getCode().equals(timeType))
                {
                    double times= new BigDecimal(fs.getTotalSeconds()).divide(new BigDecimal(60), 2, RoundingMode.HALF_EVEN).doubleValue();
                    d.setTime(times);
                }else
                {
                    d.setTime(fs.getTotalSeconds());
                }
            }else
            {
                double times= new BigDecimal(fs.getTotalSeconds()).divide(new BigDecimal(60), 2, RoundingMode.HALF_EVEN).doubleValue();
                d.setTime(times);
            }
            d.setStationId(fs.getStationId());
            d.setSnapId(SnowflakeGenerator.generateId());
            d.setWindturbineId(fs.getWtId());
            if(CacheContext.wtmap.containsKey(fs.getWtId()))
            {
                ProBasicEquipment  wt=CacheContext.wtmap.get(fs.getStationId());
                d.setWindturbineCode(wt.getNemCode());
            }

            StringBuilder sb=new StringBuilder();
            sb.append(fs.getStationId()).append("_").append(fs.getAlarmid());

            if(vomap.containsKey(String.valueOf(sb)))
            {
                List<AlarmStatVo> ls=vomap.get(String.valueOf(sb));
                ls.add(d);
            }else
            {
                List<AlarmStatVo> ls=new ArrayList<>();
                ls.add(d);
                vomap.put(String.valueOf(sb),ls);
            }
            resultList.add(d);
        }


        return resultList;
    }
    private  static void setCtValues(Date statDate,Map<String, ProBasicFeatureStat> map, List<ProBasicFeatureStat> vos, ProBasicEquipment wt, ProEconAlarmRule at) {

        ProBasicFeatureStat fs = new ProBasicFeatureStat();

        StringBuilder sb = new StringBuilder();
        sb.append(wt.getId()).append("_").append(at.getId());
        if (map.containsKey(String.valueOf(sb))) {
            ProBasicFeatureStat old = map.get(String.valueOf(sb));
//            BeanUtil.copyProperties(old, fs);
//            fs.setAlarmid(old.getAlarmid());

            fs.setStatDate(old.getStatDate());
            fs.setId(old.getId());
            fs.setWtId(wt.getId());
            fs.setStationId(old.getStationId());
            fs.setTypeCode(old.getTypeCode());
            fs.setTypeName(old.getTypeName());
            fs.setAlarmid(at.getId());
            fs.setDescription(old.getDescription());
            fs.setTotal(old.getTotal());
            fs.setAvgSeconds(old.getAvgSeconds());
            fs.setMaxSeconds(old.getMaxSeconds());
            fs.setMinSeconds(old.getMinSeconds());
            fs.setTotalSeconds(old.getTotalSeconds());
        } else {
            fs.setStatDate(new Timestamp(statDate.getTime()));
            fs.setId(String.valueOf(SnowflakeGenerator.generateId()));
            fs.setWtId(wt.getId());
            fs.setStationId(wt.getWindpowerstationId());
            fs.setTypeCode(at.getRelatedParts());
            if(CacheContext.alarmTypeMap.containsKey(at.getRelatedParts()))
            {
                fs.setTypeName(CacheContext.alarmTypeMap.get(at.getRelatedParts()).getName());
            }
            fs.setAlarmid(at.getId());
            fs.setDescription(at.getName());
            fs.setTotal(0l);
            fs.setAvgSeconds(0.0);
            fs.setMaxSeconds(0.0);
            fs.setMinSeconds(0.0);
            fs.setTotalSeconds(0.0);

        }
        vos.add(fs);
    }


}
