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


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 Members(Base):
    """
    用户表
    """
    __tablename__ = "members"

    id = Column(BigInteger, primary_key=True)
    name = Column(VARCHAR(50), comment="用户名")
    password = Column(VARCHAR(255), comment="密码")
    head_image = Column(VARCHAR(255), comment="头像")
    position = Column(VARCHAR(100), comment="职位")
    role = Column(Integer, comment="角色")
    phone = Column(VARCHAR(20), comment="电话")
    email = Column(VARCHAR(50), comment="邮箱")
    create_time = Column(BigInteger, comment="创建时间")
    login_time = Column(BigInteger, comment="登录时间")
    status = Column(Integer, comment="(0:启用；1：禁用)")
    remark = Column(VARCHAR(255), comment="备注")
    wechat_url = Column(VARCHAR(255), comment="微信访问接口")
    dingding_url = Column(BigInteger, comment="钉钉访问接口")
    del_flag = Column(Integer, comment="(0:存在；1：删除)")
    silence_time = Column(VARCHAR(32), comment="静默时间 时间单位（m:分钟，h:小时，d:天）")
    period = Column(VARCHAR(32), comment="工作时间")
    severity = Column(VARCHAR(32), comment="告警级别")


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

        self.table = Members

    def insert_one(self, session, name=None, password=None, role=None):
        """
        :param session: 指针
        :param name:
        :param password:
        :param role:
        :return:
        """
        self.log.debug("新增表数据:")
        try:
            base = UtilsDataBase()
            base.add_param(_key="name", value=name)
            base.add_param(_key="password", value=password)
            base.add_param(_key="role", value=role)
            sql_rep = self.table(**base.param)

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

    def select_all_from_allKeys(self, session, _id=None, name=None, role=None, status=None, del_flag=None):
        """
        :param session: 指针
        :param _id:
        :param name:
        :param role:
        :param status:
        :param del_flag:
        :return: 查询结果
        """
        self.log.debug("查询数据库:")
        try:
            base = UtilsDataBase()
            base.add_param(_key="id", value=_id)
            base.add_param(_key="name", value=name)
            base.add_param(_key="role", value=role)
            base.add_param(_key="status", value=status)
            base.add_param(_key="del_flag", value=del_flag)
            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 update_del_flag(self, session, _id, value):
        """
        :param session: 指针
        :param _id:
        :param value:
        :return:
        """
        self.log.debug("查询数据库:")
        try:
            self.log.debug("更新相关测试数据")
            sql_rep = session.query(self.table).filter_by(id=_id).one()
            sql_rep.del_flag = value
            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 update_status(self, session, _id, value):
        """
        :param session: 指针
        :param _id:
        :param value:
        :return:
        """
        self.log.debug("查询数据库:")
        try:
            self.log.debug("更新相关测试数据")
            sql_rep = session.query(self.table).filter_by(id=_id).one()
            sql_rep.status = value
            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 update_password(self, session, _id, value):
        """
        :param session: 指针
        :param _id:
        :param value:
        :return:
        """
        self.log.debug("查询数据库:")
        try:
            self.log.debug("更新相关测试数据")
            sql_rep = session.query(self.table).filter_by(id=_id).one()
            sql_rep.password = value
            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
