from app.config.config import settings
from app.models.dialog_model import DialogModel
from app.models.knowledge_model import KnowledgeModel
from app.models.llm_model import CommonLlmModel
from app.models.group_model import GroupModel
from app.models.user_model import UserModel
from app.service.ragflow import RagflowService
from app.service.service_token import get_ragflow_token
from Log import logger
from sqlalchemy import and_


async def group_list(db, page_size: int, page_index: int, keyword: str):
    # logger.info("-------------------------group_list----------------------------------")
    query = db.query(GroupModel)
    # if role_key != "admin":
    #     query.filter(GroupModel.creator==user_id)
    if keyword:
        query = query.filter(GroupModel.group_name.like('%{}%'.format(keyword)))
    total = query.count()
    items = query.order_by(GroupModel.id.desc()).limit(page_size).offset((page_index - 1) * page_size)

    return {"total":total , "items": [item.to_json() for item in items.all()]}


async def create_group(db, group_name: str, group_description: str, user_id):
    try:
        group_model = GroupModel(group_name=group_name, group_description=group_description, creator=user_id)
        db.add(group_model)
        db.commit()
        db.refresh(group_model)
    except Exception as e:
        logger.error(e)
        db.rollback()
        return False
    return True


async def edit_group_data(db, group_id: int, data):
    try:
        db.query(GroupModel).filter(GroupModel.id == group_id).update(data)
        db.commit()
    except Exception as e:
        logger.error(e)
        db.rollback()
        return False
    return True


async def delete_group_data(db, group_id: int):
    try:
        db.query(GroupModel).filter(GroupModel.id == group_id).delete()
        db.commit()
    except Exception as e:
        logger.error(e)
        db.rollback()
        return False
    return True


async def get_group_users(db, group_id):
    not_group_user = []
    in_group_user = []
    user_list = [u.id for u in db.query(GroupModel).filter(GroupModel.id.__eq__(group_id)).first().users]
    for u in db.query(UserModel.id, UserModel.username, UserModel.permission).filter(
        and_(UserModel.permission != "admin", UserModel.status != 2)
    ).order_by(UserModel.id.desc()).all():
        if u.id in user_list:
            in_group_user.append({"userId": u.id, "userName": u.username})
        else:
            not_group_user.append({"userId": u.id, "userName": u.username})
    return {"inGroup": in_group_user, "notInGroup": not_group_user}


async def save_user_to_group(db, user_id, group_id, user_list):
    # group_user_list = [u.id for i in
    #              db.query(GroupModel).filter(GroupModel.id.__eq__(group_id)).all() for u in i.users]
    # new_users = set([i for i in user_list if i not in group_user_list])
    # delete_user = [i for i in group_user_list if i not in user_list]
    # print(new_users)
    # if new_users:
    #
    #     user_dict = {i.id: {"rg_id": i.ragflow_id, "email": i.email} for i in
    #                  db.query(UserModel.id, UserModel.email, UserModel.ragflow_id).filter(
    #                      UserModel.id.in_(user_list)).all()}
    #     # print(user_dict)
    #     ragflow_service = RagflowService(settings.fwr_base_url)
    #     token = await get_ragflow_token(db, user_id)
    #
    #     try:
    #         for old_user in group_user_list:
    #             if old_user in delete_user:
    #                 continue
    #             for new_user in new_users:
    #                 await ragflow_service.add_user_tenant(token, user_dict[old_user]["rg_id"], user_dict[new_user]["email"],
    #                                                       user_dict[new_user]["rg_id"])
    #                 await ragflow_service.add_user_tenant(token, user_dict[new_user]["rg_id"], user_dict[old_user]["email"],
    #                                               user_dict[old_user]["rg_id"])
    #         for user1 in new_users:
    #             for user2 in new_users:
    #                 if user1 != user2:
    #                     print(user1, user2)
    #                     await ragflow_service.add_user_tenant(token, user_dict[user1]["rg_id"],
    #                                                           user_dict[user2]["email"],
    #                                                           user_dict[user2]["rg_id"])
    #     except Exception as e:
    #         logger.error(e)
    #         return False

    try:
        group = db.query(GroupModel).filter(GroupModel.id.__eq__(group_id)).first()
        group.users = [db.get(UserModel, user) for user in user_list]
        db.commit()
    except Exception as e:
        logger.error(e)
        return False
    return True

async def save_group_resource(db, user_id, group_id, llms, dialogs, knowledges):
    try:
        group = db.query(GroupModel).filter(GroupModel.id.__eq__(group_id)).first()

        group.dialogs = [db.get(DialogModel, user) for user in dialogs]
        group.knowledges = [db.get(KnowledgeModel, user) for user in knowledges]
        db.commit()
    except Exception as e:
        logger.error(e)
        return False
    return True