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); }
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 _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 _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; }
/**
 * 导入组件
 * @author 施阳 2023-06-01
 */
import React, { useState, useEffect, cloneElement, useContext } from 'react';
import { Button, Space } from 'antd';
import { useInterval, useRequest, useUpdateEffect } from 'ahooks';
import { useConfig } from "../_util/hooks";
import Modal from "../modal/index";
import Initial from "./Initial"; // 导入前
import Confirm from "./Confirm"; // 导入结果确认
import Progressing from "./Progressing"; // 导入中
import Success from "./Success"; // 全部导入成功
import PartialSuccess from "./PartialSuccess"; // 部分导入成功
import Error from "./Error"; // 导入失败
import { validateProgressFn, importProgressFn, confirmImportFn } from "./service";
import { ConfigContext } from "../config-provider/context";
import "./index.less";
var FileImport = function FileImport(props) {
  var _ref;
  var componentContext = useContext(ConfigContext);
  var uiLocale = componentContext.uiLocale;
  var children = props.children,
    title = props.title,
    baseURL = props.baseURL,
    width = props.width,
    template = props.template,
    notice = props.notice,
    successTip = props.successTip,
    errorTip = props.errorTip,
    _props$delay = props.delay,
    delay = _props$delay === void 0 ? 1000 : _props$delay,
    bucketName = props.bucketName,
    _props$forceOpen = props.forceOpen,
    forceOpen = _props$forceOpen === void 0 ? true : _props$forceOpen,
    open = props.open,
    footer = props.footer,
    customRender = props.customRender,
    tableProps = props.tableProps,
    importFn = props.importFn,
    progressFn = props.progressFn,
    onError = props.onError,
    onSuccess = props.onSuccess,
    onVisibleChange = props.onVisibleChange;
  var _useRequest = useRequest(confirmImportFn, {
      manual: true
    }),
    loading = _useRequest.loading,
    runAsync = _useRequest.runAsync;
  var _useState = useState('initial'),
    _useState2 = _slicedToArray(_useState, 2),
    status = _useState2[0],
    setStatus = _useState2[1];
  var _useState3 = useState(open || false),
    _useState4 = _slicedToArray(_useState3, 2),
    visible = _useState4[0],
    setVisible = _useState4[1];
  var _useState5 = useState(0),
    _useState6 = _slicedToArray(_useState5, 2),
    key = _useState6[0],
    setKey = _useState6[1]; // Initial组件key值，控制该组件的卸载
  var _useState7 = useState(''),
    _useState8 = _slicedToArray(_useState7, 2),
    processKey = _useState8[0],
    setProcessKey = _useState8[1]; // 导入任务ID
  var _useState9 = useState(false),
    _useState10 = _slicedToArray(_useState9, 2),
    isCancel = _useState10[0],
    setIsCancel = _useState10[1]; // 是否为取消上传
  var _useState11 = useState(0),
    _useState12 = _slicedToArray(_useState11, 2),
    percent = _useState12[0],
    setPercent = _useState12[1]; // 导入进度（文件上传进度占总进度30%；文件校验进度占总进度70%）
  var _useState13 = useState(),
    _useState14 = _slicedToArray(_useState13, 2),
    step = _useState14[0],
    setStep = _useState14[1]; // 当step为undefined时，定时器会停止轮询
  var _useState15 = useState(),
    _useState16 = _slicedToArray(_useState15, 2),
    progressData = _useState16[0],
    setProgress = _useState16[1];
  var _useState17 = useState(0),
    _useState18 = _slicedToArray(_useState17, 2),
    total = _useState18[0],
    setTotal = _useState18[1]; // 导入数据总条数
  var _useState19 = useState(''),
    _useState20 = _slicedToArray(_useState19, 2),
    fileUrl = _useState20[0],
    setFileUrl = _useState20[1]; // 文件上传后的在线链接地址

  // 进度查询接口的回调函数
  var progressCallback = function progressCallback(data) {
    var statusCode = data.status,
      progress = data.progress;
    setProgress(data);

    // 若取消上传，阻止继续执行
    if (isCancel) {
      setIsCancel(false);
      return;
    }

    // 数据校验中
    if (statusCode === '301') {
      setPercent(30 + progress * 0.7);
      return;
    }

    // 数据校验完成
    if (statusCode === '300') {
      setStatus('confirm');
      return;
    }

    // 导入中
    if (statusCode === '201') {
      setPercent(progress);
      return;
    }

    // 导入成功
    if (statusCode === '200') {
      setStatus('success');
      onSuccess === null || onSuccess === void 0 ? void 0 : onSuccess({
        status: 'success',
        processKey: processKey,
        fileUrl: fileUrl
      }); // 导入成功时，触发成功的回调函数
      return;
    }

    // 部分导入成功
    if (statusCode === '203') {
      setStatus('partial-success');
      onSuccess === null || onSuccess === void 0 ? void 0 : onSuccess({
        status: 'partial-success',
        processKey: processKey,
        fileUrl: fileUrl
      }); // 部分导入成功也会触发成功的回调函数
      return;
    }

    // 数据校验失败
    setStatus('error');
    onError === null || onError === void 0 ? void 0 : onError(data);
  };

  // 受控模式下弹窗的显隐控制
  useUpdateEffect(function () {
    if (open !== undefined) {
      setVisible(open);
    }
  }, [open]);
  useUpdateEffect(function () {
    onVisibleChange === null || onVisibleChange === void 0 ? void 0 : onVisibleChange(visible);
  }, [visible]);

  // 导入状态变化时，需要重置状态
  useEffect(function () {
    setPercent(0); // 重置进度
    setStep(undefined); // 停止轮询
  }, [status]);

  // 检测是否存在导入中的任务，如果存在，则打开弹窗
  useEffect(function () {
    if (forceOpen) {
      progressFn === null || progressFn === void 0 ? void 0 : progressFn().then(function (data) {
        if ((data === null || data === void 0 ? void 0 : data.status) === '201') {
          setVisible(true);
          setStatus('progressing');
          setProcessKey(data.processKey);
          setPercent(data.progress);
          setStep(delay); // 轮询查导入进度
        }
      });
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [delay, forceOpen]);

  // 查询文件校验、导入进度
  useInterval(function () {
    var fetchFn = status === 'uploading' ? validateProgressFn : importProgressFn;
    fetchFn === null || fetchFn === void 0 ? void 0 : fetchFn({
      processKey: processKey
    }, {
      baseURL: baseURL
    }).then(progressCallback).catch(function (err) {
      setStatus('error');
      onError === null || onError === void 0 ? void 0 : onError(err);
    });
  }, step, {
    immediate: true
  });

  // 文件导入
  var importFile = function importFile(url) {
    importFn(url).then(function (processKey) {
      setProcessKey(processKey);
      setStep(delay); // 开始校验文件
    }).catch(function (err) {
      setStatus('error');
      onError === null || onError === void 0 ? void 0 : onError(err);
    });
  };

  // 文件上传
  var onChange = function onChange(file) {
    if (file.status === 'uploading') {
      setStatus('uploading');
      setPercent((file.percent || 0) * 0.3);
    } else if (file.status === 'done') {
      importFile(file.url);
      setFileUrl(file.url);
    } else {
      setStatus('error');
      onError === null || onError === void 0 ? void 0 : onError(file);
    }
  };

  // 取消上传
  var onCancelUpload = function onCancelUpload() {
    setStatus('initial');
    setKey(key + 1); // 如果文件在上传阶段，则卸载Initial模块，终止文件上传
    setIsCancel(true);
  };

  // 关闭弹窗
  var onClose = function onClose(showConfirm) {
    var reset = function reset() {
      setVisible(false);
      setTimeout(function () {
        return setStatus('initial');
      }, 100); // 避免关闭弹窗的瞬间弹窗内容切换造成一闪而过的画面
    };

    if (showConfirm) {
      Modal.confirm({
        className: 'file-confirm-modal',
        title: uiLocale.FileImport.modalConfirmTitle,
        content: uiLocale.FileImport.modalConfirmContent,
        okText: uiLocale.global.okText,
        cancelText: uiLocale.global.cancelText,
        onOk: reset
      });
      return;
    }
    reset();
  };

  // 确认导入
  var onConfirmImport = function onConfirmImport() {
    runAsync({
      processKey: processKey
    }, {
      baseURL: baseURL
    }).then(function () {
      if (forceOpen) {
        setStatus('progressing');
        setStep(delay); // 开始查询导入进度
      } else {
        onSuccess === null || onSuccess === void 0 ? void 0 : onSuccess({
          status: 'confirm',
          processKey: processKey,
          fileUrl: fileUrl
        });
        onClose();
      }
    }).catch(function (err) {
      setStatus('error');
      onError === null || onError === void 0 ? void 0 : onError(err);
    });
  };

  // 渲染不同状态下弹框展示内容
  var renderContent = function renderContent() {
    var defaultDom;

    // 导入前
    if (['initial', 'uploading'].includes(status)) {
      defaultDom = /*#__PURE__*/React.createElement(Initial, {
        key: key,
        status: status,
        template: template,
        notice: notice,
        bucketName: bucketName,
        percent: percent,
        onCancelUpload: onCancelUpload,
        onUpload: onChange
      });
    }

    // 确认导入
    if (status === 'confirm') {
      defaultDom = /*#__PURE__*/React.createElement(Confirm, {
        baseURL: baseURL,
        tableProps: tableProps,
        setTotal: setTotal,
        processKey: processKey,
        renderNotice: customRender === null || customRender === void 0 ? void 0 : customRender.notice,
        renderContent: customRender === null || customRender === void 0 ? void 0 : customRender.confirm
      });
    }

    // 导入中
    if (status === 'progressing') {
      defaultDom = /*#__PURE__*/React.createElement(Progressing, {
        percent: percent
      });
      if (customRender !== null && customRender !== void 0 && customRender.progressing) {
        return customRender === null || customRender === void 0 ? void 0 : customRender.progressing(defaultDom, {
          percent: percent
        });
      }
    }

    // 全部导入成功
    if (status === 'success') {
      defaultDom = /*#__PURE__*/React.createElement(Success, {
        successTip: successTip,
        onReImport: function onReImport() {
          return setStatus('initial');
        }
      });
      if (customRender !== null && customRender !== void 0 && customRender.success) {
        return customRender === null || customRender === void 0 ? void 0 : customRender.success(defaultDom, {
          setStatus: setStatus
        });
      }
    }

    // 部分导入成功
    if (status === 'partial-success') {
      var _progressData$nosUrl, _progressData$total, _progressData$success, _progressData$errorCo;
      var options = {
        errorFileUrl: (_progressData$nosUrl = progressData === null || progressData === void 0 ? void 0 : progressData.nosUrl) !== null && _progressData$nosUrl !== void 0 ? _progressData$nosUrl : '',
        totalCount: (_progressData$total = progressData === null || progressData === void 0 ? void 0 : progressData.total) !== null && _progressData$total !== void 0 ? _progressData$total : 0,
        successCount: (_progressData$success = progressData === null || progressData === void 0 ? void 0 : progressData.successCount) !== null && _progressData$success !== void 0 ? _progressData$success : 0,
        errorCount: (_progressData$errorCo = progressData === null || progressData === void 0 ? void 0 : progressData.errorCount) !== null && _progressData$errorCo !== void 0 ? _progressData$errorCo : 0
      };
      defaultDom = /*#__PURE__*/React.createElement(PartialSuccess, _extends({}, options, {
        onReImport: function onReImport() {
          return setStatus('initial');
        }
      }));
      if (customRender !== null && customRender !== void 0 && customRender.partialSuccess) {
        return customRender === null || customRender === void 0 ? void 0 : customRender.partialSuccess(defaultDom, _objectSpread(_objectSpread({}, options), {}, {
          setStatus: setStatus
        }));
      }
    }

    // 导入失败
    if (status === 'error') {
      var _progressData$nosUrl2;
      defaultDom = /*#__PURE__*/React.createElement(Error, {
        errorTip: errorTip,
        errorFileUrl: (_progressData$nosUrl2 = progressData === null || progressData === void 0 ? void 0 : progressData.nosUrl) !== null && _progressData$nosUrl2 !== void 0 ? _progressData$nosUrl2 : '',
        onReImport: function onReImport() {
          return setStatus('initial');
        }
      });
      if (customRender !== null && customRender !== void 0 && customRender.error) {
        var _progressData$nosUrl3;
        return customRender === null || customRender === void 0 ? void 0 : customRender.error(defaultDom, {
          setStatus: setStatus,
          errorFileUrl: (_progressData$nosUrl3 = progressData === null || progressData === void 0 ? void 0 : progressData.nosUrl) !== null && _progressData$nosUrl3 !== void 0 ? _progressData$nosUrl3 : ''
        });
      }
    }
    return defaultDom;
  };

  // 渲染页脚
  var renderFooter = function renderFooter() {
    if (status === 'confirm') {
      return /*#__PURE__*/React.createElement(Space, null, /*#__PURE__*/React.createElement(Button, {
        onClick: function onClick() {
          return onClose(true);
        }
      }, uiLocale.global.cancelText), total > 0 ? /*#__PURE__*/React.createElement(Button, {
        type: "primary",
        onClick: onConfirmImport,
        loading: loading
      }, customRender !== null && customRender !== void 0 && customRender.notice ? uiLocale.FileImport.noticeBtnText : uiLocale.FileImport.confirmBtnText) : /*#__PURE__*/React.createElement(Button, {
        type: "primary",
        onClick: function onClick() {
          return setStatus('initial');
        }
      }, uiLocale.FileImport.repeatBtnText));
    }
    if (status === 'success') {
      return /*#__PURE__*/React.createElement(Button, {
        type: "primary",
        onClick: function onClick() {
          return onClose();
        }
      }, uiLocale.FileImport.finishBtnText);
    }
    return null;
  };
  return useConfig( /*#__PURE__*/React.createElement(Modal, {
    className: "u-file-import",
    title: title,
    width: (_ref = _typeof(width) === 'object' ? width[status] : width) !== null && _ref !== void 0 ? _ref : 600,
    open: visible,
    closable: !['uploading', 'progressing'].includes(status),
    footer: renderFooter(),
    onCancel: function onCancel() {
      return onClose(status === 'confirm');
    },
    triggerDom: /*#__PURE__*/cloneElement(children !== null && children !== void 0 ? children : /*#__PURE__*/React.createElement(Button, {
      type: "primary"
    }, title), {
      onClick: function onClick() {
        return setVisible(true);
      }
    })
  }, renderContent(), (footer === null || footer === void 0 ? void 0 : footer[status]) && /*#__PURE__*/React.createElement("div", {
    className: "footer"
  }, footer[status])));
};
export default FileImport;