from fastapi import APIRouter, Request, Depends, HTTPException
from sqlalchemy.exc import IntegrityError

from fastapi.responses import JSONResponse
from database import get_db
from sqlalchemy.orm import Session
from models import *
import json
import random
from sqlalchemy import create_engine, select
router = APIRouter()

# @router.post('/create')
# async def create_knowledge(request:Request,db:Session = Depends(get_db)):
#     data = await request.body()
#     body = data.decode(encoding='utf-8')
#     if len(body) > 0:
#         body = json.loads(body)
#     print(body)
#     random_10_digit_number = random.randint(1000000000, 9999999999)
#     # file_identifier = 'f'
#     reportId = 'ZJBG'+str(random_10_digit_number)
#     # file_identifier =
#     reportName = body["reportName"]
#     subject = body["subject"]
#     eventType = body["eventType"]
#     publishingUnit = body["publishingUnit"]
#     publishDate = body["publishDate"]
#     summary = body["summary"]
#
#     notificationType = body["notificationType"]
#
#     base_code = 'base'+str(random.randint(1000000000, 9999999999))
#
#     fileNames = body["fileName"]
#     filePath = '/data/upload/mergefile/'
#
#
#
#     konwledge = KnowledgeBase(
#         reportId=reportId,
#
#         reportName=reportName,
#         subject=subject,
#         eventType=eventType,
#         publishingUnit=publishingUnit,
#         publishDate=publishDate,
#         summary = summary,
#         notificationType = notificationType,
#
#         base_code = base_code
#     )
#     db.add(konwledge)
#
#     for fileName in fileNames:
#         file_identifier='file'+str(random.randint(1000000000, 9999999999))
#         knowledge_file = KnowledgeFile(
#             file_identifier=file_identifier,
#             file_path=filePath,
#             file_name = fileName,
#             is_deleted = 0,
#             knowledge_base_code = base_code
#         )
#         db.add(knowledge_file)
#
#     db.commit()
#     return {
#         "code":0,
#         "data":{
#             "reportId": reportId,
#             "status": "success",
#             "message": "总结报告创建成功"
#         }
#     }


@router.post('/create')
async def create_knowledge(request: Request, db: Session = Depends(get_db)):
    try:
        data = await request.body()
        body = json.loads(data.decode(encoding='utf-8'))

        # 验证必需的字段
        required_fields = ['reportName', 'subject', 'eventType', 'publishingUnit', 'publishDate', 'summary',
                           'fileNames']
        missing_fields = [field for field in required_fields if field not in body]
        print('missing_fields',missing_fields)
        if missing_fields:
            raise HTTPException(status_code=401, detail=f"Missing required fields: {', '.join(missing_fields)}")

            # 生成随机的报告ID和基础知识代码
        random_10_digit_number = random.randint(1000000000, 9999999999)
        reportId = 'ZJBG' + str(random_10_digit_number)
        base_code = 'base' + str(random.randint(1000000000, 9999999999))

        # 从请求体中提取其他数据
        reportName = body["reportName"]
        subject = body["subject"]
        eventType = body["eventType"]
        publishingUnit = body["publishingUnit"]
        publishDate = body["publishDate"]
        summary = body["summary"]
        # notificationType = body["notificationType"]
        notificationType = "总结报告"
        fileNames = body["fileNames"]  # 注意：这里假设它是列表

        # 创建 KnowledgeBase 实例
        konwledge = KnowledgeBase(
            reportId=reportId,
            reportName=reportName,
            subject=subject,
            eventType=eventType,
            publishingUnit=publishingUnit,
            publishDate=publishDate,
            summary=summary,
            notificationType=notificationType,
            base_code=base_code
        )
        db.add(konwledge)

        # 创建 KnowledgeFile 实例
        filePath = '/data/upload/mergefile/'
        for fileName in fileNames:
            file_identifier = 'file' + str(random.randint(1000000000, 9999999999))
            knowledge_file = KnowledgeFile(
                file_identifier=file_identifier,
                file_path=filePath + fileName,  # 如果fileName是完整的路径，则可能不需要再次添加filePath
                file_name=fileName,
                is_deleted=0,
                knowledge_base_code=base_code
            )
            db.add(knowledge_file)

        db.commit()

        return {
            "code": 0,
            "data": {
                "reportId": reportId,
                "status": "success",
                "message": "总结报告创建成功"
            }
        }

    except json.JSONDecodeError:
        raise HTTPException(status_code=400, detail="Invalid JSON data")
    except IntegrityError as e:
        db.rollback()
        raise HTTPException(status_code=409, detail=f"Database error: {str(e)}")
    except Exception as e:
        db.rollback()
        print(e)
        raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")



@router.post('/select')
@router.get('/select')
async def select_knowledge(request: Request, db: Session = Depends(get_db)):
    # 尝试从请求体中解析 JSON 数据
    data = await request.json()  # 注意：这里直接使用 request.json() 而不是 request.body()
    try:
        page = int(data.get('page', 1))  # 如果没有提供 page，则默认为 1
        size = int(data.get('size', 10)) # 如果没有提供 size，则默认为 10
        if size >100:
            size = 100
    except ValueError as e:
        # 如果转换失败，则抛出 HTTPException
        raise HTTPException(status_code=400, detail=f"Invalid pagination parameters: {e}")

        # 计算 offset
    offset = (page - 1) * size

    # 使用 ORM 查询并应用分页
    data = db.query(KnowledgeBase).offset(offset).limit(size).all()

    # 打印结果（可选，用于调试）
    # for i in data:
    #     print(i)
    print(f"Returned {len(data)} results from page {page} with size {size}")

    # 计算总条数（注意：这可能会很慢，特别是对于大型数据集）
    total_count = db.query(func.count(KnowledgeBase.reportId)).scalar()

    # 计算总页数
    total_pages = (total_count // size) + (1 if total_count % size else 0)

    # 返回查询结果
    result = {
        "code": 0,
        'msg': 'success',
        'data': {
            'pages': total_pages,
            'total': total_count,
            "currentPage":page,
            "pageSize":size,
            "list": data
        }
    }
    return result





@router.post('/detail')
@router.get('/detail')
async def get_knowledge_detail(request: Request, db: Session = Depends(get_db)):
    # 尝试从请求体中解析 JSON 数据
    data = await request.json()
    report_id = data.get('reportID')
    if not report_id:
        raise HTTPException(status_code=400, detail="Missing required parameter 'reportID'")

        # 查询 KnowledgeBase
    kb_entry = db.query(KnowledgeBase).filter(KnowledgeBase.reportId == report_id).first()
    if not kb_entry:
        raise HTTPException(status_code=404, detail="No knowledge base found for the given report ID")

    kf_entries = db.query(KnowledgeFile).filter(KnowledgeFile.knowledge_base_code == kb_entry.base_code).all()

    # 准备返回的数据
    result = {
        "code": 0,
        "msg": "success",
        "data": {
            "report_id": kb_entry.reportId,
            "reportName": kb_entry.reportName,
            "subject": kb_entry.subject,
            "eventType": kb_entry.eventType,
            "publishDate": kb_entry.publishDate,
            "publishingUnit": kb_entry.publishingUnit,
            "summary": kb_entry.summary,
            "notificationType": kb_entry.notificationType,
            # "knowledge_base_code": kb_entry.base_code,
            "file": [
                {
                 "content": kf.file_name,
                 "url": 'http://127.0.0.1:9988/api/file/download/'+kf.file_name
                 }  # 根据需要调整返回的字段
                for kf in kf_entries
            ]
            }
    }

    return result