<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { listContracts } from '@/api/scores'
import { listCandles, type Candle } from '@/api/candles'
import { listScores, type Score } from '@/api/scores'
import { runFull, type RunFullResponse } from '@/api/run'
import KLineChart from '@/components/KLineChart.vue'
import { useMobile } from '@/composables/useMobile'

const { isMobile } = useMobile()

const filter = reactive<{ ts_code: string; range: [string, string] | [] }>({
  ts_code: '',
  range: [],
})

const contracts = ref<string[]>([])
const candles = ref<Candle[]>([])
const scores = ref<Score[]>([])
const loading = ref(false)
const fullLoading = ref(false)
const fullResult = ref<RunFullResponse | null>(null)

async function reload() {
  if (!filter.ts_code) {
    ElMessage.warning('请选择合约')
    return
  }
  loading.value = true
  try {
    const [start, end] = filter.range || []
    const [candleData, scoreData] = await Promise.all([
      listCandles(filter.ts_code, start, end),
      listScores({ ts_code: filter.ts_code, start, end, limit: 1000 }),
    ])
    candles.value = candleData
    scores.value = scoreData
  } finally {
    loading.value = false
  }
}

async function handleFetchAndScore() {
  if (!filter.ts_code) {
    ElMessage.warning('请输入或选择合约')
    return
  }

  try {
    await ElMessageBox.confirm(
      `即将拉取 ${filter.ts_code} 的全部历史数据并逐日打分，这可能需要一些时间。`,
      '拉取并打分',
      { confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning' },
    )
  } catch {
    return
  }

  fullLoading.value = true
  fullResult.value = null
  try {
    const resp = await runFull({ ts_code: filter.ts_code })
    fullResult.value = resp
    ElMessage.success(`完成: ${resp.scored_count} 天已打分, ${resp.skipped_count} 天跳过`)
    await reload()
  } catch (err: any) {
    const msg = err?.response?.data?.error || err.message || '请求失败'
    ElMessage.error(msg)
  } finally {
    fullLoading.value = false
  }
}

onMounted(async () => {
  contracts.value = await listContracts().catch(() => [])
  if (contracts.value.length > 0) {
    filter.ts_code = contracts.value[0]
    await reload()
  }
})
</script>

<template>
  <div class="page">
    <el-card shadow="never" class="filter-card">
      <el-form :inline="!isMobile">
        <el-form-item label="合约">
          <div style="display: flex; gap: 8px;">
            <el-input
              v-model="filter.ts_code"
              placeholder="输入合约代码如 FG2509"
              clearable
              :style="{ width: isMobile ? '100%' : '200px' }"
            />
            <el-select
              v-model="filter.ts_code"
              placeholder="已存合约"
              clearable
              style="width: 120px"
            >
              <el-option v-for="c in contracts" :key="c" :label="c" :value="c" />
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="日期">
          <el-date-picker
            v-model="filter.range"
            type="daterange"
            value-format="YYYYMMDD"
            range-separator="→"
            start-placeholder="起"
            end-placeholder="止"
            :style="{ width: isMobile ? '100%' : 'auto' }"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="loading" @click="reload">刷新</el-button>
          <el-button type="warning" :loading="fullLoading" @click="handleFetchAndScore">
            拉取并打分
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card v-if="fullResult" shadow="never" class="result-card">
      <el-descriptions :column="isMobile ? 2 : 4" border>
        <el-descriptions-item label="合约">{{ fullResult.ts_code }}</el-descriptions-item>
        <el-descriptions-item label="总天数">{{ fullResult.total_days }}</el-descriptions-item>
        <el-descriptions-item label="已打分">{{ fullResult.scored_count }}</el-descriptions-item>
        <el-descriptions-item label="跳过">{{ fullResult.skipped_count }}</el-descriptions-item>
      </el-descriptions>
    </el-card>

    <el-card shadow="never" class="chart-card" v-loading="loading">
      <KLineChart
        :data="candles"
        :scores="scores.map((s) => ({ trade_date: s.trade_date, composite: s.composite }))"
      />
    </el-card>
  </div>
</template>

<style scoped>
.page {
  display: flex;
  flex-direction: column;
  gap: 12px;
}
.filter-card :deep(.el-card__body) {
  padding: 12px 16px;
}
.result-card :deep(.el-card__body) {
  padding: 12px 16px;
}
.chart-card :deep(.el-card__body) {
  padding: 8px;
}
</style>
