import pymysql, json
import app_conf

conf = app_conf.conf()


def getConn():
    return pymysql.Connect(
        host=conf.get("database", "host"),
        user=conf.get("database", "user"),
        port=conf.getint("database", "port"),
        database=conf.get("database", "database"),
        password=conf.get("database", "password"),
    )


def saveFzData(data) -> bool:
    "将数据存入数据库"
    sql = """
    INSERT INTO table_zhapian 
    VALUES (
    %(uuid)s,%(callednm)s,%(zptype)s,%(zpfeatures)s,%(early_warning_time)s,
    %(warninglevel)s,%(zpcallernm)s,%(talktime)s,%(auth_code)s,%(student_number)s,
    %(transfer_amout)s,%(url_or_app_name)s,%(zp_account)s
    );
    """
    conn = getConn()
    cursor = conn.cursor()
    try:
        for message in data:
            message.setdefault("uuid",None)
            message.setdefault("callednm",None)
            message.setdefault("zptype",None)
            message.setdefault("zpfeatures",None)
            message.setdefault("early_warning_time",None)
            message.setdefault("warninglevel",None)
            message.setdefault("zpcallernm",None)
            message.setdefault("talktime",None)
            message.setdefault("auth_code",None)
            message.setdefault("student_number",None)
            message.setdefault("transfer_amout",None)
            message.setdefault("url_or_app_name",None)
            message.setdefault("zp_account",None)
            cursor.execute(sql,message)
        conn.commit()
    except:
        return False
    conn.close()
    return True

def LoadFzData():
    "从数据库读取数据"
    sql = """
    SELECT * FROM `table_zhapian` ORDER BY `early_warning_time` DESC LIMIT 0,1000;
    """
    conn = getConn()
    cursor = conn.cursor()
    try:
        cursor.execute(sql)
        results = cursor.fetchall()
    except:
        conn.close()
        return None
    conn.close()

    return results

def total():
    "返回数据库总条目数量"
    sql = """
    SELECT COUNT(*) AS total_count FROM table_zhapian;
    """
    conn = getConn()
    cursor = conn.cursor()
    try:
        cursor.execute(sql)
        results = cursor.fetchone()
    except:
        conn.close()
        return None
    conn.close()

    return results[0]
