import pandas as pd
from sqlalchemy import create_engine
from databaseConn import *
#conn_db_48=create_engine('mysql://qa:{}@172.17.5.48:31393'.format('qatest'))
#conn_db_119 = create_engine('mysql://{}:{}@{}:{}'.format('root', 'quantGroup#com', '172.24.17.119', 15307))
#conn_db_220 = create_engine('mysql://recommender_user_rw:rkwnPEG4@172.30.220.11:15307')
#conn_db_27 = create_engine('mysql://real_data_test:{}@172.30.5.27:8066'.format('qpRBSarm$Tv*YO!n'))
# 172.29.2.5：3306     用户名：root  密码：123456 saas一期
#conn_db_2_5 = create_engine('mysql://root:123456@172.29.2.5:3306')
# conn_db_5_16 = create_engine('mysql://root:root@172.29.5.16:3306')

def mysqlInfo(namespace,dbtype='mysql'):
    """
    :param namespace:
    :param  dbtype:查询的类型，目前支持mysql和mongo
    :return: 获取namespace对应的mysql信息，对大数据的mysql不适用，此时需要自定义mysql_info
    """
    url="https://holmes.liangkebang.com/k8s/service/detail?namespace={}" \
        "&serviceType=base&serviceName={dbtype}".format(namespace,dbtype=dbtype)
    result=mysql_info.get(str(namespace)) or {}
    if result:
        return result
    try:
        resp=requests.get(url)
        result['host']=jsonpath.jsonpath(resp.json(),'$..lanIp')[0]
        result['port']=jsonpath.jsonpath(resp.json(),'$..nodePort')[0]
        result['pwd']='qatest'
        result['name']='qa'
        return result
    except:
        raise Exception("该namespace[{}]找不到对应的mysql信息".format(namespace))

def mysql_universal(namespace):
    mysql_universal="mysql://{name}:{pwd}@{host}:{port}"
    mysql_info=mysqlInfo(namespace)
    #print(mysql_info)
    temp=create_engine(mysql_universal.format(**mysql_info))
    print("mysql连接信息:",temp)
    return temp

def execmysl(namespace,sql):
    if 'select' not in sql or 'from' not in sql:
        raise Exception('在mysql看来不是有效的sql',sql)
    try:
        print(sql)
        df=pd.read_sql(sql,con=mysql_universal(namespace))
        return df
    except Exception as e:
        print('mysql执行报错：')
        traceback.print_exc(limit=2)
        #print('mysql执行报错：',traceback.print_stack())


def concatSql(sql,**kwargs):
    '''
    :param sql:
    :param kwargs:
    :return: 只针对select的sql拼接，拼接后where是and的关系
    '''
    if not kwargs:
        return sql
    temp=' '
    for k,v in kwargs.items():
        if isinstance(v,(list,tuple)):
            if len(v)>1:
                concatinfo=k+" in "+ '{}' +' and '
                temp+=concatinfo.format(tuple(v))
            else:
                temp+=k+'='+"'"+str(v[0])+"'" +' and '

        else:
            temp+=k+'='+"'"+str(v)+"'" +' and '
    return sql+' where '+temp[:-4]

if __name__ == '__main__':
    print(mysqlInfo('test1'))
    #print(execmysl('test1',"select key_word as word,key_word_url as jumpUrl,icon_url as iconUrl from t_app_config_search_keyword where status=1 and DATE_FORMAT(end_time,'%Y-%m-%d') >= DATE_FORMAT('2022-06-14 15:38:50','%Y-%m-%d') and DATE_FORMAT('2022-06-14 15:38:50','%Y-%m-%d') >= DATE_FORMAT(start_time,'%Y-%m-%d') order by sort"))