import _toConsumableArray from '@babel/runtime/helpers/toConsumableArray';
import def from './default.js';
import { min, max, to, numeralFormat, simpleMinMaxIndex, minimum, maximum } from '../../utils/tools.js';
import { renderAltitudeMark, toIndex } from '../../utils/render.js';
import config, { TYPE_SYMBOL } from '../../config.js';
import { createLinearInterpolator } from 'commons-math-interpolation/Linear';
import assign from '../../utils/assign.js';
import units from '../../utils/units.js';
import { ref } from 'vue';
import get from 'lodash-es/get';
import { useECharts } from '../../hooks/useECharts.js';
import { useToolTip } from '../../view/useToolTip.js';
import { useTable } from '../../view/useTable.js';

function useCapacity(chartRef) {
  var _useECharts = useECharts(chartRef),
    setOptions = _useECharts.setOptions,
    echarts = _useECharts.echarts,
    getInstance = _useECharts.getInstance,
    container = _useECharts.container;
  var visible = ref(false);
  var _useToolTip = useToolTip(container),
    offset = _useToolTip.offset,
    content = _useToolTip.content,
    openToolTip = _useToolTip.open,
    closeToolTip = _useToolTip.close;
  var _useTable = useTable(),
    openTable = _useTable.open,
    closeTable = _useTable.close,
    props = _useTable.props,
    toggleTable = _useTable.toggleTable;
  props.container = container;
  var assemble = function assemble(value, options) {
    var optioned = assign({}, def, options);
    var chart = getInstance();
    console.log('chart', chart);
    if (value != null) {
      var _value$points, _value$indices, _optioned$series;
      props.value = value;
      props.chart = chart;
      optioned.dataset.source = value.source;
      optioned.xAxis[1].show = value.dimensions.length > 2;
      optioned.xAxis[0].name = value.dimensions[1];
      optioned.series = value.dimensions.filter(function (e, i) {
        return i > 0;
      }).map(function (e, i) {
        return assign({
          name: e
        }, optioned.series[i]);
      });
      if ((_value$points = value.points) !== null && _value$points !== void 0 && _value$points.length) {
        var lft = min(value.source, 1);
        var rgt = max(value.source, 1);
        var top = max(value.source, 0);
        var bom = min(value.source, 0);
        var sv = (top - bom) / 1000;
        var sh = (rgt - lft) / 1000;
        var start = (top - bom) / 3 * 2;
        var counter = 0;
        var current = value.points.find(function (e) {
          return e.type === 'current';
        });
        optioned.series.push(assign({
          renderItem: function renderItem(params, api) {
            return renderAltitudeMark(params, api, current && current.altitude);
          },
          data: value.points.slice().sort(function (a, b) {
            return b.altitude - a.altitude;
          }).map(function (e) {
            var symbol = e.symbol || TYPE_SYMBOL[e.type];
            var x1 = symbol ? lft : rgt;
            var y1 = e.altitude;
            var x2 = x1 - sh * 60;
            var y2 = bom + (start - counter * sv * 70);
            var x3 = x2 - sh * 20;
            var y3 = y2;
            if (symbol == null) counter++;
            return {
              value: [x1, y1, x2, y2, x3, y3, e.label || e.name, symbol, e.level]
            };
          })
        }, optioned.$mark));
      }
      var indices = (_value$indices = value.indices) === null || _value$indices === void 0 ? void 0 : _value$indices.map(function (e) {
        return toIndex(e);
      });
      if (indices !== null && indices !== void 0 && indices.length) (_optioned$series = optioned.series).push.apply(_optioned$series, _toConsumableArray(indices));
      optioned.legend.data = optioned.series.map(function (e) {
        return {
          name: e.name,
          nameStyle: {
            color: e.color
          }
        };
      });
      optioned.legend.selected = optioned.series.reduce(function (p, v) {
        return p[v.name] = v.selected != null ? v.selected : true, p;
      }, {});
      optioned.toolbox.feature.myTabulation = {
        onclick: function onclick() {
          props.visible = !props.visible;
          console.log('打开', props);
          props.visible ? openTable() : closeTable();
        },
        icon: config.icon.tabulation,
        title: '表格'
      };
      console.log('container', container);
      try {
        var grid = optioned.grid;
        var stage = value.source.map(function (d) {
          return d[0];
        });
        var lines = value.dimensions.map(function (e, i) {
          return !i ? function (v) {
            return v;
          } : createLinearInterpolator(stage, value.source.map(function (d) {
            return d[i];
          }));
        });
        if (!container.value) return;
        var el = container.value;
        console.log({
          el: el
        });
        el.onclick = function () {
          console.log('---');
        };
        el.onmouseout = function () {
          visible.value = false;
          closeToolTip();
        };
        el.onmousemove = function (_ref) {
          var offsetY = _ref.offsetY,
            offsetX = _ref.offsetX;
          var width = chart.getWidth();
          var height = chart.getHeight();
          visible.value = offsetX >= grid.left && offsetX <= width - grid.right && offsetY >= grid.top && offsetY <= height - grid.bottom;
          if (visible.value) {
            openToolTip();
            offset.x = offsetX + 10;
            offset.y = offsetY + 10;
            if (offset.x > width - 180) offset.x -= 180;
            if (offset.y > height - 80) offset.y -= 80;
            var coords = chart.convertFromPixel({
              seriesIndex: 0
            }, [0, offsetY]);
            var fields = value.dimensions.map(function (e, i) {
              var color = i && get(optioned.series[i - 1], 'lineStyle.color');
              return "<li>\n                          <span class=\"mark\" style=\"background: ".concat(color, "\"></span>\n                          <i>").concat(e, "</i>\n                          <i>").concat(to(lines[i](+coords[1]), '0.000'), "</i>\n                        </li>");
            }).join('');
            content.value = "<fieldset>".concat(fields, "</fieldset>");
          } else {
            closeToolTip();
          }
        };
      } catch (e) {}
    }
    console.log('container', container);
    return optioned;
  };
  var transform = function transform(data) {
    if (data != null) {
      var _maximum = data.source.reduce(function (p, v) {
        return v[1] > p ? v[1] : p;
      }, 0);
      var unit = units.find(function (e) {
        return _maximum >= e.value;
      });
      if ((unit === null || unit === void 0 ? void 0 : unit.value) !== 0) {
        data.source.forEach(function (e) {
          return e[1] = numeralFormat(e[1] / unit.value, '0.000');
        });
        data.unit = unit;
        data.dimensions = ['水位（m）', "\u6C34\u4F4D-\u5E93\u5BB9\uFF08".concat(unit.symbol, "\uFF09"), '水位-面积（km²）'];
      }
    }
  };
  var createOptions = function createOptions(data) {
    if (data != null) {
      var cap = simpleMinMaxIndex(data);
      return {
        yAxis: [{
          min: function min(v) {
            return minimum(v, cap);
          },
          max: function max(v) {
            return maximum(v, cap);
          }
        }]
      };
    }
  };
  return {
    setOptions: setOptions,
    echarts: echarts,
    getInstance: getInstance,
    container: container,
    assemble: assemble,
    transform: transform,
    createOptions: createOptions,
    toggleTable: toggleTable
  };
}

export { useCapacity };
