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

from fastapi import APIRouter, Request, Depends,Query, HTTPException, status
from pydantic import BaseModel
from typing import List
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 = [
            {
                "planUid": plan.plan_id,
                "planId": plan.plan_number,
                "planName": plan.plan_name,
                "planType": plan.plan_type_desc,
                "organUnit": plan.organizing_unit,
                "document": plan.document_number,
                "publish_date": plan.publish_date.strftime('%Y-%m-%d')
            }
            for plan in emergency_plans
        ]

        # 构建分页信息
        pagination_info = {

        }

        # 返回结果
        return {
            "code": 200,
            "msg": "成功获取预案列表",
            "data": emergency_plans_list,
            "total": total_items,
            "page": page,
            "page_size": page_size,
            "total_pages": (total_items + page_size - 1) // page_size
        }
    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(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(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(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))


@router.get('/drill/list')
async def get_emergency_drill_list(
    planNum: 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(EmergencyDrill)
        query = query.filter(EmergencyDrill.del_flag != '2')
        # 应用查询条件
        if planNum:
            query = query.filter(EmergencyDrill.plan_number == planNum)
        else:
            return 'planNum不存在'

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

        # 执行分页查询
        emergency_drill = query.all()   # .offset((page - 1) * page_size).limit(page_size)
        print(emergency_drill)
        # 将查询结果转换为列表形式的字典
        emergency_drill_list = [
            {
                "drillId": drill.drill_id,
                "drillName": drill.drill_name,
                "drillUnit": drill.organizing_unit,
                "year": "%s年"%drill.planned_annual,
                "drillTime": drill.planned_time.strftime('%Y-%m-%d %H:%M:%S'),
                "drillAddress": drill.drill_location,
                "drillProject":drill.drillProject,
                "drillVideo":[{    'file_name':'123456.mp4',
    'file_name_desc':'测试.mp4'}],
                "drillPicture": [{    'file_name':'123456.png',
    'file_name_desc':'测试.png'}]
            }
            for drill in emergency_drill
        ]


            # 返回结果
        return {
            "code": 200,
            "msg": "成功",
            "data": emergency_drill_list,
            "total": total_items,
            "page": page,
            "page_size": page_size,
            "total_pages": (total_items + page_size - 1) // page_size
        }
    except Exception as e:
        # 处理异常
        raise HTTPException(status_code=500, detail=str(e))

class DrillCreateForm(BaseModel):
    plan_number : str
    drill_name : str
    organizing_unit : str
    planned_annual : int
    planned_time: str
    drill_location : str
    drill_lon : float
    drill_lat : float
    scheme_file_list : List[File] = []
    video_file_list : List[File] = []
    pic_file_list : List[File] = []

@router.post('/drill/create')
async def create_emergency_drill(
    form_data:DrillCreateForm,
    db: Session = Depends(get_db)
):
    try:
        # 提取请求数据
        plan_number = form_data.plan_number
        drill_name = form_data.drill_name
        organizing_unit = form_data.organizing_unit
        planned_annual = form_data.planned_annual
        planned_time = form_data.planned_time
        drill_location = form_data.drill_location
        drill_lon = form_data.drill_lon
        drill_lat = form_data.drill_lat


        # 创建新的预案记录
        new_drill = EmergencyDrill(
            drill_id=new_guid(),  # 假设使用 UUID 作为预案 UID
            plan_number = plan_number,
            drill_name=drill_name,
            organizing_unit = organizing_unit,
            planned_annual = planned_annual,
            planned_time = planned_time,
            drill_location = drill_location,
            drill_lon = drill_lon,
            drill_lat = drill_lat
        )

        # 添加到数据库会话并提交
        db.add(new_drill)
        db.commit()
        db.refresh(new_drill)  # 可选，如果需要刷新实例状态

        for file in form_data.scheme_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_drill.drill_id,
                from_scenario = 'emergencyPlans_drill_scheme',
                file_name=file_name,
                file_name_desc = file_name_desc,
                file_path = file_path
            )
            db.add(new_file)
            db.commit()
            db.refresh(new_file)
        for file in form_data.video_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_drill.drill_id,
                from_scenario = 'emergencyPlans_drill_video',
                file_name=file_name,
                file_name_desc = file_name_desc,
                file_path = file_path
            )
            db.add(new_file)
            db.commit()
            db.refresh(new_file)
        for file in form_data.pic_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_drill.drill_id,
                from_scenario = 'emergencyPlans_drill_pic',
                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.get('/training/list')
async def get_emergency_training_list(
    planNum: 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(EmergencyTrainingSession)
        query = query.filter(EmergencyTrainingSession.del_flag != '2')
        # 应用查询条件
        if planNum:
            query = query.filter(EmergencyTrainingSession.plan_number == planNum)
        else:
            return 'planNum不存在'

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

        # 执行分页查询
        emergency_training = query.all()   # .offset((page - 1) * page_size).limit(page_size)
        # print(emergency_drill)
        # 将查询结果转换为列表形式的字典
        emergency_training_list = [
            {
                "textId": training.training_id,
                "theme": training.training_theme,
                "unitName": training.training_unit,
                "peopleNum": "%s人"%training.participant_count,
                "trainingWay":training.training_method,
                "startTime":training.start_time.strftime('%Y-%m-%d %H:%M:%S'),
                "endTime": training.end_time.strftime('%Y-%m-%d %H:%M:%S'),
                "address": training.training_location,
                "Content":training.training_content
            }
            for training in emergency_training
        ]


            # 返回结果
        return {
            "code": 200,
            "msg": "成功",
            "data": emergency_training_list,
            "total": total_items,
            "page": page,
            "page_size": page_size,
            "total_pages": (total_items + page_size - 1) // page_size
        }
    except Exception as e:
        # 处理异常
        raise HTTPException(status_code=500, detail=str(e))

class TrainingCreateForm(BaseModel):
    training_theme : str
    training_unit : str
    training_method : str
    participant_count: int
    start_time : str
    end_time : str
    training_content :str
    drill_location : str
    drill_lon : float
    drill_lat : float

@router.post('/training/create')
async def create_emergency_training(
    form_data:TrainingCreateForm,
    db: Session = Depends(get_db)
):
    try:
        # 创建新的预案记录
        new_training = EmergencyTrainingSession(
            training_id=new_guid(),  # 假设使用 UUID 作为预案 UID
            training_theme=form_data.training_theme,
            training_unit=form_data.training_unit,
            training_method=form_data.training_method,
            participant_count=form_data.participant_count,
            start_time=form_data.start_time,
            end_time=form_data.end_time,
            training_content=form_data.training_content,
            drill_location=form_data.drill_location,
            drill_lon=form_data.drill_lon,
            drill_lat=form_data.drill_lat
        )

        # 添加到数据库会话并提交
        db.add(new_training)
        db.commit()
        db.refresh(new_plan)  # 可选，如果需要刷新实例状态

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