package com.gyee.alarm.service;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gyee.alarm.init.CacheContext;
import com.gyee.alarm.mapper.auto.AlarmTsMapper;
import com.gyee.alarm.mapper.auto.ProEconAlarmRuleMapper;
import com.gyee.alarm.model.auto.*;


import com.gyee.alarm.model.vo.AlarmConfigurationVo;
import com.gyee.alarm.model.vo.AlarmRuleVo;

import com.gyee.alarm.service.auto.IProEconAlarmPlanService;
import com.gyee.alarm.service.auto.IProEconAlarmRuleService;
import com.gyee.alarm.util.SnowflakeGenerator;
import com.gyee.alarm.util.StringUtil;
import com.gyee.alarm.util.StringUtils;
import org.springframework.stereotype.Service;

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



@Service
public class AlarmRuleService {

    @Resource
    private ProEconAlarmRuleMapper proEconAlarmRuleMapper;
    @Resource
    private RuleUpdateEventService ruleUpdateEventService;

    @Resource
    private IProEconAlarmPlanService proEconAlarmPlanService;

    @Resource
    private IProEconAlarmRuleService proEconAlarmRuleService;
    /**
     * 查询报警信息接口
     * @param wpId 场站不编号
     * @param modelId 型号编号
     * @param components 部件编号
     * @return
     */
    public List<AlarmConfigurationVo> queryWtAlarmDescList(String wpId, String modelId, String components) {

        List<AlarmConfigurationVo> vos=new ArrayList<>();
        StringBuilder sb=new StringBuilder();
        sb.append(wpId).append(modelId);


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

        if(com.gyee.common.model.StringUtils.notEmp(components))
        {
            String [] componentsStr=components.split(",");
            for(String c:componentsStr)
            {
                map.put(c,c);
            }

        }
        if(CacheContext.ctAlarmlsMap.containsKey(String.valueOf(sb)))
        {
            List<ProEconAlarmRule> ls=CacheContext.ctAlarmlsMap.get(String.valueOf(sb));

            if(!ls.isEmpty())
            {
                for(ProEconAlarmRule ac:ls)
                {
                    if(map.containsKey(ac.getRelatedParts()))
                    {

                        AlarmConfigurationVo vo=new AlarmConfigurationVo();
                        vo.setAlarmId(ac.getId());
                        vo.setDescription(ac.getDescription());
                        vos.add(vo);
                    }
                }
            }

        }

        return vos;
    }
    /**
     * 查询报警信息接口
     * @param wpId 场站不编号
     * @param modelId 型号编号
     * @param components 部件编号
     * @return
     */
    public List<AlarmConfigurationVo> queryCtAlarmDescList(String wpId, String modelId, String components) {

        List<AlarmConfigurationVo> vos=new ArrayList<>();
        StringBuilder sb=new StringBuilder();
        sb.append(wpId).append(modelId);


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

        if(com.gyee.common.model.StringUtils.notEmp(components))
        {
            String [] componentsStr=components.split(",");
            for(String c:componentsStr)
            {
                map.put(c,c);
            }

        }
        if(CacheContext.ctAlarmlsMap.containsKey(String.valueOf(sb)))
        {
            List<ProEconAlarmRule> ls=CacheContext.ctAlarmlsMap.get(String.valueOf(sb));

            if(!ls.isEmpty())
            {
                for(ProEconAlarmRule ac:ls)
                {
                    if(map.containsKey(ac.getRelatedParts()))
                    {

                        AlarmConfigurationVo vo=new AlarmConfigurationVo();
                        vo.setAlarmId(ac.getId());
                        vo.setDescription(ac.getDescription());
                        vos.add(vo);
                    }
                }
            }

        }

        return vos;
    }
    private int saveAlertrule(ProEconAlarmRule alarmRule) throws Exception {

        int result = 0;

        if (StringUtils.notEmp(alarmRule)) {

            alarmRule.setCreateTime(new Date());
            alarmRule.setId(String.valueOf(SnowflakeGenerator.generateId()));
            alarmRule.setEnable(true);
            alarmRule.setUniformCode("");
            alarmRule.setRange("0");
            result= proEconAlarmRuleMapper.insert(alarmRule);
        }
//        if (result > 0) {
//            int i = eventService.saveEventAlertRule(alarmRule, oldRule2, userData.getUserName());




        return result;
    }


    public int saveAndUpdateAlertrule(ProEconAlarmRule alarmRule) throws Exception {

        int result = 0;

        if (StringUtils.notEmp(alarmRule)) {

            if(StringUtils.notEmp(alarmRule.getId()))
            {
                List<ProEconAlarmRule>  oldRulels = proEconAlarmRuleMapper.queryObject(alarmRule.getName(),alarmRule.getStationId(),alarmRule.getModelId());
                if(!oldRulels.isEmpty())
                {
                    ProEconAlarmRule   oldRule2=oldRulels.get(0);
                    alarmRule.setId(oldRule2.getId());
                    result = proEconAlarmRuleMapper.updateByAlertruleId(alarmRule);
                    ruleUpdateEventService.saveEventAlertRule(alarmRule,oldRule2);
                }else
                {
                    result = proEconAlarmRuleMapper.updateByAlertruleId(alarmRule);
                }
            }else
            {
                alarmRule.setId(String.valueOf(SnowflakeGenerator.generateId()));
                alarmRule.setCreateTime(new Date());
                ruleUpdateEventService.saveEventAlertRule(alarmRule,null);
                result = saveAlertrule(alarmRule);
            }

            //同步内存和实时数据库新建测点

            // 设置最大重试次数
            int maxRetries = 6;
            int retries = 0;

            while (retries < maxRetries) {
                try {
                    // 尝试执行可能会抛出异常的操作
                    proEconAlarmRuleService.inital(alarmRule);
                    System.out.println("操作成功！");
                    break; // 如果操作成功，跳出循环
                } catch (Exception e) {
                    retries++;
                    System.out.println("操作失败，正在重试...（" + retries + "次尝试）");
                    if (retries >= maxRetries) {
                        System.out.println("已达到最大重试次数，程序终止。");
                        break; // 如果达到最大重试次数，跳出循环
                    }
                }
            }

//

            proEconAlarmPlanService.updatePlanlistById(alarmRule.getId(), alarmRule.getAlarmPlan());
        }

        return result;
    }

