from fastapi import APIRouter, Request, Depends, HTTPException, Query
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
from typing import Optional
from utils.StripTagsHTMLParser import *

router = APIRouter()

@router.post('/create')
async def create_event(request: Request, db: Session = Depends(get_db), body = Depends(remove_xss_json)):
    try:
        # 验证必需的字段
        required_fields = ['eventTitle', 'eventType', 'eventLevel', 'eventStatus', 'eventTime', 'reportTime',
                           'deaths', 'injuries', "missing", "eventSource", "longitude", "latitude", "eventDescription", "address"]
        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)}")
        
        random_10_digit_number = random.randint(1000000000, 9999999999)
        eventId = 'YJSJ' + str(random_10_digit_number)
        username = "..."

        # 创建 事件 实例
        incident_base = Incident(
            code = eventId,
            title = body["eventTitle"],
            incident_type = body["eventType"],
            incident_level = body["eventLevel"],
            status = body["eventStatus"],
            occurrence_time = body["eventTime"],
            report_time = body["reportTime"],
            fatalities = body["deaths"],
            injuries = body["injuries"],
            missing = body["missing"],
            source = body["eventSource"],
            location = body["address"],
            longitude = body["longitude"],
            latitude = body["latitude"],
            summary = body["eventDescription"],
            recorded_by = username,
            del_flag = "0"
        )
        db.add(incident_base)
        return {
            "code": 200,
            "msg": "事件创建成功",
            "status": "success",
            "data": eventId
        }
        
    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.get('/list')
async def get_event_list(
    eventType: str = Query(None, description='事件类型的字典键值'),
    eventLevel: str = Query(None, description='事件等级的字典键值'),
    eventStatus: str = Query(None, description='事件状态的字典键值'),
    eventTime: str = Query(None, description='事发时间'),
    regionCode: str = Query(None, description='行政区划代码'),
    searchTerm: str = Query(None, description='根据事件标题或描述中的关键字进行模糊搜索'),
    
    sortBy: str = Query(None, description='排序字段'),
    sortOrder: str = Query("asc", description='排序方式'),
    page: int = Query(1, gt=0, description='页码'),
    pageSize: int = Query(10, gt=0, description='pageSize'),
    db: Session = Depends(get_db)
):
    try:
        # 构建查询
        query = db.query(Incident)
        query = query.filter(Incident.del_flag != '2')
        # 应用查询条件

        # 计算总条目数
        total_items = query.count()
        # 执行分页查询
        rows = query.offset((page - 1) * pageSize).limit(pageSize).all()
        data = [
            {
                "eventId": row.code,
                "eventTitle": row.title,
                "eventType": row.incident_type,
                "eventLevel": row.incident_level,
                "eventStatus": row.status,
                "latitude": row.latitude,
                "longitude": row.longitude,
                "address": row.location,
                "eventTime": row.occurrence_time.strftime("%Y-%m-%d %H:%M")
            }
            for row in rows
        ]

        # 返回结果
        return {
            "code": 200,
            "msg": "成功",
            "data": data,
            "total": total_items,
            "currentPage": page,
            "pageSize": pageSize,
            "totalPages": (total_items + pageSize - 1) // pageSize
        }

    except Exception as e:
        # 处理异常
        raise HTTPException(status_code=500, detail=str(e))


@router.get('/detail')
async def get_event_detail(
    request: Request, 
    eventId: str, 
    db: Session = Depends(get_db)):
    
    try: 
        # 构建查询
        query = db.query(Incident)
        query = query.filter(Incident.code == eventId)

        # 执行查询
        row = query.first()
        if row is not None:
            eventTimeline = []
            commandRecords = []
            return {
                "code": 200,
                "msg": "查询成功",
                "data": {
                    "eventId": row.code,
                    "eventTitle": row.title,
                    "eventType": row.incident_type,
                    "eventLevel": row.incident_level,
                    "eventStatus": row.status,
                    "eventSource": row.source,
                    "eventTime": row.occurrence_time.strftime("%Y-%m-%d %H:%M"),
                    "reportTime": row.report_time.strftime("%Y-%m-%d %H:%M"),
                    "deaths": row.fatalities,
                    "injuries": row.injuries,
                    "missing": row.missing,
                    "reportedBy": row.recorded_by,
                    "contact": row.contact,
                    "eventDescription": row.summary,
                    "latitude": row.latitude,
                    "longitude": row.longitude,
                    "address": row.location,
                    "eventTimeline": eventTimeline,
                    "commandRecords": commandRecords
                }
            }
        else:
            return {
                "code": 500,
                "msg": "查询失败"
            }

    except Exception as e:
        # 处理异常
        raise HTTPException(status_code=500, detail=str(e))
    

@router.post('/close')
async def close_event(
    request: Request,  
    db: Session = Depends(get_db), 
    body = Depends(remove_xss_json)):

    try:
        # 验证必需的字段
        required_fields = ['eventId', 'eventStatus', 'deaths', 'injuries', 'missing', '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)}")

        return {
            "code": 200,
            "msg": "总结报告创建成功"
        }

    except Exception as e:
        # 处理异常
        raise HTTPException(status_code=500, detail=str(e))