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 _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 { CaretRightOutlined, HomeOutlined } from '@ant-design/icons';
import { Button, Checkbox, Image, Space, Spin, Table } from 'antd';
import React, { forwardRef, useCallback, useImperativeHandle, useMemo, useState } from 'react';
import back from "./images/back.png";
import excel from "./images/excel.png";
import folder from "./images/folder.png";
import jpeg from "./images/jpeg.png";
import jpg from "./images/jpg.png";
import normal from "./images/normal.png";
import png from "./images/png.png";
import tar from "./images/tar.png";
import text from "./images/text.png";
import zip from "./images/zip.png";
import { useReadFileStyles } from "./styles";
var FileRead = /*#__PURE__*/forwardRef(function (props, ref) {
  var _props$tools;
  var _useReadFileStyles = useReadFileStyles(),
    styles = _useReadFileStyles.styles;
  var data = props.data,
    onClickPath = props.onClickPath,
    operations = props.operations,
    fieldNames = props.fieldNames,
    loading = props.loading;
  var backValue = new Date().getTime().toString() + 'back';
  var _useState = useState([]),
    _useState2 = _slicedToArray(_useState, 2),
    multiples = _useState2[0],
    setMultiples = _useState2[1];
  var _useState3 = useState([]),
    _useState4 = _slicedToArray(_useState3, 2),
    paths = _useState4[0],
    setPaths = _useState4[1];
  useImperativeHandle(ref, function () {
    return {
      paths: paths,
      multiples: multiples
    };
  }, [paths, multiples]);
  var goBack = useCallback(function () {
    var newPaths = paths.slice(0, -1);
    var lastPath = newPaths[newPaths.length - 1];
    onClickPath(lastPath ? '/' + lastPath.path : '', newPaths);
    setPaths(newPaths);
  }, [paths, onClickPath]);
  var goDownUp = useCallback(function (item) {
    if (item.folder) {
      var newPaths = [].concat(_toConsumableArray(paths), [{
        title: item.fileName,
        path: item.fileName
      }]);
      setPaths(newPaths);
      var nowPath = paths.length ? item.fileName + '/' : '/' + item.fileName + '/';
      onClickPath(nowPath, newPaths);
    }
  }, [paths, onClickPath]);
  var getIconType = useCallback(function (item) {
    var mapSuffixs = [{
      suffix: "(png)",
      type: png
    }, {
      suffix: "(jpg)",
      type: jpg
    }, {
      suffix: "(jpeg)",
      type: jpeg
    }, {
      suffix: "(excel|csv)",
      type: excel
    }, {
      suffix: "(txt|text)",
      type: text
    }, {
      suffix: "(tar)",
      type: tar
    }, {
      suffix: "(zip)",
      type: zip
    }];
    var findType = mapSuffixs.find(function (i) {
      var Reg = new RegExp(".*.".concat(i.suffix));
      return Reg.test(item.toLocaleLowerCase());
    });
    if (findType) {
      return findType.type;
    }
    return normal;
  }, []);
  var fileTableMemo = useMemo(function () {
    var sharedOnCell = function sharedOnCell(_, index, key) {
      if (index === 0 && fieldNames && _[fieldNames[0]] === backValue) {
        return {
          colSpan: 0
        };
      }
      return {};
    };
    var cloumns = fieldNames === null || fieldNames === void 0 ? void 0 : fieldNames.map(function (item, index) {
      return {
        title: item,
        dataIndex: item,
        onCell: index === 0 ? function (_, index) {
          return {
            colSpan: _[item] === backValue && index === 0 ? fieldNames.length + 1 + (props.customColumnsRender ? props.customColumnsRender.length : 0) : 1
          };
        } : function (_, idx) {
          return sharedOnCell(_, idx, item);
        },
        // width: index !== 0 ? 180 : undefined,
        render: function render(r, record) {
          var _props$fieldVisible;
          var findItem = (_props$fieldVisible = props.fieldVisible) === null || _props$fieldVisible === void 0 ? void 0 : _props$fieldVisible.find(function (f) {
            return f.dataIndex === item;
          });
          if (findItem && record[findItem.visibleKey] === findItem.visibleValue) {
            return '-';
          }
          if (index === 0) {
            return /*#__PURE__*/React.createElement(Space, {
              align: "baseline"
            }, /*#__PURE__*/React.createElement(Image, {
              width: 16,
              className: 'img',
              src: r === backValue ? back : record.folder ? folder : getIconType(r),
              preview: false
            }), /*#__PURE__*/React.createElement("span", {
              onClick: function onClick() {
                if (r === backValue) {
                  setMultiples([]);
                  goBack();
                } else {
                  goDownUp(record);
                }
              },
              className: record.folder || record[fieldNames[0]] === backValue ? 'linkPath' : ''
            }, r === backValue ? '上一级' : r ? r : '-'));
          }
          return r ? r : '-';
        }
      };
    });
    if (props.customColumnsRender) {
      props.customColumnsRender.forEach(function (i) {
        cloumns.push(_objectSpread(_objectSpread({}, i), {}, {
          onCell: function onCell(_, idx) {
            return sharedOnCell(_, idx, '');
          }
        }));
      });
    }
    var operationCloumn = [{
      title: '操作',
      width: operations.length * 50,
      onCell: function onCell(_, idx) {
        return sharedOnCell(_, idx);
      },
      render: function render(record, r, idx) {
        return operations === null || operations === void 0 ? void 0 : operations.map(function (item) {
          if (item.displayKey && item.displayValue) {
            if (record[item.displayKey] === item.displayValue) {
              return null;
            }
          }
          if (item.render) {
            return item.render(record, paths);
          }
          return /*#__PURE__*/React.createElement(Button, {
            size: "small",
            onClick: function onClick() {
              item.onClick(record, paths);
            },
            style: {
              margin: 0,
              padding: '0 5px'
            },
            key: item.key,
            type: "link",
            danger: item.type === 'danger'
          }, item.title);
        });
      }
    }];
    return /*#__PURE__*/React.createElement(Table, {
      size: "small",
      rowSelection: props.multiple ? {
        preserveSelectedRowKeys: false,
        selectedRowKeys: multiples.map(function (i) {
          return i[fieldNames[0]];
        }),
        onChange: function onChange(keys, selectedRows) {
          setMultiples(selectedRows);
        },
        getCheckboxProps: function getCheckboxProps(record) {
          return {
            disabled: record[fieldNames[0]] === backValue
          };
        }
      } : undefined,
      rowKey: function rowKey(r) {
        return r ? r[fieldNames[0]] : 'file';
      },
      loading: loading,
      showHeader: false,
      pagination: false,
      dataSource: paths.length >= 1 ? [fieldNames && _defineProperty({}, fieldNames[0], backValue)].concat(_toConsumableArray(data)) : data,
      columns: [].concat(_toConsumableArray(cloumns), operationCloumn)
    });
  }, [data, fieldNames, operations, paths, props.fieldVisible, multiples]);
  return /*#__PURE__*/React.createElement("div", {
    className: styles.default
  }, /*#__PURE__*/React.createElement("div", {
    className: 'fileContainer'
  }, /*#__PURE__*/React.createElement("div", {
    className: 'toolContainer'
  }, props.multiple && /*#__PURE__*/React.createElement(Checkbox, {
    indeterminate: multiples.length > 0 && multiples.length < data.length,
    checked: multiples.length === data.length,
    style: {
      marginLeft: '8px'
    },
    onChange: function onChange(e) {
      if (e.target.checked) {
        setMultiples(data);
      } else {
        setMultiples([]);
      }
    }
  }), /*#__PURE__*/React.createElement("div", {
    className: 'pathsContainer'
  }, /*#__PURE__*/React.createElement(HomeOutlined, {
    onClick: function onClick() {
      if (onClickPath) {
        onClickPath('', []);
        setMultiples([]);
        setPaths([]);
      }
    }
  }), paths.map(function (item, index) {
    return /*#__PURE__*/React.createElement("div", {
      className: 'pathItem',
      key: index
    }, /*#__PURE__*/React.createElement(CaretRightOutlined, {
      className: 'icon'
    }), /*#__PURE__*/React.createElement("div", {
      onClick: function onClick() {
        var list = paths.slice(0, index + 1);
        onClickPath('', list);
        setPaths(list);
      },
      className: 'des'
    }, item.title));
  })), /*#__PURE__*/React.createElement("div", {
    className: 'tools'
  }, (_props$tools = props.tools) === null || _props$tools === void 0 ? void 0 : _props$tools.map(function (item) {
    if (!!item.multiple) {
      return multiples.length ? /*#__PURE__*/React.createElement("div", {
        className: 'renderItem'
      }, item.DOM) : null;
    }
    return /*#__PURE__*/React.createElement("div", {
      className: 'renderItem'
    }, item.DOM);
  }))), /*#__PURE__*/React.createElement("div", {
    style: {
      overflow: 'hidden'
    }
  }, /*#__PURE__*/React.createElement(Spin, {
    spinning: loading !== null && loading !== void 0 ? loading : false
  }, fileTableMemo))));
});
export default FileRead;