"use strict";

function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;
var _react = _interopRequireWildcard(require("react"));
var _vmTable = _interopRequireDefault(require("../../../vm-table"));
var _api = require("../../api");
var _vmSubTitle = _interopRequireDefault(require("../../../vm-sub-title"));
var _lodash = _interopRequireWildcard(require("lodash"));
var _dayjs = _interopRequireDefault(require("dayjs"));
var _echartsForReact = _interopRequireDefault(require("echarts-for-react"));
var _vmNodata = _interopRequireDefault(require("../../../vm-nodata"));
var echarts = _interopRequireWildcard(require("echarts"));
var _antd = require("antd");
var _useSettings2 = _interopRequireDefault(require("../../../vm-hooks/useSettings"));
require("./index.less");
var _config = require("../../config");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, "default": e }; if (null === e || "object" != _typeof(e) && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t in e) "default" !== _t && {}.hasOwnProperty.call(e, _t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t)) && (i.get || i.set) ? o(f, _t, i) : f[_t] = e[_t]); return f; })(e, t); }
function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); }
function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }
function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
var prefix = 'vtx-device-modal-basic';
var RealTimeList = function RealTimeList(_ref) {
  var _ref$id = _ref.id,
    id = _ref$id === void 0 ? '' : _ref$id;
  var _BaseService$useRealt = _api.BaseService.useRealtimeList(id),
    data = _BaseService$useRealt.data;
  var _useState = (0, _react.useState)([]),
    _useState2 = _slicedToArray(_useState, 2),
    ids = _useState2[0],
    setIds = _useState2[1];
  var _useSettings = (0, _useSettings2["default"])(),
    chartFontColor = _useSettings.chartFontColor,
    theme = _useSettings.theme;
  var endTime = (0, _react.useMemo)(function () {
    return (0, _dayjs["default"])().format('YYYY-MM-DD HH:mm:ss');
  }, [ids]);
  var _BaseService$useGetCh = _api.BaseService.useGetChartData({
      monitorItemIds: ids,
      collectFrequency: 'realtime',
      startTime: (0, _dayjs["default"])().format('YYYY-MM-DD 00:00:00'),
      endTime: endTime,
      deviceId: id
    }),
    chartData = _BaseService$useGetCh.data,
    loading = _BaseService$useGetCh.loading;
  var option = (0, _react.useMemo)(function () {
    if ((0, _lodash.isEmpty)(chartData)) {
      return {};
    }
    var list = chartData.map(function (item) {
      var values = item.values;
      var xData = [],
        yData = [],
        markLine = [],
        dataList = [];
      var type = (item === null || item === void 0 ? void 0 : item.monitorItemDefaultChartType) || 'line';
      if (values.length) {
        values.map(function (one) {
          xData.push(one.x);
          yData.push(one.y);
          dataList.push({
            date: one.x,
            value: type === 'stack' ? one.yformat || one.y : Number(one.y) ? Number(one.y) : one.y,
            originValue: one.y
          });
          if (!markLine.map(function (m) {
            return (0, _dayjs["default"])(m).format('YYYY-MM-DD');
          }).includes((0, _dayjs["default"])(one.x).format('YYYY-MM-DD'))) {
            markLine.push(one.x);
          }
        });
      }
      item.name = "".concat(item.typeChs ? "".concat(item.typeChs, "-") : '').concat(item.monitorItemName);
      item.dataList = dataList;
      item.markLine = markLine;
      item.xData = xData;
      item.yData = yData;
      item.showMode = type;
      var yDataList = yData.map(function (ele) {
        return Number(ele);
      });
      item.maximumValue = _lodash["default"].max(yDataList);
      item.minimumValue = _lodash["default"].min(yDataList);
      return item;
    });
    var xData = _lodash["default"].uniq(_lodash["default"].flatMap(list, 'xData').sort());
    var offsetList = [];
    list.forEach(function (_unused, index) {
      var maxLength = 0;
      if (index === 0) {
        offsetList.push(0);
        return;
      }
      var item = list[index - 1];
      item.yData.map(function (v) {
        maxLength = Math.max(maxLength, v.length);
      });
      var lastValue = _lodash["default"].last(offsetList) || 0;
      offsetList.push(lastValue + (maxLength * 10 + 20));
    });
    var legendData = [];
    list.forEach(function (item, index) {
      if (item.showMode === 'stack') {
        var state = _lodash["default"].map(_lodash["default"].uniqBy(item.dataList, 'value'));
        var _colors = ['#73a0fa', '#73deb3'];
        var stateColor = {};
        state.forEach(function (v, index) {
          stateColor[v.value] = _colors[index % 2];
        });
        legendData.push.apply(legendData, _toConsumableArray((state || []).map(function (item) {
          return {
            name: item.value,
            itemStyle: {
              color: stateColor[item.value]
            }
          };
        })));
      } else {
        legendData.push({
          name: item.newName || item.name || '',
          itemStyle: {
            color: _config.colors[index % 5].lineColor
          }
        });
      }
    });
    return {
      color: _config.colors.map(function (color) {
        return color.lineColor;
      }),
      grid: {
        top: 70,
        left: 100 + offsetList.length * 10,
        right: 50,
        bottom: 50,
        containLabel: true
      },
      toolbox: {
        show: true,
        feature: {
          saveAsImage: {
            show: true
          }
        }
      },
      legend: {
        type: 'scroll',
        itemWidth: 17,
        itemHeight: 10,
        textStyle: {
          color: theme === 'blue' ? '#fff' : chartFontColor
        },
        top: 35,
        left: 'center',
        data: legendData
      },
      tooltip: {
        trigger: 'axis',
        formatter: function formatter(data) {
          var circle = "<span style=\"display:inline-block;margin-right:5px;border-radius:50%;width:10px;height:10px;left:5px;background-color:";
          var result = "";
          data.map(function (v) {
            var info = list.find(function (item) {
              return item.name === v.seriesName;
            }) || {};
            if (v.componentSubType === 'custom') {
              result += "".concat(circle + v.color, "\"></span>").concat(v.name, "\uFF1A").concat(v.value.slice(1).join('~')).concat(info.unit || '', "<br/>");
            } else {
              result += "".concat(circle + _config.colors[v.seriesIndex % 5].lineColor, "\"></span>").concat(v.seriesName, "\uFF1A").concat(v.value).concat(info.unit || '', "<br/>");
            }
          });
          return result;
        }
      },
      xAxis: [{
        type: 'category',
        boundaryGap: false,
        axisLine: {
          show: true,
          lineStyle: {
            color: theme === 'blue' ? '#fff' : chartFontColor
          }
        },
        axisLabel: {
          textStyle: {
            color: theme === 'blue' ? '#fff' : chartFontColor,
            fontSize: 12
          }
        },
        axisTick: {
          show: false
        },
        data: xData
      }],
      yAxis: list.map(function (item, index) {
        return {
          name: "".concat(item.newName || item.name || '').concat(item.unit ? "(".concat(item.unit, ")") : ''),
          minInterval: 1,
          offset: offsetList[index],
          position: 'left',
          // maxInterval: 5,
          nameTextStyle: {
            color: _config.colors[index % 5].lineColor
          },
          nameLocation: 'middle',
          nameGap: 0,
          splitLine: {
            lineStyle: {
              color: '#E8E8E8',
              type: 'dashed'
            }
          },
          axisLine: {
            show: true,
            color: _config.colors[index % 5].lineColor
          },
          axisLabel: {
            color: _config.colors[index % 5].lineColor,
            margin: 20
          },
          axisTick: {
            show: false
          },
          type: 'category',
          data: []
        };
      }),
      series: list.flatMap(function (item, index) {
        if (item.showMode === 'stack') {
          var state = _lodash["default"].map(_lodash["default"].uniqBy(item.dataList, 'value'));
          var _colors2 = ['#73a0fa', '#73deb3'];
          var stateColor = {};
          state.forEach(function (v, index) {
            stateColor[v.value] = _colors2[index % 2];
          });
          return [].concat(_toConsumableArray((state || []).map(function (v) {
            return {
              name: v.value,
              type: 'bar',
              data: [],
              yAxisIndex: index,
              markLine: {
                symbol: ['none', 'none'],
                data: (item.markLine || []).filter(function (_unused, i) {
                  return i !== 0;
                }).map(function (m, i) {
                  return {
                    name: (0, _dayjs["default"])(m.data).format('YYYY-MM-DD'),
                    xAxis: "(".concat(i + 1, ")").concat((0, _dayjs["default"])(m.data).format('HH:mm')),
                    lineStyle: {
                      color: '#4159A7'
                    },
                    label: {
                      position: 'end',
                      formatter: '{b}'
                    }
                  };
                })
              }
            };
          })), [{
            type: 'custom',
            yAxisIndex: index,
            renderItem: function renderItem(params, api) {
              var categoryIndex = api.value(0);
              var start = api.coord([api.value(1), categoryIndex]);
              var end = api.coord([api.value(2), categoryIndex]);
              var height = 18;
              return {
                type: 'rect',
                shape: echarts.graphic.clipRectByRect({
                  x: start[0],
                  y: start[1] - height / 2 - index * 30,
                  width: end[0] - start[0],
                  height: height
                }, {
                  x: params.coordSys.x,
                  y: params.coordSys.y,
                  width: params.coordSys.width,
                  height: params.coordSys.height
                }),
                style: api.style()
              };
            },
            encode: {
              x: [1, 2],
              y: 0
            },
            data: (item.dataList || []).map(function (item, i, arr) {
              var _a;
              return {
                itemStyle: {
                  normal: {
                    color: stateColor[item.value]
                  }
                },
                color: stateColor[item.value],
                name: item.value,
                label: item.value,
                value: [index, item.date, (_a = arr[i + 1]) === null || _a === void 0 ? void 0 : _a.date]
              };
            })
          }]);
        }
        return [{
          type: item.showMode,
          name: item.newName || item.name || '',
          data: (item.yData || []).map(function (y, i) {
            return {
              value: Number(y) ? Number(y) : y,
              name: item.xData[i]
            };
          }),
          animationEasing: 'linear',
          animationDuration: 2000,
          smooth: true,
          // symbol: 'none',
          symbolSize: 1,
          xAxisIndex: 0,
          yAxisIndex: index,
          lineStyle: {
            color: _config.colors[index % 5].lineColor,
            width: 2
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [{
              offset: 0,
              color: _config.colors[index % 5].areaColor0
            }, {
              offset: 1,
              color: _config.colors[index % 5].areaColor1
            }])
          }
        }];
      })
    };
  }, [chartData]);
  (0, _react.useEffect)(function () {
    if (!(0, _lodash.isEmpty)(data)) {
      setIds([data[0].monitorItemId]);
    }
  }, [data]);
  var columns = [{
    title: '监测项目',
    dataIndex: 'name',
    width: 200,
    ellipse: true
  }, {
    width: 100,
    title: '实时值',
    dataIndex: 'value',
    render: function render(text, record) {
      return text ? "".concat(text).concat(record.unit || '') : '-';
    }
  }, {
    title: '数据更新时间',
    dataIndex: 'timeDesc',
    sorter: function sorter(a, b) {
      return a.time - b.time;
    },
    width: 160
  }];
  return /*#__PURE__*/_react["default"].createElement("div", {
    className: "".concat(prefix, "-right")
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: "".concat(prefix, "-right--content")
  }, /*#__PURE__*/_react["default"].createElement(_vmSubTitle["default"], {
    title: "\u5B9E\u65F6\u76D1\u6D4B"
  }), /*#__PURE__*/_react["default"].createElement(_vmTable["default"], {
    columns: columns,
    dataSource: data,
    size: "small",
    pagination: false,
    height: 200,
    rowSelection: {
      selectedRowKeys: ids,
      onChange: function onChange(selectedRowKeys) {
        setIds(selectedRowKeys);
      }
    },
    rowKey: 'monitorItemId'
  })), /*#__PURE__*/_react["default"].createElement("div", {
    className: "".concat(prefix, "-right--content"),
    style: {
      flex: 1,
      minHeight: 0
    }
  }, /*#__PURE__*/_react["default"].createElement(_vmSubTitle["default"], {
    title: "\u6570\u636E\u5206\u6790"
  }), /*#__PURE__*/_react["default"].createElement("div", {
    className: "".concat(prefix, "-right--chart")
  }, loading ? (/*#__PURE__*/_react["default"].createElement(_antd.Spin, {
    spinning: true
  })) : (0, _lodash.isEmpty)(chartData) ? (/*#__PURE__*/_react["default"].createElement(_vmNodata["default"], {
    style: {
      height: 300
    }
  })) : (/*#__PURE__*/_react["default"].createElement(_echartsForReact["default"], {
    option: option,
    notMerge: true,
    lazyUpdate: true,
    style: {
      height: '100%',
      width: '100%'
    }
  })))));
};
var _default = exports["default"] = RealTimeList;
//# sourceMappingURL=RealTimeList.js.map
