"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;

var _react = _interopRequireWildcard(require("react"));

var _ahooks = require("ahooks");

var _antd = require("antd");

var _icons = require("@ant-design/icons");

var _config = require("../../config");

var _dayjs = _interopRequireDefault(require("dayjs"));

var _utils = require("@vtx/utils");

var _vmFilter = require("../vm-filter");

var _vmTable = _interopRequireWildcard(require("../vm-table"));

var _useSettings2 = _interopRequireDefault(require("../vm-hooks/useSettings"));

var _api = require("./api");

var _vmSubTabs = _interopRequireWildcard(require("../vm-sub-tabs"));

var _propTypes = _interopRequireDefault(require("prop-types"));

var _vmChart = _interopRequireDefault(require("../vm-chart"));

require("./style");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

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 _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e2) { throw _e2; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e3) { didErr = true; err = _e3; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; }

function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

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(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

var WarningContent = function WarningContent(props) {
  var id = props.id,
      seed = props.seed,
      carType = props.carType;

  var _useSetState = (0, _ahooks.useSetState)({
    start: (0, _dayjs["default"])(),
    end: (0, _dayjs["default"])(),
    ids: [],
    tab: 'all',
    totalTab: 'table'
  }),
      _useSetState2 = _slicedToArray(_useSetState, 2),
      state = _useSetState2[0],
      setState = _useSetState2[1];

  var _useRequest = (0, _ahooks.useRequest)(function (_ref) {
    var current = _ref.current,
        pageSize = _ref.pageSize;
    var func = carType === 'jxh' ? _api.WarningData.getJxhWarningList : _api.WarningData.getWarningList;
    return func(current, pageSize, id, state.start, state.end, state.tab === 'all' ? '' : state.tab);
  }, {
    defaultPageSize: 10,
    paginated: true,
    refreshDeps: [state.tab, state.start, state.end, id]
  }),
      tableProps = _useRequest.tableProps; // eslint-disable-next-line no-undef


  (0, _react.useEffect)(function () {
    if (seed) setState({
      start: (0, _dayjs["default"])(),
      end: (0, _dayjs["default"])(),
      ids: []
    });
  }, [id, seed]);

  var statList = _api.WarningData.useStatList(id, state.start, state.end, carType);

  var handleTabChange = function handleTabChange(activeKey) {
    setState({
      tab: activeKey
    });
  };

  var handleDateChange = function handleDateChange(start, end) {
    setState({
      start: start,
      end: end
    });
  };

  var handleExport = function handleExport(type) {
    var _tableProps$dataSourc;

    var downloadAll = false;
    var ids = '';

    switch (type) {
      case 'all':
        downloadAll = true;
        break;

      case 'select-rows':
        ids = state.ids.join(',');
        break;

      case 'current-page':
        ids = tableProps === null || tableProps === void 0 ? void 0 : (_tableProps$dataSourc = tableProps.dataSource) === null || _tableProps$dataSourc === void 0 ? void 0 : _tableProps$dataSourc.map(function (i) {
          return i.id;
        }).join(',');
        break;

      default:
        break;
    }

    if (!downloadAll && ids.length === 0) {
      _antd.message.info('当前未选中数据！');

      return;
    }

    console.log(tableProps);

    if (carType === 'jxh') {
      _api.WarningData.exportJxhData({
        tenantId: (0, _utils.getUrlParam)('tenantId'),
        carIds: id,
        startDate: state.start,
        endDate: state.end,
        subCategoryCode: state.tab === 'all' ? '' : state.tab,
        categoryCode: 'Alarm',
        columnJson: (0, _vmTable.renderColumnParam)(columns),
        ids: ids
      });

      return;
    }

    _api.WarningData.exportData({
      carIds: id,
      startTime: state.start,
      endTime: state.end,
      downloadAll: downloadAll,
      ids: ids,
      alarmStrategyName: state.tab === 'all' ? '' : state.tab,
      columnJson: (0, _vmTable.renderColumnParam)(columns)
    });
  };

  return /*#__PURE__*/_react["default"].createElement("div", {
    className: "vehicle-warning-content"
  }, /*#__PURE__*/_react["default"].createElement(_antd.Space, {
    className: "filter"
  }, /*#__PURE__*/_react["default"].createElement(_vmFilter.VMDatePicker, {
    defaultValue: [state.start, state.end],
    onChange: function onChange(dates) {
      return dates && handleDateChange(dates[0], dates[1]);
    }
  }), state.totalTab === 'table' && /*#__PURE__*/_react["default"].createElement(_vmTable.ExportBtn, {
    onClick: handleExport
  })), /*#__PURE__*/_react["default"].createElement(_vmSubTabs["default"], {
    defaultActiveKey: state.totalTab,
    onChange: function onChange(activeKey) {
      return setState({
        totalTab: activeKey
      });
    }
  }, /*#__PURE__*/_react["default"].createElement(_vmSubTabs.SubTabPane, {
    tab: /*#__PURE__*/_react["default"].createElement("span", null, /*#__PURE__*/_react["default"].createElement(_icons.UnorderedListOutlined, null), "\u5217\u8868"),
    key: "table"
  }, /*#__PURE__*/_react["default"].createElement(_vmTable.TableTabs, {
    activeKey: state.tab,
    onChange: handleTabChange
  }, statList.map(function (item) {
    return /*#__PURE__*/_react["default"].createElement(_vmTable.TableTabsPane, {
      tab: "".concat(item.label, "(").concat(carType === 'jxh' ? tableProps.pagination.total || 0 : item.count, ")"),
      key: item.key
    }, /*#__PURE__*/_react["default"].createElement("div", {
      className: "table-container"
    }, /*#__PURE__*/_react["default"].createElement(_vmTable["default"], _extends({
      columns: carType === 'jxh' ? jxhColumns : columns,
      rowSelection: {
        selectedRowKeys: state.ids,
        onChange: function onChange(rowKeys) {
          return setState({
            ids: rowKeys
          });
        }
      }
    }, tableProps))));
  }))), /*#__PURE__*/_react["default"].createElement(_vmSubTabs.SubTabPane, {
    tab: /*#__PURE__*/_react["default"].createElement("span", null, /*#__PURE__*/_react["default"].createElement(_icons.ClockCircleOutlined, null), "\u56FE\u8868"),
    key: "chart"
  }, /*#__PURE__*/_react["default"].createElement(ChartContent, {
    id: id,
    carType: carType,
    jxhTrendData: tableProps.dataSource,
    start: state.start.format('YYYY-MM-DD hh:mm:ss'),
    end: state.end.format('YYYY-MM-DD hh:mm:ss')
  }))), /*#__PURE__*/_react["default"].createElement("div", {
    className: "top-bar"
  }));
};

WarningContent.propTypes = {
  id: _propTypes["default"].string,
  seed: _propTypes["default"].string
};

var ChartContent = function ChartContent(props) {
  var id = props.id,
      start = props.start,
      end = props.end,
      carType = props.carType,
      jxhTrendData = props.jxhTrendData;

  var _BaseData$useAlarmSta = _api.BaseData.useAlarmStat(id, start, end),
      statChartInfo = _BaseData$useAlarmSta.statChartInfo,
      statLineInfo = _BaseData$useAlarmSta.statLineInfo;

  return /*#__PURE__*/_react["default"].createElement("div", {
    style: {
      height: '100%'
    }
  }, carType === 'jxh' ? /*#__PURE__*/_react["default"].createElement(JxhTrendChart, {
    data: jxhTrendData,
    start: start,
    end: end
  }) : /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement(StatChart, {
    data: statChartInfo
  }), /*#__PURE__*/_react["default"].createElement(TrendChart, {
    data: statLineInfo,
    height: 260
  })));
};

