# -*- coding: utf_8 -*-
# 表名: alarm_rule
# 作者: 陈磊
# 时间: 2019-11-28


from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, VARCHAR, SMALLINT, DATETIME, DECIMAL, BigInteger, FLOAT, NUMERIC, TEXT
from sqlalchemy.orm.exc import MultipleResultsFound, NoResultFound
from sqlalchemy import or_

from WorkUtils.UtilsLog import UtilsLog
from WorkUtils.UtilsDataBase import UtilsDataBase

import time

Base = declarative_base()


class AlarmRule(Base):
    """
    告警规则表
    """
    __tablename__ = "alarm_rule"

    alarm_ruleid = Column(BigInteger, primary_key=True)
    name = Column(VARCHAR(255), comment="规则名称")
    triggerid = Column(BigInteger, comment="触发器ID")
    description = Column(VARCHAR(255), comment="描述")
    status = Column(Integer, comment="启用（ 0 不启用，1启用）")
    period = Column(Integer, comment="时间周期")
    period_unit = Column(VARCHAR(50), comment="时间单位（m:分钟，h:小时，d:天）")
    severity = Column(Integer, comment="告警级别")
    url = Column(VARCHAR(255), comment="跳转路径")
    manual_close = Column(Integer, comment="是否支持人工关闭(0:不允许，1：允许)")
    enable_time_default = Column(Integer, comment="静默时间（0：不启用，启用）")
    create_time = Column(BigInteger, comment="创建时间")


class DataAlarmRule(object):
    def __init__(self):
        self.log = UtilsLog()
        self.log.info(self.__class__)

        self.table = AlarmRule

    def select_all_from_allKeys(self, session, alarm_ruleid=None, name=None, triggerid=None):
        """
        :param session: 指针
        :param alarm_ruleid:
        :param name:
        :param triggerid:
        :return: 查询结果
        """
        self.log.debug("查询数据库:")
        try:
            base = UtilsDataBase()
            base.add_param(_key="alarm_ruleid", value=alarm_ruleid)
            base.add_param(_key="name", value=name)
            base.add_param(_key="triggerid", value=triggerid)
            sql_rep = session.query(self.table).filter_by(**base.param).all()
            self.log.debug(sql_rep)
            session.close()
            return sql_rep
        except UtilsDataBase().errors as error:
            self.log.error("异常:")
            self.log.error(error)
            session.close()
            return error

    def delete_like_name(self, session, name):
        """
        :param session: 指针
        :param name:
        :return:
        """
        self.log.debug("查询数据库:")
        try:
            self.log.debug("删除相关测试数据")
            session.query(self.table).filter(self.table.name.like(str(name) + "%")).delete(synchronize_session=False)
            # session.delete(sql)
            session.commit()
            session.close()
            self.log.debug("删除成功")
            return True
        except UtilsDataBase().errors as error:
            self.log.error("异常:")
            self.log.error(error)
            session.close()
            return error

    def insert_one(self, session, alarm_ruleid=None, name=None, triggerid=None, description=None, status=None,
                   period=None, period_unit=None, severity=None, url=None, manual_close=None, enable_time_default=None,
                   create_time=None):
        """
        :param session: 指针
        :param alarm_ruleid:
        :param name:
        :param triggerid:
        :param description:
        :param status:
        :param period:
        :param period_unit:
        :param severity:
        :param url:
        :param manual_close:
        :param enable_time_default:
        :param create_time:
        :return:
        """
        self.log.debug("新增表数据:")
        try:
            base = UtilsDataBase()
            base.add_param(_key="alarm_ruleid", value=alarm_ruleid)
            base.add_param(_key="name", value=name)
            base.add_param(_key="triggerid", value=triggerid)
            base.add_param(_key="description", value=description)
            base.add_param(_key="status", value=status)
            base.add_param(_key="period", value=period)
            base.add_param(_key="period_unit", value=period_unit)
            base.add_param(_key="severity", value=severity)
            base.add_param(_key="url", value=url)
            base.add_param(_key="manual_close", value=manual_close)
            base.add_param(_key="enable_time_default", value=enable_time_default)
            base.add_param(_key="create_time", value=create_time)
            sql_rep = self.table(**base.param)

            session.add(sql_rep)
            session.commit()
            alarm_ruleid = sql_rep.alarm_ruleid
            self.log.debug("新增的alarm_ruleid:%s" % alarm_ruleid)
            session.close()
            return alarm_ruleid
        except UtilsDataBase().errors as error:
            self.log.error("异常:")
            self.log.error(error)
            session.close()
            return error
