# encoding:utf8

import os
from sqlalchemy import create_engine


class sql_engine():
    def __init__(self, db, db_name=None, echo=False):
        """
        给出数据库名字，创建数据库连接
        :param db:
        :param db_name:
        :param echo:
        """
        try:
            import Configparser
            self.cf = Configparser.ConfigParser()
        except:
            import configparser
            self.cf = configparser.ConfigParser()
        self.cf.read(os.path.join(os.path.split(os.path.realpath(__file__))[0], 'config.ini'))
        host = self.cf.get(db, 'host')
        user = self.cf.get(db, 'user')
        passwd = self.cf.get(db, 'passwd')
        port = int(self.cf.get(db, 'port'))
        if not db_name:
            db_name = self.cf.get(db, 'db')
        try:
            self.__engine = create_engine(
                'mysql+mysqldb://%s:%s@%s:%s/%s?charset=utf8' % (user, passwd, host, port, db_name), echo=echo,
                connect_args={'connect_timeout': 3600})
        except:
            self.__engine = create_engine(
                'mysql+pymysql://%s:%s@%s:%s/%s?charset=utf8' % (user, passwd, host, port, db_name), echo=echo,
                connect_args={'connect_timeout': 3600})

    def get_engine(self):
        return self.__engine


if 'echo' not in vars():
    echo = False

engine_xyqb = sql_engine('xyqb', 'xyqb', echo).get_engine()
engine_pay_center = sql_engine('paycenter', 'payment_center', echo).get_engine()
engine_audit = sql_engine('audit_w', 'audit', echo).get_engine()
engine_bt_audit = sql_engine('audit_w', 'baitiao_audit', echo).get_engine()
engine_trans = sql_engine('audit_w', 'new_transaction', echo).get_engine()
engine_test = sql_engine('audit_w', 'test_mzh', echo).get_engine()
engine_analysis = sql_engine('analysis', 'analysis', echo).get_engine()
engine_mall = sql_engine('paycenter', 'mall').get_engine()
engine_financial = sql_engine('paycenter', 'financial_system').get_engine()
engine_offline = sql_engine('paycenter', 'offline').get_engine()
engine_merchant = sql_engine('paycenter', 'merchant').get_engine()

engine_trans_tmp = sql_engine('audit_w_tmp', 'new_transaction', echo).get_engine()

if __name__ == '__main__':
    import pandas as pd

    engine = sql_engine('local', 'test').get_engine()
    result = engine.execute(
        'select biz_type, plan_id, repay_type, record_id, ref_amount from repay_plan_repay_record_ref limit 10;')
    df = pd.DataFrame(data=list(result), columns=['biz_type', 'plan_id', 'repay_type', 'record_id', 'ref_amount'])

    print(df.head())
