<template>
  <div class="index-query">
    <el-card>
      <el-form :model="queryForm" inline>
        <el-form-item label="指数代码">
          <el-input v-model="queryForm.code" placeholder="如: BK0001, BK0002" style="width: 150px;" />
        </el-form-item>
        <el-form-item label="开始日期">
          <el-date-picker
            v-model="queryForm.startDate"
            type="date"
            placeholder="开始日期"
            value-format="YYYYMMDD"
            style="width: 140px;"
          />
        </el-form-item>
        <el-form-item label="结束日期">
          <el-date-picker
            v-model="queryForm.endDate"
            type="date"
            placeholder="结束日期"
            value-format="YYYYMMDD"
            style="width: 140px;"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery" :loading="loading">
            <el-icon><Search /></el-icon> 查询
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <el-card class="basic-card" v-if="indexBasic">
      <template #header>
        <span>指数基础信息</span>
      </template>
      <el-descriptions :column="3" border>
        <el-descriptions-item label="指数代码">{{ indexBasic.code }}</el-descriptions-item>
        <el-descriptions-item label="指数名称">{{ indexBasic.name }}</el-descriptions-item>
        <el-descriptions-item label="成分个数">{{ indexBasic.component_count }}</el-descriptions-item>
      </el-descriptions>
    </el-card>
    
    <el-card class="chart-card" v-if="chartData.categoryData.length > 0">
      <template #header>
        <span>指数K线图 - {{ indexBasic?.name || queryForm.code }}</span>
      </template>
      <div ref="chartRef" class="kline-chart"></div>
    </el-card>
    
    <el-card class="data-card" v-if="tableData.length > 0">
      <template #header>
        <span>交易数据列表</span>
      </template>
      <el-table :data="tableData" stripe height="300">
        <el-table-column prop="trade_date" label="日期" width="120" />
        <el-table-column prop="open" label="开盘" :formatter="formatNumber" />
        <el-table-column prop="close" label="收盘" :formatter="formatNumber" />
        <el-table-column prop="high" label="最高" :formatter="formatNumber" />
        <el-table-column prop="low" label="最低" :formatter="formatNumber" />
        <el-table-column prop="change_pct" label="涨跌幅%">
          <template #default="{ row }">
            <el-tag :type="row.change_pct >= 0 ? 'success' : 'danger'" size="small">
              {{ row.change_pct?.toFixed(2) || '-' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="volume" label="成交量" :formatter="formatVolume" />
        <el-table-column prop="amount" label="成交额(百万)" :formatter="formatNumber" />
        <el-table-column prop="up_count" label="上涨家数" width="90" />
        <el-table-column prop="down_count" label="下跌家数" width="90" />
        <el-table-column prop="limit_up_count" label="涨停" width="70" />
        <el-table-column prop="limit_down_count" label="跌停" width="70" />
        <el-table-column prop="pe_ratio" label="市盈率" :formatter="formatNumber" />
        <el-table-column label="新高/新低" width="90">
          <template #default="{ row }">
            <el-tag v-if="row.is_new_high" type="success" size="small">新高</el-tag>
            <el-tag v-if="row.is_new_low" type="danger" size="small">新低</el-tag>
            <span v-if="!row.is_new_high && !row.is_new_low">-</span>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import { getIndexChartData, getIndexTradeData } from '@/api/index'

const loading = ref(false)
const chartRef = ref<HTMLElement>()
let chartInstance: echarts.ECharts | null = null

const queryForm = reactive({
  code: 'BK0001',
  startDate: getDefaultStartDate(),
  endDate: getDefaultEndDate()
})

const indexBasic = ref<any>(null)
const chartData = reactive({
  categoryData: [] as string[],
  values: [] as number[][],
  volumes: [] as number[][]
})

const tableData = ref<any[]>([])

function getDefaultStartDate() {
  const date = new Date()
  date.setMonth(date.getMonth() - 6)
  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 formatVolume(row: any, column: any, value: number) {
  if (!value) return '-'
  if (value >= 100000000) {
    return (value / 100000000).toFixed(2) + '亿'
  }
  if (value >= 10000) {
    return (value / 10000).toFixed(2) + '万'
  }
  return value.toString()
}

const handleQuery = async () => {
  if (!queryForm.code) {
    ElMessage.warning('请输入指数代码')
    return
  }
  
  loading.value = true
  try {
    const res: any = await getIndexChartData(queryForm.code, {
      start_date: queryForm.startDate,
      end_date: queryForm.endDate
    })
    
    if (res.data) {
      indexBasic.value = {
        code: res.data.code,
        name: res.data.name,
        component_count: res.data.component_count
      }
      
      chartData.categoryData = res.data.categoryData || []
      chartData.values = res.data.values || []
      chartData.volumes = res.data.volumes || []
      
      nextTick(() => {
        renderChart()
      })
    }
    
    const tradeRes: any = await getIndexTradeData({
      codes: queryForm.code,
      start_date: queryForm.startDate,
      end_date: queryForm.endDate
    })
    
    if (tradeRes.data && tradeRes.data[queryForm.code]) {
      const tradeData = tradeRes.data[queryForm.code]
      indexBasic.value = tradeData.basic || indexBasic.value
      tableData.value = tradeData.trades || []
    }
  } catch (error) {
    console.error(error)
    ElMessage.error('查询失败')
  } finally {
    loading.value = false
  }
}

const renderChart = () => {
  if (!chartRef.value) return
  
  if (chartInstance) {
    chartInstance.dispose()
  }
  
  chartInstance = echarts.init(chartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'cross' }
    },
    grid: [
      { left: '10%', right: '8%', height: '50%' },
      { left: '10%', right: '8%', top: '68%', height: '16%' }
    ],
    xAxis: [
      {
        type: 'category',
        data: chartData.categoryData,
        scale: true,
        boundaryGap: false,
        axisLine: { onZero: false },
        splitLine: { show: false },
        min: 'dataMin',
        max: 'dataMax'
      },
      {
        type: 'category',
        gridIndex: 1,
        data: chartData.categoryData,
        scale: true,
        boundaryGap: false,
        axisLine: { onZero: false },
        axisTick: { show: false },
        splitLine: { show: false },
        axisLabel: { show: false },
        min: 'dataMin',
        max: 'dataMax'
      }
    ],
    yAxis: [
      {
        scale: true,
        splitArea: { show: true }
      },
      {
        scale: true,
        gridIndex: 1,
        splitNumber: 2,
        axisLabel: { show: false },
        axisLine: { show: false },
        axisTick: { show: false },
        splitLine: { show: false }
      }
    ],
    dataZoom: [
      { type: 'inside', xAxisIndex: [0, 1], start: 50, end: 100 },
      { show: true, xAxisIndex: [0, 1], type: 'slider', top: '85%', start: 50, end: 100 }
    ],
    series: [
      {
        name: 'K线',
        type: 'candlestick',
        data: chartData.values,
        itemStyle: {
          color: '#ef232a',
          color0: '#14b143',
          borderColor: '#ef232a',
          borderColor0: '#14b143'
        }
      },
      {
        name: '成交量',
        type: 'bar',
        xAxisIndex: 1,
        yAxisIndex: 1,
        data: chartData.volumes
      }
    ]
  }
  
  chartInstance.setOption(option)
}

window.addEventListener('resize', () => {
  chartInstance?.resize()
})
</script>

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

.basic-card {
  margin-top: 20px;
}

.chart-card {
  margin-top: 20px;
}

.kline-chart {
  width: 100%;
  height: 400px;
}

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