ChartContent.propTypes = {
  id: _propTypes["default"].string,
  start: _propTypes["default"].string,
  end: _propTypes["default"].string
};

var StatChart = function StatChart(props) {
  var data = props.data;

  var _useSettings = (0, _useSettings2["default"])(),
      isDark = _useSettings.isDark;

  var total = (0, _react.useMemo)(function () {
    var result = 0;

    var _iterator = _createForOfIteratorHelper(data),
        _step;

    try {
      for (_iterator.s(); !(_step = _iterator.n()).done;) {
        var item = _step.value;
        result += item.count;
      }
    } catch (err) {
      _iterator.e(err);
    } finally {
      _iterator.f();
    }

    return result;
  }, [data]);
  var chartData = data.map(function (item, index) {
    return {
      value: item.count,
      name: item.alarmTypeName,
      itemStyle: {
        color: item.color ? _config.ECHARTS_COLOR[item.color] : _config.COLOR_COLLECTION[index]
      }
    };
  });
  var option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      icon: 'circle',
      orient: 'vertical',
      top: '35%',
      left: '65%',
      itemHeight: 8,
      itemWidth: 8,
      itemGap: 14,
      textStyle: {
        fontSize: 14,
        fontFamily: 'PingFangSC-Regular',
        rich: {
          a: {
            color: isDark ? 'white' : '#666'
          },
          b: {
            color: isDark ? 'white' : '#222'
          }
        }
      },
      formatter: function formatter(name) {
        var _data$find;

        var num = ((_data$find = data.find(function (i) {
          return i.alarmTypeName === name;
        })) === null || _data$find === void 0 ? void 0 : _data$find.count) || 0;
        return "{a|".concat(name, "}      {b|").concat(num, "\u6B21(").concat(total === 0 ? 0 : Math.round(num * 100 / total), "%)}");
      }
    },
    graphic: [{
      type: 'group',
      left: '40%',
      top: '50%',
      bounding: 'raw',
      children: [{
        type: 'text',
        style: {
          text: '违规次数',
          fontFamily: 'PingFangSC-Regular',
          fontSize: 14,
          fill: '#858A91',
          align: 'center',
          y: -20
        }
      }, {
        type: 'text',
        style: {
          text: total,
          fontWeight: 'bold',
          fontSize: 20,
          fill: isDark ? 'white' : '#222',
          fontFamily: 'DIN-Regular',
          align: 'center',
          y: 10
        }
      }]
    }],
    series: [{
      name: '',
      type: 'pie',
      radius: ['45%', '70%'],
      center: ['40%', '50%'],
      label: {
        show: false
      },
      labelLine: {
        show: false
      },
      data: chartData
    }]
  };
  return /*#__PURE__*/_react["default"].createElement(_vmChart["default"], {
    option: option,
    height: 260,
    width: "100%"
  });
};

