import { useEffect, useState } from 'react';
import { observer } from 'mobx-react';
import { Bullet } from '@ant-design/plots';
import { sortBy, merge } from '../utils/commons';
import { dataFieldAlias } from '../libs/ht';

export default observer((props) => {
  const { dataSource, itemLength, ...extProps } = props;
  // 处理进度图的数据格式, number -> array
  const dataParser = (origin) => {
    const { measureField, rangeField, targetField } = extProps;
    const maxKPI = Math.max(...(origin || []).map((ele) => (ele?.[targetField] || 0)));
    const maxValue = Math.max(...(origin || []).map((ele) => ele[measureField]));
    const _max = Math.max(maxKPI, maxValue);
    const sortData = origin.sort(sortBy(measureField)).slice(-itemLength);
    // 顶格的值定在更远
    const _parseData = sortData?.map((ele) => ({ ...ele, [rangeField]: [0, Math.ceil(_max / 0.9)], [measureField]: [ele[measureField]], [targetField]: (ele?.targetField || 0) }));
    return _parseData;
  };

  const [parseData, setParseData] = useState([]);
  useEffect(() => {
    setParseData(dataParser(dataSource));
    return () => {};
  }, [extProps.measureField, dataSource]);

  const config = merge({
    color: {
      range: [ '#FFF3E1', '#FFF3E1'],
      // range: [ '#FFF3E1', '#FFF3E1', '#FFe0b0', '#bfeec8'], // '#FFbcb8', '#FFe0b0',
      measure: ['#5B8FF9', '#61ddaa'],
      target: '#FF9845',
    },
    label: {
      target: false,
      measure: {
        position: extProps?.layout === 'vertical' ? 'top' : 'right',
      //   style: {
      //     fill: '#063CAA',
      //   },
        formatter: (v) => {
          return dataFieldAlias[extProps.measureField]?.formatter(v[extProps.measureField]) || v;
        }
      },
    },
    xAxis: {
      line: null,
      label: {
        autoHide: false,
        autoRotate: true,
      },
    },
    yAxis: false,
    // 自定义 legend
    legend: {
      custom: true,
      position: 'bottom',
      items: [
        {
          value: '实际',
          name: '实际',
          marker: {
            symbol: 'square',
            style: {
              fill: '#5B8FF9',
              r: 5,
            },
          },
        },
        {
          value: '目标',
          name: '目标',
          marker: {
            symbol: 'line',
            style: {
              stroke: '#FF9845', // '#39a3f4',
              r: 5,
            },
          },
        },
      ],
    },
    // ? 全局的alias不起作用
    tooltip: {
      customItems: (originalItems) => {
        // process originalItems,
        return originalItems.map((ele) => ({ ...ele, value: dataFieldAlias[ele.name]?.formatter(Number(ele.value)), name: dataFieldAlias[ele.name]?.alias || ele.name }));
      },
    },
  }, extProps);
  return (
    <>
      <Bullet {...config} data={parseData} />
    </>
  );
});
