package com.example.demo.model;

import java.time.LocalDateTime;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.EnumType;
import jakarta.persistence.Enumerated;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;

/**
 * 分镜视频任务实体
 */
@Entity
@Table(name = "storyboard_video_tasks")
public class StoryboardVideoTask {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false, unique = true, length = 50)
    private String taskId;

    @Column(nullable = false, length = 100)
    private String username;

    @Column(columnDefinition = "TEXT")
    private String prompt; // 文本描述

    @Column(name = "image_url", columnDefinition = "LONGTEXT")
    private String imageUrl; // 上传的参考图片URL（可选，支持Base64格式）

    @Column(nullable = false, length = 10)
    private String aspectRatio; // 16:9, 4:3, 1:1, 3:4, 9:16

    @Column(nullable = false)
    private boolean hdMode; // 是否高清模式

    @Column(nullable = false)
    private Integer duration; // 视频时长（秒）：5, 10, 15

    @Column(name = "image_model", length = 50)
    private String imageModel = "nano-banana-2"; // 图像生成模型：nano-banana, nano-banana-2

    @Column(name = "uploaded_images", columnDefinition = "LONGTEXT")
    private String uploadedImages; // 用户上传的多张参考图片（JSON数组，最多3张Base64格式）- 生成分镜图时使用

    @Column(name = "video_reference_images", columnDefinition = "LONGTEXT")
    private String videoReferenceImages; // 视频阶段用户上传的参考图片（JSON数组）- 生成视频时使用

    @Enumerated(EnumType.STRING)
    @Column(nullable = false, length = 20)
    private TaskStatus status;

    @Column(nullable = false)
    private int progress; // 0-100

    @Column(name = "result_url", columnDefinition = "LONGTEXT")
    private String resultUrl; // 分镜图URL（Base64编码的图片，可能非常大）- 网格图

    @Column(name = "storyboard_images", columnDefinition = "LONGTEXT")
    private String storyboardImages; // 单独的分镜图片（JSON数组，每张图片为Base64格式，带data URI前缀）

    @Column(name = "real_task_id")
    private String realTaskId; // 主任务ID（已废弃，保留用于兼容）

    @Column(name = "video_task_ids", columnDefinition = "TEXT")
    private String videoTaskIds; // 多个视频任务ID（JSON数组，每张图片对应一个视频任务）

    @Column(name = "video_urls", columnDefinition = "LONGTEXT")
    private String videoUrls; // 多个视频URL（JSON数组，用于拼接）

    @Column(columnDefinition = "TEXT")
    private String errorMessage;

    // 大模型优化后的提示词字段
    @Column(name = "shot_list", columnDefinition = "TEXT")
    private String shotList; // 镜头列表描述

    @Column(name = "image_prompt", columnDefinition = "TEXT")
    private String imagePrompt; // 生成分镜图的提示词

    @Column(name = "video_prompt", columnDefinition = "TEXT")
    private String videoPrompt; // 生成视频的提示词

    @Column(nullable = false)
    private int costPoints; // 消耗积分

    @Column(nullable = false, updatable = false)
    private LocalDateTime createdAt;

    @Column(nullable = false)
    private LocalDateTime updatedAt;

    @Column
    private LocalDateTime completedAt;

    /**
     * 任务来源类型：AI_GENERATED = AI生成分镜图，UPLOADED = 直接上传图片
     */
    @Enumerated(EnumType.STRING)
    @Column(name = "source_type", length = 20)
    private SourceType sourceType = SourceType.AI_GENERATED;

    public enum TaskStatus {
        PENDING, PROCESSING, COMPLETED, FAILED, CANCELLED
    }

    public enum SourceType {
        AI_GENERATED,  // AI生成分镜图
        UPLOADED       // 直接上传图片
    }

    // 构造函数
    public StoryboardVideoTask() {
        this.createdAt = LocalDateTime.now();
        this.updatedAt = LocalDateTime.now();
    }

    public StoryboardVideoTask(String username, String prompt, String aspectRatio, boolean hdMode, Integer duration) {
        this();
        this.username = username;
        this.prompt = prompt;
        this.aspectRatio = aspectRatio;
        this.hdMode = hdMode;
        this.duration = duration != null ? duration : 10; // 默认10秒
        
        // 计算消耗积分
        this.costPoints = calculateCost();
    }
    
    // 保留旧的构造函数以保持向后兼容
    public StoryboardVideoTask(String username, String prompt, String aspectRatio, boolean hdMode) {
        this(username, prompt, aspectRatio, hdMode, 10);
    }

    /**
     * 计算任务消耗积分
     */
    private Integer calculateCost() {
        int baseCost = 10; // 基础消耗
        int hdCost = hdMode ? 20 : 0; // 高清模式消耗
        
        return baseCost + hdCost;
    }

    /**
     * 更新任务状态
     */
    public void updateStatus(TaskStatus newStatus) {
        this.status = newStatus;
        this.updatedAt = LocalDateTime.now();
        
        // 任务结束状态都应该设置完成时间
        if (newStatus == TaskStatus.COMPLETED || newStatus == TaskStatus.FAILED || newStatus == TaskStatus.CANCELLED) {
            this.completedAt = LocalDateTime.now();
        }
    }

    /**
     * 更新进度
     */
    public void updateProgress(Integer progress) {
        this.progress = Math.min(100, Math.max(0, progress));
        this.updatedAt = LocalDateTime.now();
    }

    // Getters and Setters
    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }
    public String getTaskId() { return taskId; }
    public void setTaskId(String taskId) { this.taskId = taskId; }
    public String getUsername() { return username; }
    public void setUsername(String username) { this.username = username; }
    public String getPrompt() { return prompt; }
    public void setPrompt(String prompt) { this.prompt = prompt; }
    public String getImageUrl() { return imageUrl; }
    public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; }
    public String getAspectRatio() { return aspectRatio; }
    public void setAspectRatio(String aspectRatio) { this.aspectRatio = aspectRatio; }
    public boolean isHdMode() { return hdMode; }
    public void setHdMode(boolean hdMode) { this.hdMode = hdMode; }
    public boolean getHdMode() { return hdMode; } // 添加getHdMode方法以支持Boolean类型调用
    public Integer getDuration() { return duration; }
    public void setDuration(Integer duration) { this.duration = duration; }
    public String getImageModel() { return imageModel; }
    public void setImageModel(String imageModel) { this.imageModel = imageModel; }
    public String getUploadedImages() { return uploadedImages; }
    public void setUploadedImages(String uploadedImages) { this.uploadedImages = uploadedImages; }
    public String getVideoReferenceImages() { return videoReferenceImages; }
    public void setVideoReferenceImages(String videoReferenceImages) { this.videoReferenceImages = videoReferenceImages; }
    public TaskStatus getStatus() { return status; }
    public void setStatus(TaskStatus status) { this.status = status; }
    public int getProgress() { return progress; }
    public void setProgress(int progress) { this.progress = progress; }
    public String getResultUrl() { return resultUrl; }
    public void setResultUrl(String resultUrl) { this.resultUrl = resultUrl; }
    public String getStoryboardImages() { return storyboardImages; }
    public void setStoryboardImages(String storyboardImages) { this.storyboardImages = storyboardImages; }
    public String getErrorMessage() { return errorMessage; }
    public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; }
    public String getRealTaskId() { return realTaskId; }
    public void setRealTaskId(String realTaskId) { this.realTaskId = realTaskId; }
    public String getVideoTaskIds() { return videoTaskIds; }
    public void setVideoTaskIds(String videoTaskIds) { this.videoTaskIds = videoTaskIds; }
    public String getVideoUrls() { return videoUrls; }
    public void setVideoUrls(String videoUrls) { this.videoUrls = videoUrls; }
    public int getCostPoints() { return costPoints; }
    public void setCostPoints(int costPoints) { this.costPoints = costPoints; }
    public LocalDateTime getCreatedAt() { return createdAt; }
    public void setCreatedAt(LocalDateTime createdAt) { this.createdAt = createdAt; }
    public LocalDateTime getUpdatedAt() { return updatedAt; }
    public void setUpdatedAt(LocalDateTime updatedAt) { this.updatedAt = updatedAt; }
    public LocalDateTime getCompletedAt() { return completedAt; }
    public void setCompletedAt(LocalDateTime completedAt) { this.completedAt = completedAt; }
    public SourceType getSourceType() { return sourceType; }
    public void setSourceType(SourceType sourceType) { this.sourceType = sourceType; }
    public String getShotList() { return shotList; }
    public void setShotList(String shotList) { this.shotList = shotList; }
    public String getImagePrompt() { return imagePrompt; }
    public void setImagePrompt(String imagePrompt) { this.imagePrompt = imagePrompt; }
    public String getVideoPrompt() { return videoPrompt; }
    public void setVideoPrompt(String videoPrompt) { this.videoPrompt = videoPrompt; }
}
