<template>
  <view class="page result-page">
    <text class="page-title">视频结果</text>
    <text class="page-subtitle">{{ project?.name || project?.title || "视频项目" }}</text>

    <VideoPreview :src="videoUrl" class="result-preview" />

    <view class="result-info panel">
      <text class="result-info__title">制作摘要</text>
      <view class="result-info__row">
        <text>当前状态</text>
        <text>{{ statusText(run?.status) }}</text>
      </view>
      <view class="result-info__row">
        <text>Agent 步骤</text>
        <text>{{ run?.steps?.length || 0 }} 个</text>
      </view>
      <view class="result-info__row">
        <text>视频任务</text>
        <text>{{ succeededVideoCount }}/{{ videoTasks.length }} 完成</text>
      </view>
      <view v-if="assemblyStatus" class="result-info__row">
        <text>合成状态</text>
        <text>{{ assemblyStatus }}</text>
      </view>
      <view class="result-info__row result-info__row--goal">
        <text>制作目标</text>
        <text>{{ run?.goal || project?.description || "暂无" }}</text>
      </view>
    </view>

    <button class="secondary-button result-back" @tap="backToProgress">回到进度</button>
  </view>
</template>

<script setup lang="ts">
import { computed, ref } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import VideoPreview from "@/components/VideoPreview.vue";
import { getLatestRun } from "@/api/agent";
import { getProject } from "@/api/projects";
import { getAssemblyTask, listVideoTasks } from "@/api/video";
import type { AgentRun, AiTask, AssemblyTask, ProjectDetail } from "@/types/api";
import { statusText } from "@/utils/format";

const projectId = ref("");
const project = ref<ProjectDetail | null>(null);
const run = ref<AgentRun | null>(null);
const videoUrl = ref("");
const videoTasks = ref<AiTask[]>([]);
const assemblies = ref<AssemblyTask[]>([]);

const succeededVideoCount = computed(() => videoTasks.value.filter((task) => task.status === "succeeded").length);
const assemblyStatus = computed(() => {
  if (!assemblies.value.length) return "";
  const succeeded = assemblies.value.filter((task) => task.status === "succeeded").length;
  return `${succeeded}/${assemblies.value.length} 完成`;
});

onLoad(async (query) => {
  projectId.value = String(query?.projectId || "");
  if (!projectId.value) return;
  await loadResult();
});

async function loadResult() {
  try {
    const [projectResult, runResult, taskResult] = await Promise.all([
      getProject(projectId.value),
      getLatestRun(projectId.value),
      listVideoTasks(projectId.value)
    ]);
    project.value = projectResult;
    run.value = runResult;
    videoTasks.value = taskResult || [];
    await loadAssemblies();
    videoUrl.value = pickBestVideoUrl();
  } catch (error) {
    uni.showToast({ title: error instanceof Error ? error.message : "结果读取失败", icon: "none" });
  }
}

async function loadAssemblies() {
  const episodeIds = Array.from(
    new Set(videoTasks.value.map((task) => task.episodeId).filter((episodeId): episodeId is string | number => Boolean(episodeId)))
  );
  const results = await Promise.all(episodeIds.map((episodeId) => getAssemblyTask(projectId.value, episodeId).catch(() => null)));
  assemblies.value = results.filter((task): task is AssemblyTask => Boolean(task));
}

function pickBestVideoUrl() {
  const assembly = assemblies.value.find((task) => task.status === "succeeded" && task.downloadUrl);
  if (assembly?.downloadUrl) return assembly.downloadUrl;

  const shot = videoTasks.value.find((task) => task.status === "succeeded" && task.resultVideoUrl);
  return shot?.resultVideoUrl || "";
}

function backToProgress() {
  uni.navigateTo({ url: `/pages/project-progress/index?projectId=${projectId.value}` });
}
</script>

<style scoped lang="scss">
.result-preview {
  margin-top: 34rpx;
}

.result-info {
  margin-top: 24rpx;
  padding: 30rpx;
}

.result-info__title {
  display: block;
  margin-bottom: 16rpx;
  color: #101828;
  font-size: 31rpx;
  font-weight: 840;
}

.result-info__row {
  display: flex;
  justify-content: space-between;
  gap: 28rpx;
  padding: 20rpx 0;
  border-top: 1rpx solid #eef1f6;
  color: #475467;
  font-size: 25rpx;
  line-height: 1.5;
}

.result-info__row text:last-child {
  flex: 1;
  color: #101828;
  text-align: right;
}

.result-info__row--goal {
  align-items: flex-start;
}

.result-back {
  margin-top: 26rpx;
}
</style>
