#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from fastapi import APIRouter, Request, Depends
from pydantic import BaseModel
from fastapi.responses import JSONResponse
from database import get_db
from sqlalchemy.orm import Session
from datetime import datetime
from models import *
from utils import *
import json

router = APIRouter()

@router.get('/plan/list')
async def get_emergency_plan_list(
    plan_type: str = Query(None, description='预案类型'),
    publish_date: datetime = Query(None, description='发布日期'),
    plan_name: str = Query(None, description='预案名称'),
    page: int = Query(1, gt=0, description='页码'),
    page_size: int = Query(10, gt=0, description='每页条目数量'),
    db: Session = Depends(get_db)
):
    try:
        # 构建查询
        query = db.query(EmergencyPlan)
        query = query.filter(EmergencyPlan.del_flag != '2')
        # 应用查询条件
        if plan_type:
            query = query.filter(EmergencyPlan.plan_type == plan_type)
        if publish_date:
            query = query.filter(EmergencyPlan.publish_date == publish_date)
        if plan_name:
            query = query.filter(EmergencyPlan.plan_name.like(f'%{plan_name}%'))

            # 计算总条目数
            total_items = query.count()

            # 执行分页查询
            emergency_plans = query.offset((page - 1) * page_size).limit(page_size).all()

            # 将查询结果转换为列表形式的字典
            emergency_plans_list = [
                {
                    "plan_id": plan.plan_id,
                    "plan_number": plan.plan_number,
                    "plan_name": plan.plan_name,
                    "plan_type_desc": plan.plan_type_desc,
                    "organizing_unit": plan.organizing_unit,
                    "document_number": plan.document_number,
                    "publish_date": plan.publish_date.strftime('%Y-%m-%d %H:%M:%S')
                }
                for plan in emergency_plans
            ]

            # 构建分页信息
            pagination_info = {
                "total": total_items,
                "page": page,
                "page_size": page_size,
                "total_pages": (total_items + page_size - 1) // page_size
            }

            # 返回结果
            return {
                "code": 200,
                "msg": "成功获取预案列表",
                "data": {
                    "list": emergency_plans_list
                },
                "pagination": pagination_info
            }
    except Exception as e:
        # 处理异常
        raise HTTPException(status_code=500, detail=str(e))

class File(BaseModel):
    file_name:str
    file_name_desc:str
    file_path : str = 'null'

class PlanCreateForm(BaseModel):
    plan_name : str
    plan_type : int
    plan_type_desc : str
    publish_date: str
    organizing_unit : str
    document_number : str
    file_list : List[File] = []

@router.post('/plan/create')
async def create_emergency_plan(
    form_data:PlanCreateForm,
    db: Session = Depends(database.get_db)
):
    try:
        # 提取请求数据
        plan_name = form_data.plan_name
        plan_type = form_data.plan_type
        plan_type_desc = form_data.plan_type_desc
        publish_date = form_data.publish_date  # 如果没有提供发布日期，则使用当前时间
        organizing_unit = form_data.organizing_unit  # 使用用户位置作为编制单位
        document_number = form_data.document_number

        # 创建新的预案记录
        new_plan = EmergencyPlan(
            plan_id=new_guid(),  # 假设使用 UUID 作为预案 UID
            plan_name=plan_name,
            plan_type=plan_type,
            plan_type_desc=plan_type_desc,
            publish_date=publish_date,
            organizing_unit=organizing_unit,
            document_number=document_number
        )

        # 添加到数据库会话并提交
        db.add(new_plan)
        db.commit()
        db.refresh(new_plan)  # 可选，如果需要刷新实例状态
        new_plan.plan_number= f'YJYA{str(new_plan.id).zfill(10)}'
        db.commit()
        for file in form_data.file_list:
            file_name = file.file_name
            file_name_desc = file.file_name_desc
            file_path = file.file_path
            new_file = EmergencyFile(
                file_id = new_guid(),
                foreign_key = new_plan.plan_id,
                from_scenario = 'emergencyPlans_plan',
                file_name=file_name,
                file_name_desc = file_name_desc,
                file_path = file_path
            )
            db.add(new_file)
            db.commit()
            db.refresh(new_file)

        # 返回创建成功的响应
        return {
            "code": 200,
            "msg": "预案创建成功",
            "data": None
        }
    except Exception as e:
        # 处理异常
        raise HTTPException(status_code=500, detail=str(e))


# @router.put('/plan/update')
# async def update_emergency_plan(
#     plan_data: dict,
#     db: Session = Depends(database.get_db)
# ):
#     try:
#         # 提取请求数据
#         query = db.query(EmergencyPlan)
#         query = query.filter(EmergencyPlan.plan_id == plan_data.get('plan_id'))
#         query = query.filter(EmergencyPlan.del_flag != '2')
#         plan = query.first()
#         if not plan:
#             detail = "预案不存在"
#             raise HTTPException(status_code=404, detail="预案不存在")
#
#         plan.plan_name = plan_data.get('plan_name')
#         plan.plan_type = plan_data.get('plan_type')
#         plan.plan_type_desc = plan_data.get('plan_type_desc')
#         plan.publish_date = plan_data.get('publish_date')  # 如果没有提供发布日期，则使用当前时间
#         plan.organizing_unit = plan_data.get('organizing_unit')  # 使用用户位置作为编制单位
#         plan.document_number = plan_data.get('document_number')
#
#
#         # 更新到数据库会话并提交
#         db.commit()
#         db.refresh(new_plan)  # 可选，如果需要刷新实例状态
#
#         # 返回创建成功的响应
#         return {
#             "code": 200,
#             "msg": "预案更新成功",
#             "data": None
#         }
#     except Exception as e:
#         # 处理异常
#         if str(e)=='':
#             e = detail
#         raise HTTPException(status_code=500, detail=str(e))
#
#
# @router.delete('/plan/delete')
# async def delete_emergency_plan(
#         plan_data: dict,
#         db: Session = Depends(database.get_db)
# ):
#     try:
#         # 提取请求数据
#         query = db.query(EmergencyPlan)
#         query = query.filter(EmergencyPlan.plan_id == plan_data.get('plan_id'))
#         query = query.filter(EmergencyPlan.del_flag != '2')
#         plan = query.first()
#         if not plan:
#             detail = "预案不存在"
#             raise HTTPException(status_code=404, detail="预案不存在")
#
#         plan.del_flag = '2'
#
#         # 更新到数据库会话并提交
#         db.commit()
#         db.refresh(new_plan)  # 可选，如果需要刷新实例状态
#
#         # 返回创建成功的响应
#         return {
#             "code": 200,
#             "msg": "预案删除成功",
#             "data": None
#         }
#     except Exception as e:
#         # 处理异常
#         if str(e) == '':
#             e = detail
#         raise HTTPException(status_code=500, detail=str(e))

