from fastapi import Depends, APIRouter
from sqlalchemy.orm import Session
from app import get_db
from app.api.account import schemas, crud
from app.api.statement import crud as statement_crud
from libs.result_format import HttpResultResponse, HttpMessage

router = APIRouter()


@router.post("/create")
def create_account(data: schemas.AccountCreate, db: Session = Depends(get_db)):
    """添加账户"""
    db_info = crud.get_account(db, name=data.name)
    if db_info:
        return HttpResultResponse(code=400, msg=HttpMessage.ACCOUNT_EXIST)
    res = crud.create_account(db=db, param=data)
    if not res:
        return HttpResultResponse(code=500, msg=res)
    return HttpResultResponse(data=res.id)


@router.post("/list")
def user_list(data: schemas.AccountList, db: Session = Depends(get_db)):
    """账户列表"""
    result = crud.get_account_list(db, data)
    return HttpResultResponse(total=len(result), data=result)


@router.get("/gift/type")
def gift_type_list(db: Session = Depends(get_db)):
    """礼物类型配置返回"""
    result = crud.get_gift_type(db)
    return HttpResultResponse(data=result)


@router.post("/update")
def read_account(data: schemas.AccountUpdate, db: Session = Depends(get_db)):
    """账户修改"""
    crud.update_account_info(db, data)
    return HttpResultResponse()


@router.post("/finance/info")
def finance_information(data: schemas.FinanceInfo, db: Session = Depends(get_db)):
    """账户财务信息"""
    res, total = crud.get_finance_info(db, data, 1)
    return HttpResultResponse(total=total, data=res[int(data.page-1)*data.size:data.page*data.size])


@router.post("/finance/info/excel")
def finance_info_excel(data: schemas.FinanceInfo, db: Session = Depends(get_db)):
    """账户财务信息导出"""
    statement_list = crud.get_finance_info(db, data)
    return statement_crud.data_to_file(statement_list, "财务信息")


@router.post("/finance/details")
def finance_details(data: schemas.FinanceDetails, db: Session = Depends(get_db)):
    """账户财务明细"""
    res, total, count = crud.get_finance_details(db, data, 1)
    return HttpResultResponse(total=total, data=res, count=count)


@router.post("/finance/details/excel")
def finance_info_excel(data: schemas.FinanceDetails, db: Session = Depends(get_db)):
    """账户财务明细导出"""
    statement_list = crud.get_finance_details(db, data)
    return statement_crud.data_to_file(statement_list, "财务明细")
