#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from fastapi import FastAPI, Request #, Response,HTTPException
from fastapi.responses import PlainTextResponse, JSONResponse, RedirectResponse
from fastapi.exceptions import RequestValidationError
from fastapi.middleware.cors import CORSMiddleware
from starlette.middleware.sessions import SessionMiddleware
from starlette.staticfiles import StaticFiles
from routers import home, api ,prod_api
from exceptions import *
from pymysql.err import OperationalError
import os
import platform

app = FastAPI()
# app.include_router(home.router)
app.include_router(api.router, prefix="/api")
app.include_router(prod_api.router, prefix="")

@app.get("/", response_class=PlainTextResponse)
async def main():
    return "应急后端接口9988"

app.add_middleware(SessionMiddleware, secret_key='MM-ZHCS-YJ-API', max_age=36000 * 24)
app.add_middleware(CORSMiddleware,allow_origins=['*'],allow_credentials=False,allow_methods=['*'],allow_headers=['*'])

app.mount('/static', StaticFiles(directory='static'), name='static')

# @app.exception_handler(RequestValidationError)
# async def validation_exception_handler(request, exc):
#     return JSONResponse(status_code=200, content={ "errcode": 100060, "errmsg": "参数错误" }, )

@app.exception_handler(TokenException)
async def exception_handler(request: Request, exc: TokenException):
    return JSONResponse(
        status_code=200,
        content={"errcode": "4001", "errmsg":"验证不通过"}
    )

@app.exception_handler(OperationalError)
async def exception_handler(request: Request, exc: OperationalError):
    return JSONResponse(
        status_code=412,
        content={"code": "412", "msg":f"接口对应sql异常，请检查{exc}"}
    )


# @app.exception_handler(AttributeError)
# async def exception_handler(request: Request, exc: TokenException):
#     return JSONResponse(
#         status_code=200,
#         content={"errcode": "500", "errmsg":"Internal Server Error"}
#     )


@app.exception_handler(AuthException)
async def exception_handler(request: Request, exc: TokenException):
    return RedirectResponse("/")
    
@app.exception_handler(AlertException)
async def exception_handler(request: Request, exc: AlertException):
    return JSONResponse(
        status_code=200,
        content={"ret": 1, "msg": exc.msg}
    )


    
if __name__ == '__main__':
    import uvicorn
    sys = platform.system()
    if sys == "Windows":
        os.system("title 茂名应急数据中台 DEV")
    # print(1234567890)
    uvicorn.run(app='main:app', host='0.0.0.0',port=9988, reload=True, debug=True)

    # uvicorn.run(app='main:app', host='0.0.0.0', port=9988)
