# -*- coding:utf-8 -*-

# 引入需要的模块
# from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
# 使用MySQL数据库
from collections import Iterable
import json,datetime
from datetime import date
# import pymysql
# pymysql.install_as_MySQLdb()
# 导入自己拆分的数据类型模块
# from . import models
# from model_data_api.models import *
from model_data_api.config import *
# 定义一个基础管理类

# Base = DB_Base()
class BaseManager:
    def __init__(self):
        # 创建数据库引擎
        self.engine = create_engine(settings.DB_CONNECT_STRING['model_db'],echo=True,connect_args={"use_unicode":True,"charset":"utf8"})
        # self.engine =DB_Base()
        #     self.engine = Base
        # 创建连接会话
        Session = sessionmaker(bind=self.engine)
        self.session = Session()

        # print(self.session)
        # self.cls = cls
    # 公用方法
    def update_obj(self, **kw):
        self.session.commit()

    def delete_obj(self, **kw):
        self.session.delete(**kw)
        self.session.commit()

    def find_single(self, **kw):
        raise Exception("这个函数必须重写")

    def find_condition(self, **kw):
        raise Exception("这个函数必须重写")

    def close(self):
        self.session.close()

    def create_obj(self,cls,**kw):
        p = cls(**kw)
        self.session.add(p)
        self.session.commit()
        pass
    #
    # def create_obj_all(self,cls,**kw):
    #     p = cls(**kw)
    #     self.session.add(p)
    #     self.session.commit()
    #     pass

    def get_json(self,result):
        try:
            if isinstance(result, Iterable):
                tmp = [dict(zip(res.__dict__.keys(), res.__dict__.values())) for res in result]
                for t in tmp:
                    t.pop('_sa_instance_state')
            else:
                tmp = dict(zip(result.__dict__.keys(), result.__dict__.values()))
                tmp.pop('_sa_instance_state')
            return tmp
        except BaseException as e:
            print(e.args)
        raise TypeError('Type error of parameter')

    # def __default__(self,obj):
    #     if isinstance(obj, datetime):
    #         return obj.strftime('%Y-%m-%d %H:%M:%S')
    #     elif isinstance(obj, date):
    #         return obj.strftime('%Y-%m-%d')
    #     else:
    #         raise TypeError('%r is not JSON serializable' % obj)
    #
    # def json_dumps(self,_json):
    #     """ """
    #     return json.dumps(_json,ensure_ascii=False,default=self.__default)

    # def get_json_params(self,*args):
    #     for i,values in args:
