export const allowedChartSpans = [12, 6, 4]

export function isChartDefinition(definition) {
  return definition?.kind === 'chart'
}

export function buildDefaultChartInstance(definition, id) {
  const chartType = definition?.chartType || 'line'
  return {
    id,
    blockCode: definition.code,
    name: definition.name || definition.code,
    span: allowedChartSpans.includes(definition.defaultSpan) ? definition.defaultSpan : 12,
    config: {},
    dataset: {
      schema: definition.datasetSchema || 'single-table-aggregate-v1',
      table: '',
      dimension: chartType === 'metric' ? null : { field: '', timeUnit: '' },
      metrics: [{
        field: '',
        aggregate: chartType === 'metric' ? 'count' : 'sum',
        alias: 'metric1',
        label: '指标 1'
      }],
      filters: [],
      dateRange: null,
      sort: chartType === 'metric' ? null : { by: 'dimension', order: 'asc' },
      limit: chartType === 'pie' ? 10 : chartType === 'bar' ? 20 : chartType === 'metric' ? 1 : 100
    },
    display: {
      showTitle: true,
      showLegend: chartType !== 'metric',
      emptyText: '暂无数据',
      smooth: chartType === 'line',
      donut: chartType === 'pie',
      horizontal: false,
      stacked: false
    }
  }
}

export function updateChartDataset(block, dataset) {
  return { ...block, dataset: structuredClone(dataset || {}) }
}

export function updateChartDisplay(block, display) {
  return { ...block, display: structuredClone(display || {}) }
}

export function validateChartInstance(definition, block, tables) {
  const errors = []
  const dataset = block?.dataset || {}
  const table = tables.find((item) => item.tableName === dataset.table)
  if (!table) {
    errors.push({ key: 'table', message: '请选择数据表' })
  }
  if (definition?.chartType !== 'metric' && !dataset.dimension?.field) {
    errors.push({ key: 'dimension.field', message: '请选择维度字段' })
  }
  if (!Array.isArray(dataset.metrics)
    || !dataset.metrics.length
    || dataset.metrics.some((item) => !item.field)) {
    errors.push({ key: 'metrics', message: '请配置指标字段' })
  }
  return errors
}

export function sampleChartData(definition) {
  if (definition?.chartType === 'metric') {
    return { dimensions: [], series: [], summary: { value: 86420, count: 328 } }
  }
  return {
    dimensions: [
      { key: 'A', label: 'A' },
      { key: 'B', label: 'B' },
      { key: 'C', label: 'C' },
      { key: 'D', label: 'D' }
    ],
    series: [{ key: 'metric1', name: '指标 1', values: [32, 51, 46, 78] }],
    summary: { value: 207, count: 4 }
  }
}

export function buildChartOption(definition, block, data = sampleChartData(definition)) {
  const labels = data.dimensions.map((item) => item.label)
  const sourceSeries = data.series || []
  if (definition?.chartType === 'pie') {
    const values = sourceSeries[0]?.values || []
    return {
      tooltip: { trigger: 'item' },
      legend: { show: block?.display?.showLegend !== false },
      series: [{
        type: 'pie',
        radius: block?.display?.donut ? ['45%', '70%'] : '70%',
        label: { show: block?.display?.showLabel !== false },
        data: labels.map((name, index) => ({ name, value: values[index] ?? 0 }))
      }]
    }
  }

  const horizontal = definition?.chartType === 'bar' && block?.display?.horizontal
  const series = sourceSeries.map((item) => ({
    name: item.name,
    type: definition?.chartType === 'bar' ? 'bar' : 'line',
    smooth: definition?.chartType === 'line' && Boolean(block?.display?.smooth),
    stack: definition?.chartType === 'bar' && block?.display?.stacked ? 'total' : undefined,
    areaStyle: definition?.chartType === 'line' && block?.display?.area ? {} : undefined,
    data: item.values || []
  }))
  return {
    tooltip: { trigger: 'axis' },
    legend: { show: block?.display?.showLegend !== false },
    xAxis: horizontal ? { type: 'value' } : { type: 'category', data: labels },
    yAxis: horizontal ? { type: 'category', data: labels } : { type: 'value' },
    series
  }
}
