"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 _classnames = _interopRequireDefault(require("classnames"));

var _dialog = _interopRequireDefault(require("../dialog"));

var _searchInput = _interopRequireDefault(require("../search-input"));

var _getLocale = require("../../utils/getLocale");

var _checkboxList = _interopRequireDefault(require("../checkbox-list"));

var _filePreview = _interopRequireWildcard(require("../file-preview"));

var _nav = _interopRequireDefault(require("../nav"));

var _tools = require("../../utils/tools");

var _utils = require("./utils");

var _button = _interopRequireDefault(require("../button"));

var _scrollContainer = _interopRequireDefault(require("../scroll-container"));

var _loading = _interopRequireDefault(require("../loading"));

require("./index.css");

var _excluded = ["title", "defaultQQDocsData", "onSubmit", "fileNumLimit"];

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 _extends() { _extends = Object.assign || 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) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

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 asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

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; }

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; }

var preCls = 'titaui-dialog-qq-docs';
var catchNavPath = [];
var catchSearchContent = '';
var init = true;
var defaultnNavPath = [{
  label: (0, _getLocale.getLocale)('Feed_Breadcrumb_Allfil'),
  id: undefined
}];

var DialogQQDocs = function DialogQQDocs(_ref) {
  var _ref$title = _ref.title,
      title = _ref$title === void 0 ? (0, _getLocale.getLocale)('Pro_newpro_Upload') : _ref$title,
      defaultQQDocsData = _ref.defaultQQDocsData,
      onSubmit = _ref.onSubmit,
      fileNumLimit = _ref.fileNumLimit,
      restProps = _objectWithoutProperties(_ref, _excluded);

  var _useState = (0, _react.useState)(defaultnNavPath),
      _useState2 = _slicedToArray(_useState, 2),
      navPath = _useState2[0],
      setNavPath = _useState2[1];

  var _useState3 = (0, _react.useState)(''),
      _useState4 = _slicedToArray(_useState3, 2),
      searchContent = _useState4[0],
      setSearchContent = _useState4[1];

  var _useState5 = (0, _react.useState)(false),
      _useState6 = _slicedToArray(_useState5, 2),
      loading = _useState6[0],
      setLoading = _useState6[1];

  var _useState7 = (0, _react.useState)(false),
      _useState8 = _slicedToArray(_useState7, 2),
      isEnd = _useState8[0],
      setIsEnd = _useState8[1];

  var isRoot = navPath.length === 1;
  var isSearch = !!searchContent; // 普通查询：next 为 0 时代表已经加载完成了
  // 模糊搜索：list 为空数组时代表已经加载完成了

  var _useState9 = (0, _react.useState)({
    next: -1,
    list: []
  }),
      _useState10 = _slicedToArray(_useState9, 2),
      docsData = _useState10[0],
      setDocsData = _useState10[1];

  var _useState11 = (0, _react.useState)([]),
      _useState12 = _slicedToArray(_useState11, 2),
      checkListData = _useState12[0],
      setCheckListData = _useState12[1];

  var checkedNum = checkListData.filter(function (item) {
    return item.checked;
  }).length;

  function fetch(_x) {
    return _fetch.apply(this, arguments);
  }

  function _fetch() {
    _fetch = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(params) {
      var res;
      return regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              setLoading(true);
              _context.prev = 1;
              _context.next = 4;
              return (0, _utils.checkTencentAuth)(params);

            case 4:
              res = _context.sent;
              return _context.abrupt("return", res);

            case 8:
              _context.prev = 8;
              _context.t0 = _context["catch"](1);

            case 10:
              _context.prev = 10;
              setLoading(false);
              return _context.finish(10);

            case 13:
              return _context.abrupt("return", {
                next: 0,
                list: []
              });

            case 14:
            case "end":
              return _context.stop();
          }
        }
      }, _callee, null, [[1, 8, 10, 13]]);
    }));
    return _fetch.apply(this, arguments);
  }

  function changeNavPath(docItem, idx) {
    // 如果传了 idx 说明需要再现有的 nav 中截取（直接点击现有的 nav 的情况）
    if (idx !== undefined) setNavPath(navPath.slice(0, idx + 1));else setNavPath([].concat(_toConsumableArray(navPath), [_objectSpread({
      label: docItem.title
    }, docItem)]));
  }

  function refreshFolder() {
    return _refreshFolder.apply(this, arguments);
  }

  function _refreshFolder() {
    _refreshFolder = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() {
      var docItem, data;
      return regeneratorRuntime.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              docItem = navPath[navPath.length - 1];
              _context2.next = 3;
              return fetch({
                folderID: docItem.id
              });

            case 3:
              data = _context2.sent;

              if (data) {
                _context2.next = 6;
                break;
              }

              return _context2.abrupt("return");

            case 6:
              setIsEnd(data.next === 0 || data.list.length < 20);
              setDocsData(data);

            case 8:
            case "end":
              return _context2.stop();
          }
        }
      }, _callee2);
    }));
    return _refreshFolder.apply(this, arguments);
  }

  function onSearch(_x2) {
    return _onSearch.apply(this, arguments);
  }

  function _onSearch() {
    _onSearch = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3(content) {
      var data;
      return regeneratorRuntime.wrap(function _callee3$(_context3) {
        while (1) {
          switch (_context3.prev = _context3.next) {
            case 0:
              _context3.next = 2;
              return fetch({
                content: content
              });

            case 2:
              data = _context3.sent;

              if (data) {
                _context3.next = 5;
                break;
              }

              return _context3.abrupt("return");

            case 5:
              setIsEnd(data.list.length < 20); // 重制 vav

              setNavPath(defaultnNavPath);
              setDocsData(data);

            case 8:
            case "end":
              return _context3.stop();
          }
        }
      }, _callee3);
    }));
    return _onSearch.apply(this, arguments);
  }

  function next() {
    return _next2.apply(this, arguments);
  }

  function _next2() {
    _next2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee4() {
      var newData, lastFolder;
      return regeneratorRuntime.wrap(function _callee4$(_context4) {
        while (1) {
          switch (_context4.prev = _context4.next) {
            case 0:
              lastFolder = navPath[navPath.length - 1]; // 分三种情况
              // 1. 普通模式（未搜索，直接查询）
              // 2. 搜索模式（搜索后第一页）
              // 3. 搜索后点击了某个文件夹

              if (!(searchContent && navPath.length === 1)) {
                _context4.next = 8;
                break;
              }

              _context4.next = 4;
              return fetch({
                start: docsData.next,
                content: searchContent
              });

            case 4:
              newData = _context4.sent;
              setIsEnd(newData.list.length < 20);
              _context4.next = 12;
              break;

            case 8:
              _context4.next = 10;
              return fetch({
                start: docsData.next,
                folderID: lastFolder.id
              });

            case 10:
              newData = _context4.sent;
              setIsEnd(newData.next === 0 || newData.list.length < 20);

            case 12:
              setDocsData({
                next: newData.next,
                list: [].concat(_toConsumableArray(docsData.list), _toConsumableArray(newData.list))
              });

            case 13:
            case "end":
              return _context4.stop();
          }
        }
      }, _callee4);
    }));
    return _next2.apply(this, arguments);
  }

  (0, _react.useEffect)(function () {
    // 初始化会从外部传入文档数据，所以不需要查询
    if (init) {
      init = false;
      return;
    } // navPath 更新后刷新当前的文件列表
    // navPath !== defaultnNavPath 是避免在搜索时重制 nav 造成重复请求到问题，因为搜索会调 onSearch，如果再调 refreshFolder 就重复了


    if (navPath !== defaultnNavPath) refreshFolder();
  }, [navPath]);

  var onClickTitleHandler = function onClickTitleHandler(docItem) {
    // 切换文件夹
    if (docItem.type === _filePreview.DocType.FOLDER) {
      changeNavPath(docItem);
      return;
    } // 在线预览


    (0, _tools.openUrl)(docItem.url);
  };

  function createCheckListData(list) {
    return list.map(function (docItem, i) {
      return _objectSpread({
        component: /*#__PURE__*/_react["default"].createElement(_filePreview["default"], {
          onClickTitle: function onClickTitle() {
            return onClickTitleHandler(docItem);
          },
          title: docItem.title,
          secondTitle: isSearch ? docItem.lastModifyTime : docItem.createTime,
          type: docItem.type
        }),
        isFolder: docItem.type === _filePreview.DocType.FOLDER,
        checked: checkListData[i] && checkListData[i].checked
      }, docItem);
    });
  } // 文件列表数据更新后，同步更新 checkListData


  (0, _react.useEffect)(function () {
    setCheckListData(createCheckListData(docsData.list || []));
  }, [docsData]); // 传入默认的文件列表

  (0, _react.useEffect)(function () {
    if (defaultQQDocsData) {
      setDocsData(defaultQQDocsData);
      setCheckListData(createCheckListData(defaultQQDocsData.list));
    }
  }, [defaultQQDocsData]);
  var onSelectNavHandler = (0, _react.useCallback)(function (idx, nav) {
    // 如果再搜索模式下，切换到了根目录，应该继续执行搜索
    if ((searchContent || catchSearchContent) && idx === 0) {
      setSearchContent('');
      catchSearchContent = '';
      setNavPath([].concat(defaultnNavPath));
      return;
    }

    changeNavPath(nav, idx);
  }, [changeNavPath, searchContent]);
  var onChangeCheckBoxListHandler = (0, _react.useCallback)(function (dataList, idx, item) {
    // 判断点击的是否是文件夹
    if (item.isFolder) {
      setCheckListData(checkListData.map(function (item) {
        return _objectSpread(_objectSpread({}, item), {}, {
          checked: false
        });
      })); // 如果是在搜索模式下，缓存搜索内容，清空搜索框

      if (searchContent) {
        catchSearchContent = searchContent;
        setSearchContent('');
      }

      changeNavPath(item);
      return;
    }

    setCheckListData(dataList);
  }, [changeNavPath, checkListData]);
  var onSearchHandler = (0, _react.useCallback)(function (e) {
    if (searchContent === e) return; // 清空搜索后，恢复到搜索前的状态

    if (!e) {
      setSearchContent(e);
      setNavPath(_toConsumableArray(catchNavPath));
      catchSearchContent = '';
      return;
    } // 当触发搜索时，记录一下搜索前到路径


    catchNavPath = navPath;
    onSearch(e);
    setSearchContent(e);
  }, [navPath, searchContent]);
  var onScrollBottomHandler = (0, _react.useCallback)(function () {
    if (isEnd) return;
    next();
  }, [next, isEnd]);
  var onSubmitHandler = (0, _react.useCallback)(function () {
    if (onSubmit) onSubmit(checkListData.filter(function (item) {
      return item.checked;
    }));
  }, [checkListData]);

  var footer = /*#__PURE__*/_react["default"].createElement("div", {
    className: "".concat(preCls, "__footer")
  }, /*#__PURE__*/_react["default"].createElement("div", null, !!checkedNum && /*#__PURE__*/_react["default"].createElement("p", null, (0, _getLocale.getLocale)('Feed_Set_Pop_Sel'), " ", /*#__PURE__*/_react["default"].createElement("span", {
    className: "".concat(preCls, "__checked-num")
  }, checkedNum), " ", (0, _getLocale.getLocale)('Feed_Set_Pop_Ite'))), /*#__PURE__*/_react["default"].createElement("div", {
    className: "".concat(preCls, "__footer__actions")
  }, /*#__PURE__*/_react["default"].createElement(_button["default"].Rect, {
    onClick: restProps.onClose,
    className: "".concat(preCls, "__cancel-btn")
  }, (0, _getLocale.getLocale)('Mod_Cancel')), /*#__PURE__*/_react["default"].createElement(_button["default"].Rect, {
    onClick: onSubmitHandler,
    disabled: !checkedNum,
    type: "primary"
  }, (0, _getLocale.getLocale)('OKR_MyO_Butt_Determine'))));

  var isSearchNull = checkListData.length === 0 && searchContent;
  var onCloseHandler = (0, _react.useCallback)(function () {
    setSearchContent('');
    setNavPath(defaultnNavPath);
    if (restProps.onClose) restProps.onClose();
  }, [restProps.onClose]);
  return /*#__PURE__*/_react["default"].createElement(_dialog["default"], _extends({
    title: title
  }, restProps, {
    onClose: onCloseHandler,
    extraClass: [preCls, restProps.className || ''],
    footer: footer
  }), /*#__PURE__*/_react["default"].createElement("div", {
    className: "".concat(preCls, "__content")
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: "px-32"
  }, /*#__PURE__*/_react["default"].createElement(_searchInput["default"], {
    onSearch: onSearchHandler,
    value: searchContent,
    placeholder: (0, _getLocale.getLocale)('Feed_Set_Pop_Seaallfil'),
    style: {
      height: 36,
      width: '100%'
    }
  })), !isSearchNull && /*#__PURE__*/_react["default"].createElement("p", {
    className: (0, _classnames["default"])("".concat(preCls, "__search-result-text"), _defineProperty({}, "".concat(preCls, "__search-result-text--hide"), !searchContent))
  }, (0, _getLocale.getLocale)('Per_Ma_form_Searchreslt')), /*#__PURE__*/_react["default"].createElement(_nav["default"], {
    onSelect: onSelectNavHandler,
    className: (0, _classnames["default"])("".concat(preCls, "__nav px-32"), _defineProperty({}, "".concat(preCls, "__nav--hide"), isRoot)),
    dataList: navPath
  }), /*#__PURE__*/_react["default"].createElement(_scrollContainer["default"], {
    className: "".concat(preCls, "__checkbox-list"),
    hideScrollbars: false,
    onScrollBottom: onScrollBottomHandler
  }, /*#__PURE__*/_react["default"].createElement(_checkboxList["default"], {
    onChange: onChangeCheckBoxListHandler,
    dataList: checkListData,
    disabled: fileNumLimit !== undefined && checkedNum >= fileNumLimit
  }), isSearchNull && /*#__PURE__*/_react["default"].createElement("div", {
    className: "".concat(preCls, "__search-null")
  }, (0, _getLocale.getLocale)('Per_Ma_form_NoSearchResul')), !isSearchNull && !loading && isEnd && /*#__PURE__*/_react["default"].createElement("p", {
    className: "".concat(preCls, "__end-text")
  }, (0, _getLocale.getLocale)('Feed_Set_Pop_Datloa'))), /*#__PURE__*/_react["default"].createElement(_loading["default"], {
    visible: loading
  })));
};

var _default = DialogQQDocs;
exports["default"] = _default;