import pandas as pd
from sqlalchemy.orm import Session
from core.config.env import env
from libs.db_link import LinkMysql
from models import statement as models
from starlette.responses import StreamingResponse


def get_statement(db: Session, user_id: int):
    return db.query(models.Statement).filter(models.Statement.id == user_id)


def get_statement_by_name(db: Session, username: str):
    return db.query(models.Statement).filter(models.Statement.username == username).first()


def get_statements(param):
    page = param.page if param.page else 1
    size = param.size if param.size else 10
    query_list = []
    if param.order_number:
        query_list.append(f"o.order_number LIKE '%{param.order_number}%'")
    if param.user_id:
        query_list.append(f"o.userid={param.user_id}")
    if param.sid:
        query_list.append(f"o.sid LIKE '%{param.sid}%'")
    if param.paychannel:
        query_list.append(f"o.paychannel LIKE '%{param.paychannel}%'")
    if param.start_time:
        query_list.append(f"o.current>='{param.start_time}'")
    if param.end_time:
        query_list.append(f"o.current <= '{param.end_time}'")
    if not query_list:
        sql = f"select order_number,userid,user_number,nick_name,cast(money as char) as money,paychannel,sid,lastupdate,cast(current as char) as current,payment_time from orders o INNER JOIN v2_user v on o.userid = v.user_id LIMIT {(int(page) - 1) * size},{page * size}"
    elif len(query_list) == 1:
        sql = f"select order_number,userid,user_number,nick_name,cast(money as char) as money,paychannel,sid,lastupdate,cast(current as char) as current,payment_time from orders o INNER JOIN v2_user v on o.userid = v.user_id where {query_list[0]} LIMIT {(int(page)-1) * size},{page * size}"
    else:
        sql = f"select order_number,userid,user_number,nick_name,cast(money as char) as money,paychannel,sid,lastupdate,cast(current as char) as current,payment_time from orders o INNER JOIN v2_user v on o.userid = v.user_id where {' and '.join(query_list)} LIMIT {(int(page) - 1) * size},{page * size}"

    query_res = LinkMysql(env.MysqlDB).query_mysql(sql)
    return query_res


# 写入文件
def data_to_file(data, name):
    bk = pd.DataFrame(data)
    with pd.ExcelWriter(f'static/{name}.xlsx') as writer:
        bk.to_excel(writer, sheet_name='Sheet1', index=False)
    file = open(writer, 'rb')
    return StreamingResponse(file)
