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

import { toArea, max, min, to, findNowIndex } from '../../utils/tools.js';
import assign from '../../utils/assign.js';
import def from './default.js';
import config, { TYPE_SYMBOL } from '../../config.js';
import last from 'lodash-es/last';
import { createLinearInterpolator } from 'commons-math-interpolation/Linear';
import { useECharts } from '../../hooks/useECharts.js';
import { useTable } from '../../view/useTable.js';

function useCrossSection(chartRef) {
  var _useECharts = useECharts(chartRef),
    setOptions = _useECharts.setOptions,
    echarts = _useECharts.echarts,
    getInstance = _useECharts.getInstance,
    container = _useECharts.container;
  var _useTable = useTable(),
    props = _useTable.props,
    toggleTable = _useTable.toggleTable;
  props.container = container;
  var assemble = function assemble(value, options) {
    var chart = getInstance();
    var optioned = assign({}, def, options),
      nodes,
      direction = [0];
    if (value != null) {
      var _value$source;
      props.value = value;
      props.chart = chart;
      var layout = value.layout;
      var source = value.source || [];
      optioned.dataset.source = (_value$source = value.source) !== null && _value$source !== void 0 ? _value$source : [];
      var area = toArea(optioned.$area, value.area, source);
      var lft = max(layout, 0);
      var rgt = min(layout, 0);
      var center = value.center || (lft + rgt) / 2;
      var sca = (lft - rgt) / 1000 * 50;
      var bom = min(layout, 1);
      var points = value.points && value.points.slice().filter(function (e) {
        return e.altitude;
      }).sort(function (a, b) {
        return b.altitude - a.altitude;
      }) || [];
      direction = points.map(function () {
        return 0;
      });
      optioned.series[1] = {
        z: 9,
        type: 'custom'
      };
      optioned.series[0].data = value.layout;
      optioned.series[1].data = points.map(function (e, i) {
        var _e$layout;
        var x1 = (_e$layout = e === null || e === void 0 ? void 0 : e.layout) !== null && _e$layout !== void 0 ? _e$layout : center + sca;
        var y1 = e.altitude;
        var symbol = e.symbol || TYPE_SYMBOL[e.type] || 'altitude';
        return {
          value: [x1, y1, e.label || e.name, symbol, e.level, i]
        };
      });
      optioned.series[1].renderItem = function (params, api) {
        var _chart$getOption, _source$index;
        var index = (_chart$getOption = chart.getOption()) === null || _chart$getOption === void 0 || (_chart$getOption = _chart$getOption.timeline) === null || _chart$getOption === void 0 || (_chart$getOption = _chart$getOption[0]) === null || _chart$getOption === void 0 ? void 0 : _chart$getOption.currentIndex;
        var stage = source.length ? source === null || source === void 0 || (_source$index = source[index]) === null || _source$index === void 0 ? void 0 : _source$index[1] : 0;
        return renderMarkPoint(params, api, stage, points, direction, 1);
      };
      nodes = source.map(function (e, i) {
        var right = last(value.layout)[0];
        var amplitude = 3;
        return {
          title: {
            text: ['时间：' + e[0], e[1] != null ? "\u6C34\u4F4D\uFF1A".concat(to(e[1]), "m") : '', e[2] != null ? "\u6D41\u91CF\uFF1A".concat(to(e[2]), "m\xB3/s") : ''].filter(function (x) {
              return x;
            }).join('  ')
          },
          series: [{}, {}, assign({
            data: [[0, e[1]], [right, e[1]], [right, bom]],
            amplitude: amplitude
          }, optioned.$water), assign({
            data: [{
              value: [center, e[1]],
              label: {
                formatter: "\u5F53\u524D\u6C34\u4F4D\uFF1A".concat(to(e[1]), "\uFF08m\uFF09\n\u5F53\u524D\u6D41\u91CF\uFF1A").concat(to(e[2]), "\uFF08m\xB3/s\uFF09")
              }
            }]
          }, optioned.$current)]
        };
      });
      optioned.timeline.data = source.map(function (e, i) {
        if (area == null) return {
          value: e[0],
          tooltip: {
            formatter: e[0]
          }
        };
        var mark = area.find(function (e) {
          return e.index[0] <= i && i <= e.index[1];
        });
        var tooltip = {
          formatter: mark ? "".concat(mark.title, " ").concat(e[0]) : e[0]
        };
        return assign({
          tooltip: tooltip,
          value: e[0]
        }, mark);
      });
      try {
        var x = Array.from(new Set([bom].concat(source.map(function (e) {
          return e[1];
        }).sort())));
        var y = Array.from(new Set([0x0].concat(source.map(function (e) {
          return e[2];
        }).sort())));
        var interpolator = createLinearInterpolator(x, y);
        optioned.tooltip.formatter = function (p) {
          var index = chart.getOption().timeline[0].currentIndex;
          var stage = value.source[index][1];
          var current = value.source[index][2];
          var flow = interpolator(p.value[1]);
          var floDiff = interpolator(p.value[1]) - current;
          var staDiff = p.value[1] - stage;
          var symbol = p.value[3];
          return symbol == 'exception' ? tooltip(p.value[2]) : tooltip(p.value[2], flow, floDiff, staDiff);
        };
      } catch (e) {}
      var history = area && area.find(function (e) {
        return e.type = 'history';
      });
      optioned.timeline.currentIndex = history == null ? findNowIndex(source) : Math.max(history.index[1], 0);
    }
    console.log({
      baseOption: optioned,
      options: nodes
    });
    return {
      baseOption: optioned,
      options: nodes
    };
  };
  var tooltip = function tooltip(name, flow, floDiff, staDiff) {
    var exception = !flow && !floDiff && !staDiff;
    return exception ? "<article class=\"tooltip\">\n            <fieldset>\n              <legend style=\"color: ".concat(config.markColor["4"], "\">").concat(name, "</legend> \n            </fieldset>\n          </article>") : "<article class=\"tooltip\">\n            <fieldset>\n              <legend>".concat(name, "</legend>\n                <li><i>\u5BF9\u5E94\u6D41\u91CF</i><i>").concat(to(flow), "\uFF08m\xB3/s\uFF09</i></li>\n                <li><i>\u6D41\u91CF\u5DEE</i><i>").concat(to(floDiff), "\uFF08m\xB3/s\uFF09</i></li>\n                <li><i>\u6C34\u4F4D\u5DEE</i><i>").concat(to(staDiff), "\uFF08m\uFF09</i></li>\n            </fieldset>\n          </article>");
  };
  var renderMarkPoint = function renderMarkPoint(params, api, current, points, direction) {
    var scale = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 1;
    var p1 = api.coord([api.value(0), api.value(1)]);
    var symbol = api.value(3),
      stage = api.value(1);
    var text = "".concat(api.value(2), "\uFF1A").concat(to(api.value(1)), "\uFF08m\uFF09");
    var color = current >= stage && config.indexColor[api.value(4)] || config.markColor.safe;
    var shadow = 'rgba(51,51,51,0.6)';
    var index = api.value(5),
      dir = direction[index - 1] || 0;
    if (index > 0) {
      var s1 = api.coord([0, points[index - 1].altitude]);
      var s2 = api.coord([0, points[index - 0].altitude]);
      if (s2[1] - s1[1] < 30) {
        dir = direction[index] = 1 - dir;
      }
    }
    if (symbol === 'stage') {
      return {
        type: 'group',
        children: [{
          type: 'path',
          shape: {
            pathData: !dir ? config.icon.stage : config.icon.stageMirror,
            x: p1[0] - 3 * scale - dir * 210,
            y: p1[1] - 18.5 * scale,
            width: 190 * scale,
            height: 30 * scale
          },
          style: {
            fill: color,
            shadowBlur: 8 * scale,
            shadowColor: 'rgba(255,255,255,0.3)'
          },
          styleEmphasis: {
            shadowBlur: 5 * scale,
            shadowColor: shadow,
            shadowOffsetX: scale,
            shadowOffsetY: 3 * scale
          }
        }, {
          type: 'text',
          style: {
            text: text,
            x: p1[0] + 20 * scale - dir * 210,
            y: p1[1] - 10 * scale,
            font: 'normal 11px arial',
            fill: '#fff',
            borderWidth: 1,
            borderRadius: 20 * scale,
            backgroundColor: color,
            lineWidth: 100 * scale,
            verticalAlign: 'middle',
            padding: [4 * scale, 5 * scale, 2 * scale, 5 * scale]
          },
          styleEmphasis: {
            font: 'normal 12px arial',
            fill: color,
            shadowColor: shadow,
            shadowBlur: 10 * scale,
            shadowOffsetX: scale,
            shadowOffsetY: 3 * scale,
            backgroundColor: '#fff'
          }
        }]
      };
    }
    if (symbol === 'altitude') {
      return {
        type: 'group',
        children: [{
          type: 'path',
          shape: {
            pathData: !dir ? config.icon.altitude : config.icon.altitudeMirror,
            x: p1[0] - 3 * scale - dir * 210,
            y: p1[1] - 23 * scale,
            width: 190 * scale,
            height: 30 * scale
          },
          style: {
            fill: color,
            shadowBlur: 8 * scale,
            shadowColor: 'rgba(255,255,255,0.3)'
          },
          styleEmphasis: {
            shadowBlur: 2 * scale,
            shadowColor: shadow,
            shadowOffsetX: scale,
            shadowOffsetY: 3 * scale
          }
        }, {
          type: 'text',
          style: {
            text: text,
            x: p1[0] + 20 * scale - dir * 210,
            y: p1[1] - 10 * scale,
            font: 'normal 11px arial',
            fill: '#fff',
            borderWidth: 1,
            borderRadius: 20 * scale,
            backgroundColor: color,
            lineWidth: 100 * scale,
            verticalAlign: 'middle',
            padding: [4 * scale, 5 * scale, 2 * scale, 5 * scale]
          },
          styleEmphasis: {
            font: 'normal 12px arial',
            fill: color,
            shadowColor: shadow,
            shadowBlur: 10 * scale,
            shadowOffsetX: scale,
            shadowOffsetY: 3 * scale,
            backgroundColor: '#fff'
          }
        }]
      };
    }
    if (symbol === 'exception') {
      color = config.markColor["4"];
      return {
        type: 'group',
        children: [{
          type: 'path',
          shape: {
            pathData: config.icon.exception,
            x: p1[0],
            y: p1[1],
            width: 10,
            height: 30
          },
          style: {
            fill: color,
            shadowBlur: 8 * scale,
            shadowColor: 'rgba(255,255,255,0.3)'
          },
          styleEmphasis: {
            shadowBlur: 2 * scale,
            shadowColor: shadow,
            shadowOffsetX: scale,
            shadowOffsetY: 3 * scale
          }
        }]
      };
    }
    var p2 = [],
      p3 = [];
    return {
      type: 'group',
      children: [{
        z2: 5,
        type: 'circle',
        shape: {
          cx: p1[0],
          cy: p1[1],
          r: 3
        },
        style: {
          fill: '#fff',
          stroke: color
        }
      }, {
        type: 'polyline',
        shape: {
          points: [p1, p2, p3]
        },
        style: {
          fill: null,
          lineWidth: 2 * scale,
          stroke: color,
          shadowBlur: 8 * scale,
          shadowColor: '#fff'
        },
        styleEmphasis: {
          shadowBlur: 2 * scale,
          shadowColor: shadow,
          shadowOffsetX: scale,
          shadowOffsetY: 3 * scale
        }
      }, {
        type: 'text',
        style: {
          text: text,
          x: p3[0],
          y: p3[1] - 12 * scale,
          font: 'normal 12px arial',
          fill: '#fff',
          borderWidth: 1,
          borderRadius: 20 * scale,
          backgroundColor: color,
          lineWidth: 100 * scale,
          padding: [6 * scale, 10 * scale, 3 * scale, 10 * scale]
        },
        styleEmphasis: {
          font: 'normal 13px arial',
          shadowColor: shadow,
          shadowBlur: 10 * scale,
          shadowOffsetX: scale,
          shadowOffsetY: 3 * scale
        }
      }]
    };
  };
  var createOptions = function createOptions(data) {
    return {};
  };
  return {
    createOptions: createOptions,
    setOptions: setOptions,
    echarts: echarts,
    getInstance: getInstance,
    container: container,
    assemble: assemble,
    tooltip: tooltip,
    renderMarkPoint: renderMarkPoint,
    toggleTable: toggleTable
  };
}

export { useCrossSection };
