function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
import { useEffect, useRef } from 'react';
import styles from "./index.module.less";
// 防抖函数
import { jsx as _jsx } from "react/jsx-runtime";
function debounce(fn, delay) {
  var handle = null;
  return function () {
    var _this = this;
    for (var _len = arguments.length, e = new Array(_len), _key = 0; _key < _len; _key++) {
      e[_key] = arguments[_key];
    }
    // 取消之前的延时调用
    clearTimeout(handle);
    handle = setTimeout(function () {
      fn.call.apply(fn, [_this].concat(e));
    }, delay);
  };
}
function PieChart(props) {
  var chartRef = useRef(null);
  var divRef = useRef(null);
  useEffect(function () {
    var chartInstance = echarts.init(chartRef.current);
    function getParametricEquation(startRatio, endRatio, isSelected, isHovered, k, height) {
      // 计算
      var midRatio = (startRatio + endRatio) / 2;
      var startRadian = startRatio * Math.PI * 2;
      var endRadian = endRatio * Math.PI * 2;
      var midRadian = midRatio * Math.PI * 2;

      // 如果只有一个扇形，则不实现选中效果。
      if (startRatio === 0 && endRatio === 1) {
        isSelected = false;
      }

      // 通过扇形内径/外径的值，换算出辅助参数 k（默认值 1/3）
      k = typeof k !== 'undefined' ? k : 1 / 3;

      // 计算选中效果分别在 x 轴、y 轴方向上的位移（未选中，则位移均为 0）
      var offsetX = isSelected ? Math.cos(midRadian) * 0.1 : 0;
      var offsetY = isSelected ? Math.sin(midRadian) * 0.1 : 0;

      // 计算高亮效果的放大比例（未高亮，则比例为 1）
      var hoverRate = isHovered ? 1.05 : 1;

      // 返回曲面参数方程
      return {
        u: {
          min: -Math.PI,
          max: Math.PI * 3,
          step: Math.PI / 32
        },
        v: {
          min: 0,
          max: Math.PI * 2,
          step: Math.PI / 20
        },
        x: function x(u, v) {
          if (u < startRadian) {
            return offsetX + Math.cos(startRadian) * (1 + Math.cos(v) * k) * hoverRate;
          }
          if (u > endRadian) {
            return offsetX + Math.cos(endRadian) * (1 + Math.cos(v) * k) * hoverRate;
          }
          return offsetX + Math.cos(u) * (1 + Math.cos(v) * k) * hoverRate;
        },
        y: function y(u, v) {
          if (u < startRadian) {
            return offsetY + Math.sin(startRadian) * (1 + Math.cos(v) * k) * hoverRate;
          }
          if (u > endRadian) {
            return offsetY + Math.sin(endRadian) * (1 + Math.cos(v) * k) * hoverRate;
          }
          return offsetY + Math.sin(u) * (1 + Math.cos(v) * k) * hoverRate;
        },
        z: function z(u, v) {
          if (u < -Math.PI * 0.5) {
            return Math.sin(u);
          }
          if (u > Math.PI * 2.5) {
            return Math.sin(u);
          }
          return Math.sin(v) > 0 ? 1 * height : -1;
        }
      };
    }
    // 生成模拟 3D 饼图的配置项
    function getPie3D(pieData, internalDiameterRatio) {
      var series = [];
      var sumValue = 0;
      var startValue = 0;
      var endValue = 0;
      var legendData = [];
      var k = typeof internalDiameterRatio !== 'undefined' ? (1 - internalDiameterRatio) / (1 + internalDiameterRatio) : 1 / 3;

      // 为每一个饼图数据，生成一个 series-surface 配置
      for (var i = 0; i < pieData.length; i++) {
        sumValue += pieData[i].value;
        var seriesItem = {
          name: typeof pieData[i].name === 'undefined' ? "series".concat(i) : pieData[i].name,
          type: 'surface',
          parametric: true,
          wireframe: {
            show: false
          },
          pieData: pieData[i],
          pieStatus: {
            selected: false,
            hovered: false,
            k: k
          }
        };
        if (typeof pieData[i].itemStyle != 'undefined') {
          var itemStyle = {};
          typeof pieData[i].itemStyle.color != 'undefined' ? itemStyle.color = pieData[i].itemStyle.color : null;
          typeof pieData[i].itemStyle.opacity != 'undefined' ? itemStyle.opacity = pieData[i].itemStyle.opacity : null;
          seriesItem.itemStyle = itemStyle;
        }
        series.push(seriesItem);
      }

      // 使用上一次遍历时，计算出的数据和 sumValue，调用 getParametricEquation 函数，
      // 向每个 series-surface 传入不同的参数方程 series-surface.parametricEquation，也就是实现每一个扇形。
      for (var _i = 0; _i < series.length; _i++) {
        endValue = startValue + series[_i].pieData.value;
        series[_i].pieData.startRatio = startValue / sumValue;
        series[_i].pieData.endRatio = endValue / sumValue;
        series[_i].parametricEquation = getParametricEquation(series[_i].pieData.startRatio, series[_i].pieData.endRatio, false, false, k, series[_i].pieData.value);
        startValue = endValue;
        legendData.push(series[_i].name);
      }
      // // 补充一个透明的圆环，用于支撑高亮功能的近似实现。
      // series.push({
      //     name: 'mouseoutSeries',
      //     type: 'surface',
      //     parametric: true,
      //     wireframe: {
      //         show: false,
      //     },
      //     itemStyle: {
      //         opacity: 0.1,
      //         color: '#05CFF7',
      //     },
      //     parametricEquation: {
      //         u: {
      //             min: 0,
      //             max: Math.PI * 2,
      //             step: Math.PI / 20,
      //         },
      //         v: {
      //             min: 0,
      //             max: Math.PI*5,
      //             step: Math.PI / 20,
      //         },
      //         x: function (u, v) {
      //             return ((Math.sin(v) * Math.sin(u) + Math.sin(u)) / Math.PI) * 2;
      //         },
      //         y: function (u, v) {
      //             return ((Math.sin(v) * Math.cos(u) + Math.cos(u)) / Math.PI) * 2;
      //         },
      //         z: function (u, v) {
      //             return Math.cos(v) > 0 ? -0.5 : -5;
      //         },
      //     },
      // });
      // series.push({
      //     name: 'mouseoutSeries',
      //     type: 'surface',
      //     parametric: true,
      //     wireframe: {
      //         show: false,
      //     },
      //     itemStyle: {
      //         opacity: 0.1,
      //         color: '#009BFF',
      //     },
      //     parametricEquation: {
      //         u: {
      //             min: 0,
      //             max: Math.PI * 2,
      //             step: Math.PI / 20,
      //         },
      //         v: {
      //             min: 0,
      //             max: Math.PI,
      //             step: Math.PI / 20,
      //         },
      //         x: function (u, v) {
      //             return ((Math.sin(v) * Math.sin(u) + Math.sin(u)) / Math.PI) * 2.2;
      //         },
      //         y: function (u, v) {
      //             return ((Math.sin(v) * Math.cos(u) + Math.cos(u)) / Math.PI) * 2.2;
      //         },
      //         z: function (u, v) {
      //             return Math.cos(v) > 0 ? -7 : -7;
      //         },
      //     },
      // });
      return series;
    }
    // 传入数据生成 option
    var r = 100;
    var optionsData = props === null || props === void 0 ? void 0 : props.optionsData;
    var series = getPie3D(optionsData, 0.8, 240, 28, 26, 0.5);
    series.push({
      name: 'pie2d',
      type: 'pie',
      label: {
        show: false,
        opacity: 1,
        fontSize: 14,
        lineHeight: 20,
        textStyle: {
          fontSize: 14,
          color: '#fff'
        }
      },
      labelLine: {
        length: 30,
        length2: 30
      },
      startAngle: -30,
      //起始角度，支持范围[0, 360]。
      clockwise: false,
      //饼图的扇区是否是顺时针排布。上述这两项配置主要是为了对齐3d的样式
      radius: ['40%', '60%'],
      center: ['50%', '50%'],
      data: optionsData,
      itemStyle: {
        opacity: 0
      }
    });
    // 准备待返回的配置项，把准备好的 legendData、series 传入。
    var option = {
      legend: {
        show: true,
        tooltip: {
          show: true
        },
        orient: 'vertical',
        data: optionsData,
        // top: "center",
        itemGap: 30,
        itemHeight: 18,
        itemWidth: 17,
        right: 10,
        top: 60,
        textStyle: {
          color: '#fff',
          fontSize: 20
        },
        formatter: function formatter(params) {
          var e = optionsData === null || optionsData === void 0 ? void 0 : optionsData.find(function (item) {
            return params == (item === null || item === void 0 ? void 0 : item.name);
          });
          var name = params.padEnd(6, ' ');
          //文字和空格宽度不同
          if (e.name.length < 7) {
            name = name + '  ';
          }
          return name + e.value / 100 + '%';
        }
      },
      animation: true,
      tooltip: {
        formatter: function formatter(params) {
          if (params.seriesName !== 'mouseoutSeries' && params.seriesName !== 'pie2d') {
            return "".concat(params.seriesName, "<br/><span style=\"display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:").concat(params.color, ";\"></span>").concat(option.series[params.seriesIndex].pieData.value / 100 + '%');
          }
        },
        textStyle: {
          fontSize: 14
        }
      },
      title: {
        x: 'center',
        top: '20',
        textStyle: {
          color: '#fff',
          fontSize: 22
        }
      },
      graphic: _objectSpread({
        type: 'text'
      }, props.titleStyle),
      labelLine: {
        show: true,
        lineStyle: {
          color: '#7BC0CB'
        },
        normal: {
          show: true,
          length: 10,
          length2: 10
        }
      },
      label: {
        show: true,
        position: 'outside',
        formatter: '{b} \n{d}%',
        textStyle: {
          color: '#fff',
          fontSize: '14px'
        }
      },
      xAxis3D: {
        min: -1,
        max: 1
      },
      yAxis3D: {
        min: -1,
        max: 1
      },
      zAxis3D: {
        min: -1,
        max: 1
      },
      grid3D: {
        show: false,
        boxHeight: 0.01,
        left: '-18%',
        viewControl: {
          distance: 180,
          minDistance: 180,
          maxDistance: 180,
          alpha: 25,
          beta: 100,
          autoRotate: true // 自动旋转
        }
      },

      series: series
    };
    if (props.optionsData) {
      chartInstance.setOption(option);
    }
  }, [props.optionsData]);
  useEffect(function () {
    var div = divRef.current;
    // 创建一个ResizeObserver实例并定义回调函数
    var resizeObserver = new ResizeObserver(function (entries) {
      var _iterator = _createForOfIteratorHelper(entries),
        _step;
      try {
        for (_iterator.s(); !(_step = _iterator.n()).done;) {
          var entry = _step.value;
          var _entry$contentRect = entry.contentRect,
            width = _entry$contentRect.width,
            height = _entry$contentRect.height;
          if (chartRef.current) {
            chartRef.current.style.transform = "scaleX(".concat(width / 800, ") scaleY(").concat(height / 500, ")");
          }
        }
      } catch (err) {
        _iterator.e(err);
      } finally {
        _iterator.f();
      }
    });
    // 开始监听div的尺寸变化
    resizeObserver.observe(div);
    return function () {
      //组件销毁停止监听
      resizeObserver.disconnect();
    };
  }, []);
  return /*#__PURE__*/_jsx("div", _objectSpread(_objectSpread({
    className: styles.container
  }, props), {}, {
    ref: divRef,
    children: /*#__PURE__*/_jsx("div", {
      ref: chartRef,
      className: styles.main
    })
  }));
}
export default PieChart;