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


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 Experience(Base):
    """
    经验手册
    """
    __tablename__ = "experience"

    experienceid = Column(BigInteger, primary_key=True)
    title = Column(VARCHAR(255), comment="标题")
    content = Column(TEXT, comment="内容")
    versions = Column(Integer, comment="版本号")
    remark = Column(VARCHAR(255), comment="备注")
    create_time = Column(BigInteger, comment="创建时间")
    create_by = Column(BigInteger, comment="创建人")
    update_time = Column(BigInteger, comment="更新时间")
    update_by = Column(BigInteger, comment="更新人")
    host_type_tree = Column(VARCHAR(255), comment="资源类型树状图")
    businessids_tree = Column(VARCHAR(255), comment="经验手册树状图")


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

        self.table = Experience

    def select_all_from_allKeys(self, session, experienceid=None, title=None, content=None):
        """
        :param session: 指针
        :param experienceid:
        :param title:
        :param content:
        :return: 查询结果
        """
        self.log.debug("查询数据库:")
        try:
            base = UtilsDataBase()
            base.add_param(_key="experienceid", value=experienceid)
            base.add_param(_key="title", value=title)
            base.add_param(_key="content", value=content)
            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_title(self, session, title):
        """
        :param session: 指针
        :param title:
        :return:
        """
        self.log.debug("查询数据库:")
        try:
            self.log.debug("删除相关测试数据")
            session.query(self.table).filter(self.table.title.like(str(title) + "%")).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