StatChart.propTypes = {
  data: _propTypes["default"].array
};

var JxhTrendChart = function JxhTrendChart(_ref2) {
  var _ref2$data = _ref2.data,
      data = _ref2$data === void 0 ? [] : _ref2$data,
      start = _ref2.start,
      end = _ref2.end;
  var startDay = (0, _dayjs["default"])(start);
  var endDay = (0, _dayjs["default"])(end);
  var days = endDay.diff(startDay, 'd') + 1;
  var chartData = {};

  var xAxis = _toConsumableArray(new Array(days)).map(function (e, i) {
    var currentDay = startDay.add(i, 'd').format('YYYY-MM-DD');
    chartData[currentDay] = {
      count: 0,
      duration: 0
    };
    var dayAlarmArr = data.filter(function (item) {
      return currentDay === (0, _dayjs["default"])(item.startTime).format('YYYY-MM-DD');
    });
    var currentDayAlarmCount = dayAlarmArr.length;
    var currentDayDuration = dayAlarmArr.reduce(function (pre, cur) {
      return pre + cur.currentDuration;
    }, 0);
    var hour = (currentDayDuration / 1000 / 3600).toFixed(2);
    chartData[currentDay].count = currentDayAlarmCount;
    chartData[currentDay].duration = hour;
    return currentDay;
  });

  var option = {
    tooltip: {
      trigger: 'axis'
    },
    grid: {
      left: '5%',
      right: '5%',
      bottom: '10%'
    },
    xAxis: {
      data: xAxis
    },
    yAxis: [{
      name: 'h',
      type: 'value',
      min: 0
    }, {
      type: 'value',
      name: '次',
      min: 0
    }],
    series: [{
      name: '超速时长',
      type: 'bar',
      data: xAxis.map(function (date) {
        return chartData[date].duration;
      })
    }, {
      name: '超速次数',
      type: 'line',
      data: xAxis.map(function (date) {
        return chartData[date].count;
      }),
      yAxisIndex: 1
    }]
  };
  return /*#__PURE__*/_react["default"].createElement(_vmChart["default"], {
    option: option,
    height: "100%",
    width: "100%"
  });
};

