package com.gyee.wisdom.alarm.sharding.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.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gyee.wisdom.alarm.sharding.entity.*;
import com.gyee.wisdom.alarm.sharding.mapper.RuleUpdateEventMapper;
import com.gyee.wisdom.alarm.sharding.util.ChineseDes;
import com.gyee.wisdom.alarm.sharding.util.SnowflakeGenerator;
import com.gyee.wisdom.alarm.sharding.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @description:
 * @auther: Wanghs
 * @date: 2022-04-01
 */
@Service
public class RuleUpdateEventService extends ServiceImpl<RuleUpdateEventMapper, RuleUpdateEvent> {


    @Autowired
    private AlarmUserService alarmUserService;

    @Autowired
    private RuleUpdateEventInfoService eventInfoService;

    public IPage<RuleUpdateEvent> getUpdateEventByPage(Page<RuleUpdateEvent> page, String ruleName, String ruleType) {
        QueryWrapper<RuleUpdateEvent> wrapper = new QueryWrapper<>();
        if (StringUtil.isNotBlank(ruleName))
            wrapper.like("RULENAME", ruleName);
        if (StringUtil.isNotBlank(ruleType))
            wrapper.eq("RULETYPE", ruleType);
        wrapper.orderByDesc("UPDATETIME");
        IPage<RuleUpdateEvent> ruleUpdateEventIPage = this.baseMapper.selectPage(page, wrapper);
        return ruleUpdateEventIPage;

    }

    public int saveEventAlertRule(Alertrule2 newRule2, Alertrule2 oldRule2, String userName) {
        AlarmUser existUser = alarmUserService.isExistUser(userName);
        //oldeRule2为空的时候代表新增
        if (oldRule2 == null) {
            RuleUpdateEvent event = new RuleUpdateEvent();
            event.setId(SnowflakeGenerator.generateId());
            event.setRuleName(newRule2.getName());
            event.setRuleId(newRule2.getId());
            event.setRuleType("自定义报警");
            event.setUpdateType("新增");
            event.setUpdateTime(new Date());
            event.setUpdateUser(existUser.getChineseName());
            event.setStation(newRule2.getStation());
            event.setModel(newRule2.getModelId());

            baseMapper.insert(event);
            return 0;

        } else {

            RuleUpdateEvent event = new RuleUpdateEvent();
            event.setId(SnowflakeGenerator.generateId());
            event.setRuleName(newRule2.getName());
            event.setRuleId(oldRule2.getId());
            event.setRuleType("自定义报警");
            event.setUpdateType("更新");
            event.setUpdateTime(new Date());
            event.setUpdateUser(existUser.getChineseName());
            event.setStation(newRule2.getStation());
            event.setModel(newRule2.getModelId());
            List<RuleUpdateEventInfo> infoList = new ArrayList<>();

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

                    Long 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();
                            RuleUpdateEventInfo info = new RuleUpdateEventInfo();
                            info.setId(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);
                        }
                    }
                }
                //执行保存操作
                baseMapper.insert(event);
                eventInfoService.saveBatch(infoList);
            } catch (Exception ex) {

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

        }

    }

    public int saveEventWarning(Warning2 newWarning, Warning2 oldWarning, String userName) {
        AlarmUser existUser = alarmUserService.isExistUser(userName);
        //oldeRule2为空的时候代表新增
        if (oldWarning == null) {
            RuleUpdateEvent event = new RuleUpdateEvent();
            event.setId(SnowflakeGenerator.generateId());
            event.setRuleName(newWarning.getChineseText());
            event.setRuleId(newWarning.getId());
            event.setRuleType("风机报警");
            event.setUpdateType("新增");
            event.setUpdateTime(new Date());
            event.setUpdateUser(existUser.getChineseName());
            event.setModel(newWarning.getModelId());
            baseMapper.insert(event);
            return 0;

        } else {

            RuleUpdateEvent event = new RuleUpdateEvent();
            event.setId(SnowflakeGenerator.generateId());
            event.setRuleName(oldWarning.getChineseText());
            event.setRuleId(oldWarning.getId());
            event.setRuleType("风机报警");
            event.setUpdateType("更新");
            event.setUpdateTime(new Date());
            event.setUpdateUser(existUser.getChineseName());
            event.setModel(oldWarning.getModelId());
            List<RuleUpdateEventInfo> infoList = new ArrayList<>();

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

                    Long 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();
                            RuleUpdateEventInfo info = new RuleUpdateEventInfo();
                            info.setId(infoId);
                            info.setEventId(eventId);
                            info.setFieldName(infoFiledName);
                            if(field.getName().toUpperCase().equals("EDNAVALUE")){
                                info.setBeforValue(val_old != null ? "DI"+val_old.toString() : null);
                                info.setAfterValue(val_new != null ? "DI"+val_new.toString() : null);

                            }else{
                                info.setBeforValue(val_old != null ? val_old.toString() : null);
                                info.setAfterValue(val_new != null ? val_new.toString() : null);
                            }

                            infoList.add(info);
                        }
                    }
                }
                //执行保存操作
                baseMapper.insert(event);
                eventInfoService.saveBatch(infoList);
            } catch (Exception ex) {

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

        }

    }

    public int saveEventScadaBj(Scadabj newScadabj, Scadabj oldScadabj, String userName) {
        AlarmUser existUser = alarmUserService.isExistUser(userName);
        //oldeRule2为空的时候代表新增
        if (oldScadabj == null) {
            RuleUpdateEvent event = new RuleUpdateEvent();
            event.setId(SnowflakeGenerator.generateId());
            event.setRuleName(newScadabj.getDescription());
            event.setRuleId(newScadabj.getId().toString());
            event.setRuleType("升压站报警");
            event.setUpdateType("新增");
            event.setUpdateTime(new Date());
            event.setUpdateUser(existUser.getChineseName());
            event.setStation(newScadabj.getStationId());

            baseMapper.insert(event);
            return 0;

        } else {

            RuleUpdateEvent event = new RuleUpdateEvent();
            event.setId(SnowflakeGenerator.generateId());
            event.setRuleName(oldScadabj.getDescription());
            event.setRuleId(oldScadabj.getId().toString());
            event.setRuleType("升压站报警");
            event.setUpdateType("更新");
            event.setUpdateTime(new Date());
            event.setUpdateUser(existUser.getChineseName());
            event.setStation(oldScadabj.getStationId());
            List<RuleUpdateEventInfo> infoList = new ArrayList<>();

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

                    Long eventId = event.getId();
                    Long infoId = SnowflakeGenerator.generateId();
                    field.setAccessible(true); //设置些属性是可以访问的
                    Object val_old = field.get(oldScadabj);//得到此属性的修改前值
                    Object val_new = field.get(newScadabj);//得到此属性的修改后值

                    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();
                            RuleUpdateEventInfo info = new RuleUpdateEventInfo();
                            info.setId(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);
                        }
                    }
                }
                //执行保存操作
                baseMapper.insert(event);
                eventInfoService.saveBatch(infoList);
            } catch (Exception ex) {

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

        }

    }


}
