<script setup lang="ts">
import type { Candidate, ScreenerRun } from "../../shared/api/screener";
import MarketEntityLink from "../../shared/market/MarketEntityLink.vue";

defineProps<{ run?: ScreenerRun; locked?: boolean }>();
const emit = defineEmits<{ track: [candidate: Candidate] }>();

function number(value: number | null, digits = 2): string {
  return value === null ? "" : value.toFixed(digits);
}
</script>

<template>
  <section class="card screener-results" :class="{ 'locked-content': locked }" :aria-disabled="locked">
    <header class="card-header">
      <div>
        <h2>候选结果</h2>
        <p v-if="run" class="faint">{{ run.strategy_name }} · {{ run.selection_date }}</p>
      </div>
      <span v-if="run" class="tag">{{ run.items.length }} 只</span>
    </header>
    <div v-if="!run || run.status === 'pending'" class="screener-empty">
      <strong>盘后选股尚未执行</strong>
      <span>当日收盘行情定稿后由后台自动计算并归档。</span>
    </div>
    <div v-else-if="run.status === 'running'" class="screener-empty">
      <strong>正在计算候选结果</strong>
      <span>完成后会自动保存本次结果。</span>
    </div>
    <div v-else-if="run.status === 'data_incomplete'" class="notice notice-warning">
      数据尚不完整：{{ run.missing_fields.join("、") }}
    </div>
    <div v-else-if="run.status === 'failed'" class="notice notice-warning">
      本次计算失败，已隔离该策略，不影响其他策略。{{ run.error_message }}
    </div>
    <div v-else-if="run.status === 'no_signal' || !run.items.length" class="screener-empty">
      <strong>暂无符合条件个股</strong>
      <span>完整数据下无信号会保留为空，不补造候选。</span>
    </div>
    <div v-else class="data-table-wrap">
      <table class="data-table">
        <thead><tr><th>代码</th><th>股票</th><th>行业</th><th class="numeric">收盘价（元）</th><th class="numeric">涨跌幅（%）</th><th class="numeric">综合分</th><th>主要依据</th><th>操作</th></tr></thead>
        <tbody>
          <tr v-for="item in run.items" :key="item.identifier">
            <td class="code-column"><MarketEntityLink :entity="{ entity_type: 'stock', identifier: item.identifier, code: item.code, name: item.name, sector: item.sector || null }" /></td><td>{{ item.name }}</td><td>{{ item.sector }}</td>
            <td class="numeric">{{ number(item.close) }}</td>
            <td class="numeric" :class="{ up: Number(item.pct_chg) > 0, down: Number(item.pct_chg) < 0 }">{{ number(item.pct_chg) }}</td>
            <td class="numeric"><strong>{{ number(item.score_display, 1) }}</strong></td>
            <td class="wide-column">{{ item.reason }}</td>
            <td><button class="btn btn-small" type="button" :disabled="locked" @click="emit('track', item)">加入跟踪</button></td>
          </tr>
        </tbody>
      </table>
    </div>
  </section>
</template>
