<template>
  <div class="future-batch-query">
    <el-card>
      <el-form :model="queryForm" label-width="80px">
        <el-form-item label="期货代码">
          <el-input
            v-model="codeInput"
            type="textarea"
            :rows="4"
            placeholder="输入期货代码，每行一个或逗号分隔，如：&#10;IF2401.CFE&#10;IC2401.CFE"
          />
        </el-form-item>
        <el-form-item label="开始日期">
          <el-date-picker
            v-model="queryForm.startDate"
            type="date"
            placeholder="开始日期"
            value-format="YYYYMMDD"
          />
        </el-form-item>
        <el-form-item label="结束日期">
          <el-date-picker
            v-model="queryForm.endDate"
            type="date"
            placeholder="结束日期"
            value-format="YYYYMMDD"
          />
        </el-form-item>
        <el-form-item label="周期">
          <el-select v-model="queryForm.period" style="width: 120px;">
            <el-option label="日线" value="daily" />
            <el-option label="1分钟" value="min1" />
            <el-option label="5分钟" value="min5" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery" :loading="loading">
            <el-icon><Search /></el-icon> 查询
          </el-button>
          <el-button @click="handleExport" :disabled="!hasData">
            <el-icon><Download /></el-icon> 导出
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <el-card class="result-card" v-if="hasData">
      <template #header>
        <span>查询结果</span>
      </template>
      <el-tabs v-model="activeCode">
        <el-tab-pane
          v-for="(data, code) in resultData"
          :key="code"
          :label="code"
          :name="code"
        >
          <el-table :data="data" stripe height="400">
            <el-table-column prop="trade_date" label="日期" width="120" />
            <el-table-column prop="open" label="开盘" :formatter="formatNumber" />
            <el-table-column prop="high" label="最高" :formatter="formatNumber" />
            <el-table-column prop="low" label="最低" :formatter="formatNumber" />
            <el-table-column prop="close" label="收盘" :formatter="formatNumber" />
            <el-table-column prop="volume" label="成交量" />
            <el-table-column prop="amount" label="成交额" :formatter="formatAmount" />
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { batchGetFutureKline } from '@/api/future'

const loading = ref(false)
const codeInput = ref('IF2401.CFE\nIC2401.CFE')
const activeCode = ref('')
const resultData = ref<Record<string, any[]>>({})

const hasData = computed(() => Object.keys(resultData.value).length > 0)

const queryForm = reactive({
  startDate: getDefaultStartDate(),
  endDate: getDefaultEndDate(),
  period: 'daily'
})

function getDefaultStartDate() {
  const date = new Date()
  date.setMonth(date.getMonth() - 3)
  return formatDate(date)
}

function getDefaultEndDate() {
  return formatDate(new Date())
}

function formatDate(date: Date) {
  return date.toISOString().slice(0, 10).replace(/-/g, '')
}

function formatNumber(row: any, column: any, value: number) {
  return value?.toFixed(2) || '-'
}

function formatAmount(row: any, column: any, value: number) {
  if (!value) return '-'
  return (value / 10000).toFixed(2) + '万'
}

const parseCodes = () => {
  return codeInput.value
    .split(/[\n,，]/)
    .map(c => c.trim())
    .filter(c => c.length > 0)
}

const handleQuery = async () => {
  const codes = parseCodes()
  if (codes.length === 0) {
    ElMessage.warning('请输入期货代码')
    return
  }
  
  loading.value = true
  try {
    const res: any = await batchGetFutureKline({
      codes,
      start_date: queryForm.startDate,
      end_date: queryForm.endDate,
      period: queryForm.period
    })
    
    if (res.data) {
      resultData.value = res.data
      activeCode.value = codes[0]
    }
  } catch (error) {
    console.error(error)
    ElMessage.error('查询失败')
  } finally {
    loading.value = false
  }
}

const handleExport = () => {
  let csv = '代码,日期,开盘,最高,最低,收盘,成交量,成交额\n'
  
  for (const [code, data] of Object.entries(resultData.value)) {
    for (const item of data) {
      csv += `${code},${item.trade_date || item.trade_datetime},${item.open},${item.high},${item.low},${item.close},${item.volume},${item.amount}\n`
    }
  }
  
  const blob = new Blob(['\ufeff' + csv], { type: 'text/csv;charset=utf-8;' })
  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = `future_kline_${new Date().toISOString().slice(0, 10)}.csv`
  link.click()
  
  ElMessage.success('导出成功')
}
</script>

<style scoped>
.future-batch-query {
  padding: 10px;
}

.result-card {
  margin-top: 20px;
}
</style>