import uuid

from Log import logger
from app.config.const import DEPT_STATUS_ON
from app.models import OrganizationModel
from app.models.resource_model import ResourceModel
from app.models.role_model import RoleModel



async def role_list(db, page_size: int, page_index: int, keyword: str, role_key:str, user_id):
    query = db.query(RoleModel)
    # if role_key != "admin":
    #     query.filter(RoleModel.creator==user_id)
    if keyword:
        query = query.filter(RoleModel.name.like('%{}%'.format(keyword)))
    total = query.count()
    roles = query.order_by(RoleModel.created_at.desc()).limit(page_size).offset(
        (page_index - 1) * page_size).all()
    return {"total": total, "rows":  [role.to_json() for role in roles if role.status == DEPT_STATUS_ON]}


async def create_role(db, role_name: str, description: str, role_key, data_scope, user_id):
    try:
        role_model = RoleModel(id=str(uuid.uuid4()),name=role_name, description=description,creator=user_id, dataScope=data_scope)
        if role_key:
            role_model.roleKey = role_key
        db.add(role_model)
        db.commit()
        db.refresh(role_model)
    except Exception as e:
        logger.error(e)
        db.rollback()
        return False
    return True

async def delete_role_data(db, role_id: str):
    try:
        db.query(RoleModel).filter(RoleModel.id == role_id).delete()
        db.commit()
    except Exception as e:
        logger.error(e)
        db.rollback()
        return False
    return True


async def edit_role_status(db, status: str, role_id: str):
    try:
        db.query(RoleModel).filter(RoleModel.id == role_id).update({"status":status})
        db.commit()
    except Exception as e:
        logger.error(e)
        db.rollback()
        return False
    return True


async def edit_role_resource(db, role_id:str, role_name:str, description:str,role_key:str, data_scope:int, resources:list, edit_type:int, depts:list):
    try:
        role = db.query(RoleModel).filter(RoleModel.id == role_id).first()
        if edit_type == 1:
            role.name = role_name
            role.description = description

            if role_key:
                role.roleKey = role_key
            if data_scope:
                role.dataScope = data_scope
        elif edit_type == 2:
            role.resources = [db.get(ResourceModel, resourcesId) for resourcesId in resources]
        elif edit_type == 3:
            role.organizations = [db.get(OrganizationModel, deptId) for deptId in depts]
        db.add(role)
        db.commit()
    except Exception as e:
        logger.error(e)
        db.rollback()
        return False
    return True