import BoxContent from '@/components/Common/BoxContent'
import { Pie, measureTextWidth } from '@ant-design/plots'
import React, { useState, useRef, useEffect } from 'react';
import './index.less'

function renderStatistic(containerWidth: any, text: any, style: any) {
  const { width: textWidth, height: textHeight } = measureTextWidth(text, style)
  const R = containerWidth / 2 // r^2 = (w / 2)^2 + (h - offsetY)^2

  let scale = 1

  if (containerWidth < textWidth) {
    scale = Math.min(Math.sqrt(Math.abs(Math.pow(R, 2) / (Math.pow(textWidth / 2, 2) + Math.pow(textHeight, 2)))), 1)
  }

  const textStyleStr = `width:${containerWidth}px;`
  return `<div style="${textStyleStr};font-size:${scale}em;line-height:${scale < 1 ? 1 : 'inherit'};">${text}</div>`
}

const data = [
  {
    type: 'MPV',
    value: 0
  },
  {
    type: 'SUV',
    value: 0
  },
  {
    type: '轿车',
    value: 0
  },
]
const config = {
  appendPadding: 10,
  data,
  angleField: 'value',
  colorField: 'type',
  radius: 1,
  innerRadius: 0.7,
  legend: {
    position: 'bottom'
  },
  meta: {
    value: {
      formatter: (v: any) => `${v}`
    }
  },
  label: {
    type: 'inner',
    offset: '-50%',
    style: {
      textAlign: 'center',
      color: '#333'
    },
    autoRotate: false,
    content: '{value}'
  },
  statistic: {
    title: {
      offsetY: -4,
      style: {
        color: '#333'
      },
      customHtml: (container: any, view: any, datum: any) => {
        const { width, height } = container.getBoundingClientRect()
        const d = Math.sqrt(Math.pow(width / 2, 2) + Math.pow(height / 2, 2))
        const text = datum ? datum.type : '总计'
        return renderStatistic(d, text, {
          fontSize: 16
        })
      }
    },
    content: {
      offsetY: 4,
      style: {
        fontSize: '16px',
        color: '#fff'
      },
      customHtml: (container: any, view: any, datum: any, data: any) => {
        const { width } = container.getBoundingClientRect()
        const text = datum ? `${datum.value}` : `${data.reduce((r: any, d: any) => r + d.value, 0)}`
        return renderStatistic(width, text, {
          fontSize: 16
        })
      }
    },

  },
  // 添加 中心统计文本 交互
  interactions: [
    {
      type: 'element-selected',
    },
    {
      type: 'element-active',
    },
  ],
} as any

const DemoPie = (props: any) => {

  const [options, setOptions] = useState<any>(config)

  useEffect(() => {
    if (props.data) {
      console.log(props.data);

      let obj = options
      obj.data = props.data
      setOptions({ ...obj })
    }
  }, [props.data]);


  return (
    <>
      <BoxContent {...props}>
        <div id="Pie">
          <Pie className="Pie" {...options} />
        </div>
      </BoxContent>
    </>
  )
}
export default React.memo(DemoPie)
