var _excluded = ["uiType", "request", "isBatch", "buttonProps", "onSuccess", "qrBeforeClick", "confirmBeforeClick"],
  _excluded2 = ["renderClassName", "renderContent", "className", "content"];
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; }
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 _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); }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
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(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
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 React, { useState, useCallback, useMemo, useEffect, useRef } from 'react';
import { ConfigProvider } from 'antd';
// import { QuestionCircleFilled } from '@ant-design/icons';

import { QueryFilter } from '@ant-design/pro-form';
import { logger } from '@irim/saber';
import ActionButton from "../button";
import useRequest from "../common/use-request";
import get from 'lodash/get';
// @ts-ignore
import Table from "../table";
import FilterItem from "./filter-item";
import NoticeSection from "./notice-section";
import Sort from "./sort";
import moment from 'dayjs';
import "./index.less";
import emptySVG from "./empty_02.svg";
export default function ComposeManage(_ref) {
  var _dataRequest$params;
  var alertProps = _ref.alertProps,
    dataRequest = _ref.dataRequest,
    dataFormatter = _ref.dataFormatter,
    filterProps = _ref.filterProps,
    _ref$filterSpan = _ref.filterSpan,
    filterSpan = _ref$filterSpan === void 0 ? null : _ref$filterSpan,
    _ref$filterLabelWidth = _ref.filterLabelWidth,
    filterLabelWidth = _ref$filterLabelWidth === void 0 ? '80' : _ref$filterLabelWidth,
    _ref$synchValues = _ref.synchValues,
    synchValues = _ref$synchValues === void 0 ? null : _ref$synchValues,
    tableProps = _ref.tableProps,
    _ref$sortProps = _ref.sortProps,
    sortProps = _ref$sortProps === void 0 ? null : _ref$sortProps,
    _ref$removeResetButto = _ref.removeResetButton,
    removeResetButton = _ref$removeResetButto === void 0 ? false : _ref$removeResetButto,
    _ref$filterClassName = _ref.filterClassName,
    filterClassName = _ref$filterClassName === void 0 ? 'ss-query-filter' : _ref$filterClassName,
    tooltip = _ref.tooltip,
    _ref$buttonList = _ref.buttonList,
    buttonList = _ref$buttonList === void 0 ? [] : _ref$buttonList,
    onSearchChange = _ref.onSearchChange,
    onRequestSuccess = _ref.onRequestSuccess,
    onEmit = _ref.onEmit,
    initialFilterValues = _ref.initialFilterValues;
  // 定义data数据
  var _useState = useState([]),
    _useState2 = _slicedToArray(_useState, 2),
    pageData = _useState2[0],
    setPageData = _useState2[1];
  // 定义Table的数据源
  var _useState3 = useState([]),
    _useState4 = _slicedToArray(_useState3, 2),
    tableSource = _useState4[0],
    setTableSource = _useState4[1];
  var _useState5 = useState(null),
    _useState6 = _slicedToArray(_useState5, 2),
    sortTable = _useState6[0],
    setSortTable = _useState6[1];
  // 定义pageSize
  var _useState7 = useState(get(tableProps, 'pagination.pageSize', (dataRequest === null || dataRequest === void 0 || (_dataRequest$params = dataRequest.params) === null || _dataRequest$params === void 0 ? void 0 : _dataRequest$params.pageSize) || 20)),
    _useState8 = _slicedToArray(_useState7, 2),
    pageSize = _useState8[0],
    setPageSize = _useState8[1];
  // 当前页码
  var _useState9 = useState(1),
    _useState10 = _slicedToArray(_useState9, 2),
    pageNo = _useState10[0],
    setPageNo = _useState10[1];
  // 总数据条数
  var _useState11 = useState(0),
    _useState12 = _slicedToArray(_useState11, 2),
    total = _useState12[0],
    setTotal = _useState12[1];
  // 查询条件
  var _useState13 = useState(initialFilterValues),
    _useState14 = _slicedToArray(_useState13, 2),
    search = _useState14[0],
    setSearch = _useState14[1];
  // Table组件的checkbox的选择值集合
  var _useState15 = useState([]),
    _useState16 = _slicedToArray(_useState15, 2),
    selectedRowKeys = _useState16[0],
    setSelectedRowKeys = _useState16[1];
  var _useState17 = useState(Date.now()),
    _useState18 = _slicedToArray(_useState17, 2),
    t = _useState18[0],
    setT = _useState18[1];
  // const [filterForm] = Form.useForm();
  // Table组件是否需要分页
  var hasPage = (tableProps === null || tableProps === void 0 ? void 0 : tableProps.pagination) !== false;
  // 使用lodash.get从dataRequest读取method属性，如果读不到，默认使用'GET'
  var method = get(dataRequest, ['method'], 'GET');
  // const [form] = ProForm.useForm()
  var formRef = useRef(); // 搜索框表单实力
  // 请求
  var _useRequest = useRequest(dataRequest, {
      data: _objectSpread(_objectSpread({}, method.toUpperCase() === 'GET' ? search || {} : {
        search: search
      }), {}, {
        pageNo: pageNo,
        pageSize: pageSize
      }),
      showError: true,
      _t: t
    }, dataFormatter, function (data) {
      var _data$pagination;
      // 从 data 中得到 dataSource 数据

      var nextDataSource = get(data, 'dataSource', []);
      setPageData(data);
      setTableSource(nextDataSource);
      setSelectedRowKeys([]);
      setTotal((tableProps === null || tableProps === void 0 ? void 0 : tableProps.total) || (data === null || data === void 0 || (_data$pagination = data.pagination) === null || _data$pagination === void 0 ? void 0 : _data$pagination.total) || (nextDataSource === null || nextDataSource === void 0 ? void 0 : nextDataSource.length) || 0);
      onRequestSuccess && onRequestSuccess(data);
      // 兼容边界条件：如果删除了某一页的唯一一行，则将分页切回上一页
      if (pageNo > 1 && (nextDataSource === null || nextDataSource === void 0 ? void 0 : nextDataSource.length) === 0) {
        setPageNo(pageNo - 1);
        setT(Date.now());
      }
    }),
    _useRequest2 = _slicedToArray(_useRequest, 2),
    loading = _useRequest2[1];
  if (sortProps && sortProps !== null && sortProps !== void 0 && sortProps.sortRequest) {
    useRequest(sortProps === null || sortProps === void 0 ? void 0 : sortProps.sortRequest, {
      data: _objectSpread(_objectSpread({}, method.toUpperCase() === 'GET' ? search || {} : {
        search: search
      }), {}, {
        pageNo: pageNo,
        pageSize: pageSize
      }),
      showError: true,
      _t: t
    }, dataFormatter, function (data) {
      // 从 data 中得到 dataSource 数据

      var nextDataSource = get(data, 'dataSource', []);
      // if (!data) return;
      setSortTable(nextDataSource);
    });
  }
  useEffect(function () {
    onSearchChange && onSearchChange(search);
  }, [onSearchChange, search]);

  // 执行分页的逻辑;
  var handlePageChange = function handlePageChange(nextPage, pageSize) {
    setPageNo(nextPage);
    setPageSize(pageSize);
  };
  // 执行查询的逻辑
  // const handleSearch = useCallback(() => {
  //   setPageNo(1);
  //   setSearch(filterForm.getFieldsValue());
  // }, []);

  // 执行查询的逻辑;
  var handleSearch = function handleSearch() {
    var values = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    filterProps === null || filterProps === void 0 || filterProps.map(function (item) {
      if (item.type === 'datepicker') {
        values[item.name] = values[item.name] ? moment(values[item.name]).format(item.props._format) : '';
      }
      if (item.type === 'dateRangePicker') {
        var _values$item$name, _item$props, _item$props2;
        values[item.name] = (_values$item$name = values[item.name]) !== null && _values$item$name !== void 0 && _values$item$name.length ? [values[item.name][0] ? moment(values[item.name][0]).format(((_item$props = item.props) === null || _item$props === void 0 ? void 0 : _item$props.format) || 'YYYY-MM-DD') : null, values[item.name][1] ? moment(values[item.name][1]).format(((_item$props2 = item.props) === null || _item$props2 === void 0 ? void 0 : _item$props2.format) || 'YYYY-MM-DD') : null] : [];
      }
      if (item.type === 'dateTimeRangePicker') {
        // console.log(values[item.name], 'xxx');
        if (values[item.name]) {
          var _item$props3, _item$props4;
          values[item.name] = [moment(values[item.name][0]).format((_item$props3 = item.props) === null || _item$props3 === void 0 ? void 0 : _item$props3.format), moment(values[item.name][1]).format((_item$props4 = item.props) === null || _item$props4 === void 0 ? void 0 : _item$props4.format)];
        }
      }
    });
    setPageNo(1);
    // 判断是需要同步
    if (synchValues) {
      setSearch(_objectSpread(_objectSpread({}, values), search));
    } else {
      setSearch(values);
    }
    return Promise.resolve();
  };
  var handleReset = function handleReset() {
    var values = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    setPageNo(1);
    setSearch(initialFilterValues ? initialFilterValues : null);
    formRef.current.resetFields(); // 重置搜索框中表单
    formRef.current.setFieldsValue(initialFilterValues);
    return Promise.resolve();
  };

  // 批量操作;
  var handleRequestButtonSuccess = useCallback(function () {
    // message.success('操作成功！');
    setT(Date.now()); // 触发列表更新
  }, []);

  // 表格事件
  var handleTableEmit = useCallback(function (eventType, record, response) {
    logger.debug("handleTableEmit: ".concat(eventType), record, response);
    onEmit && onEmit(eventType, record, response);
    if (eventType === 'refreshTableData') {
      setT(Date.now());
    }
  }, []);
  // Table组件checkbox的props;
  var rowSelectionProps = {};
  var primaryKey = (tableProps === null || tableProps === void 0 ? void 0 : tableProps.primaryKey) || 'id';
  var _onSelectChange = tableProps.onSelectChange;
  if (tableProps !== null && tableProps !== void 0 && tableProps.checkable || tableProps !== null && tableProps !== void 0 && tableProps.rowSelection) {
    rowSelectionProps = {
      checkable: true,
      rowSelection: tableProps.rowSelection || {},
      selectedRowKeys: selectedRowKeys,
      primaryKey: primaryKey,
      onSelectChange: function onSelectChange(keys, rows) {
        _onSelectChange && _onSelectChange(keys, rows);
        setSelectedRowKeys(keys);
      }
    };
  }
  // Table组件pagination的props;
  var tablePagination = (tableProps === null || tableProps === void 0 ? void 0 : tableProps.pagination) === false ? false : _objectSpread(_objectSpread({
    className: 'cf-compose-manage-pagination',
    total: total,
    size: 'default',
    current: pageNo,
    pageSize: pageSize,
    pageSizeOptions: (tableProps === null || tableProps === void 0 ? void 0 : tableProps.pageSizeOptions) || ['20', '50', '100', '200'],
    showSizeChanger: total - 20 >= 0,
    showQuickJumper: true
  }, tableProps === null || tableProps === void 0 ? void 0 : tableProps.pagination), {}, {
    showTotal: function showTotal() {
      return "\u5171 ".concat(total, " \u6761\u8BB0\u5F55 \u7B2C ").concat(pageNo, "/").concat(Math.ceil(total / pageSize), " \u9875");
    }
  });
  // 使用useMemo缓存选中的table行值;
  var selectedRowList = useMemo(function () {
    // 当primaryKey为函数时，列表勾选的key也要通过该函数转换才能取到正确值
    return selectedRowKeys.map(function (rowId) {
      return tableSource.find(function (rowData) {
        return (typeof primaryKey === 'function' ? primaryKey(rowData) : rowData[primaryKey]) === rowId;
      });
    });
  }, [selectedRowKeys]);
  var formProps = useMemo(function () {
    return {
      colon: true,
      defaultCollapsed: false,
      // layout: 'vertical',
      dateFormatter: false,
      className: filterClassName,
      onFinish: handleSearch,
      onReset: handleReset,
      labelWidth: filterLabelWidth,
      submitter: {
        resetButtonProps: {
          style: {
            // 隐藏重置按钮
            display: removeResetButton ? 'none' : 'block'
          }
        }
      },
      initialValues: search
    };
  }, [search]);
  var renderEmpty = function renderEmpty() {
    return /*#__PURE__*/React.createElement("div", {
      className: "table-empty-style"
    }, /*#__PURE__*/React.createElement("img", {
      src: emptySVG,
      alt: ""
    }), /*#__PURE__*/React.createElement("span", null, "\u6682\u65E0\u6570\u636E"));
  };
  var transformValue = function transformValue() {
    var originText = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
    return originText.toString().replace(/\$\{([\w.]+)\}/g, function (matched, $1) {
      switch ($1) {
        default:
          return get(pageData, $1, matched);
      }
    });
  };
  var tableTitle = function tableTitle() {
    if ((typeof (tooltip === null || tooltip === void 0 ? void 0 : tooltip.title) === 'string' || /*#__PURE__*/React.isValidElement(tooltip === null || tooltip === void 0 ? void 0 : tooltip.title)) && tooltip !== null && tooltip !== void 0 && tooltip.title) {
      return /*#__PURE__*/React.createElement("div", {
        className: "manage-tooltip-left"
      }, tooltip === null || tooltip === void 0 ? void 0 : tooltip.title);
    }
    if (_typeof(tooltip === null || tooltip === void 0 ? void 0 : tooltip.title) === 'object') {
      var _tooltip$title, _tooltip$title2, _tooltip$title3;
      return /*#__PURE__*/React.createElement("div", {
        className: "manage-tooltip-left"
      }, tooltip === null || tooltip === void 0 || (_tooltip$title = tooltip.title) === null || _tooltip$title === void 0 ? void 0 : _tooltip$title.left, /*#__PURE__*/React.createElement("span", {
        className: "center"
      }, transformValue(tooltip === null || tooltip === void 0 || (_tooltip$title2 = tooltip.title) === null || _tooltip$title2 === void 0 ? void 0 : _tooltip$title2.center)), tooltip === null || tooltip === void 0 || (_tooltip$title3 = tooltip.title) === null || _tooltip$title3 === void 0 ? void 0 : _tooltip$title3.right);
    }
    return null;
  };
  return /*#__PURE__*/React.createElement("div", {
    className: "ss-compose-manage-container"
  }, /*#__PURE__*/React.createElement(NoticeSection, {
    alertProps: alertProps,
    onRefresh: function onRefresh() {
      setT(Date.now());
    }
  }), (filterProps === null || filterProps === void 0 ? void 0 : filterProps.length) > 0 && /*#__PURE__*/React.createElement(QueryFilter, _extends({
    formRef: formRef
  }, formProps, {
    span: filterSpan
  }), filterProps === null || filterProps === void 0 ? void 0 : filterProps.map(function (f) {
    return /*#__PURE__*/React.createElement(FilterItem, _extends({
      key: f.name
    }, f));
  })), /*#__PURE__*/React.createElement("section", {
    className: "section-caption"
  }, /*#__PURE__*/React.createElement("div", {
    className: "caption-left-side"
  }, buttonList.map(function (btnProps, index) {
    var uiType = btnProps.uiType,
      request = btnProps.request,
      isBatch = btnProps.isBatch,
      buttonProps = btnProps.buttonProps,
      _onSuccess = btnProps.onSuccess,
      _btnProps$qrBeforeCli = btnProps.qrBeforeClick,
      qrBeforeClick = _btnProps$qrBeforeCli === void 0 ? false : _btnProps$qrBeforeCli,
      confirmBeforeClick = btnProps.confirmBeforeClick,
      others = _objectWithoutProperties(btnProps, _excluded);
    if (request) {
      var _buttonProps, _request, _request2;
      buttonProps = _objectSpread(_objectSpread({}, buttonProps || {}), {}, {
        disabled: isBatch ? !selectedRowKeys.length : (_buttonProps = buttonProps) === null || _buttonProps === void 0 ? void 0 : _buttonProps.disabled
      });
      request = _objectSpread(_objectSpread({}, request || {}), {}, {
        params: uiType === 'download' ? _objectSpread(_objectSpread({}, ((_request = request) === null || _request === void 0 ? void 0 : _request.params) || {}), {}, {
          search: _objectSpread({}, search),
          idList: selectedRowKeys
        }) : _objectSpread(_objectSpread({}, ((_request2 = request) === null || _request2 === void 0 ? void 0 : _request2.params) || {}), {}, {
          idList: selectedRowKeys
          // rowList: selectedRowList || [],
        })
      });

      // confirm 的占位
      var nextConfirmBeforeClick = confirmBeforeClick;
      if (confirmBeforeClick) {
        var _request3, _request4;
        var renderClassName = confirmBeforeClick.renderClassName,
          renderContent = confirmBeforeClick.renderContent,
          className = confirmBeforeClick.className,
          content = confirmBeforeClick.content,
          otherConfirmClick = _objectWithoutProperties(confirmBeforeClick, _excluded2);
        nextConfirmBeforeClick = _objectSpread({
          className: typeof renderContent === 'function' ? renderClassName((_request3 = request) === null || _request3 === void 0 ? void 0 : _request3.params) : className,
          content: typeof renderContent === 'function' ? renderContent((_request4 = request) === null || _request4 === void 0 ? void 0 : _request4.params) : content
        }, otherConfirmClick);
      }
      return /*#__PURE__*/React.createElement(ActionButton, _extends({
        uiType: uiType,
        key: index,
        request: request,
        onSuccess: function onSuccess() {
          _onSuccess && _onSuccess.apply(void 0, arguments);
          handleRequestButtonSuccess();
        },
        qrBeforeClick: qrBeforeClick,
        isBatch: isBatch,
        buttonProps: buttonProps,
        selectedRowKeys: selectedRowKeys,
        confirmBeforeClick: nextConfirmBeforeClick
      }, others));
    }
    return /*#__PURE__*/React.createElement(ActionButton, _extends({
      key: index
    }, btnProps, {
      qrBeforeClick: qrBeforeClick,
      isBatch: isBatch,
      selectedRowKeys: selectedRowKeys,
      onSuccess: function onSuccess() {
        _onSuccess && _onSuccess.apply(void 0, arguments);
        handleRequestButtonSuccess();
      }
    }));
  }), sortProps ? /*#__PURE__*/React.createElement(Sort, _extends({}, sortProps, {
    primaryKey: primaryKey,
    dataSource: sortTable || tableSource,
    tableProps: tableProps,
    onRefresh: handleRequestButtonSuccess
  })) : null)), tooltip ? /*#__PURE__*/React.createElement("div", {
    className: "manage-tooltip"
  }, tableTitle(), /*#__PURE__*/React.createElement("span", {
    className: "manage-tooltip-right"
  }, "\u5171 ", total, " \u6761\u8BB0\u5F55")) : null, /*#__PURE__*/React.createElement(ConfigProvider, {
    renderEmpty: renderEmpty
  }, /*#__PURE__*/React.createElement(Table, _extends({}, tableProps, {
    loading: loading,
    pagination: tablePagination,
    onPageChange: handlePageChange,
    onShowSizeChange: handlePageChange
  }, rowSelectionProps, {
    onEmit: handleTableEmit,
    comsMap: tableProps === null || tableProps === void 0 ? void 0 : tableProps.comsMap,
    primaryKey: tableProps === null || tableProps === void 0 ? void 0 : tableProps.primaryKey,
    hasBorder: tableProps === null || tableProps === void 0 ? void 0 : tableProps.hasBorder,
    columns: tableProps === null || tableProps === void 0 ? void 0 : tableProps.columns,
    dataSource: tableSource || []
  }))));
}