import traceback

import pymysql


def get_data_from_jerry_test(sql):
    try:
        db = pymysql.connect(host="172.16.40.170",
                             port=4000,
                             user="st_user",
                             passwd="aqpuBLYzEV7tML5RPsN1pntUzFy",
                             db="jerry_test",
                             charset="utf8",
                             cursorclass=pymysql.cursors.DictCursor)
        cursor = db.cursor()
        cursor.execute(sql)
        results = cursor.fetchall()
        db.close()
        return results
    except Exception as e:
        print(traceback.format_exc())
        return traceback.format_exc()


def get_data_from_zhengxing(sql):
    try:
        db = pymysql.connect(host="172.16.30.141",
                             port=3306,
                             user="zx_str",
                             passwd="ZXueX58pStrage",
                             db="zhengxing",
                             charset="utf8",
                             cursorclass=pymysql.cursors.DictCursor)
        cursor = db.cursor()
        cursor.execute(sql)
        results = cursor.fetchall()
        db.close()
        return results
    except Exception as e:
        print(traceback.format_exc())
        return traceback.format_exc()


def get_device_click_tractate_ids():
    sql = "select device, tractate_ids from device_click_tractate"
    data = get_data_from_jerry_test(sql)
    res = {}
    if data:
        for i in data:
            res[i["device"]] = i["tractate_ids"].rstrip("\n").split(",")
    return res


def get_all_business_tags():
    sql = "select name from api_tag where tag_type+0<'4'+0 and is_online = 1"
    data = get_data_from_zhengxing(sql)
    res = []
    if data:
        for i in data:
            tag = i.get("name", "")
            if tag:
                res.append(tag)
    return res
