<script setup lang="ts">
import {onMounted, onBeforeUnmount, ref} from "vue";
import AudioPlayer from "../../components/common/AudioPlayer.vue";
import {useCheckAll} from "../../components/common/check-all";
import TaskBizStatus from "../../components/common/TaskBizStatus.vue";
import VideoPlayer from "../../components/common/VideoPlayer.vue";
import ServerTaskResultParam from "../../components/Server/ServerTaskResultParam.vue";
import TaskBatchDeleteAction from "../../components/Server/TaskBatchDeleteAction.vue";
import TaskBatchDownloadAction from "../../components/Server/TaskBatchDownloadAction.vue";
import TaskCancelAction from "../../components/Server/TaskCancelAction.vue";
import TaskDeleteAction from "../../components/Server/TaskDeleteAction.vue";
import TaskDownloadAction from "../../components/Server/TaskDownloadAction.vue";
import TaskDuration from "../../components/Server/TaskDuration.vue";
import TaskTitleField from "../../components/Server/TaskTitleField.vue";
import TaskLogButton from "../../components/common/TaskLogButton.vue";
import {TaskRecord, TaskService} from "../../service/TaskService";
import {usePaginate} from "../../hooks/paginate";
import {useTaskChangeRefresh} from "../../hooks/task";
import {useTaskStore} from "../../store/modules/task";
import VideoGenCreate from "./components/VideoGenCreate.vue";
import VideoGenFormViewBody from "./components/VideoGenFormViewBody.vue";
import ServerNameVersion from "../../components/Server/ServerNameVersion.vue";
import TextTruncateView from "../../components/TextTruncateView.vue";

const videoGenCreate = ref<InstanceType<typeof VideoGenCreate> | null>(null);
const taskStore = useTaskStore();

const {page, records, recordsForPage} = usePaginate<TaskRecord>();

const {mergeCheck, isIndeterminate, isAllChecked, onCheckAll, checkRecords} = useCheckAll({
    records: recordsForPage,
});

useTaskChangeRefresh("VideoGen", () => {
    doRefresh();
});

onMounted(() => {
    doRefresh();
});

const doRefresh = async () => {
    // 🔧 核心修复：同时检查内存和数据库的任务状态
    const memoryTasks = taskStore.records.filter(r => r.biz === "VideoGen");
    const dbTasks = await TaskService.list("VideoGen");

    // 用 bizId 匹配任务（bizId 是数据库 id）
    const allTasks = dbTasks.map(dbTask => {
        const memTask = memoryTasks.find(t => t.bizId === String(dbTask.id));

        // 关键逻辑：
        // 1. 如果任务已完成（success/fail），使用数据库的完整数据（包括result）
        // 2. 如果任务还在运行（running/querying），使用内存的最新状态
        if (memTask && (memTask.status === "running" || memTask.status === "querying")) {
            // 任务还在运行，用内存的实时状态，但保留数据库中的其他数据
            return {
                ...dbTask,
                status: memTask.status,
                statusMsg: memTask.msg,
            };
        }

        // 任务已完成或数据库状态更新，直接使用数据库数据
        return dbTask;
    });

    records.value = mergeCheck(allTasks);
};

// 🔧 包装 doRefresh，从 @submitted 事件调用时添加延迟，确保数据库写入完成
const onTaskSubmitted = async () => {
    console.log(`[VideoGen.onTaskSubmitted] 📥 任务已提交，等待100ms让数据库同步...`);
    // 等待100ms确保数据库写入完成
    await new Promise(r => setTimeout(r, 100));
    console.log(`[VideoGen.onTaskSubmitted] 📥 开始刷新任务列表...`);
    await doRefresh();
    console.log(`[VideoGen.onTaskSubmitted] ✓ 任务列表刷新完成`);
};
</script>

