package com.gyee.wisdom.alarm.sharding.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gyee.wisdom.alarm.sharding.entity.*;
import com.gyee.wisdom.alarm.sharding.logtool.LogService;
import com.gyee.wisdom.alarm.sharding.mapper.AlarmSnapMapper;
import com.gyee.wisdom.alarm.sharding.mapper.Alertrule2Mapper;
import com.gyee.wisdom.alarm.sharding.model.Alertrule2Example;
import com.gyee.wisdom.alarm.sharding.model.TreeNode;
import com.gyee.wisdom.alarm.sharding.util.DateUtils;
import com.gyee.wisdom.alarm.sharding.util.StringUtil;
import com.gyee.wisdom.alarm.sharding.util.UUIDUtil;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;


@Service
@Slf4j
public class Alertrule2Service extends ServiceImpl<Alertrule2Mapper, Alertrule2> {
    Logger logger = LogManager.getLogger();

    @Autowired
    private Alertrule2Mapper alertrule2Mapper;

    @Autowired
    private LogService logService;

    @Autowired
    private RuleUpdateEventService eventService;


    public int saveAndUpdateAlertrule2(Alertrule2 alertrule2,String userName) {

        int result = 0;
        Alertrule2 oldRule2=null;
        if (StringUtils.isBlank(alertrule2.getId())) {
            //生成id,生成规则为HD+自增数
//            String station = StringUtils.substringBefore(alertrule2.getStation(), "_");
            Integer maxEdnaValue = alertrule2Mapper.getMaxEdnaValue();
           int max = maxEdnaValue + 1;
            String first="";
            String[] s = alertrule2.getStation().split("_");
            if(s.length>1)
                first=s[0];
            String newId = first+"_"+ max;
            //验证生成的id是否已存在
            List<Alertrule2> selectList = alertrule2Mapper.getById(newId);
            if (selectList.size() > 0) {
                return -999;
            }

            if (maxEdnaValue == 0) {
                logger.error("获取最大EdnaValue失败");
                return 0;
            } else {
                Integer nextEdnaValue = maxEdnaValue + 1;
                alertrule2.setId(newId);

                alertrule2.setEdnaValue(nextEdnaValue);
                alertrule2.setCreatetime(DateUtils.getNowDate());
                result = alertrule2Mapper.insertAlerture2(alertrule2);
                if (result > 0) {
                    logService.alertRuleAddLog(alertrule2, alertrule2.getUserName());
                }
            }

        } else {
             oldRule2 = alertrule2Mapper.selectByAlertrule2Id(alertrule2.getId());
            if (oldRule2 != null) {
                result = alertrule2Mapper.updateByAlertrule2Id(alertrule2);
                if (result > 0) {
                    logService.alertRuleUpdateLog(oldRule2, alertrule2, alertrule2.getUserName());
                }
            }
        }
        if(result>0) {
            int i = eventService.saveEventAlertRule(alertrule2, oldRule2,userName);
        }
        return result;
    }

    public int deleteAlertrule2(Alertrule2 alertrule2) {
        return alertrule2Mapper.deleteById(alertrule2.getId());
    }

    public IPage<Alertrule2> pageQueryAll(Page page, String name,String station,String modelId,String rank,String category) {
        return alertrule2Mapper.pageQueryAll(page, name,station,modelId,rank,category);
    }

    //根据场站风机型号生成最新自定义报警规则ID
    public String createNextId(String station, String model) {
        String nextId = "";
        String idString = station + model;
        //获取同一个风场同一个型号的所有规则列表
        List<Alertrule2> lst = alertrule2Mapper.getAllByStationIdAndModelId(idString);

        String maxId = Collections.max(lst.stream().map(Alertrule2::getId).collect(Collectors.toList()));

        int maxNum = Integer.parseInt(maxId.substring(2, 5));
        int incrementId = 0;
        incrementId = maxNum + 1;
        if (incrementId < 100) {
            nextId = "ZX" + "0" + incrementId + station + model;

        } else {
            nextId = "ZX" + incrementId + station + model;

        }

        return nextId;
    }


    public List<Alertrule2> queryTree() {
        List<Alertrule2> dsList = alertrule2Mapper.queryTree();
        return dsList;
    }

    public List<Map<String, Alertrule2>> queryTree2(String relatedParts) {
        List<Map<String, Alertrule2>> dsList = alertrule2Mapper.quertByrelatedParts(relatedParts);
        return dsList;
    }

    public List<Map<String, Alertrule2>> queryMap() {
        List<Map<String, Alertrule2>> alertrule2Map = new ArrayList<>();
        List<Alertrule2> alertrule = alertrule2Mapper.queryMap();
        if (alertrule != null && alertrule.size() > 0) {
            List<Map<String, Alertrule2>> alertrule2Map2 = new ArrayList<>();
            for (Alertrule2 alertrule2 : alertrule) {
                alertrule2.getRelatedParts();
                alertrule2.getName();
                alertrule2Map2 = queryTree2(alertrule2.getRelatedParts());
                alertrule2Map.addAll(alertrule2Map2);
            }
        }
        return alertrule2Map;
    }

    public List<String> getUniformCodeByNameAndStation(String name, String station, String modelid){
        Alertrule2Example example = new Alertrule2Example();
        example.createCriteria().andNameEqualTo(name)
                .andStationEqualTo(station)
                .andModelidEqualTo(modelid);
//               .andWindturbineLike("%" + wtId + "%");

        List<Alertrule2> rules = alertrule2Mapper.selectByExample(example);
        if (rules == null || rules.size() == 0)
            return null;

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

        return list;
    }
}
