/**
 * 
 *     @dfsj/echarts： 专业的水文曲线组件或构造函数以及通用的echart二次封装图表
 *     版本: v3.7.0
 *     作者：yangbo <1747837358@qq.com>
 *     日期：2025-05-27 15:53:33
 *     
 *     
 */

import { createLinearInterpolator } from 'commons-math-interpolation';
import get from 'lodash-es/get';
import { ref } from 'vue';
import assign from '../../utils/assign.js';
import { toIndex, renderAltitudeMark } from '../../utils/render.js';
import { min, max, to } from '../../utils/tools.js';
import config, { TYPE_SYMBOL } from '../../config.js';
import def from './default.js';
import { useECharts } from '../../hooks/useECharts.js';
import { useToolTip } from '../../view/useToolTip.js';
import { useTable } from '../../view/useTable.js';

function useStageflow(chartRef) {
  var _this = this;
  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(),
    props = _useTable.props,
    toggleTable = _useTable.toggleTable;
  props.container = container;
  var assemble = function assemble(value, options) {
    var optioned = assign({}, def, options);
    var chart = getInstance();
    if (value != null) {
      var _value$indices;
      props.value = value;
      props.chart = chart;
      optioned.dataset.source = value.source;
      var indices = (_value$indices = value.indices) === null || _value$indices === void 0 ? void 0 : _value$indices.map(function (e) {
        return toIndex(e);
      });
      if (indices && indices.length) {
        indices.forEach(function (e) {
          return optioned.series.push(e);
        });
      }
      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;
      }, {});
      if (value.points) {
        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;
            console.log([x1, y1, x2, y2, x3, y3, e.label || e.name, symbol, e.level]);
            if (symbol == null) counter++;
            return {
              value: [x1, y1, x2, y2, x3, y3, e.label || e.name, symbol, e.level]
            };
          })
        }, optioned.$mark));
      }
      optioned.toolbox.feature.myTabulation = {
        onclick: function onclick() {
          return _this.tools.tabulation = !_this.tools.tabulation;
        },
        icon: config.icon.tabulation,
        title: '表格'
      };
      try {
        var grid = optioned.grid;
        var dimensions = value.dimensions || ['水位（m）', '流量（m³/s）'];
        var stage = value.source.map(function (d) {
          return d[0];
        });
        var lines = 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;
        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])), "</i>\n                     </li>");
            }).join('');
            content.value = "<fieldset>".concat(fields, "</fieldset>");
          } else {
            closeToolTip();
          }
        };
        optioned.tooltip.formatter = function (p) {
          var _p$value, _p$value2;
          var symbol = p === null || p === void 0 || (_p$value = p.value) === null || _p$value === void 0 ? void 0 : _p$value[7];
          var name = p === null || p === void 0 || (_p$value2 = p.value) === null || _p$value2 === void 0 ? void 0 : _p$value2[6];
          if (symbol !== 'exception') return;
          return "<article class=\"tooltip\">\n                            <fieldset>\n                              <legend style=\"color: ".concat(config.markColor["4"], "\">").concat(name, "</legend> \n                            </fieldset>\n                          </article>");
        };
      } catch (e) {}
    }
    return optioned;
  };
  var createOptions = function createOptions(data) {
    return {};
  };
  return {
    setOptions: setOptions,
    createOptions: createOptions,
    echarts: echarts,
    getInstance: getInstance,
    container: container,
    assemble: assemble,
    toggleTable: toggleTable
  };
}

export { useStageflow };
