import random
from datetime import datetime
from sqlalchemy.orm import Session
from app.api.role.crud import get_id_to_authority
from app.api.users import schemas
from libs.functions import md5, uuid, wrapper_out
from models import users as models
from core.config.env import env


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


@wrapper_out()
def get_users(db: Session, param):
    """
    分组统计求和  from sqlalchemy import func as fc
    r = db.query(fc.sum(r_model.Rolesfsas.aority), fc.sum(r_model.Rolesfsas.remark)).having(r_model.Rolesfsas.goods >
    10).group_by(r_model.Rolesfsas.goods).all()
    """
    username = param.username if param.username else ""
    if username:
        res = db.query(models.User).filter(models.User.username.like(f'%{username}%')).order_by(models.User.id.desc()).offset((int(param.page) - 1) * param.size).limit(param.page * param.size)
    else:
        res = db.query(models.User).order_by(models.User.id.desc()).offset((int(param.page) - 1) * param.size).limit(param.page * param.size)
    if not res:
        return []
    result_list = []
    for i in res:
        serializer_info = i.to_dict()
        if i.role_id:
            role_id = serializer_info.get('role_id')
            role_info = get_id_to_authority(db, role_id)
            if not role_info:
                serializer_info['role_name'] = ''
                continue
            serializer_info['role_name'] = role_info.role_name
        else:
            serializer_info['role_name'] = ''
        result_list.append(serializer_info)
    return result_list


def generate_random_str():
    random_str = ""
    base_str = 'ABCDEFGHIGKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789'
    length = len(base_str) - 1
    for i in range(10):
        random_str += base_str[random.randint(0, length)]
    return random_str


def create_user(db: Session, user: schemas.UserCreate):
    try:
        db_user = models.User(username=user.username, remark=user.remark, unique=uuid(),
                              config_key=generate_random_str(), uuid=uuid(), role_id=user.role_id,
                              hashed_password=md5(env.PASSWORD), create_time=datetime.now())
        db.add(db_user)
        db.commit()
        db.refresh(db_user)
    except Exception as e:
        print(e)
        return {}
    return db_user


def update_user(db: Session, data):

    if data.role_id:
        db.query(models.User).filter(models.User.id == data.id).update({models.User.role_id: data.role_id})
    if data.remark:
        db.query(models.User).filter(models.User.id == data.id).update({models.User.remark: data.remark})
    db.commit()


def delete_user(db: Session, user_id: int):

    db.query(models.User).filter(models.User.id == user_id).delete()
    db.commit()
