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.model.auto.*;
import com.gyee.alarm.model.vo.AlarmType;
import com.gyee.alarm.model.vo.AlarmTypeValue;
import com.gyee.alarm.service.auto.IProBasicFeatureStatService;
import com.gyee.alarm.service.auto.IProEconRuleUpdateEventService;
import com.gyee.alarm.service.auto.IProEconRuleUpdateInfoService;
import com.gyee.alarm.util.ChineseDes;
import com.gyee.alarm.util.SnowflakeGenerator;
import com.gyee.alarm.util.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;


@Service
public class RuleUpdateEventService {


    @Resource
    private IProEconRuleUpdateEventService proEconRuleUpdateEventService;

    @Resource
    private IProEconRuleUpdateInfoService proEconRuleUpdateInfoService;

    public IPage<ProEconRuleUpdateEvent> getUpdateEventByPage(Page<ProEconRuleUpdateEvent> page, String ruleName, String ruleType) {
        QueryWrapper<ProEconRuleUpdateEvent> wrapper = new QueryWrapper<>();
        if (StringUtils.notEmp(ruleName))
            wrapper.like("rule_name", "%"+ruleName+"%");
        if (StringUtils.notEmp(ruleType))
            wrapper.eq("rule_type", ruleType);

        wrapper.orderByDesc("update_time");


        IPage<ProEconRuleUpdateEvent> ruleUpdateEventIPage =proEconRuleUpdateEventService.getBaseMapper().selectPage(page, wrapper);

        if(!ruleUpdateEventIPage.getRecords().isEmpty())
        {


            for(ProEconRuleUpdateEvent vo:ruleUpdateEventIPage.getRecords())
            {
                if(CacheContext.wpmap.containsKey(vo.getStationId()))
                {
                    ProBasicPowerstation wp=CacheContext.wpmap.get(vo.getStationId());
                    vo.setStationName(wp.getName());
                }
                if(CacheContext.subwpmap.containsKey(vo.getStationId()))
                {
                    ProBasicSubStation wp=CacheContext.subwpmap.get(vo.getStationId());
                    vo.setStationName(wp.getName());
                }
                List<ProEconRuleUpdateInfo> infoList=new ArrayList<>();
                QueryWrapper<ProEconRuleUpdateInfo> wrapper2 = new QueryWrapper<>();

                if (StringUtils.notEmp(vo.getId()))
                {
                    wrapper2.eq("event_id", vo.getId());
                }

                infoList= proEconRuleUpdateInfoService.list(wrapper2);
                vo.setInfoList(infoList);
            }
        }

        return ruleUpdateEventIPage;

    }

    public int saveEventAlertRule(ProEconAlarmRule newRule2, ProEconAlarmRule oldRule2) {

        HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
        String token = request.getHeader("token");
        String userId = request.getHeader("userId");


        if (StringUtils.notEmp(token) && StringUtils.notEmp(userId))
        {
//oldeRule2为空的时候代表新增
            if (oldRule2 == null) {
                ProEconRuleUpdateEvent event = new ProEconRuleUpdateEvent();
                event.setId(String.valueOf(SnowflakeGenerator.generateId()));
                event.setRuleName(newRule2.getName());
                event.setRuleId(newRule2.getId());
                event.setRuleType("自定义报警");
                event.setUpdateType("新增");
                event.setUpdateTime(new Date());
                event.setUpdateUser(userId);
                event.setStationId(newRule2.getStationId());
                event.setModelId(newRule2.getModelId());
                if(CacheContext.wpmap.containsKey(newRule2.getStationId()))
                {
                    ProBasicPowerstation wp=CacheContext.wpmap.get(newRule2.getStationId());
                    event.setStationName(wp.getName());
                }
                if(CacheContext.subwpmap.containsKey(newRule2.getStationId()))
                {
                    ProBasicSubStation wp=CacheContext.subwpmap.get(newRule2.getStationId());
                    event.setStationName(wp.getName());
                }
                proEconRuleUpdateEventService.save(event);
                return 0;

            } else {

                ProEconRuleUpdateEvent event = new ProEconRuleUpdateEvent();
                event.setId(String.valueOf(SnowflakeGenerator.generateId()));
                event.setRuleName(newRule2.getName());
                event.setRuleId(oldRule2.getId());
                event.setRuleType("自定义报警");
                event.setUpdateType("更新");
                event.setUpdateTime(new Date());
                event.setUpdateUser(userId);
                event.setStationId(newRule2.getStationId());

                if(CacheContext.wpmap.containsKey(newRule2.getStationId()))
                {
                    ProBasicPowerstation wp=CacheContext.wpmap.get(newRule2.getStationId());
                    event.setStationName(wp.getName());
                }
                if(CacheContext.subwpmap.containsKey(newRule2.getStationId()))
                {
                    ProBasicSubStation wp=CacheContext.subwpmap.get(newRule2.getStationId());
                    event.setStationName(wp.getName());
                }
                event.setModelId(newRule2.getModelId());
                List<ProEconRuleUpdateInfo> infoList = new ArrayList<>();

                Field[] declaredFieldOld = oldRule2.getClass().getDeclaredFields();
                try {
                    for (Field field :
                            declaredFieldOld) {

                        String eventId = event.getId();
                        Long infoId = SnowflakeGenerator.generateId();

                        field.setAccessible(true); //设置些属性是可以访问的
                        Object val_old = field.get(oldRule2);//得到此属性的修改前值
                        Object val_new = field.get(newRule2);//得到此属性的修改后值

                        if (!Objects.equals(val_old, val_new)) {
                            boolean annotationPresent = field.isAnnotationPresent(ChineseDes.class);
                            if (annotationPresent) {
                                ChineseDes methodAnno = field.getAnnotation(ChineseDes.class);
                                // 根据对象获取注解值
                                String infoFiledName = methodAnno.value();
                                ProEconRuleUpdateInfo info = new ProEconRuleUpdateInfo();
                                info.setId(String.valueOf(infoId));
                                info.setEventId(eventId);
                                info.setFieldName(infoFiledName);
                                info.setBeforValue(val_old != null ? val_old.toString() : null);
                                info.setAfterValue(val_new != null ? val_new.toString() : null);
                                infoList.add(info);
                            }
                        }
                    }
                    //执行保存操作
                    proEconRuleUpdateEventService.save(event);
                    proEconRuleUpdateInfoService.saveBatch(infoList);
                } catch (Exception ex) {

//                log.error("保存日志失败"+ex.getStackTrace());
                } finally {
                    return 0;
                }

            }

        }
        return 0;
    }

