from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import FileResponse
import base64
import os

app = FastAPI()


@app.get("/")
async def root():
    return {"message": "Hello World"}


@app.get("/hello/{name}")
async def say_hello(name: str):
    return {"message": f"Hello {name}"}


@app.post("/user/login")
async def login(request: Request):
    print(request)
    data = await request.json()
    username = data.get("username")
    password = data.get("password")
    print(f"username: {username},password: {password}")
    # Replace with your actual validation logic
    if username == "1" and password == "1":
        data1 = None
        return {"code": "0", "msg": "ok", "data": data1}
    else:
        data2 = None
        return {"code": "-1", "msg": "账号或密码错误", "data": data2}


@app.get("/api/get-menu")
async def get_menu():
    pic_list = [
        {id: 1, "menu_name": "政策查询", "url": "/pages/policy/policy", "path": "assets/images/icon/政策解读.png"},
        {id: 2, "menu_name": "问答", "url": "/pages/qa/qa", "path": "assets/images/icon/问答.png"},
        {id: 3, "menu_name": "信息管理", "url": "/pages/assist/assist", "path": "assets/images/icon/群众信息管理.png"},
        {id: 4, "menu_name": "招聘", "url": "/pages/recruit/recruit", "path": "assets/images/icon/招聘.png"}
    ]
    data = []
    for item in pic_list:
        with open(item['path'], "rb") as image_file:
            encoded_string = base64.b64encode(image_file.read()).decode()
            data.append({
                "id": item[id],
                "menu_name": item['menu_name'],
                "url": item['url'],
                "base64EncodedImage": encoded_string
            })

    return {
        "code": 0,
        "msg": "ok",
        "data": data
    }


@app.get("/api/get-swiper-list")
async def get_swiper_list():
    # 设置图片所在的目录
    directory = "assets/images/pictures"
    base_url = "http://127.0.0.1:8000/api/swiper-image/"

    # 列出目录下所有文件
    files = os.listdir(directory)
    for i in files:
        if i == '.DS_Store':
            files.remove(i)
    print(files)
    # 生成包含完整路径的图片列表
    swiper_list = [{"id": i + 1, "path": base_url + file} for i, file in enumerate(files)]

    return {
        "code": 0,
        "msg": "ok",
        "data": swiper_list
    }


@app.get("/api/swiper-image/{image_id}.png")
async def get_swiper_image(image_id: str):
    base_image_path = "assets/images/pictures"
    # 构造图片文件的完整路径
    image_path = f"{base_image_path}/{image_id}.png"  # 假设图片格式为png，根据需要修改
    print(image_path)
    try:
        # 返回图片文件的响应
        return FileResponse(image_path)
    except FileNotFoundError:
        # 如果文件没有找到，返回404错误
        raise HTTPException(status_code=404, detail="Image not found")