# -*- coding: utf_8 -*-
# 表名: problem
# 作者: 陈磊
# 时间: 2019-12-04


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 Problem(Base):
    """
    问题表
    """
    __tablename__ = "problem"

    eventid = Column(Integer, primary_key=True)
    source = Column(Integer, comment="问题事件的类型。0：由触发器创建的事件，3：内部事件")
    object = Column(Integer, comment="与问题事件相关的对象类型。详细见附录页【事件相关的对象类型】中的触发器和内部事件")
    objectid = Column(BigInteger, comment="相关对象的id")
    clock = Column(Integer, comment="问题事件创建的时间")
    ns = Column(Integer, comment="问题事件创建时的纳秒")
    r_eventid = Column(Integer, comment="恢复的事件id")
    r_clock = Column(VARCHAR(128), comment="创建恢复事件的时间")
    r_ns = Column(Integer, comment="创建恢复事件的纳秒")
    correlationid = Column(Integer, comment="相关规则的id。如果事件被全局相关规则恢复")
    userid = Column(VARCHAR(255), comment="问题事件被手动关闭的用户id")
    name = Column(VARCHAR(255), comment="域名")
    acknowledged = Column(VARCHAR(255), comment="0：不确定；1：确定")
    acknowledged_time = Column(VARCHAR(255), comment="确认时间")
    severity = Column(Integer, comment="未分离：0；信息：1；警告：2；一般严重：3；严重：4;灾难：5")
    hostid = Column(Integer, comment="资产编号")
    status = Column(Integer, comment="0:不忽略，1：忽略")
    ignore_time = Column(BigInteger, comment="忽略时间")
    type = Column(VARCHAR(255), comment="告警类型 cpu 温度..")


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

        self.table = Problem

    def select_all_from_allKeys(self, session, hostid=None, host_name=None, available=None, monitor_status=None):
        """
        :param session: 指针
        :param hostid:
        :param host_name:
        :param available:
        :param monitor_status:
        :return: 查询结果
        """
        self.log.debug("查询数据库:")
        try:
            base = UtilsDataBase()
            base.add_param(_key="hostid", value=hostid)
            base.add_param(_key="host_name", value=host_name)
            base.add_param(_key="available", value=available)
            base.add_param(_key="monitor_status", value=monitor_status)
            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_hostid(self, session, hostid):
        """
        :param session: 指针
        :param hostid:
        :return:
        """
        self.log.debug("查询数据库:")
        try:
            self.log.debug("删除相关测试数据")
            session.query(self.table).filter_by(hostid=hostid).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 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 delete_like_eventid(self, session, eventid):
        """
        :param session: 指针
        :param eventid:
        :return:
        """
        self.log.debug("查询数据库:")
        try:
            self.log.debug("删除相关测试数据")
            session.query(self.table).filter(self.table.eventid.like(str(eventid/100) + "%")).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, eventid=None, source=None, _object=None, objectid=None, clock=None, ns=None,
                   r_clock=None, r_ns=None, hostid=None, name=None, acknowledged=None, acknowledged_time=None,
                   severity=None, status=None,):
        """
        :param session: 指针
        :param eventid:
        :param source:
        :param _object:
        :param objectid:
        :param clock:
        :param ns:
        :param r_clock:
        :param r_ns:
        :param hostid:
        :param name:
        :param acknowledged:
        :param acknowledged_time:
        :param severity:
        :param status:
        :return:
        """
        self.log.debug("新增表数据:")
        try:
            base = UtilsDataBase()
            base.add_param(_key="eventid", value=eventid)
            base.add_param(_key="hostid", value=hostid)
            base.add_param(_key="name", value=name)
            base.add_param(_key="source", value=source)
            base.add_param(_key="object", value=_object)
            base.add_param(_key="objectid", value=objectid)
            base.add_param(_key="clock", value=clock)
            base.add_param(_key="ns", value=ns)
            base.add_param(_key="r_clock", value=r_clock)
            base.add_param(_key="r_ns", value=r_ns)
            base.add_param(_key="acknowledged", value=acknowledged)
            base.add_param(_key="acknowledged_time", value=acknowledged_time)
            base.add_param(_key="severity", value=severity)
            base.add_param(_key="status", value=status)
            sql_rep = self.table(**base.param)

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