import os
from typing import List
from ninja import Router, File
from ninja.files import UploadedFile
from django.conf import settings
from datetime import datetime

router = Router()

# 确保上传目录存在
UPLOAD_DIR = os.path.join(settings.MEDIA_ROOT, 'uploads')
if not os.path.exists(UPLOAD_DIR):
    os.makedirs(UPLOAD_DIR)

@router.post("/image")
def upload_image(request, file: UploadedFile = File(...)):
    """上传图片"""
    # 生成文件名
    timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
    filename = f"{timestamp}_{file.name}"
    
    # 构建文件路径
    file_path = os.path.join(UPLOAD_DIR, filename)
    
    # 保存文件
    with open(file_path, 'wb+') as destination:
        for chunk in file.chunks():
            destination.write(chunk)
    
    # 返回完整的文件URL
    file_url = f"{request.build_absolute_uri('/')[:-1]}/media/uploads/{filename}"
    return {"url": file_url}

@router.post("/images")
def upload_images(request, files: List[UploadedFile] = File(...)):
    """批量上传图片"""
    urls = []
    for file in files:
        timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
        filename = f"{timestamp}_{file.name}"
        file_path = os.path.join(UPLOAD_DIR, filename)
        
        with open(file_path, 'wb+') as destination:
            for chunk in file.chunks():
                destination.write(chunk)
        
        file_url = f"{request.build_absolute_uri('/')[:-1]}/media/uploads/{filename}"
        urls.append(file_url)
    
    return {"urls": urls}
