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

import { heavenApi, type HeavenReading } from "../../shared/api/heaven";
import { useMarketStore } from "../../shared/stores/market";
import { useUiStore } from "../../shared/stores/ui";
import HexagramGraphic from "./HexagramGraphic.vue";

const props = defineProps<{ disabled: boolean; initialQuery?: string }>();
const emit = defineEmits<{ interpret: [reading: HeavenReading] }>();
const market = useMarketStore();
const ui = useUiStore();
const query = ref("");
const loading = ref(false);
const response = ref<any>(null);
const showChecks = ref(false);
const showManual = ref(false);
const manual = ref<Record<string, string | number>>({});
const result = computed(() => response.value?.result);
const stock = computed(() => result.value?.stock ?? response.value?.stock);
const sector = computed(() => result.value?.sector ?? response.value?.sector);

async function load(withManual = false): Promise<void> {
  if (!query.value.trim() || props.disabled) return;
  loading.value = true;
  try {
    response.value = await heavenApi.trend(
      query.value,
      market.selectedDate,
      withManual ? { sector: manual.value } : {},
    );
    if (!response.value.ready) showChecks.value = true;
  } catch (error) {
    ui.showToast(error instanceof Error ? error.message : "观势数据读取失败");
  } finally {
    loading.value = false;
  }
}

function reading(): HeavenReading {
  return {
    id: response.value.reading_id,
    mode: "trend",
    date: result.value.trade_date,
    subject_key: result.value.stock.identifier,
    result: result.value,
    interpretation: "",
    status: "pending",
    created_at: "",
  };
}

onMounted(() => {
  const initial = props.initialQuery?.trim();
  if (!initial || props.disabled) return;
  query.value = initial;
  void load(false);
});
</script>

<template>
  <section class="heaven-panel trend-panel">
    <div class="card heaven-trend-input">
      <div class="field heaven-stock-field">
        <label for="heaven-stock">股票代码或名称</label>
        <div class="heaven-inline-control">
          <input id="heaven-stock" v-model="query" class="input" placeholder="输入六位代码或股票名称" :disabled="disabled || loading" @keydown.enter="load(false)" />
          <button class="btn btn-primary" type="button" :disabled="disabled || loading || !query.trim()" @click="load(false)">{{ loading ? '载入中' : '载入' }}</button>
        </div>
      </div>
      <p v-if="stock" class="heaven-current-target">当前标的：<strong>{{ stock.name }}</strong>&nbsp;&nbsp;申万二级·<strong>{{ sector?.name || '待核验' }}</strong></p>
    </div>

    <div v-if="loading" class="card heaven-awaiting"><span class="heaven-bagua" aria-hidden="true">☰</span><strong>三才六爻正在取象</strong><p>核验个股、申万二级行业、市场与三大指数</p></div>
    <div v-else-if="!response" class="card heaven-awaiting"><span class="heaven-bagua" aria-hidden="true">☷</span><strong>请输入股票代码或股票名称</strong></div>
    <template v-else-if="response.ready">
      <div class="heaven-trend-grid">
        <article class="card heaven-lines-card">
          <header class="card-header"><h2>三才六爻</h2><span class="tag">{{ result.trade_date }}</span></header>
          <div class="heaven-line-list">
            <div v-for="line in [...result.hexagram.lines].reverse()" :key="line.position" class="heaven-line-row">
              <span>{{ line.position_name }}</span><span>{{ line.talent }}·{{ line.layer }}</span>
              <span class="heaven-line-mini" :class="{ yin: line.value % 2 === 0 }"><i /><i /></span>
              <strong>{{ line.role }}</strong><small class="numeric">{{ (line.score * 100).toFixed(0) }}</small>
            </div>
          </div>
        </article>
        <article class="card heaven-outcome-card">
          <div class="heaven-momentum"><span>势值</span><strong class="numeric">{{ result.momentum_score }}</strong><small>{{ result.momentum_label }}</small></div>
          <HexagramGraphic :hexagram="result.hexagram" />
          <p class="heaven-hex-text">{{ result.hexagram.text }}</p>
          <button class="btn btn-primary" type="button" @click="emit('interpret', reading())">解势</button>
        </article>
      </div>
    </template>
    <div v-else class="card heaven-not-ready"><strong>暂不成卦</strong><p>{{ response.message }}</p></div>

    <section v-if="response" class="card heaven-validation">
      <button class="heaven-section-toggle" type="button" @click="showChecks = !showChecks"><span>六爻数据校验</span><span>{{ showChecks ? '收起' : '展开' }}</span></button>
      <div v-if="showChecks" class="heaven-check-list">
        <div v-for="check in response.checks || result?.checks" :key="check.position" class="heaven-check" :class="check.passed ? 'is-pass' : 'is-fail'">
          <strong>{{ check.position_name }} · {{ check.role }}</strong><span>{{ check.message }}</span><small>{{ check.source === 'manual' ? '用户补录' : check.passed ? '自动通过' : '需要补充' }}</small>
        </div>
        <button v-if="!response.ready" class="btn btn-small" type="button" @click="showManual = !showManual">{{ showManual ? '收起手动补录' : '手动补录客观数据' }}</button>
        <form v-if="showManual" class="heaven-manual-grid" @submit.prevent="load(true)">
          <label class="field"><span class="field-label">行业涨跌 (%)</span><input v-model="manual.change" class="input" type="number" step="0.01" /></label>
          <label class="field"><span class="field-label">上涨 / 下跌成分</span><span class="heaven-dual-input"><input v-model="manual.up_count" class="input" type="number" /><input v-model="manual.down_count" class="input" type="number" /></span></label>
          <label class="field"><span class="field-label">成员总数 / 有效数</span><span class="heaven-dual-input"><input v-model="manual.member_count" class="input" type="number" /><input v-model="manual.quoted_count" class="input" type="number" /></span></label>
          <label class="field"><span class="field-label">覆盖率 (0-1)</span><input v-model="manual.coverage" class="input" type="number" step="0.01" /></label>
          <label class="field"><span class="field-label">成分等权涨跌 (%)</span><input v-model="manual.member_equal_change" class="input" type="number" step="0.01" /></label>
          <label class="field"><span class="field-label">领涨股 / 涨跌</span><span class="heaven-dual-input"><input v-model="manual.leader" class="input" /><input v-model="manual.leading_pct" class="input" type="number" step="0.01" /></span></label>
          <div class="form-actions"><button class="btn btn-primary" type="submit">重新核验并成卦</button><button class="btn" type="button" @click="manual = {}; load(false)">恢复自动数据</button></div>
        </form>
      </div>
    </section>
  </section>
</template>