    public int deleteAlertrule(String id) {
        return proEconAlarmRuleMapper.deleteById(id);
    }


    public IPage<ProEconAlarmRule> pageQueryAll(Page page, String name, String station, String modelId, Integer rank, String category, Boolean enabled, String relatedparts) {


        if(StringUtils.notEmp(name))
        {
            name="%"+name+"%";
        }else
        {
            name=null;
        }
        if(StringUtils.empty(station))
        {
            station=null;
        }
        if(StringUtils.empty(modelId))
        {
            modelId=null;
        }
        if(StringUtils.empty(rank))
        {
            rank=null;
        }
        if(StringUtils.empty(category))
        {
            category=null;
        }
        if(StringUtils.empty(enabled))
        {
            enabled=null;
        }
        if(StringUtils.empty(relatedparts))
        {
            relatedparts=null;
        }

        IPage<ProEconAlarmRule> alertruleIPage = proEconAlarmRuleMapper.pageQueryAll(page, name, station, modelId, rank, category, enabled, relatedparts);

        if(!alertruleIPage.getRecords().isEmpty())
        {
            for(ProEconAlarmRule ar:alertruleIPage.getRecords())
            {
                if(CacheContext.wpmap.containsKey(ar.getStationId()))
                {
                    ProBasicPowerstation wp=CacheContext.wpmap.get(ar.getStationId());
                    ar.setStationName(wp.getName());
                }

                if(CacheContext.alarmTypeMap.containsKey(ar.getRelatedParts()))
                {
                    ProEconAlarmType type=CacheContext.alarmTypeMap.get(ar.getRelatedParts());
                    ar.setRelatedPartsName(type.getName());
                }

                if(CacheContext.subwpmap.containsKey(ar.getStationId()))
                {
                    ProBasicSubStation type=CacheContext.subwpmap.get(ar.getStationId());
                    ar.setStationName(type.getName());
                }
            }
        }
        return alertruleIPage;
    }


    public List<AlarmRuleVo> queryTree() {
        List<AlarmRuleVo> dsList = proEconAlarmRuleMapper.queryTree();
        return dsList;
    }



    //首页风机部件查询
    public Map<String, Integer> queryList(String station, String modelId) {
        Map<String, Integer> map2 = new HashMap<>();
        map2.put("CLX", 0);
        map2.put("YP", 0);
        map2.put("YY", 0);
        map2.put("BJXT", 0);
        map2.put("PHXT", 0);
        map2.put("BPXT", 0);
        map2.put("CFXT", 0);
        map2.put("ZZ", 0);
        map2.put("FDJ", 0);
        map2.put("QT", 0);

        List<ProEconAlarmRule> dslist = proEconAlarmRuleMapper.getAllByStationIdAndModelId(station, modelId);
        map2.put("SUM", dslist.size());
        for (ProEconAlarmRule ar : dslist) {
            int cnt = 0;
            switch (ar.getRelatedParts()) {
                case "CLX":
                    cnt = map2.get("CLX").intValue();
                    map2.put("CLX", ++cnt);
                    break;
                case "YP":
                    cnt = map2.get("YP").intValue();
                    map2.put("YP", ++cnt);
                    break;
                case "YY":
                    cnt = map2.get("YY").intValue();
                    map2.put("YY", ++cnt);
                    break;
                case "BJXT":
                    cnt = map2.get("BJXT").intValue();
                    map2.put("BJXT", ++cnt);
                    break;
                case "PHXT":
                    cnt = map2.get("PHXT").intValue();
                    map2.put("PHXT", ++cnt);
                    break;
                case "BPXT":
                    cnt = map2.get("BPXT").intValue();
                    map2.put("BPXT", ++cnt);
                    break;
                case "CFXT":
                    cnt = map2.get("CFXT").intValue();
                    map2.put("CFXT", ++cnt);
                    break;
                case "ZZ":
                    cnt = map2.get("ZZ").intValue();
                    map2.put("ZZ", ++cnt);
                    break;
                case "FDJ":
                    cnt = map2.get("FDJ").intValue();
                    map2.put("FDJ", ++cnt);
                    break;
                default:
                    cnt = map2.get("QT").intValue();
                    map2.put("QT", ++cnt);
                    break;
            }
        }
        return map2;
    }




    public List<String> getUniformCodeByNameAndStation(String name, String station, String modelid) {

        List<ProEconAlarmRule> rules = proEconAlarmRuleMapper.getUniformCodeByNameAndStation(name, station, modelid);
        if (rules == null || rules.size() == 0)
        {
            return null;
        }


        ProEconAlarmRule rule = rules.get(0);
        String expression = "(([A][I])|([D][I]))([0-9]+)";
        List<String> list = StringUtil.pattern(rule.getExpression(), expression);

        return list;
    }

    public ProEconAlarmRule selectByAlertruleId(String id) {
        return proEconAlarmRuleMapper.selectById(id);
    }

}
