<template>
  <div class="h-chart-test-container">
    <h2>HChart 组件测试案例</h2>

    <section class="test-section">
      <h3>测试1: 通过 queryParamsName 查询配置（从后端获取配置和数据）</h3>
      <div class="chart-wrapper">
        <HChart
          ref="chart1"
          query-params-name="accountsReceivableChart"
          :fixed-query-form="{ condition: '1=1', dateRange: '2024-01' }"
          service-name="af-his"
          @init="handleChartInit"
          @dataLoaded="handleDataLoaded"
          @error="handleError"
        />
      </div>
      <div class="test-actions">
        <a-button @click="refreshChart1">刷新图表</a-button>
        <a-button @click="reloadChart1">重新加载（更新查询条件）</a-button>
      </div>
    </section>

    <section class="test-section">
      <h3>测试日志</h3>
      <div class="log-container">
        <div v-for="(log, index) in logs" :key="index" class="log-item">
          <span class="log-time">{{ log.time }}</span>
          <span class="log-type" :class="log.type">{{ log.type }}</span>
          <span class="log-message">{{ log.message }}</span>
        </div>
      </div>
      <a-button @click="clearLogs">清空日志</a-button>
    </section>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { message } from 'ant-design-vue'
import HChart from './HChart.vue'

const chart1 = ref(null)

const logs = ref([])

const addLog = (type, messageText) => {
  logs.value.unshift({
    time: new Date().toLocaleTimeString(),
    type,
    message: typeof messageText === 'object' ? JSON.stringify(messageText, null, 2) : messageText
  })
  if (logs.value.length > 50) logs.value.pop()
}

const clearLogs = () => {
  logs.value = []
}

const handleChartInit = (config) => {
  addLog('init', `图表初始化: ${config?.title || '未知'}`)
  message.success(`图表初始化成功: ${config?.title || '未知'}`)
}

const handleDataLoaded = (data) => {
  addLog('dataLoaded', `数据加载完成，共 ${data?.length || 0} 条`)
  console.log('数据加载完成:', data)
}

const handleError = (error) => {
  addLog('error', `错误: ${error?.message || String(error)}`)
  message.error(`图表加载错误: ${error?.message || String(error)}`)
}

const refreshChart1 = () => {
  if (!chart1.value) return
  chart1.value.refresh()
  addLog('action', '刷新图表')
  message.info('正在刷新图表...')
}

const reloadChart1 = () => {
  if (!chart1.value) return
  chart1.value.reload({ condition: '1=1', dateRange: '2024-02' })
  addLog('action', '重新加载图表，更新查询条件')
  message.info('正在重新加载图表...')
}
</script>
