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); }
var _excluded = ["dataSource", "columns", "dispatch", "style", "filter", "sort", "buttons", "actionButtons", "title", "showTitle", "subTitle", "showSubTitle", "summary", "onValuesChange", "columnSetting", "dataSourceGroup", "view", "gallery", "currentSettingKey", "exportImport", "currentComponentId", "tabs"];
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 ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
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 = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
import { useDebounce, useSize } from 'ahooks';
import { Form } from 'antd';
import React, { forwardRef, useEffect, useImperativeHandle, useMemo, useRef } from 'react';
import classNames from 'classNames';
import Tabs from "./Tabs";
import { useSharedState } from "../../hooks";
import useEngineContext from "../../hooks/useEngineContext";
import Actions from "./Actions";
import Header from "./Header";
import Summary from "./Summary";
import { clearTableSettingToLocalStorage, getCurrentViewModeFromLocalStorage, getHash, getTableSettingFromLocalStorage, mergeColumnSetting, omit, stringify } from "./Table/utils";
import View from "./View";
import useTableSetting from "./hooks/useTableSetting";
import useTransDataSourceGroupSetting from "./hooks/useTransDataSourceGroupSetting";
import useTransFilterSetting from "./hooks/useTransFilterSetting";
import useTransSortSetting from "./hooks/useTransSortSetting";
import useTriggerValuesChange from "./hooks/useTriggerValuesChange";
import { Context, Provider, formatColumn } from "./model";
import "./index.less";
var defaultView = {
  defaultViewMode: 'grid',
  multiple: false,
  modeList: []
};
var GridView = Provider( /*#__PURE__*/forwardRef(function (props, ref) {
  var _context$appHelper, _other$pagination2, _other$pagination5, _other$pagination6, _other$pagination8;
  var dataSource = props.dataSource,
    propsColumns = props.columns,
    dispatch = props.dispatch,
    style = props.style,
    propsFilter = props.filter,
    propsSort = props.sort,
    buttons = props.buttons,
    actionButtons = props.actionButtons,
    title = props.title,
    _props$showTitle = props.showTitle,
    showTitle = _props$showTitle === void 0 ? true : _props$showTitle,
    subTitle = props.subTitle,
    _props$showSubTitle = props.showSubTitle,
    showSubTitle = _props$showSubTitle === void 0 ? true : _props$showSubTitle,
    summary = props.summary,
    _onValuesChange = props.onValuesChange,
    columnSetting = props.columnSetting,
    propsDataSourceGroup = props.dataSourceGroup,
    _props$view = props.view,
    view = _props$view === void 0 ? defaultView : _props$view,
    gallery = props.gallery,
    currentSettingKey = props.currentSettingKey,
    exportImport = props.exportImport,
    currentComponentId = props.currentComponentId,
    tabs = props.tabs,
    other = _objectWithoutProperties(props, _excluded);
  var modal = useSharedState(Context);
  var _Form$useForm = Form.useForm(),
    _Form$useForm2 = _slicedToArray(_Form$useForm, 1),
    form = _Form$useForm2[0];
  var defaultViewMode = view.defaultViewMode,
    multiple = view.multiple;
  var viewMode = Form.useWatch('view_mode', {
    form: form,
    preserve: true
  });
  var context = useEngineContext();
  var wrapRef = useRef(null);
  var tableSettingRef = useRef({});
  var filterDefaultRef = useRef({});
  var initialValuesRef = useRef({});
  var _ref = useSize(wrapRef) || {},
    width = _ref.width;
  var debouncedWidth = useDebounce(width, {
    wait: 100
  });
  var utils = context === null || context === void 0 ? void 0 : (_context$appHelper = context.appHelper) === null || _context$appHelper === void 0 ? void 0 : _context$appHelper.utils;
  var isTerminal = useMemo(function () {
    var _utils$isTerminal;
    return utils === null || utils === void 0 ? void 0 : (_utils$isTerminal = utils.isTerminal) === null || _utils$isTerminal === void 0 ? void 0 : _utils$isTerminal.call(utils);
  }, [utils]);
  var tableId = useMemo(function () {
    if (props.__designMode === 'design') {
      return 'designMode-mock-table-id';
    }
    return (props === null || props === void 0 ? void 0 : props.currentComponentId) || props.__id;
  }, [props.__id, props.__designMode, props === null || props === void 0 ? void 0 : props.currentComponentId]);
  var columns = useMemo(function () {
    return propsColumns.filter(function (item) {
      return !item.hidden;
    });
  }, [propsColumns]);
  var originColumnsMap = useMemo(function () {
    return new Map(columns.map(function (item) {
      return [item.key, formatColumn(item)];
    }));
  }, [columns]);
  var sort = useTransSortSetting({
    sort: propsSort,
    originColumnsMap: originColumnsMap
  });
  var filter = useTransFilterSetting({
    filter: propsFilter,
    originColumnsMap: originColumnsMap
  });
  var dataSourceGroup = useTransDataSourceGroupSetting({
    dataSourceGroup: propsDataSourceGroup,
    originColumnsMap: originColumnsMap
  });
  var currentViewMode = useMemo(function () {
    var localCurrentMode = getCurrentViewModeFromLocalStorage(tableId);
    // 如果是多视图模式默认取
    if (multiple) {
      return viewMode || localCurrentMode;
    }
    return viewMode || defaultViewMode;
  }, [viewMode, defaultViewMode, multiple]);
  var removeTitleColumns = useMemo(function () {
    var _columns = columns.map(function (item) {
      return _objectSpread(_objectSpread({}, item), {}, {
        title: undefined
      });
    });
    return _columns;
  }, [columns]);
  var currentSettingHash = useMemo(function () {
    return currentSettingKey || getHash(removeTitleColumns) || '';
  }, [currentSettingKey, JSON.stringify(removeTitleColumns)]);
  useEffect(function () {
    var setting = getTableSettingFromLocalStorage(tableId);
    if (setting.currentSettingHash !== currentSettingHash) {
      clearTableSettingToLocalStorage(tableId);
    }
  }, [currentSettingHash, tableId]);
  useEffect(function () {
    if (debouncedWidth) {
      modal.dispatch({
        type: 'setTableWidth',
        payload: debouncedWidth || {}
      });
    }
  }, [debouncedWidth]);
  var _useTableSetting = useTableSetting({
      tableId: tableId,
      filter: filter,
      columns: columns,
      columnSetting: columnSetting,
      dataSourceGroup: dataSourceGroup,
      sort: sort,
      view: view,
      currentViewMode: currentViewMode,
      gallery: gallery,
      currentSettingHash: currentSettingHash
    }),
    setTableSetting = _useTableSetting.setTableSetting,
    tableSetting = _useTableSetting.tableSetting;

  // 是否触发onValuesChange
  var getIsTriggerValuesChange = useTriggerValuesChange({
    filter: filter,
    columnSetting: columnSetting,
    dataSourceGroup: dataSourceGroup,
    sort: sort,
    currentViewMode: currentViewMode
  });
  useEffect(function () {
    modal.dispatch({
      type: 'setUtils',
      payload: utils || {}
    });
    modal.dispatch({
      type: 'setIsTerminal',
      payload: isTerminal
    });
  }, [utils, isTerminal]);
  useEffect(function () {
    modal.dispatch({
      type: 'setDefaultColumns',
      payload: mergeColumnSetting({
        columns: columns,
        tableId: tableId,
        currentViewMode: currentViewMode
      })
    });
    modal.dispatch({
      type: 'setOriginColumns',
      payload: columns
    });
  }, [columns, tableId, currentViewMode]);
  useEffect(function () {
    modal.dispatch({
      type: 'setDataSource',
      payload: dataSource
    });
    modal.dispatch({
      type: 'setOriginDataSource',
      payload: dataSource
    });
  }, [dataSource]);
  useEffect(function () {
    modal.dispatch({
      type: 'setTableId',
      payload: tableId
    });
  }, [tableId]);
  useEffect(function () {
    var _other$pagination;
    modal.dispatch({
      type: 'setLocalPagination',
      payload: other === null || other === void 0 ? void 0 : (_other$pagination = other.pagination) === null || _other$pagination === void 0 ? void 0 : _other$pagination.localPagination
    });
  }, [other === null || other === void 0 ? void 0 : (_other$pagination2 = other.pagination) === null || _other$pagination2 === void 0 ? void 0 : _other$pagination2.localPagination]);
  useEffect(function () {
    setTimeout(function () {
      document.body.id = 'body';
    }, 200);
  }, []);
  var filterDefaultValues = useMemo(function () {
    var _other$pagination3, _other$pagination4;
    var defaultValues = ((filter === null || filter === void 0 ? void 0 : filter.list) || []).reduce(function (p, c) {
      var _c$other;
      return _objectSpread(_objectSpread({}, p), {}, _defineProperty({}, c.name, c === null || c === void 0 ? void 0 : (_c$other = c.other) === null || _c$other === void 0 ? void 0 : _c$other.defaultValue));
    }, {
      pagination: {
        page: ((_other$pagination3 = other.pagination) === null || _other$pagination3 === void 0 ? void 0 : _other$pagination3.current) || 1,
        size: ((_other$pagination4 = other.pagination) === null || _other$pagination4 === void 0 ? void 0 : _other$pagination4.pageSize) || 10
      }
    });
    return defaultValues;
  }, [JSON.stringify(filter === null || filter === void 0 ? void 0 : filter.list), (_other$pagination5 = other.pagination) === null || _other$pagination5 === void 0 ? void 0 : _other$pagination5.current, (_other$pagination6 = other.pagination) === null || _other$pagination6 === void 0 ? void 0 : _other$pagination6.pageSize]);
  filterDefaultRef.current = filterDefaultValues;
  tableSettingRef.current = tableSetting;
  initialValuesRef.current = _objectSpread(_objectSpread({}, filterDefaultValues), tableSetting);
  useImperativeHandle(ref, function () {
    if (wrapRef.current) {
      wrapRef.current.formInstance = form;
    }
    // forwardRef 后需要返回元素才能选中
    return wrapRef.current;
  });
  useEffect(function () {
    // 当前视图变更时重置form tableSetting 及 筛选项默认值全部重置
    // form.resetFields();
    form.setFieldsValue(initialValuesRef.current);
  }, [currentViewMode]);
  useEffect(function () {
    // 虚拟表columns由接口获取 columns变更时只重新设置tableSetting
    // 直接设置column_setting对象时useWatch监听数据有误，先设置{}后再设置useWatch可以监听到变更数据
    form.setFieldValue('column_setting', {});
    form.setFieldValue('column_setting', tableSettingRef.current.column_setting);
    // JSON.stringify会丢失 render函数变更的监听 使用自定义stringify处理
  }, [stringify(removeTitleColumns)]);
  useEffect(function () {
    form.setFieldsValue(initialValuesRef.current);
    // ArraySetter在面板state变更时指针改变
  }, [stringify(propsFilter)]);
  return /*#__PURE__*/React.createElement(Form, {
    form: form,
    layout: "vertical",
    onValuesChange: function onValuesChange(cur, values) {
      // 旧版时过滤条件没有 filters 包裹, 此处做出兼容
      var _values = _objectSpread(_objectSpread({}, form.getFieldsValue(true)), values.filters || {});
      var _cur = _objectSpread(_objectSpread({}, cur), cur.filters || {});
      var currentKey = Object.keys(cur)[0];
      if (currentKey !== 'pagination') {
        _values.pagination = _objectSpread(_objectSpread({}, _values.pagination), {}, {
          page: 1
        });
      } else {
        var _other$pagination7;
        // 如果使用本地分页 不执行onValuesChange
        if (other !== null && other !== void 0 && (_other$pagination7 = other.pagination) !== null && _other$pagination7 !== void 0 && _other$pagination7.localPagination) {
          return;
        }
      }

      // if (other?.pagination?.localPagination) {
      setTableSetting(_values);
      // }

      form.setFieldsValue({
        pagination: _values.pagination
      });
      /** 表格内部分组列配置筛选等跳过onValuesChange */
      if (!getIsTriggerValuesChange(cur, values)) {
        return;
      }
      _onValuesChange === null || _onValuesChange === void 0 ? void 0 : _onValuesChange(omit(_cur, ['filters']), _values);
    },
    className: "materials-grid-form-wrap"
  }, /*#__PURE__*/React.createElement("div", {
    className: classNames('materials-grid', {
      'materials-grid-terminal': isTerminal
    }),
    style: style,
    ref: wrapRef
  }, /*#__PURE__*/React.createElement(Header, {
    title: title,
    showTitle: showTitle,
    subTitle: subTitle,
    showSubTitle: showSubTitle,
    buttons: buttons
  }), (tabs === null || tabs === void 0 ? void 0 : tabs.show) && /*#__PURE__*/React.createElement(Form.Item, {
    name: "tabs",
    noStyle: true
  }, /*#__PURE__*/React.createElement(Tabs, tabs)), /*#__PURE__*/React.createElement(Actions, {
    view: view,
    buttons: actionButtons,
    columnSetting: columnSetting,
    dataSourceGroup: dataSourceGroup,
    filter: filter,
    sort: sort,
    tableId: tableId,
    localPagination: other === null || other === void 0 ? void 0 : (_other$pagination8 = other.pagination) === null || _other$pagination8 === void 0 ? void 0 : _other$pagination8.localPagination,
    gallery: gallery,
    exportImport: exportImport
  }), /*#__PURE__*/React.createElement(Summary, {
    summary: summary
  }), /*#__PURE__*/React.createElement(View, _extends({}, props, {
    filter: filter,
    sort: sort,
    setTableSetting: setTableSetting,
    dataSourceGroup: dataSourceGroup
  }))));
}));
export default /*#__PURE__*/forwardRef(GridView);