"use strict";

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); }

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Pie = void 0;

var _react = _interopRequireWildcard(require("react"));

var _number = require("mathjs/number");

var _lodash = require("lodash");

var _core = _interopRequireDefault(require("echarts-for-react/lib/core"));

var echarts = _interopRequireWildcard(require("echarts/core"));

var _src = require("../../../packages/core/src");

var _ChartProvider = require("../../../packages/core/src/ChartProvider");

var _charts = require("echarts/charts");

var _components = require("echarts/components");

var _renderers = require("echarts/renderers");

var _excluded = ["option"],
    _excluded2 = ["dimension", "valueList", "echartsSeries", "showInRing", "setOption"];

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

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) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

echarts.use([_charts.PieChart, _renderers.CanvasRenderer, _renderers.SVGRenderer, _components.GridSimpleComponent, _components.GridComponent, _components.SingleAxisComponent, _components.GraphicComponent, _components.ToolboxComponent, _components.TooltipComponent, _components.AxisPointerComponent, _components.BrushComponent, _components.TitleComponent, _components.TimelineComponent, _components.MarkPointComponent, _components.MarkLineComponent, _components.MarkAreaComponent, _components.LegendComponent, _components.LegendScrollComponent, _components.LegendPlainComponent, _components.DataZoomComponent, _components.DataZoomInsideComponent, _components.DataZoomSliderComponent, _components.VisualMapComponent, _components.VisualMapContinuousComponent, _components.VisualMapPiecewiseComponent, _components.AriaComponent, _components.TransformComponent, _components.DatasetComponent]);

var Pie = function Pie(props) {
  var _useContext = (0, _react.useContext)(_ChartProvider.ChartContext),
      data = _useContext.data,
      echartsOptions = _useContext.echartsOptions,
      chartOption = _useContext.echartsOptionsBase,
      userOptions = _useContext.userOptions;

  var _ref = echartsOptions || {},
      option = _ref.option,
      resetOptions = _objectWithoutProperties(_ref, _excluded);

  var dimension = props.dimension,
      valueList = props.valueList,
      echartsSeries = props.echartsSeries,
      showInRing = props.showInRing,
      setOption = props.setOption,
      restSettings = _objectWithoutProperties(props, _excluded2);

  var getCenter = function getCenter() {
    var _centerLeft = '50%';
    var _centerTop = '50%';

    if (props.legendPosition === 'left') {
      _centerLeft = '55%';
    } else if (props.legendPosition === 'right') {
      _centerLeft = '45%';
    } else if (props.legendPosition === 'top') {
      _centerTop = '55%';
    } else if (props.legendPosition === 'bottom') {
      _centerTop = '45%';
    }

    return {
      top: _centerTop,
      left: _centerLeft
    };
  };

  var _chartOption = (0, _lodash.cloneDeep)(chartOption || {});

  _chartOption.xAxis = {
    show: false
  };
  _chartOption.yAxis = {
    show: false
  };
  var _series = [];

  if (_chartOption) {
    if (dimension && dimension.length > 0) {
      // 有维度
      _series = valueList && valueList.slice(0, 1).map(function (item, i) {
        var _sum = data === null || data === void 0 ? void 0 : data.reduce(function (s, c) {
          s = s + (c[item.fieldKey] || 0);
          return s;
        }, 0);

        return {
          name: dimension === null || dimension === void 0 ? void 0 : dimension[0].fieldName,
          type: 'pie',
          minAngle: 5,
          radius: showInRing ? ['30%', '50%'] : '50%',
          center: [getCenter().left, getCenter().top],
          data: data === null || data === void 0 ? void 0 : data.map(function (d) {
            var text = d[dimension === null || dimension === void 0 ? void 0 : dimension[0].fieldKey];
            return {
              name: text,
              value: d[item.fieldKey] ? d[item.fieldKey] != null && !isNaN(d[item.fieldKey]) ? d[item.fieldKey].toFixed(Math.abs(d[item.fieldKey]) > 1 ? 2 : 4) : d[item.fieldKey] : 0
            };
          }),
          label: {
            show: true,
            position: 'outside',
            formatter: function formatter(params) {
              var _percent = (0, _number.round)((0, _number.multiply)((0, _number.divide)((0, _number.round)(Number(params.value), 4), _sum), 100), 2);

              var res = '';

              try {
                res += "".concat(_percent, "%");
              } catch (_unused) {
                res += '--%';
              }

              return res;
            },
            fontSize: 12
          }
        };
      }) || [];
    } else {
      // 无维度
      var d = data && (0, _lodash.cloneDeep)(data)[0] || {};

      var _valueListClone = (0, _lodash.cloneDeep)(valueList);

      var _sum = _valueListClone === null || _valueListClone === void 0 ? void 0 : _valueListClone.reduce(function (s, c) {
        s = s + (d[c.fieldKey] || 0);
        return s;
      }, 0);

      _series = [{
        name: '',
        type: 'pie',
        minAngle: 5,
        radius: showInRing ? ['30%', '50%'] : '50%',
        center: [getCenter().left, getCenter().top],
        data: _valueListClone === null || _valueListClone === void 0 ? void 0 : _valueListClone.map(function (item) {
          return {
            name: item.fieldName,
            value: d[item.fieldKey] ? d[item.fieldKey] != null && !isNaN(d[item.fieldKey]) ? parseFloat(d[item.fieldKey]).toFixed(Math.abs(d[item.fieldKey]) > 1 ? 2 : 4) : d[item.fieldKey] : 0,
            emphasis: {
              label: {
                show: true
              }
            },
            label: {
              show: true,
              position: 'outside',
              formatter: function formatter(params) {
                try {
                  var _percent = (0, _number.round)((0, _number.multiply)((0, _number.divide)((0, _number.round)(Number(params.value), 4), _sum), 100), 2);

                  var res = '';

                  try {
                    res += "".concat(_percent, "%");
                  } catch (_unused2) {
                    res += '--%';
                  }

                  return res;
                } catch (e) {
                  return '--';
                }
              },
              fontSize: 12
            }
          };
        })
      }];
    }
  }

  _chartOption.series = echartsSeries || _series;
  var builtOption = (0, _src.buildChartOption)(_chartOption, restSettings, 'pie');
  var options = (0, _src.mergeOption)(builtOption, userOptions);

  if (setOption) {
    options = setOption((0, _lodash.cloneDeep)(options));
  }

  return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement(_core["default"], _extends({
    echarts: echarts,
    option: _objectSpread({}, (0, _lodash.cloneDeep)(options)),
    notMerge: true,
    opts: {
      renderer: 'svg'
    },
    style: {
      height: '100%',
      width: '100%'
    }
  }, resetOptions)));
};

exports.Pie = Pie;