<script setup lang="ts">
import { computed, ref, watch } from "vue";

import type { Candidate, ScreenerRun, ScreenerStrategy } from "../../shared/api/screener";
import CandidateTable from "./CandidateTable.vue";

const props = defineProps<{ strategies: ScreenerStrategy[]; runs: ScreenerRun[]; locked: boolean }>();
const emit = defineEmits<{ track: [run: ScreenerRun, candidate: Candidate] }>();
const selected = ref(props.runs[0]?.strategy_id ?? props.strategies[0]?.id ?? "");
const run = computed(() => props.runs.find((item) => item.strategy_id === selected.value));
const strategy = computed(() => props.strategies.find((item) => item.id === (run.value?.strategy_id ?? selected.value)));
const runState = computed<"idle" | "running" | "failed" | "completed">(() => {
  if (!run.value || run.value.status === "pending") return "idle";
  if (run.value.status === "running") return "running";
  if (run.value.status === "failed") return "failed";
  return "completed";
});
const runStateLabel = computed(() => ({
  idle: "未执行",
  running: "执行中",
  failed: "失败",
  completed: "已完成",
})[runState.value]);

watch(
  () => props.runs,
  (runs) => {
    if (!runs.some((item) => item.strategy_id === selected.value)) {
      selected.value = runs[0]?.strategy_id ?? props.strategies[0]?.id ?? "";
    }
  },
);
</script>

<template>
  <section class="stage-overview card" :class="{ 'locked-content': locked }" :aria-disabled="locked">
    <header class="stage-heading">
      <div><span>当前阶段自动候选</span><strong>{{ strategy?.display_name ?? "等待盘后判定" }}</strong></div>
      <p>{{ strategy?.description ?? "每日收盘数据定稿后自动生成，结果允许为空。" }}</p>
      <span class="tag" :class="{ warning: runState === 'failed' }">{{ runStateLabel }}</span>
    </header>
    <div class="stage-flow" aria-label="自动选股流程">
      <span :class="{ done: runState !== 'idle' }">阶段识别</span><i></i>
      <span :class="{ done: runState !== 'idle' }">策略匹配</span><i></i>
      <span :class="{ done: runState === 'running' || runState === 'completed' }">自动计算</span><i></i>
      <span :class="{ done: runState === 'completed' }">结果归档</span>
    </div>
    <nav v-if="runs.length > 1" class="stage-run-tabs" aria-label="当日阶段策略">
      <button v-for="item in runs" :key="item.id" type="button" :class="{ active: selected === item.strategy_id }" @click="selected = item.strategy_id">{{ item.strategy_name }}</button>
    </nav>
  </section>
  <CandidateTable :run="run" :locked="locked" @track="(candidate) => run && emit('track', run, candidate)" />
</template>
