import React, { useRef, useEffect, useState, useCallback } from 'react'
import ReactEChartsCore from 'echarts-for-react/lib/core'
import { echarts } from '../echarts'
import { PieChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  LegendScrollComponent,
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
import merge from 'lodash/merge'
import { pieSeriesMapping } from '../preset'
import { defineConfig } from '@/utils/common'
import { genPercentObject } from '@/utils/echarts'
import type { EChartsOption } from 'echarts'
import type { MyEChartProps } from '../types'

// const isSmallScreen = !!(window.screen.width < 576)

// 注册 echarts 组件
echarts.use([
  // charts
  PieChart,
  // components
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  LegendScrollComponent,
  // render
  CanvasRenderer,
])

function genDefaultOptions(series: []): EChartsOption {
  const mapping = genPercentObject(series, 'name', 'value')
  const options: EChartsOption = {
    title: {
      show: false,
    },
    legend: {
      type: 'scroll',
      top: 10,
      orient: 'vertical',
      left: 'left',
      textStyle: {
        fontSize: 10,
      },
      formatter: (name: string) => {
        const mapObj = mapping[name]
        if (!mapObj) {
          return name
        }
        return `${name} | ${mapObj.percent}% | ${mapObj.value}`
      },
    },
    tooltip: {
      show: true,
      trigger: 'item',
      padding: [8, 12],
      appendToBody: true,
      textStyle: {
        fontSize: 12,
        lineHeight: 18,
        fontFamily: `'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande',
        'Lucida Sans Unicode', Geneva, Verdana, sans-serif`,
      },
      formatter: (params) => {
        const { name, seriesName, marker, value, percent } = params as any
        return `<div>
        <div style="margin-bottom: 0.5rem;">${seriesName}</div>
        <div style="display: flex; justify-content: space-between">
          <span style="padding-right: 1rem;">${marker} ${name}</span>
          <strong>
            <span>${value}</span>
            <span style="padding-left: 0.5rem;">${percent}%</span>
          </strong>
        </div>
        </div>`
      },
    },
  }
  return options
}

const YaPie: React.FC<MyEChartProps> = (props) => {
  const {
    opts = {},
    series = [],
    containerStyle = {},
    mode = 'light',
    onChartReady,
    onClick,
    loading = false,
  } = props
  const chartRef = useRef<any>(null)
  const [chartOptions, setChartOptions] = useState<any>({})

  const genOptions = useCallback(() => {
    const seriesData = (series && series[0] && series[0].data) || []
    return genDefaultOptions(seriesData)
  }, [series])

  useEffect(() => {
    if (chartRef && chartRef.current) {
      // get echarts instance
      const ins = chartRef.current.getEchartsInstance()
      // click
      ins.on('click', (params: any) => onClick && onClick(params))
    }
  }, [])

  useEffect(() => {
    if (!!series && Object.keys(series).length) {
      const defaultStyleOptions = genOptions()
      const staticsOpts = merge(defaultStyleOptions, opts)
      const initOptions = {
        ...staticsOpts,
        series,
      }
      setChartOptions(initOptions)
    }
  }, [series])

  return (
    <>
      <ReactEChartsCore
        ref={chartRef}
        style={containerStyle}
        showLoading={loading}
        echarts={echarts}
        option={chartOptions}
        notMerge={true}
        lazyUpdate={true}
        theme={mode}
        onChartReady={(instance) => onChartReady && onChartReady(instance, chartOptions)}
      />
    </>
  )
}

// Used to render series
export function genPieSeriesOps(type: 'default' | 'circle' = 'default') {
  return defineConfig({
    type: 'pie',
    avoidLabelOverlap: false,
    ...pieSeriesMapping[type],
  })
}

export default YaPie
