import _selectFiles from "parsec-hooks/lib/utils/selectFiles";
import _useStateRef from "parsec-hooks/lib/stateRefHooks";
import _useRefState3 from "parsec-hooks/lib/refStateHooks";

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 _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e2) { throw _e2; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e3) { didErr = true; err = _e3; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }

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

import { View, Text, Image } from '@remax/one';
import classNames from 'classnames';
import React from 'react';
import styles from './index.module.less';
import Icon from '../icon';
import getPlatform from '../get-platform';
export default (function (_ref) {
  var _ref$length = _ref.length,
      length = _ref$length === void 0 ? 1 : _ref$length,
      _ref$multiple = _ref.multiple,
      multiple = _ref$multiple === void 0 ? false : _ref$multiple,
      _ref$showMenu = _ref.showMenu,
      showMenu = _ref$showMenu === void 0 ? false : _ref$showMenu,
      uploadFn = _ref.uploadFn,
      maxSize = _ref.maxSize,
      onMaxError = _ref.onMaxError,
      onError = _ref.onError,
      _ref$beforeUpload = _ref.beforeUpload,
      beforeUpload = _ref$beforeUpload === void 0 ? function () {
    return true;
  } : _ref$beforeUpload,
      _ref$value = _ref.value,
      value = _ref$value === void 0 ? [] : _ref$value,
      onChange = _ref.onChange;

  var _useRefState = _useRefState3([]),
      _useRefState2 = _slicedToArray(_useRefState, 3),
      loadingArr = _useRefState2[0],
      setLoadingArr = _useRefState2[1],
      loadingArrRef = _useRefState2[2];

  var valueRef = _useStateRef(value);

  return /*#__PURE__*/React.createElement(View, {
    className: classNames(styles.uploadImg)
  }, [].concat(_toConsumableArray(value), _toConsumableArray(loadingArr)).map(function (item, index) {
    var loading = loadingArr.includes(item);
    return /*#__PURE__*/React.createElement(View, {
      className: classNames(styles.uploadImgItem),
      key: index
    }, /*#__PURE__*/React.createElement(Image, {
      className: classNames(styles.uploadImgItemImage),
      src: item,
      "show-menu-by-longpress": showMenu
    }), loading ? /*#__PURE__*/React.createElement(View, {
      className: styles.loading
    }, /*#__PURE__*/React.createElement(Icon, {
      name: 'loading',
      color: '#fff'
    })) : /*#__PURE__*/React.createElement(Icon, {
      className: classNames(styles.uploadImgItemDelete),
      name: "clear2",
      color: "#EA5328",
      onTap: function onTap() {
        var temp = _toConsumableArray(value);

        temp.splice(index, 1);
        onChange && onChange(_toConsumableArray(temp));
      }
    }));
  }), value.length + loadingArr.length < length && /*#__PURE__*/React.createElement(View, {
    className: classNames(styles.uploadImgIcon),
    onTap: function onTap() {
      if (valueRef.current.length >= length) {
        return;
      }

      _selectFiles({
        multiple: multiple,
        accept: 'image/*'
      }).then( /*#__PURE__*/function () {
        var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(data) {
          var tempData, _iterator, _step, _loop, _ret, temp;

          return regeneratorRuntime.wrap(function _callee$(_context2) {
            while (1) {
              switch (_context2.prev = _context2.next) {
                case 0:
                  tempData = [];
                  _iterator = _createForOfIteratorHelper(data);
                  _context2.prev = 2;
                  _loop = /*#__PURE__*/regeneratorRuntime.mark(function _loop() {
                    var file, maxErrFn, result, tempFile, fileUrl;
                    return regeneratorRuntime.wrap(function _loop$(_context) {
                      while (1) {
                        switch (_context.prev = _context.next) {
                          case 0:
                            file = _step.value;

                            maxErrFn = function maxErrFn() {
                              return maxSize && file.size > maxSize;
                            };

                            _context.prev = 2;
                            _context.next = 5;
                            return maxErrFn();

                          case 5:
                            if (!_context.sent) {
                              _context.next = 9;
                              break;
                            }

                            if (onMaxError) {
                              onMaxError();
                            }

                            onError && onError('beforeUpload');
                            return _context.abrupt("return", {
                              v: void 0
                            });

                          case 9:
                            _context.next = 11;
                            return beforeUpload(file);

                          case 11:
                            result = _context.sent;
                            tempFile = file;

                            if (!(typeof result === 'boolean')) {
                              _context.next = 18;
                              break;
                            }

                            if (result) {
                              _context.next = 16;
                              break;
                            }

                            return _context.abrupt("return", {
                              v: void 0
                            });

                          case 16:
                            _context.next = 19;
                            break;

                          case 18:
                            tempFile = result;

                          case 19:
                            fileUrl = getPlatform === 'web' && tempFile instanceof File ? URL.createObjectURL(tempFile) : tempFile;
                            setLoadingArr([].concat(_toConsumableArray(loadingArrRef.current), [fileUrl]));
                            _context.next = 23;
                            return uploadFn(tempFile).then(function (url) {
                              loadingArrRef.current.splice(loadingArrRef.current.findIndex(function (i) {
                                return i === fileUrl;
                              }), 1);
                              setLoadingArr(_toConsumableArray(loadingArrRef.current));
                              tempData.push(url);
                            }).catch(onError);

                          case 23:
                            _context.next = 28;
                            break;

                          case 25:
                            _context.prev = 25;
                            _context.t0 = _context["catch"](2);
                            onError && onError('beforeUpload');

                          case 28:
                          case "end":
                            return _context.stop();
                        }
                      }
                    }, _loop, null, [[2, 25]]);
                  });

                  _iterator.s();

                case 5:
                  if ((_step = _iterator.n()).done) {
                    _context2.next = 12;
                    break;
                  }

                  return _context2.delegateYield(_loop(), "t0", 7);

                case 7:
                  _ret = _context2.t0;

                  if (!(_typeof(_ret) === "object")) {
                    _context2.next = 10;
                    break;
                  }

                  return _context2.abrupt("return", _ret.v);

                case 10:
                  _context2.next = 5;
                  break;

                case 12:
                  _context2.next = 17;
                  break;

                case 14:
                  _context2.prev = 14;
                  _context2.t1 = _context2["catch"](2);

                  _iterator.e(_context2.t1);

                case 17:
                  _context2.prev = 17;

                  _iterator.f();

                  return _context2.finish(17);

                case 20:
                  temp = [].concat(_toConsumableArray(valueRef.current), tempData).slice(0, length);
                  onChange && onChange(_toConsumableArray(temp));

                case 22:
                case "end":
                  return _context2.stop();
              }
            }
          }, _callee, null, [[2, 14, 17, 20]]);
        }));

        return function (_x) {
          return _ref2.apply(this, arguments);
        };
      }());
    }
  }, /*#__PURE__*/React.createElement(Icon, {
    className: classNames(styles.uploadImgIconAdd),
    name: "add",
    color: "#999999"
  })), !((value === null || value === void 0 ? void 0 : value.length) + loadingArr.length) && /*#__PURE__*/React.createElement(View, {
    className: classNames(styles.promptText)
  }, /*#__PURE__*/React.createElement(Text, {
    className: classNames(styles.promptText1)
  }, "\u6DFB\u52A0\u56FE\u7247"), /*#__PURE__*/React.createElement(Text, {
    className: classNames(styles.promptText2)
  }, "\u8BF7\u4E0A\u4F20\u9AD8\u6E05\u539F\u56FE\uFF0C\u6700\u591A\u4E0A\u4F20", length, "\u5F20")));
});