    public int saveEventWarning(ProEconAlarmConfiguration newWarning, ProEconAlarmConfiguration oldWarning) {

        HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
        String token = request.getHeader("token");
        String userId = request.getHeader("userId");


        if (StringUtils.notEmp(token) && StringUtils.notEmp(userId))
        {
            //oldeRule2为空的时候代表新增
            if (oldWarning == null) {
                ProEconRuleUpdateEvent event = new ProEconRuleUpdateEvent();
                event.setId(String.valueOf(SnowflakeGenerator.generateId()));
                event.setRuleName(newWarning.getDescription());
                event.setRuleId(newWarning.getId());
                if(newWarning.getAlarmType().equals(AlarmTypeValue.WT.getCode()))
                {
                    event.setRuleType("风机报警");
                }else  if(newWarning.getAlarmType().equals(AlarmTypeValue.IN.getCode()))
                {
                    event.setRuleType("逆变器报警");
                }else  if(newWarning.getAlarmType().equals(AlarmTypeValue.BT.getCode()))
                {
                    event.setRuleType("升压站报警");
                }
                event.setId(String.valueOf(SnowflakeGenerator.generateId()));
                event.setUpdateType("新增");
                event.setUpdateTime(new Date());
                event.setUpdateUser(userId);
                event.setModelId(newWarning.getModelId());
                event.setStationId(newWarning.getStationId());
                if(CacheContext.wpmap.containsKey(newWarning.getStationId()))
                {
                    event.setStationName(CacheContext.wpmap.get(newWarning.getStationId()).getName());
                }else  if(CacheContext.subwpmap.containsKey(newWarning.getStationId()))
                {
                    event.setStationName(CacheContext.subwpmap.get(newWarning.getStationId()).getName());
                }
                proEconRuleUpdateEventService.save(event);
                return 0;

            } else {

                ProEconRuleUpdateEvent event = new ProEconRuleUpdateEvent();
                event.setId(String.valueOf(SnowflakeGenerator.generateId()));
                event.setRuleName(oldWarning.getDescription());
                event.setRuleId(oldWarning.getId());
                if(newWarning.getAlarmType().equals(AlarmTypeValue.WT.getCode()))
                {
                    event.setRuleType("风机报警");
                }else  if(newWarning.getAlarmType().equals(AlarmTypeValue.IN.getCode()))
                {
                    event.setRuleType("逆变器报警");
                }else  if(newWarning.getAlarmType().equals(AlarmTypeValue.BT.getCode()))
                {
                    event.setRuleType("升压站报警");
                }
                event.setUpdateType("更新");
                event.setUpdateTime(new Date());
                event.setUpdateUser(userId);
                event.setModelId(newWarning.getModelId());

                event.setStationId(newWarning.getStationId());
                if(CacheContext.wpmap.containsKey(newWarning.getStationId()))
                {
                    event.setStationName(CacheContext.wpmap.get(newWarning.getStationId()).getName());
                }else  if(CacheContext.subwpmap.containsKey(newWarning.getStationId()))
                {
                    event.setStationName(CacheContext.subwpmap.get(newWarning.getStationId()).getName());
                }
                List<ProEconRuleUpdateInfo> infoList = new ArrayList<>();

                Field[] declaredFieldOld = oldWarning.getClass().getDeclaredFields();
                try {
                    for (Field field :
                            declaredFieldOld) {

                        String eventId = event.getId();
                        Long infoId = SnowflakeGenerator.generateId();

                        field.setAccessible(true); //设置些属性是可以访问的
                        Object val_old = field.get(oldWarning);//得到此属性的修改前值
                        Object val_new = field.get(newWarning);//得到此属性的修改后值

                        if (!Objects.equals(val_old, val_new)) {
                            boolean annotationPresent = field.isAnnotationPresent(ChineseDes.class);
                            if (annotationPresent) {
                                ChineseDes methodAnno = field.getAnnotation(ChineseDes.class);
                                // 根据对象获取注解值
                                String infoFiledName = methodAnno.value();
                                ProEconRuleUpdateInfo info = new ProEconRuleUpdateInfo();
                                info.setId(String.valueOf(infoId));
                                info.setEventId(eventId);
                                info.setFieldName(infoFiledName);
                                info.setBeforValue(val_old != null ? val_old.toString() : null);
                                info.setAfterValue(val_new != null ? val_new.toString() : null);

                                infoList.add(info);
                            }
                        }
                    }
                    //执行保存操作
                    proEconRuleUpdateEventService.save(event);
                    proEconRuleUpdateInfoService.saveBatch(infoList);
                } catch (Exception ex) {

                    //log.error("保存日志失败"+ex.getStackTrace());
                } finally {
                    return 0;
                }

            }

        }
        return 0;
    }


}
