function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _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(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _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(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
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(arr) { if (Array.isArray(arr)) return arr; }
import { ChartIcon, ListIcon } from "../../../_util/iconSvgHtml";
import { useSetState } from 'ahooks';
import { Col, Row, Space, Spin, message } from 'antd';
import classnames from 'classnames';
import dayjs from 'dayjs';
import * as echarts from 'echarts';
import ReactEcharts from 'echarts-for-react';
import { isEmpty } from 'lodash';
import { useEffect, useState } from 'react';
import { VmEmpty, VmExtraTab, VmFilter, VmTable, VmTag, VmTitle, VmWrapper } from "../../../_components";
import useSettings from "../../../_hooks/useSettings";
import { BaseService } from "../../api";
import "./index.less";
import TabsList from "./TabsList";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
var MonitorAnalysis = function MonitorAnalysis(_ref) {
  var _newList$, _newList$2, _newList$3;
  var id = _ref.id;
  var _useSettings = useSettings(),
    chartFontColor = _useSettings.chartFontColor,
    chartLineColor = _useSettings.chartLineColor,
    isDark = _useSettings.isDark,
    theme = _useSettings.theme;
  var blueColor = '#1677FF';
  var greenColor = '#0fb964';
  var areaColor = ['rgba(22, 119, 255, 0.30)', 'rgba(22, 119, 255, 0)'];
  if (isDark) {
    blueColor = '#009dff';
    greenColor = ' #13f97';
    areaColor = ['rgba(22, 119, 255, 0.30)', 'rgba(22, 119, 255, 0)'];
  }
  var _BaseService$useRealt = BaseService.useRealtimeList(id),
    data = _BaseService$useRealt.data;
  var _useState = useState([]),
    _useState2 = _slicedToArray(_useState, 2),
    monitorItemIds = _useState2[0],
    setMonitorItemIds = _useState2[1];
  var _BaseService$useColle = BaseService.useCollectList({
      deviceIds: id,
      monitorItemIds: monitorItemIds
    }),
    _BaseService$useColle2 = _BaseService$useColle.data,
    collectList = _BaseService$useColle2 === void 0 ? [] : _BaseService$useColle2;
  useEffect(function () {
    if (!isEmpty(data)) {
      setMonitorItemIds([data[0].monitorItemId]);
    }
  }, [JSON.stringify(data)]);
  var _useSetState = useSetState({
      startDate: dayjs().startOf('date'),
      endDate: dayjs().endOf('date'),
      collectFrequency: '',
      danTimeType: '24h',
      showType: 'chart'
    }),
    _useSetState2 = _slicedToArray(_useSetState, 2),
    state = _useSetState2[0],
    setState = _useSetState2[1];
  var startDate = state.startDate,
    endDate = state.endDate,
    collectFrequency = state.collectFrequency,
    danTimeType = state.danTimeType,
    showType = state.showType;
  var tabList = [{
    label: '24小时',
    value: '24h'
  }, {
    label: '3天',
    value: '3days'
  }, {
    label: '7天',
    value: '7days'
  }].concat(_toConsumableArray(collectFrequency === 'day' ? [{
    label: '月',
    value: 'month'
  }] : []), _toConsumableArray(collectFrequency === 'month' ? [{
    label: '年',
    value: 'year'
  }] : []), [{
    label: '自定义',
    value: 'self'
  }]);
  useEffect(function () {
    if (!isEmpty(collectList)) {
      var _collectList$;
      setState({
        collectFrequency: collectList === null || collectList === void 0 || (_collectList$ = collectList[0]) === null || _collectList$ === void 0 ? void 0 : _collectList$.id
      });
    }
  }, [JSON.stringify(collectList)]);
  var _BaseService$useGetAn = BaseService.useGetAnalysis({
      timeType: 'danTime',
      danTimeEndTime: dayjs(endDate).format('YYYY-MM-DD HH:mm:ss'),
      danTimeType: danTimeType,
      danTimeStartTime: dayjs(startDate).format('YYYY-MM-DD HH:mm:ss'),
      collectFrequency: collectFrequency,
      deviceIds: id,
      monitorItemIds: monitorItemIds
    }),
    chartDataList = _BaseService$useGetAn.data,
    loading = _BaseService$useGetAn.loading;
  var isHasChartData = function isHasChartData() {
    var isHasData = true;
    if (chartDataList.length) {
      isHasData = true;
      if (chartDataList.some(function (item) {
        return item.values && item.values.length;
      })) {
        isHasData = true;
      } else {
        isHasData = false;
      }
    } else {
      isHasData = false;
    }
    return isHasData;
  };
  var isHasChartItemData = function isHasChartItemData(item) {
    var isHasData = true;
    if (item.values.length) {
      isHasData = true;
    } else {
      isHasData = false;
    }
    return isHasData;
  };
  var newList = isHasChartData() ? chartDataList.filter(function (item) {
    return isHasChartItemData(item);
  }) : null;
  var getGroupDanOption = function getGroupDanOption(list) {
    var xData = _.uniq(_.flatMap(list, 'xData').sort());
    var legendData = [];
    list.forEach(function (item, index) {
      if (item.showMode === 'stack') {
        var _state = _.map(_.uniqBy(item.dataList, 'value'));
        var colors = [blueColor, greenColor];
        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: blueColor
          }
        });
      }
    });
    return {
      color: [blueColor],
      grid: {
        top: 26,
        left: 40,
        right: 50,
        bottom: 50,
        containLabel: true
      },
      legend: {
        type: 'scroll',
        itemWidth: 17,
        itemHeight: 10,
        textStyle: {
          color: chartFontColor
        },
        top: 0,
        left: 'center'
      },
      tooltip: {
        trigger: 'axis',
        valueFormatter: function valueFormatter(value) {
          var _list$;
          return "".concat(value).concat((list === null || list === void 0 || (_list$ = list[0]) === null || _list$ === void 0 ? void 0 : _list$.unit) || '');
        },
        position: function position(point, _params, _dom, _rect, size) {
          // 固定在顶部
          var leftSize = point[0] - size.contentSize[0];
          return [point[0] + size.contentSize[0] > size.viewSize[0] ? leftSize < 0 ? '35%' : leftSize : point[0], '0%'];
        }
      },
      dataZoom: [{
        type: 'slider',
        show: true,
        bottom: 20,
        fillerColor: theme === 'light' ? 'rgba(22, 119, 255, 0.10)' : 'rgba(0, 157, 255, 0.10)',
        textStyle: {
          color: chartFontColor
        }
      }],
      xAxis: [{
        type: 'category',
        boundaryGap: false,
        axisLine: {
          show: true,
          lineStyle: {
            color: chartLineColor
          }
        },
        axisLabel: {
          textStyle: {
            color: chartFontColor,
            fontSize: 12
          }
        },
        axisTick: {
          show: false
        },
        data: xData
      }],
      yAxis: list.map(function (item, index) {
        return {
          minInterval: 1,
          position: 'left',
          // maxInterval: 5,
          nameTextStyle: {
            color: chartFontColor
          },
          nameLocation: 'middle',
          nameGap: 0,
          splitLine: {
            lineStyle: {
              color: chartLineColor,
              type: 'dashed'
            }
          },
          axisLine: {
            show: true,
            color: chartFontColor
          },
          axisLabel: {
            color: chartFontColor,
            margin: 20
          },
          axisTick: {
            show: false
          }
        };
      }),
      series: list.flatMap(function (item, index) {
        if (item.showMode === 'stack') {
          var _state2 = _.map(_.uniqBy(item.dataList, 'value'));
          var colors = [blueColor, greenColor];
          var stateColor = {};
          _state2.forEach(function (v, index) {
            stateColor[v.value] = colors[index % 2];
          });
          return [].concat(_toConsumableArray((_state2 || []).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: dayjs(m.data).format('YYYY-MM-DD'),
                    xAxis: "(".concat(i + 1, ")").concat(dayjs(m.data).format('HH:mm')),
                    lineStyle: {
                      color: blueColor
                    },
                    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,
                  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, index, arr) {
              var _arr;
              return {
                itemStyle: {
                  normal: {
                    color: stateColor[item.originValue]
                  }
                },
                color: stateColor[item.originValue],
                name: item.value,
                label: item.value,
                value: [0, item.date, (_arr = arr[index + 1]) === null || _arr === void 0 ? void 0 : _arr.date]
              };
            })
          }]);
        }
        return [{
          type: item.showMode,
          name: item.newName || item.name || '',
          data: (item.yData || []).map(function (y, i) {
            return {
              value: y,
              name: item.xData[i]
            };
          }),
          animationEasing: 'linear',
          animationDuration: 2000,
          smooth: true,
          // symbol: 'none',
          symbolSize: 1,
          xAxisIndex: 0,
          yAxisIndex: index,
          itemStyle: {
            normal: {
              lineStyle: {
                color: blueColor,
                width: 2
              },
              areaStyle: {
                color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [{
                  offset: 0,
                  color: areaColor[0]
                }, {
                  offset: 1,
                  color: areaColor[1]
                }])
              }
            }
          }
        }];
      })
    };
  };
  var columns = [{
    title: '监测项目',
    dataIndex: 'monitorItemName',
    width: 120,
    ellipsis: true,
    fixed: 'left'
  }, {
    width: 80,
    title: '监测值',
    dataIndex: 'value',
    align: 'right',
    render: function render(text, record) {
      return text ? "".concat(text).concat(record.unit || '') : '-';
    }
  }, {
    width: 80,
    title: '是否告警',
    dataIndex: 'onAlarm',
    render: function render(text) {
      return /*#__PURE__*/_jsx(VmTag, {
        title: /*#__PURE__*/_jsxs(Space, {
          children: [/*#__PURE__*/_jsx("div", {
            className: classnames('vtx-device-analysis-dot', {
              error: text
            })
          }), /*#__PURE__*/_jsx("span", {
            children: text ? '是' : '否'
          })]
        }),
        type: text ? 'red' : 'green'
      });
    }
  }, {
    width: 80,
    title: '阈值',
    dataIndex: 'alarmDescription',
    ellipsis: true,
    render: function render(text) {
      return text ? text : '-';
    }
  }, {
    title: '刷新时间',
    dataIndex: 'timeDesc',
    sorter: function sorter(a, b) {
      return a.time - b.time;
    },
    width: 160
  }];
  var getActiveModeFill = function getActiveModeFill(key) {
    if (isDark) {
      return showType === key ? '#fff' : '#009DFF';
    }
    return showType === key ? '#1677FF' : '#8C8C8C';
  };
  return /*#__PURE__*/_jsx("div", {
    style: {
      height: 348
    },
    children: /*#__PURE__*/_jsx(VmWrapper, {
      title: '指标分析',
      contentStyle: {
        padding: '0 16px 16px'
      },
      filterType: 'rangePicker',
      filterChange: function filterChange(date) {
        if (!(date !== null && date !== void 0 && date[0]) || !(date !== null && date !== void 0 && date[1])) {
          return;
        }
        if (date[1].diff(date[0], 'd') > 7) {
          message.warning('时间跨度不能超过7天');
          return;
        }
        setState({
          startDate: date[0],
          endDate: date[1]
        });
      },
      pickerProps: {
        disabled: danTimeType !== 'self',
        showTime: {
          defaultValue: [dayjs().startOf('date'), dayjs().endOf('date')]
        }
      },
      extraLeft: /*#__PURE__*/_jsxs(Space, {
        children: [/*#__PURE__*/_jsxs(Space, {
          size: 0,
          children: [/*#__PURE__*/_jsx("div", {
            style: {
              fontSize: 14
            },
            children: "\u6307\u6807\u5468\u671F\uFF1A"
          }), /*#__PURE__*/_jsx(VmFilter.VMSelect, {
            value: collectFrequency,
            options: collectList.map(function (item) {
              return {
                label: item.name,
                value: item.code
              };
            }),
            style: {
              width: 120
            },
            onChange: function onChange(e) {
              return setState({
                collectFrequency: e
              });
            }
          })]
        }), /*#__PURE__*/_jsx(TabsList, {
          list: tabList,
          activeKey: danTimeType,
          setActiveKey: function setActiveKey(key) {
            setState({
              danTimeType: key
            });
            if (key !== 'self') {
              var _endDate = dayjs().endOf('date');
              var day = 0;
              if (key === '3days') {
                day = 3;
              } else if (key === '7days') {
                day = 7;
              }
              setState({
                startDate: dayjs().subtract(day, 'day').startOf('date'),
                endDate: _endDate
              });
            }
          }
        })]
      }),
      dateValue: [state.startDate, state.endDate],
      children: /*#__PURE__*/_jsxs(Row, {
        gutter: [20, 20],
        style: {
          height: '100%'
        },
        children: [/*#__PURE__*/_jsxs(Col, {
          span: 12,
          style: {
            height: '100%'
          },
          children: [/*#__PURE__*/_jsx(VmTitle, {
            title: '监测指标',
            border: false
          }), /*#__PURE__*/_jsx("div", {
            style: {
              height: 'calc(100% - 48px',
              width: '100%'
            },
            children: /*#__PURE__*/_jsx(VmTable, {
              columns: columns,
              dataSource: data,
              pagination: false,
              rowKey: 'monitorItemId',
              isIndex: false,
              rowSelection: {
                fixed: true,
                type: 'radio',
                selectedRowKeys: monitorItemIds,
                onChange: function onChange(selectedRowKeys) {
                  setMonitorItemIds(selectedRowKeys);
                }
              }
            })
          })]
        }), /*#__PURE__*/_jsxs(Col, {
          span: 12,
          style: {
            height: '100%'
          },
          children: [/*#__PURE__*/_jsx(VmTitle, {
            title: '监测趋势',
            border: false,
            extra: /*#__PURE__*/_jsx(VmExtraTab, {
              value: showType,
              onChange: function onChange(key) {
                return setState({
                  showType: key
                });
              },
              data: [{
                key: 'chart',
                title: /*#__PURE__*/_jsx(ListIcon, {
                  width: 14,
                  height: 14,
                  fill: getActiveModeFill('chart')
                }),
                name: '图表'
              }, {
                key: 'list',
                title: /*#__PURE__*/_jsx(ChartIcon, {
                  width: 14,
                  height: 14,
                  fill: getActiveModeFill('list')
                }),
                name: '列表'
              }]
            })
          }), /*#__PURE__*/_jsx("div", {
            style: {
              height: 'calc(100% - 48px'
            },
            children: loading ? /*#__PURE__*/_jsx(Row, {
              align: 'middle',
              justify: 'center',
              style: {
                height: '100%'
              },
              children: /*#__PURE__*/_jsx(Spin, {
                spinning: true
              })
            }) : isEmpty(newList) ? /*#__PURE__*/_jsx(VmEmpty, {}) : showType === 'chart' ? /*#__PURE__*/_jsx(ReactEcharts, {
              option: getGroupDanOption(newList),
              notMerge: true,
              lazyUpdate: true,
              style: {
                height: '100%',
                width: '100%'
              }
            }) : /*#__PURE__*/_jsx(VmTable, {
              columns: [{
                title: '刷新时间',
                dataIndex: 'date',
                sorter: function sorter(a, b) {
                  return a.date > b.date ? 1 : -1;
                },
                width: 160
              }, {
                title: "".concat(newList === null || newList === void 0 || (_newList$ = newList[0]) === null || _newList$ === void 0 ? void 0 : _newList$.monitorItemName).concat((newList === null || newList === void 0 || (_newList$2 = newList[0]) === null || _newList$2 === void 0 ? void 0 : _newList$2.unit) || ''),
                dataIndex: 'originValue',
                width: 160,
                align: 'right'
              }],
              dataSource: ((_newList$3 = newList[0]) === null || _newList$3 === void 0 ? void 0 : _newList$3.dataList) || [],
              size: "small",
              pagination: true,
              rowKey: 'monitorItemId'
            })
          })]
        })]
      })
    })
  });
};
export default MonitorAnalysis;