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

import assign from '../../utils/assign.js';
import { toArea, to, findNowIndex, numeralFormat } from '../../utils/tools.js';
import last from 'lodash-es/last';
import config, { TYPE_SYMBOL } from '../../config.js';
import def, { IMAGES, TYPES } from './default.js';
import img from './images/-1.png.js';
import { createLinearInterpolator } from 'commons-math-interpolation/Linear';
import units from '../../utils/units.js';
import { useECharts } from '../../hooks/useECharts.js';

function useDamSchematic(chartRef) {
  var _useECharts = useECharts(chartRef),
    setOptions = _useECharts.setOptions,
    echarts = _useECharts.echarts,
    getInstance = _useECharts.getInstance,
    container = _useECharts.container;
  var assemble = function assemble(value, options) {
    var chart = getInstance();
    var optioned = assign({}, def, options);
    var times,
      points = value === null || value === void 0 ? void 0 : value.points;
    if (points !== null && points !== void 0 && points.length) {
      var source = value.source || [];
      var area = toArea(optioned.$area, value.area, source);
      var grid = optioned.grid;
      var availableHeight = chart.getHeight() - (grid.top + grid.bottom);
      var availableWidth = chart.getWidth() - (grid.left + grid.right);
      optioned.graphic.style.image = IMAGES[value.type] || img;
      optioned.graphic.style.width = availableWidth;
      optioned.graphic.style.height = availableHeight;
      var _cfg = TYPES[value.type];
      var section = _cfg.section.slice();
      var top = (points.find(function (e) {
        return e.type === 'top';
      }) || last(value.points)).altitude;
      var bom = (points.find(function (e) {
        return e.type === 'bottom';
      }) || points[0]).altitude;
      var diff = top - bom;
      var scale = availableHeight / section[3];
      var pixel = diff / (section[1] * scale);
      var min = bom - section[0] * scale * pixel;
      var max = min + scale * section[3] * pixel;
      var limit = bom;
      var counter = 0;
      optioned.yAxis.min = min;
      optioned.yAxis.max = max;
      optioned.series[0] = {
        z: 9,
        type: 'custom'
      };
      optioned.series[0].data = points.slice().filter(function (e) {
        return e.altitude && e.type !== 'bottom';
      }).sort(function (a, b) {
        return b.altitude - a.altitude;
      }).map(function (e) {
        var x1 = _cfg.point((e.altitude - min) / pixel / scale);
        var y1 = e.altitude;
        var x2 = _cfg.mark[0];
        var y2 = min + (_cfg.mark[1] - counter * 70) * scale * pixel;
        var x3 = _cfg.mark[0] + 50;
        var symbol = e.symbol || TYPE_SYMBOL[e.type];
        if (symbol == null) counter++;
        return {
          value: [x1, y1, x2, y2, x3, y2, e.label || e.name, symbol, e.level, e.color]
        };
      });
      optioned.series[0].renderItem = function (params, api) {
        var index = chart.getOption().timeline[0].currentIndex;
        var stage = source.length ? source[index][1] : 0;
        return renderAltitude(params, api, stage, 1);
      };
      times = source.map(function (e) {
        var _value$dimensions, _value$dimensions2;
        var c = e[1];
        if (bom - e[1] > 1) e[1] = bom;
        if (top - e[1] < 1) e[1] = top;
        var x1 = _cfg.water[0]((e[1] - limit) / pixel / scale);
        var x2 = _cfg.water[1]((e[1] - limit) / pixel / scale);
        var y = limit + (e[1] - limit) / 2;
        var amplitude = 3;
        return {
          title: {
            text: ['时间：' + e[0], e[1] != null ? "\u6C34\u4F4D\uFF1A".concat(to(e[1]), "\uFF08m\uFF09") : '', e[2] != null ? "\u5E93\u5BB9\uFF1A".concat(to(e[2]), "\uFF08").concat(value === null || value === void 0 || (_value$dimensions = value.dimensions) === null || _value$dimensions === void 0 || (_value$dimensions = _value$dimensions[2]) === null || _value$dimensions === void 0 ? void 0 : _value$dimensions.unit, "\uFF09") : ''].join('  '),
            subtext: c !== e[1] ? "\u6570\u636E\u6709\u8BEF\uFF0C\u5DF2\u8FDB\u884C\u8C03\u6574\uFF0C\u539F\u6C34\u4F4D\uFF1A".concat(c, "\uFF08m\uFF09") : undefined
          },
          series: [{}, assign({
            data: [[0, e[1]], [x1, e[1]], [x2, optioned.yAxis.min]],
            amplitude: amplitude
          }, optioned.$water), assign({
            data: [assign({
              value: [40, e[1]],
              label: {
                formatter: "\u5F53\u524D\u6C34\u4F4D\uFF1A".concat(to(e[1]), "\uFF08m\uFF09")
              }
            }, optioned.$stage), assign({
              value: [40, y],
              label: {
                formatter: "\u5F53\u524D\u5E93\u5BB9\uFF1A".concat(to(e[2]), "\uFF08").concat(value === null || value === void 0 || (_value$dimensions2 = value.dimensions) === null || _value$dimensions2 === void 0 || (_value$dimensions2 = _value$dimensions2[2]) === null || _value$dimensions2 === void 0 ? void 0 : _value$dimensions2.unit, "\uFF09")
              }
            }, optioned.$capacity)]
          }, 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 = source[index][1],
            current = source[index][2];
          var capacity = interpolator(p.value[1]);
          var capDiff = interpolator(p.value[1]) - current;
          var staDiff = p.value[1] - stage;
          return tooltip(p.value[6], capacity, capDiff, staDiff, value.dimensions[2].unit);
        };
      } catch (e) {}
      var history = area === null || area === void 0 ? void 0 : area.find(function (e) {
        return e.type = 'history';
      });
      optioned.timeline.currentIndex = history == null ? findNowIndex(source) : Math.max(history.index[1], 0);
    }
    return {
      baseOption: optioned,
      options: times
    };
  };
  var tooltip = function tooltip(name, capacity, capDiff, staDiff, unit) {
    return "<article class=\"tooltip\">\n            <fieldset>\n              <legend>".concat(name, "</legend>\n                <li><i>\u5BF9\u5E94\u5E93\u5BB9</i><i>").concat(to(capacity), "\uFF08").concat(unit, "\uFF09</i></li>\n                <li><i>\u5E93\u5BB9\u5DEE</i><i>").concat(to(capDiff), "\uFF08").concat(unit, "\uFF09</i></li>\n                <li><i>\u6C34\u4F4D\u5DEE</i><i>").concat(to(staDiff), "\uFF08m\uFF09</i></li>\n            </fieldset>\n          </article>");
  };
  var renderAltitude = function renderAltitude(params, api, current) {
    var scale = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 1;
    var p1 = api.coord([api.value(0), api.value(1)]);
    var p2 = api.coord([api.value(2), api.value(3)]);
    var p3 = api.coord([api.value(4), api.value(5)]);
    var symbol = api.value(7),
      stage = api.value(1);
    var text = "".concat(api.value(6), "\uFF1A").concat(to(api.value(1)), "\uFF08m\uFF09");
    var color = current >= stage && config.indexColor[api.value(8)] || api.value(9) || config.markColor.safe;
    var shadow = 'rgba(51,51,51,0.6)';
    if (symbol === 'stage') {
      return {
        type: 'group',
        z2: 1,
        children: [{
          type: 'path',
          z2: 1,
          shape: {
            pathData: config.icon.stage,
            x: p1[0] - 3 * scale,
            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',
          z2: 1,
          style: {
            text: text,
            x: p1[0] + 20 * scale,
            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',
            shadowColor: shadow,
            shadowBlur: 10 * scale,
            shadowOffsetX: scale,
            shadowOffsetY: 3 * scale,
            backgroundColor: '#fff',
            fill: color
          }
        }]
      };
    }
    if (symbol === 'altitude') {
      return {
        type: 'group',
        z2: 1,
        children: [{
          type: 'path',
          z2: 1,
          shape: {
            pathData: config.icon.altitude,
            x: p1[0] - 3 * scale,
            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',
          z2: 1,
          style: {
            text: text,
            x: p1[0] + 20 * scale,
            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',
            shadowColor: shadow,
            shadowBlur: 10 * scale,
            shadowOffsetX: scale,
            shadowOffsetY: 3 * scale,
            backgroundColor: '#fff',
            fill: color
          }
        }]
      };
    }
    return {
      type: 'group',
      z2: 0,
      children: [{
        z2: 5,
        type: 'circle',
        shape: {
          cx: p1[0],
          cy: p1[1],
          r: 3
        },
        style: {
          fill: '#fff',
          stroke: color
        },
        styleEmphasis: {
          fill: color,
          stroke: '#fff',
          shadowBlur: 3,
          shadowColor: color
        }
      }, {
        type: 'polyline',
        z2: 0,
        shape: {
          points: [p1, p2, p3]
        },
        style: {
          fill: null,
          lineWidth: 0.5,
          stroke: color,
          shadowBlur: 8 * scale,
          shadowColor: '#fff'
        },
        styleEmphasis: {
          shadowBlur: 2 * scale,
          shadowColor: shadow,
          shadowOffsetX: scale,
          shadowOffsetY: 3 * scale,
          lineWidth: 2
        }
      }, {
        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',
          fill: color,
          shadowColor: shadow,
          shadowBlur: 10 * scale,
          shadowOffsetX: scale,
          shadowOffsetY: 3 * scale,
          backgroundColor: '#fff'
        }
      }]
    };
  };
  var transform = function transform(data) {
    if (data != null) {
      var maximum = data.source.reduce(function (p, v) {
        return v[2] > p ? v[2] : p;
      }, 0);
      var unit = units.find(function (e) {
        return maximum >= e.value;
      }) || units[2];
      if (unit.value !== 0) {
        data.source.forEach(function (e) {
          return e[2] = e[2] && numeralFormat(e[2] / unit.value);
        });
        data.unit = unit;
      }
      data.dimensions = ['时间', '水位（m）', {
        name: "\u5E93\u5BB9\uFF08".concat(unit.symbol, "\uFF09"),
        unit: unit.symbol
      }, {
        name: "\u5165\u5E93\u6D41\u91CF(m\xB3/s)"
      }, {
        name: "\u4E0B\u6CC4\u6D41\u91CF(m\xB3/s)"
      }];
    }
    return data;
  };
  var createOptions = function createOptions(data) {
    return data;
  };
  return {
    setOptions: setOptions,
    echarts: echarts,
    getInstance: getInstance,
    container: container,
    assemble: assemble,
    transform: transform,
    createOptions: createOptions
  };
}

export { useDamSchematic };
