# from datetime import datetime
from typing import List
from fastapi import APIRouter, Depends, Request, UploadFile, File, Form
# from pydantic_validation_decorator import ValidateFields
# from sqlalchemy.ext.asyncio import AsyncSession
# from config.enums import BusinessType
# from config.get_db import get_db
from module_admin.annotation.log_annotation import Log
from module_admin.aspect.interface_auth import CheckUserInterfaceAuth, CheckRoleInterfaceAuth
# from module_admin.entity.vo.notice_vo import DeleteNoticeModel, NoticeModel, NoticePageQueryModel
# from module_admin.entity.vo.user_vo import CurrentUserModel
from module_admin.service.login_service import LoginService
from module_admin.service.ragflow_service import RAGFlowService

from utils.log_util import logger
# from utils.page_util import PageResponseModel
from utils.response_util import ResponseUtil
from module_admin.entity.vo.ragflow_vo import RagflowListQueryModel, ListDocumentsQueryModel, UpdateFileModel, DeleteFileModel, CreateDatasetModel, DocumentIdsModel, UpdateChatAssistantModel,\
    CreateSessionWithChatModel, ConverseWithChatAssistantModel
import asyncio
# from config.env import RAGFlowConfig



ragflowController = APIRouter(prefix="/system/ragflow", dependencies=[Depends(LoginService.get_current_user)])



# 查看数据集列表
@ragflowController.post("/dataset_list"
                        # , response_model=PageResponseModel
                        # , dependencies=[Depends(CheckUserInterfaceAuth("system:ragflow:list"))]"
                        )
async def get_system_ragflow_list(
    request: Request,
    rage_flow_dastset_query: RagflowListQueryModel ,
    # query_db: AsyncSession = Depends(get_db),
):
    
    result = await RAGFlowService.get_ragflow_dataset_list_services(None, rage_flow_dastset_query)
    
    return parse_result(result)
    
# 创建数据集
@ragflowController.post('/create_dataset')
async def create_dataset(
    request: Request,
    create_dataset_params: CreateDatasetModel,
):
    
    result = await RAGFlowService.create_dataset_services(create_dataset_params)
    return parse_result(result)

# 更新数据集
@ragflowController.post('/update_dataset/{dataset_id}')
async def update_dataset(
    request: Request,
    dataset_id: str,
    update_dataset_params: CreateDatasetModel,
):
    result = await RAGFlowService.update_dataset_services(dataset_id, update_dataset_params)
    return parse_result(result)


# 列出数据集中文档列表
@ragflowController.get("/list_documents/{dataset_id}")
async def list_documents_by_dataset_id(
    request: Request,
    dataset_id: str,
    list_documents_query: ListDocumentsQueryModel = Depends(ListDocumentsQueryModel.as_query),
    
    # query_db: AsyncSession = Depends(get_db),
):
    """
    列出数据集中文档列表
    """
    print(list_documents_query)
    result = await RAGFlowService.list_documents_services(None, dataset_id, list_documents_query)
    
    return parse_result(result)
    

# 上传文件到数据集
@ragflowController.post("/upload_file/{dataset_id}")
async def upload_file_dataset(
    dataset_id: str,
    files: List[UploadFile] = File(...),
    # query_db: AsyncSession = Depends(get_db),
):
    """
    上传文件到数据集
    """
    # print(file)
    result = await RAGFlowService.upload_file_dataset_services(None, dataset_id ,files)
    
    return parse_result(result)
    
# 更新文档
@ragflowController.post("/update_file/{dataset_id}/{document_id}")
async def update_file_dataset(
    dataset_id: str,
    document_id: str,
    update_params: UpdateFileModel,
    # query_db: AsyncSession = Depends(get_db),
):
    """
    更新文件到数据集
    """
    # print(file)
    result = await RAGFlowService.update_file_dataset_services(dataset_id ,document_id, update_params)
    
    return parse_result(result)

# 开始解析文档
@ragflowController.post('/parse_documents/{dataset_id}')
async def parse_documents(
    dataset_id: str,
    parse_params: DocumentIdsModel,
    # query_db: AsyncSession = Depends(get_db),
):
    result = await RAGFlowService.parse_documents_services(dataset_id, parse_params)
    return parse_result(result)

# 停止解析文档
@ragflowController.post('/stop_parse_documents/{dataset_id}')
async def stop_parse_documents(
    dataset_id: str,
    parse_params: DocumentIdsModel,
    # query_db: AsyncSession = Depends(get_db),
):
    result = await RAGFlowService.stop_parse_documents_services(dataset_id, parse_params)
    return parse_result(result)

# 删除文档
@ragflowController.post('/delete_file/{dataset_id}')
async def delete_file(
    dataset_id: str,
    delete_params: DeleteFileModel,
    # query_db: AsyncSession = Depends(get_db),
):
    """
    删除文件
    """
    result = await RAGFlowService.delete_file_services(dataset_id, delete_params)
    
    return parse_result(result)
    
    
# 删除数据集
@ragflowController.post('/delete_datasets')
async def delete_datasets(
    delete_params: DeleteFileModel,
    # query_db: AsyncSession = Depends(get_db),
):
    """
    删除数据集
    """
    result = await RAGFlowService.delete_datasets_services(delete_params)
    return parse_result(result)

# 查看聊天助手列表
@ragflowController.post('/get_chat_assistant_list')
async def get_chat_assistant_list(
    query_params: RagflowListQueryModel,
):
    """
    查看聊天助手列表
    """
    
    result = await RAGFlowService.get_chat_assistant_list_services(query_params)
    return parse_result(result)
    
    # pass

# 更新聊天助手
@ragflowController.post('/update_chat_assistant')
async def update_chat_assistant(
    update_params: UpdateChatAssistantModel,
):
    """
    更新聊天助手
    """
    result = await RAGFlowService.update_chat_assistant_services(update_params)
    return parse_result(result)

# 创建属于聊天助手的会话
@ragflowController.post('/create_session_with_chat')
async def create_session_with_chat(
    create_params: CreateSessionWithChatModel,
):
    """
    创建属于聊天助手的会话
    """
    
    result = await RAGFlowService.create_session_with_chat_services(create_params)
    return parse_result(result)

# 与聊天助手进行对话
@ragflowController.post('/converse_with_chat_assistant')
async def converse_with_chat_assistant(
    converse_params: ConverseWithChatAssistantModel,
):
    """
    与聊天助手进行对话
    """
    
    result = await RAGFlowService.converse_with_chat_assistant_services(converse_params)
    return parse_result(result)
    
   
 
    # return parse_result(result)
    
# 获取用户权限
@ragflowController.get('/get_user_permission', dependencies=[Depends(CheckRoleInterfaceAuth('pad'))])
async def get_user_permission(current_user = Depends(LoginService.get_current_user)):
    """
    获取用户权限
    """
    
    user_auth_list = current_user.permissions
    print(user_auth_list)

    
    return ResponseUtil.success(data=user_auth_list)

def parse_result(result):
    code = result.get('code', 0)
    if code != 0:
        return ResponseUtil.error(result.get('data', None))
    return ResponseUtil.success(result.get('data', None))