var TrendChart = function TrendChart(props) {
  var data = props.data,
      height = props.height;
  var xAxisData = [];
  var legendData = [];

  var getSeries = function getSeries() {
    var series = [];

    var _iterator2 = _createForOfIteratorHelper(data),
        _step2;

    try {
      var _loop = function _loop() {
        var item = _step2.value;

        if (xAxisData.findIndex(function (x) {
          return x === item.day;
        }) === -1) {
          xAxisData.push(item.day);
        }

        if (legendData.findIndex(function (l) {
          return l === item.alarmTypeName;
        }) === -1) {
          legendData.push(item.alarmTypeName);
        }

        var s = series.find(function (s) {
          return s.name === item.alarmTypeName;
        });

        if (s) {
          s.data.push(item.count);
        } else {
          series.push({
            name: item.alarmTypeName,
            type: 'line',
            itemStyle: {
              color: item.color ? _config.ECHARTS_COLOR[item.color] : _config.COLOR_COLLECTION[xAxisData.findIndex(function (x) {
                return x === item.alarmTypeName;
              })]
            },
            data: [item.count]
          });
        }
      };

      for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
        _loop();
      }
    } catch (err) {
      _iterator2.e(err);
    } finally {
      _iterator2.f();
    }

    return series;
  };

  var option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: legendData
    },
    grid: {
      left: '5%',
      right: '5%',
      bottom: '10%'
    },
    xAxis: {
      data: xAxisData
    },
    yAxis: {
      name: '(次)'
    },
    series: getSeries()
  };
  return /*#__PURE__*/_react["default"].createElement(_vmChart["default"], {
    option: option,
    height: height,
    width: "100%"
  });
};

TrendChart.propTypes = {
  data: _propTypes["default"].array,
  height: _propTypes["default"].number
};
var columns = [{
  title: '报警类型',
  dataIndex: 'alarmTypeName',
  key: 'alarmTypeName',
  width: 80
}, {
  title: '报警等级',
  dataIndex: 'alarmLevelName',
  key: 'alarmLevelName',
  width: 80
}, {
  title: '报警开始时间',
  dataIndex: 'alarmBeginTime',
  key: 'alarmBeginTime',
  width: 120
}, {
  title: '报警结束时间',
  dataIndex: 'alarmEndTime',
  key: 'alarmEndTime',
  width: 120
}, {
  title: '报警时长',
  dataIndex: 'beginDuration',
  key: 'beginDuration',
  width: 120
}, {
  title: '当前速度(km/h)',
  dataIndex: 'positionSpeed',
  key: 'positionSpeed',
  width: 100
}, {
  title: '报警地址',
  dataIndex: 'alarmAddress',
  key: 'alarmAddress',
  width: 300
}];
var jxhColumns = [{
  title: '报警类型',
  dataIndex: 'subCategoryName',
  key: 'subCategoryName',
  width: 80
}, {
  title: '报警开始时间',
  dataIndex: 'startTime',
  key: 'startTime',
  width: 120
}, {
  title: '报警结束时间',
  dataIndex: 'endTime',
  key: 'endTime',
  width: 120
}, {
  title: '报警时长',
  dataIndex: 'currentDurationStr',
  key: 'currentDurationStr',
  width: 120
}, {
  title: '当前速度(km/h)',
  dataIndex: 'currentSpeed',
  key: 'currentSpeed',
  width: 100
}, {
  title: '报警地址',
  dataIndex: 'roadName',
  key: 'roadName',
  width: 300
}];
var _default = WarningContent;
exports["default"] = _default;
//# sourceMappingURL=warning.js.map