<template>
    <div class="video-gen-page p-6">
        <div class="mb-5 flex items-center">
            <div class="flex-grow flex items-end">
                <div class="page-title text-3xl font-bold">{{ $t("数字人合成") }}</div>
                <div class="page-subtitle text-base ml-4">{{ $t("支持音频驱动实现口型替换") }}</div>
            </div>
            <div class="flex items-center">
                <a-tooltip v-if="0" :content="$t('清空历史')" position="right" mini>
                    <a-button class="ml-1">
                        <template #icon>
                            <icon-delete/>
                        </template>
                    </a-button>
                </a-tooltip>
            </div>
        </div>
        <div>
            <VideoGenCreate ref="videoGenCreate" @submitted="onTaskSubmitted"/>
            <div v-if="records.length > 0">
                <div class="rounded-xl shadow border p-4 mt-4 hover:shadow-lg flex items-center">
                    <div class="flex-grow flex items-center">
                        <div class="mr-3">
                            <a-checkbox
                                :model-value="isAllChecked"
                                :indeterminate="isIndeterminate"
                                @change="onCheckAll"
                            >
                                {{ $t("全选") }}
                            </a-checkbox>
                        </div>
                        <TaskBatchDeleteAction :records="checkRecords" @update="doRefresh"/>
                        <TaskBatchDownloadAction :records="checkRecords"/>
                    </div>
                    <div>
                        <a-pagination
                            v-model:current="page"
                            :total="records.length"
                            :page-size="10"
                            show-total
                            simple
                        />
                    </div>
                </div>
                <div v-for="r in recordsForPage" :key="r.id">
                    <div class="rounded-xl shadow border p-4 mt-4 hover:shadow-lg">
                        <div class="flex items-center gap-1">
                            <div class="inline-flex items-start bg-blue-100 rounded-full px-2 leading-8 h-8 mr-2">
                                <div class="mr-2 h-8 pt-0.5">
                                    <a-checkbox v-model="r['_check']"/>
                                </div>
                                <div class="">
                                    <TaskTitleField
                                        :record="r"
                                        @title-click="r['_check'] = !r['_check']"
                                        @update="v => (r.title = v)"
                                    />
                                </div>
                            </div>
                            <div class="flex-grow"></div>
                            <TaskDuration :start="r.startTime" :end="r.endTime"/>
                            <TaskBizStatus :status="r.status" :status-msg="r.statusMsg"/>
                        </div>
                        <div class="mt-3 flex gap-1">
                            <ServerNameVersion :record="r"/>
                            <VideoGenFormViewBody :data="r.modelConfig"/>
                            <ServerTaskResultParam :record="r as any"/>
                        </div>
                        <div class="pt-2 flex">
                            <div class="flex-grow">
                                <div v-if="r.modelConfig.soundType === 'soundGenerate'">
                                    <div class="mb-2">
                                        <a-tag class="rounded-lg">
                                            <i class="iconfont icon-sound w-5"></i>
                                            {{ $t("声音合成") }}
                                        </a-tag>
                                    </div>
                                    <div class="text-display rounded-lg p-3 mb-3">
                                        <TextTruncateView :text="r.modelConfig.soundGenerateText"/>
                                    </div>
                                </div>
                                <div v-if="r.modelConfig.soundType === 'soundCustom'">
                                    <div class="mb-2">
                                        <a-tag class="rounded-lg">
                                            <icon-file/>
                                            {{ $t("本地文件") }}
                                        </a-tag>
                                    </div>
                                    <div class="flex-grow">
                                        <!-- 🔧 只有当文件路径存在时才渲染AudioPlayer，防止加载失败 -->
                                        <AudioPlayer v-if="r.modelConfig.soundCustomFile" :url="`file://${r.modelConfig.soundCustomFile}`"/>
                                        <div v-else class="text-gray-500 text-sm">{{ $t("音频文件路径为空") }}</div>
                                    </div>
                                </div>
                            </div>
                            <div class="flex-shrink-0 ml-8">
                                <div class="video-preview p-2 rounded-lg shadow-lg" v-if="r.result.url">
                                    <div class="w-48 h-48">
                                        <VideoPlayer :key="`video-${r.id}`" :url="'file://' + r.result.url"/>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="pt-4 flex items-center">
                            <div class="text-gray-400 flex-grow">
                                <timeago :datetime="r['createdAt'] * 1000"/>
                            </div>
                            <div class="">
                                <TaskLogButton :record="r"/>
                                <TaskDownloadAction :record="r"/>
                                <TaskDeleteAction :record="r" @update="doRefresh"/>
                                <TaskCancelAction :record="r" @update="doRefresh"/>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <m-empty v-else/>
        </div>
    </div>
</template>

<style scoped>
.video-gen-page {
    background-color: #000000;
    min-height: 100%;
}

.page-title {
    color: #ffffff;
    font-weight: 600;
}

.page-subtitle {
    color: #9ca3af;
}

.text-display {
    background: #1a1a1a;
    border: 1px solid #333;
    color: #e5e7eb;
}

.video-preview {
    background: #1a1a1a;
    border: 1px solid #333;
}

/* 任务卡片深色主题 */
:deep(.rounded-xl.shadow.border) {
    background: #141414;
    border: 1px solid #333;
    box-shadow: none;
    transition: all 0.2s;

    &:hover {
        border-color: #4b5563;
        box-shadow: 0 0 15px rgba(168, 85, 247, 0.1); /* 紫色微光 */
    }

    .bg-blue-100 {
        background: #1a1a1a;
        border: 1px solid #333;
        color: #e5e7eb; /* 确保标题文字变白 */
    }
}

/* 修复复选框文字颜色 */
:deep(.arco-checkbox-label) {
    color: #e5e7eb;
}

/* 修复按钮样式 */
:deep(.arco-btn) {
    background-color: #2a2a2a !important;
    border-color: #333 !important;
    color: #e5e7eb !important;
}

:deep(.arco-btn:hover) {
    background-color: #374151 !important;
    border-color: #4b5563 !important;
    color: #ffffff !important;
}

:deep(.arco-btn-primary) {
    background-color: #a855f7 !important; /* purple-500 */
    border-color: #a855f7 !important;
    color: #ffffff !important;
}

:deep(.arco-btn-primary:hover) {
    background-color: #c084fc !important; /* purple-400 */
    border-color: #c084fc !important;
}
</style>
