<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { listContracts } from '@/api/scores'
import { listCandles, type Candle } from '@/api/candles'
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 loading = ref(false)

async function reload() {
  if (!filter.ts_code) {
    ElMessage.warning('请选择合约')
    return
  }
  loading.value = true
  try {
    const [start, end] = filter.range || []
    candles.value = await listCandles(filter.ts_code, start, end)
  } finally {
    loading.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="合约">
          <el-select
            v-model="filter.ts_code"
            placeholder="选择合约"
            filterable
            :style="{ width: isMobile ? '100%' : '200px' }"
          >
            <el-option v-for="c in contracts" :key="c" :label="c" :value="c" />
          </el-select>
        </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-form-item>
      </el-form>
    </el-card>

    <el-card shadow="never" class="chart-card" v-loading="loading">
      <KLineChart :data="candles" />
    </el-card>
  </div>
</template>

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