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 { AppstoreOutlined, BarsOutlined, CaretRightOutlined, HomeOutlined } from '@ant-design/icons';
import { Button, Image, Space, Spin, Table } from 'antd';
import React, { forwardRef, useCallback, useEffect, 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];
  var _useState5 = useState({}),
    _useState6 = _slicedToArray(_useState5, 2),
    record = _useState6[0],
    setRecord = _useState6[1];
  var _useState7 = useState('table'),
    _useState8 = _slicedToArray(_useState7, 2),
    viewType = _useState8[0],
    setViewType = _useState8[1];
  useImperativeHandle(ref, function () {
    return {
      paths: paths,
      multiples: multiples
    };
  }, [paths, multiples]);
  useEffect(function () {
    var noClick = function noClick() {
      var dom = document.getElementById('filestools');
      if (dom && dom.style.display === 'block') {
        dom.style.display = 'none';
      }
    };
    document.addEventListener('click', noClick);
    return function () {
      document.removeEventListener('click', noClick);
    };
  }, []);
  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 showContextMenu = useCallback(function (e, item) {
    var _document$getElementB;
    e.stopPropagation();
    e.preventDefault();
    setRecord(item);
    var rect = (_document$getElementB = document.getElementById('filesMaps')) === null || _document$getElementB === void 0 ? void 0 : _document$getElementB.getBoundingClientRect();
    if (rect) {
      var mouseX = e.clientX - (rect === null || rect === void 0 ? void 0 : rect.left);
      var mouseY = e.clientY - rect.top;
      var dom = document.getElementById('filestools');
      if (dom) {
        dom.style.display = 'block';
        dom.style.left = mouseX + 20 + 'px';
        dom.style.top = mouseY + 'px';
      }
    }
  }, [record]);
  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 getFilesTools = useMemo(function () {
    return operations.length ? /*#__PURE__*/React.createElement("div", {
      className: 'filestools',
      id: "filestools"
    }, operations.map(function (operation) {
      if (operation.displayKey && operation.displayValue) {
        if (record[operation.displayKey] === operation.displayValue) {
          return null;
        }
      }
      if (operation.render) {
        return operation.render(record, paths, true);
      }
      return /*#__PURE__*/React.createElement("p", {
        key: operation.key,
        style: operation.type === 'danger' ? {
          color: 'red'
        } : {},
        onClick: function onClick(e) {
          operation === null || operation === void 0 || operation.onClick(record, paths);
        }
      }, operation.title);
    })) : null;
  }, [operations, JSON.stringify(record)]);
  var getClassNameCb = useCallback(function (item) {
    var name = multiples.find(function (i) {
      return JSON.stringify(i) === JSON.stringify(_objectSpread({}, item));
    }) ? 'activeFileItem' : '';
    return name;
  }, [multiples, data]);
  var fileViewDom = useMemo(function () {
    if (props.loading) return null;
    return data === null || data === void 0 ? void 0 : data.map(function (item, index) {
      return /*#__PURE__*/React.createElement("div", {
        key: "".concat(index, "-").concat(item.fileName),
        onMouseMove: function onMouseMove(e) {
          if (e.shiftKey && props.multiple) {
            setMultiples(function (datas) {
              var record = _objectSpread({}, item);
              return datas.some(function (i) {
                return JSON.stringify(i) === JSON.stringify(record);
              }) ? datas : [].concat(_toConsumableArray(datas), [record]);
            });
          }
        },
        onDoubleClick: function onDoubleClick(e) {
          return !e.shiftKey && goDownUp(item);
        },
        onClick: function onClick(e) {
          if (e.shiftKey && props.multiple) {
            setMultiples(function (datas) {
              var record = _objectSpread({}, item);
              return datas.some(function (i) {
                return JSON.stringify(i) === JSON.stringify(record);
              }) ? datas : [].concat(_toConsumableArray(datas), [record]);
            });
          } else {
            multiples.length > 0 && setMultiples([]);
          }
        },
        onContextMenu: function onContextMenu(e) {
          return showContextMenu(e, item);
        },
        className: "fileItem ".concat(getClassNameCb(item))
      }, /*#__PURE__*/React.createElement("div", {
        className: "img",
        style: {
          backgroundSize: '100px 100px',
          backgroundRepeat: 'no-repeat',
          backgroundImage: "url(".concat(item.folder ? folder : getIconType(item.fileName), ")")
        }
      }), /*#__PURE__*/React.createElement("div", {
        className: "des"
      }, item.fileName));
    });
  }, [props.loading, data, getClassNameCb, multiples, props.multiple, goDownUp, showContextMenu]);
  var filePicMemo = useMemo(function () {
    return /*#__PURE__*/React.createElement("div", {
      id: "filesMaps",
      className: 'filesMaps'
    }, getFilesTools, paths.length > 0 && /*#__PURE__*/React.createElement("div", {
      onContextMenu: function onContextMenu(e) {
        e.stopPropagation();
        e.preventDefault();
      },
      onDoubleClick: function onDoubleClick() {
        goBack();
      },
      className: 'fileItem'
    }, /*#__PURE__*/React.createElement(Image, {
      className: 'img',
      src: back,
      preview: false
    }), /*#__PURE__*/React.createElement("div", {
      className: 'des'
    }, "\u4E0A\u4E00\u7EA7")), fileViewDom);
  }, [data, operations, getFilesTools, multiples]);
  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: 150,
      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"
          }, 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,
      pagination: false,
      dataSource: paths.length >= 1 ? [fieldNames && _defineProperty({}, fieldNames[0], backValue)].concat(_toConsumableArray(data)) : data,
      showHeader: false,
      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'
  }, /*#__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(BarsOutlined, {
    onClick: function onClick() {
      setViewType('table');
    },
    className: 'icon'.concat(" ", viewType === 'table' ? 'activeicon' : '')
  }), /*#__PURE__*/React.createElement(AppstoreOutlined, {
    onClick: function onClick() {
      setViewType('pic');
    },
    className: 'icon'.concat(" ", viewType === 'pic' ? 'activeicon' : '')
  }))), /*#__PURE__*/React.createElement("div", {
    style: {
      borderRadius: '0 0 10px 10px',
      overflow: viewType === 'pic' ? 'visible' : 'hidden'
    }
  }, /*#__PURE__*/React.createElement(Spin, {
    spinning: loading
  }, viewType === 'pic' ? filePicMemo : fileTableMemo))));
});
export default FileRead;