from datetime import datetime
from fastapi import HTTPException, status
from sqlalchemy.orm import Session
from app.api.account import schemas
from libs.functions import wrapper_out
from models import account as models


def get_account(db: Session, name: str):
    """查询单个"""
    return db.query(models.Account).filter(models.Account.name == name).first()


def get_id_to_authority(db: Session, role_id: int):
    return db.query(models.Account).filter(models.Account.id == role_id).first()


@wrapper_out()
def get_account_list(db: Session, param):
    """列表"""
    result_list = []

    if param.name:
        query_res = db.query(models.Account).filter(models.Account.name.like(f'%{param.name}%')).\
            offset((int(param.page) - 1) * param.size).limit(param.page * param.size).all()
    else:
        query_res = db.query(models.Account).offset((int(param.page) - 1) * param.size).limit(param.page * param.size).all()
    if not query_res:
        return []
    for i in query_res:
        serializer_info = i.to_dict()
        if i.income:
            income_list = serializer_info.get('income').split(',')
            serializer_info['income'] = [int(i) for i in income_list]
        else:
            serializer_info['income'] = []
        if i.output:
            output_list = serializer_info.get('output').split(',')
            serializer_info['output'] = [int(i) for i in output_list]
        else:
            serializer_info['output'] = []
        result_list.append(serializer_info)
    return result_list


def create_account(db: Session, param: schemas.AccountCreate):
    """创建"""
    try:
        db_account = models.Account(name=param.name, unique_tag=param.unique_tag, config_key=param.config_key,
                                    remark=param.remark, create_time=datetime.now())
        db.add(db_account)
        db.commit()
        db.refresh(db_account)
    except Exception as e:
        print(e)
        return {}
    return db_account


def update_account_info(db: Session, old_data):
    """修改"""
    if old_data.name:
        db.query(models.Account).filter(models.Account.id == old_data.id).update(
            {models.Account.name: old_data.name})
    if old_data.remark:
        db.query(models.Account).filter(models.Account.id == old_data.id).update(
            {models.Account.remark: old_data.remark})
    if old_data.income:
        db.query(models.Account).filter(models.Account.id == old_data.id).update(
            {models.Account.income: ','.join(map(str, old_data.income))})
    if old_data.output:
        db.query(models.Account).filter(models.Account.id == old_data.id).update(
            {models.Account.output: ','.join(map(str, old_data.output))})
    db.commit()


def get_finance_info(db: Session, role_id: int):

    db.query(models.Account).filter(models.Account.id == role_id).delete()
    return True
