/**
 * useECharts Composable
 *
 * 封装 ECharts 初始化、更新、销毁等操作
 */

import { ref, onMounted, onBeforeUnmount, watch, nextTick } from 'vue'
import * as echarts from 'echarts'
import type { EChartOption, ECharts } from 'echarts'
import { resizeChart } from '@/utils/echarts'

/**
 * 使用 ECharts 的 Composable
 *
 * @param chartRef 图表容器引用
 * @param theme 图表主题
 */
export function useECharts(
  chartRef: Ref<HTMLElement | null>,
  theme?: string | object
) {
  const chart = ref<ECharts | null>(null)
  const loading = ref(false)
  const isReady = ref(false)

  /**
   * 初始化图表
   */
  const initChart = () => {
    if (!chartRef.value) {
      console.warn('[useECharts] Chart container not found')
      return
    }

    try {
      // 销毁已存在的图表实例
      if (chart.value) {
        chart.value.dispose()
      }

      // 创建新实例
      chart.value = echarts.init(chartRef.value, theme)
      isReady.value = true

      console.log('[useECharts] Chart initialized successfully')
    } catch (error) {
      console.error('[useECharts] Failed to initialize chart:', error)
      isReady.value = false
    }
  }

  /**
   * 设置图表配置
   */
  const setOption = (option: EChartOption, notMerge?: boolean, lazyUpdate?: boolean) => {
    if (!chart.value || !isReady.value) {
      console.warn('[useECharts] Chart not ready, skipping setOption')
      return
    }

    try {
      chart.value.setOption(option, notMerge, lazyUpdate)
      console.log('[useECharts] Option set successfully')
    } catch (error) {
      console.error('[useECharts] Failed to set option:', error)
    }
  }

  /**
   * 显示加载动画
   */
  const showLoading = (config?: {
    text?: string
    color?: string
    textColor?: string
    maskColor?: string
  }) => {
    if (!chart.value) return

    loading.value = true
    chart.value.showLoading('default', {
      text: config?.text || '加载中...',
      color: config?.color || '#475569',
      textColor: config?.textColor || '#1e293b',
      maskColor: config?.maskColor || 'rgba(255, 255, 255, 0.8)',
      zlevel: 0,
    })
  }

  /**
   * 隐藏加载动画
   */
  const hideLoading = () => {
    if (!chart.value) return

    loading.value = false
    chart.value.hideLoading()
  }

  /**
   * 调整图表尺寸
   */
  const resize = (delay?: number) => {
    if (!chart.value) return

    resizeChart(chart.value, delay)
  }

  /**
   * 销毁图表
   */
  const dispose = () => {
    if (chart.value) {
      chart.value.dispose()
      chart.value = null
      isReady.value = false
      console.log('[useECharts] Chart disposed')
    }
  }

  /**
   * 清空图表
   */
  const clear = () => {
    if (chart.value) {
      chart.value.clear()
      console.log('[useECharts] Chart cleared')
    }
  }

  /**
   * 获取图表实例
   */
  const getInstance = () => {
    return chart.value
  }

  /**
   * 绑定图表事件
   */
  const on = (eventName: string, handler: Function) => {
    if (!chart.value) return

    chart.value.on(eventName, handler)
  }

  /**
   * 解绑图表事件
   */
  const off = (eventName: string, handler?: Function) => {
    if (!chart.value) return

    chart.value.off(eventName, handler)
  }

  /**
   * 导出图表图片
   */
  const getDataURL = (opts?: {
    type?: 'png' | 'jpeg' | 'svg'
    pixelRatio?: number
    backgroundColor?: string
  }) => {
    if (!chart.value) return null

    return chart.value.getDataURL({
      type: opts?.type || 'png',
      pixelRatio: opts?.pixelRatio || 1,
      backgroundColor: opts?.backgroundColor || '#fff',
    })
  }

  /**
   * 监听窗口大小变化
   */
  const handleResize = () => {
    resize()
  }

  // 初始化
  onMounted(() => {
    nextTick(() => {
      initChart()
      window.addEventListener('resize', handleResize)
    })
  })

  // 清理
  onBeforeUnmount(() => {
    window.removeEventListener('resize', handleResize)
    dispose()
  })

  return {
    chart,
    loading,
    isReady,
    initChart,
    setOption,
    showLoading,
    hideLoading,
    resize,
    dispose,
    clear,
    getInstance,
    on,
    off,
    getDataURL,
  }
}
