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 _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

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

import { __awaiter, __rest } from "tslib";
import React, { createElement, forwardRef, useCallback, useEffect, useImperativeHandle, useRef, useState } from "react";
import classNames from 'classnames';
import { Text } from "@alifd/meet-react-component-one";
import chooseImage from 'universal-choose-image';
import Icon from '../icon';
import { useLocale } from '../locale';
import defaultLang from '../locale/lang/zh-cn';
import Message from '../message';
import { isBoolean, isFunction, isStrictWechatMiniProgram, isString, isValidArray, replaceMessage } from '../utils';
import { isPromise } from '../utils/types';
import View from '../view';
import Card from './item/card';
import { default as defaultRequest } from './request';
import { chooseImageForWechat, createFileItem, UPLOAD_THROTTLE } from './utils';
var FILE_CACHAE = {};

var updateFileStatus = function updateFileStatus() {
  var files = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];

  if (!isValidArray(files)) {
    return [];
  }

  return _toConsumableArray(files).map(function (file) {
    var uid = file.uid,
        state = file.state;

    if (FILE_CACHAE[uid] === 'done' && state === 'uploading') {
      file.state = 'done';
    }

    return file;
  });
};

var Upload = function Upload(props, ref) {
  var _props$prefix = props.prefix,
      prefix = _props$prefix === void 0 ? 'mt-' : _props$prefix,
      extraIcon = props.extraIcon,
      className = props.className,
      action = props.action,
      _props$limit = props.limit,
      limit = _props$limit === void 0 ? 1 : _props$limit,
      _props$label = props.label,
      label = _props$label === void 0 ? '' : _props$label,
      valueProp = props.value,
      defaultValue = props.defaultValue,
      dataProp = props.data,
      headers = props.headers,
      request = props.request,
      formatter = props.formatter,
      disabled = props.disabled,
      _props$size = props.size,
      size = _props$size === void 0 ? 'medium' : _props$size,
      _props$listType = props.listType,
      listType = _props$listType === void 0 ? 'card' : _props$listType,
      _props$name = props.name,
      nameProp = _props$name === void 0 ? 'file' : _props$name,
      filePicker = props.filePicker,
      withCredentials = props.withCredentials,
      fileKeyName = props.fileKeyName,
      _props$fileType = props.fileType,
      fileType = _props$fileType === void 0 ? 'image' : _props$fileType,
      _props$accept = props.accept,
      accept = _props$accept === void 0 ? 'image/*' : _props$accept,
      _props$useDataURL = props.useDataURL,
      useDataURL = _props$useDataURL === void 0 ? true : _props$useDataURL,
      _props$autoUpload = props.autoUpload,
      autoUpload = _props$autoUpload === void 0 ? true : _props$autoUpload,
      _props$hasRemove = props.hasRemove,
      hasRemove = _props$hasRemove === void 0 ? true : _props$hasRemove,
      _props$showAddButton = props.showAddButton,
      showAddButton = _props$showAddButton === void 0 ? true : _props$showAddButton,
      _props$singleLimit = props.singleLimit,
      singleLimit = _props$singleLimit === void 0 ? 9 : _props$singleLimit,
      beforeUpload = props.beforeUpload,
      afterSelect = props.afterSelect,
      onProgress = props.onProgress,
      _onSuccess = props.onSuccess,
      _onError = props.onError,
      progressProps = props.progressProps,
      onSelect = props.onSelect,
      onChange = props.onChange,
      onRemove = props.onRemove,
      onPreview = props.onPreview,
      _props$sizeType = props.sizeType,
      sizeType = _props$sizeType === void 0 ? ['original', 'compressed'] : _props$sizeType,
      _props$sourceType = props.sourceType,
      sourceType = _props$sourceType === void 0 ? ['album', 'camera'] : _props$sourceType,
      children = props.children,
      others = __rest(props, ["prefix", "extraIcon", "className", "action", "limit", "label", "value", "defaultValue", "data", "headers", "request", "formatter", "disabled", "size", "listType", "name", "filePicker", "withCredentials", "fileKeyName", "fileType", "accept", "useDataURL", "autoUpload", "hasRemove", "showAddButton", "singleLimit", "beforeUpload", "afterSelect", "onProgress", "onSuccess", "onError", "progressProps", "onSelect", "onChange", "onRemove", "onPreview", "sizeType", "sourceType", "children"]);

  var name = fileKeyName || nameProp;
  var locale = useLocale('Upload', others, defaultLang.Upload);

  var _useState = useState(valueProp || defaultValue || []),
      _useState2 = _slicedToArray(_useState, 2),
      value = _useState2[0],
      setValue = _useState2[1];

  var newestValue = useRef(value);
  var timerQueue = useRef([]);
  var uploadRef = useRef();
  useEffect(function () {
    if (isValidArray(valueProp)) {
      valueProp.forEach(function (file) {
        if (file.state && file.uid) {
          FILE_CACHAE[file.uid] = file.state;
        }
      });
    }

    return function () {
      timerQueue.current.forEach(function (x) {
        return clearInterval(x);
      });
      timerQueue.current = [];
    };
  }, []);
  var getFile = useCallback(function (uid) {
    var item = newestValue.current.find(function (it) {
      return it.uid === uid;
    });

    if (item) {
      return {
        file: item,
        index: newestValue.current.indexOf(item)
      };
    }

    return undefined;
  }, []);
  var updateFile = useCallback(function (uid, mod) {
    var gotFile = getFile(uid);

    if (!gotFile) {
      throw new Error("File id ".concat(uid, " not found"));
    }

    var file = gotFile.file,
        index = gotFile.index;

    if (mod.state) {
      FILE_CACHAE[uid] = mod.state;
    }

    var isSame = true;

    for (var k in mod) {
      if (mod.hasOwnProperty(k) && file[k] !== mod[k]) {
        isSame = false;
        break;
      }
    }

    if (isSame) {
      return file;
    }

    var newFile = Object.assign(Object.assign({}, file), mod);

    var newValue = _toConsumableArray(newestValue.current);

    newValue.splice(index, 1, newFile);
    newestValue.current = newValue;

    if (onChange) {
      onChange(newValue);
    }

    if (!('value' in props)) {
      setValue(newValue);
    }

    return newFile;
  }, [valueProp, onChange]);
  var uploadFiles = useCallback(function (files) {
    var uploadFile = function uploadFile(it) {
      return __awaiter(void 0, void 0, void 0, /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
        var uid, options, res, curFile, timer, clearTimer, complete, newProcess;
        return regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                if (!(it.state !== 'selected')) {
                  _context.next = 2;
                  break;
                }

                return _context.abrupt("return");

              case 2:
                uid = it.uid;
                updateFile(uid, {
                  state: 'pending'
                });
                options = {
                  action: action,
                  data: dataProp || {},
                  headers: headers || {}
                };

                if (isFunction(options.data)) {
                  options.data = options.data();
                }

                if (!beforeUpload) {
                  _context.next = 29;
                  break;
                }

                _context.prev = 7;
                res = beforeUpload(it, options);

                if (!isBoolean(res)) {
                  _context.next = 15;
                  break;
                }

                if (!(res === false)) {
                  _context.next = 13;
                  break;
                }

                updateFile(uid, {
                  state: 'selected'
                });
                return _context.abrupt("return");

              case 13:
                _context.next = 22;
                break;

              case 15:
                if (!isPromise(res)) {
                  _context.next = 21;
                  break;
                }

                _context.next = 18;
                return res;

              case 18:
                options = _context.sent;
                _context.next = 22;
                break;

              case 21:
                options = res;

              case 22:
                _context.next = 29;
                break;

              case 24:
                _context.prev = 24;
                _context.t0 = _context["catch"](7);
                updateFile(uid, {
                  state: 'error'
                });
                console.error(_context.t0);
                return _context.abrupt("return");

              case 29:
                curFile = updateFile(uid, {
                  state: 'uploading'
                });

                if (onProgress) {
                  onProgress();
                }

                if (options.action) {
                  _context.next = 36;
                  break;
                }

                console.warn('Upload request failed,  action prop is required');
                curFile = updateFile(uid, {
                  state: 'error'
                });

                if (_onError) {
                  _onError(curFile, newestValue.current);
                }

                return _context.abrupt("return");

              case 36:
                timer = null;

                clearTimer = function clearTimer() {
                  if (timer && timerQueue.current.includes(timer)) {
                    clearInterval(timer);
                    timerQueue.current.splice(timerQueue.current.indexOf(timer), 1);
                  }

                  timer = null;
                };

                complete = function complete() {
                  return clearTimer();
                };

                newProcess = 0;
                _context.next = 42;
                return new Promise(function (resolve, reject) {
                  var requestObj = {
                    onProgress: function onProgress(ev) {
                      if (curFile.state !== 'uploading') {
                        return;
                      }

                      if (!timer) {
                        timer = setInterval(function () {
                          if (curFile.state !== 'uploading') {
                            clearTimer();
                            return;
                          }

                          curFile = updateFile(uid, {
                            state: 'uploading',
                            percent: newProcess
                          });

                          if (newProcess === 100) {
                            clearTimer();
                          }
                        }, UPLOAD_THROTTLE);
                        timerQueue.current.push(timer);
                      }

                      newProcess = ev.percent;
                    },
                    onError: function onError(err, body) {
                      console.error('Upload request failed', err);
                      curFile = updateFile(uid, {
                        state: 'error',
                        response: body
                      });

                      if (_onError) {
                        _onError(curFile, newestValue.current);
                      }

                      resolve('error');
                      complete();
                    },
                    onSuccess: function onSuccess(res) {
                      res.status = res.statusCode;

                      if (isString(res.data)) {
                        try {
                          res.data = JSON.parse(res.data);
                        } catch (e) {}
                      }

                      var result = formatter ? formatter(res, it) : res.data;

                      if (_typeof(result) !== 'object') {
                        console.error("Expect a json object response, ".concat(result, " got"));
                        curFile = updateFile(uid, {
                          state: 'error'
                        });

                        if (_onError) {
                          _onError(curFile, newestValue.current);
                        }

                        resolve('error');
                        return;
                      }

                      var finalState = {
                        response: result,
                        percent: 100,
                        state: result.success ? 'done' : 'error'
                      };

                      if (result.success && result.url) {
                        finalState.url = result.url;
                        finalState.imgURL = result.imgURL || result.url;
                        finalState.downloadURL = result.downloadURL || result.url;
                      }

                      curFile = updateFile(uid, finalState);

                      if (finalState.state === 'done' && _onSuccess) {
                        _onSuccess(curFile, newestValue.current);
                      }

                      if (finalState.state === 'error' && _onError) {
                        _onError(curFile, newestValue.current);
                      }

                      clearTimer();
                      resolve('success');
                    },
                    fileType: fileType,
                    data: options.data,
                    filename: name,
                    file: it.file,
                    withCredentials: withCredentials,
                    action: options.action,
                    method: 'post',
                    timeout: 0,
                    headers: options.headers
                  };

                  if (request) {
                    request(requestObj);
                  } else {
                    defaultRequest(requestObj);
                  }
                });

              case 42:
              case "end":
                return _context.stop();
            }
          }
        }, _callee, null, [[7, 24]]);
      }));
    };

    if (!isValidArray(files)) {
      return;
    }

    try {
      Promise.all(files.map(function (it) {
        return uploadFile(it);
      })).then(function () {
        var arr = updateFileStatus(newestValue.current);

        if (arr) {
          if (isFunction(onChange)) {
            onChange(arr);
          }

          if (!('value' in props)) {
            setValue(arr);
            newestValue.current = arr;
          }
        }
      });
    } catch (e) {
      console.warn('上传失败');
    }
  }, [action, dataProp, headers, beforeUpload, onProgress, formatter, _onSuccess, _onError]);
  var doUpload = useCallback(function () {
    return uploadFiles(newestValue.current.filter(function (it) {
      return it.state === 'selected';
    }));
  }, []);
  var doReUpload = useCallback(function (it) {
    updateFile(it.uid, {
      state: 'selected',
      percent: 0
    });
    doUpload();
  }, []);
  var handleAdd = useCallback(function () {
    return __awaiter(void 0, void 0, void 0, /*#__PURE__*/regeneratorRuntime.mark(function _callee2() {
      var file, defaultSizeType, defaultSourceType, mediaType, fileItems, newValue;
      return regeneratorRuntime.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              if (!(limit <= newestValue.current.length || disabled)) {
                _context2.next = 3;
                break;
              }

              Message.notice(replaceMessage(locale.limit, {
                limit: limit
              }));
              return _context2.abrupt("return");

            case 3:
              defaultSizeType = ['original', 'compressed'];
              defaultSourceType = ['album', 'camera'];
              _context2.prev = 5;

              if (!isFunction(filePicker)) {
                _context2.next = 12;
                break;
              }

              _context2.next = 9;
              return filePicker();

            case 9:
              file = _context2.sent;
              _context2.next = 23;
              break;

            case 12:
              if (!isStrictWechatMiniProgram) {
                _context2.next = 20;
                break;
              }

              mediaType = ['video', 'image'];

              if (accept === 'image/*') {
                mediaType = ['image'];
              } else if (accept === 'video/*') {
                mediaType = ['video'];
              }

              _context2.next = 17;
              return chooseImageForWechat({
                count: Math.min(singleLimit, limit - newestValue.current.length),
                mediaType: mediaType,
                sizeType: sizeType || defaultSizeType,
                sourceType: sourceType || defaultSourceType
              });

            case 17:
              file = _context2.sent;
              _context2.next = 23;
              break;

            case 20:
              _context2.next = 22;
              return chooseImage({
                count: Math.min(singleLimit, limit - newestValue.current.length),
                accept: accept,
                sizeType: sizeType || defaultSizeType,
                sourceType: sourceType || defaultSourceType
              });

            case 22:
              file = _context2.sent;

            case 23:
              _context2.next = 28;
              break;

            case 25:
              _context2.prev = 25;
              _context2.t0 = _context2["catch"](5);
              console.error(_context2.t0);

            case 28:
              fileItems = file.data.map(function (it, index) {
                return createFileItem(it, file.files ? file.files[index] : null);
              });

              if (afterSelect) {
                fileItems = fileItems.filter(function (it) {
                  return afterSelect(it) !== false;
                });
              }

              if (useDataURL) {
                fileItems.forEach(function (it) {
                  if (it.dataURL && it.isImage) {
                    it.imgURL = it.dataURL;
                  }
                });
              }

              if (onSelect) {
                onSelect();
              }

              newValue = [].concat(_toConsumableArray(newestValue.current), _toConsumableArray(fileItems));

              if (onChange) {
                onChange(newValue);
              }

              if (!('value' in props)) {
                setValue(newValue);
                newestValue.current = newValue;
              }

              if (autoUpload) {
                doUpload();
              }

            case 36:
            case "end":
              return _context2.stop();
          }
        }
      }, _callee2, null, [[5, 25]]);
    }));
  }, [limit, disabled, locale, sizeType, sourceType, afterSelect, autoUpload, onSelect, onChange]);
  var handleRemove = useCallback(function (file) {
    var doRemove = function doRemove() {
      var index = newestValue.current.indexOf(file);

      if (index === -1) {
        return;
      }

      var newValue = _toConsumableArray(newestValue.current);

      newValue.splice(index, 1);

      if (onChange) {
        onChange(newValue);
      }

      if (!('value' in props)) {
        setValue(newValue);
        newestValue.current = newValue;
      }
    };

    if (!onRemove) {
      doRemove();
      return;
    }

    var result = onRemove(file);

    if (isBoolean(result)) {
      if (result === true) {
        doRemove();
      }

      return;
    }

    if (isPromise(result)) {
      result.then(function (should) {
        return should && doRemove();
      })["catch"](function () {});
    }
  }, [onChange, onRemove]);
  var handleItemClick = useCallback(function (file, e) {
    if (onPreview) {
      onPreview(file, Object.assign(Object.assign({}, e), {
        fileList: value
      }));
    }
  }, [onPreview]);
  useEffect(function () {
    if ('value' in props) {
      newestValue.current = updateFileStatus(valueProp || defaultValue || []);
      setValue(newestValue.current);

      if (autoUpload) {
        doUpload();
      }
    }
  }, [valueProp]);
  useImperativeHandle(ref, function () {
    return Object.assign(uploadRef.current, {
      add: handleAdd,
      upload: doUpload,
      getInstance: function getInstance() {
        return {
          startUpload: doUpload
        };
      }
    });
  });
  var clsPrefix = "".concat(prefix, "upload");
  var hasAdd = showAddButton && limit > value.length && !disabled;
  var ItemComponent = Card;
  return /*#__PURE__*/React.createElement(View, {
    ref: uploadRef
  }, label || extraIcon ? /*#__PURE__*/React.createElement(View, {
    className: "".concat(clsPrefix, "-header")
  }, /*#__PURE__*/React.createElement(Text, {
    className: "".concat(clsPrefix, "-label ").concat(clsPrefix, "-label--").concat(size)
  }, label), extraIcon ? /*#__PURE__*/React.createElement(View, {
    className: "".concat(clsPrefix, "-extra")
  }, /*#__PURE__*/React.createElement(Text, {
    className: "".concat(clsPrefix, "-counter")
  }, value.length || 0, "/", limit), /*#__PURE__*/React.createElement(Icon, {
    className: "".concat(clsPrefix, "-extra-icon"),
    size: size,
    onClick: handleAdd,
    name: extraIcon
  })) : null) : null, /*#__PURE__*/React.createElement(View, _extends({
    className: classNames(clsPrefix, "".concat(clsPrefix, "--").concat(listType), className)
  }, others), value.map(function (file) {
    return /*#__PURE__*/React.createElement(ItemComponent, {
      key: file.uid,
      file: file,
      prefix: clsPrefix,
      progressProps: progressProps,
      onClick: handleItemClick,
      reUpload: locale.reupload,
      onReUpload: doReUpload,
      hasRemove: hasRemove && !disabled,
      onRemove: handleRemove
    });
  }), hasAdd && /*#__PURE__*/React.createElement(View, {
    className: classNames("".concat(clsPrefix, "-item"), "".concat(clsPrefix, "-item--add"), "".concat(clsPrefix, "-item--").concat(listType)),
    onClick: handleAdd
  }, children ? children : /*#__PURE__*/React.createElement(Icon, {
    className: "".concat(clsPrefix, "-item-icon"),
    name: "add"
  }))));
};

Upload.displayName = 'Upload';
export default /*#__PURE__*/forwardRef(Upload);