import _regeneratorRuntime from "@babel/runtime/regenerator";
var _excluded = ["type", "isBrowser", "list", "upload", "uploading", "beforeChoose", "onChoose", "onDelete", "onClick", "preview"];

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

import React, { forwardRef, useState, useRef } from 'react';
import Preview from './../Preview';
import Bridge from './../Bridge';
var Photos = forwardRef(function (_ref, ref) {
  var type = _ref.type,
      isBrowser = _ref.isBrowser,
      list = _ref.list,
      upload = _ref.upload,
      uploading = _ref.uploading,
      beforeChoose = _ref.beforeChoose,
      onChoose = _ref.onChoose,
      onDelete = _ref.onDelete,
      onClick = _ref.onClick,
      _ref$preview = _ref.preview,
      preview = _ref$preview === void 0 ? true : _ref$preview,
      others = _objectWithoutPropertiesLoose(_ref, _excluded);

  // 因为在click事件内改变数据的可能性, 所以更新句柄, 防止synchronization模式读取创建时的状态
  var onChooseRef = useRef();
  var onDeleteRef = useRef();
  var onClickRef = useRef();
  onChooseRef.current = onChoose;
  onDeleteRef.current = onDelete;
  onClickRef.current = onClick;

  var _useState = useState(null),
      previewCurrent = _useState[0],
      setPreviewCurrent = _useState[1]; // 点击整个photos容器


  function handleClick(_x) {
    return _handleClick.apply(this, arguments);
  } // file框选择


  function _handleClick() {
    _handleClick = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(event) {
      var e, target, choose, targetEvent, index, _index;

      return _regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              e = event.nativeEvent;
              target = e.target;

              if (target.type === 'file') {
                target.value = ''; // 防止选择重复图片时不触发
              }

              if (!target.classList.contains('photos-upload')) {
                _context.next = 13;
                break;
              }

              // 点击添加
              choose = true;

              if (!(typeof beforeChoose === 'function')) {
                _context.next = 9;
                break;
              }

              _context.next = 8;
              return beforeChoose();

            case 8:
              choose = _context.sent;

            case 9:
              console.log('是否允许选择:' + choose); // 允许选择

              if (choose) {
                if (fileRef && fileRef.current) {
                  // PC端点击file框
                  // 触发点击
                  if (navigator.userAgent.indexOf('Trident') > -1) {
                    // IE浏览器
                    fileRef.current.click();
                  } else {
                    // 其它浏览器
                    targetEvent = document.createEvent('MouseEvents');
                    targetEvent.initEvent('click', true, true);
                    fileRef.current.dispatchEvent(targetEvent);
                  }
                } else {
                  // 手机端点击div
                  if (onChooseRef && onChooseRef.current) onChooseRef.current(e);
                }
              }

              _context.next = 14;
              break;

            case 13:
              if (target.classList.contains('photos-item')) {
                // 点击照片
                index = target.getAttribute('data-index');
                if (index && onClickRef && onClickRef.current) onClickRef.current(e, list[index].src, [list[index]], Number(index)); // 预览

                if (preview) {
                  if (typeof preview === 'function') preview(e, list[index].src, [list[index]], Number(index));
                  setPreviewCurrent(Number(index));
                }
              } else if (target.classList.contains('photos-delete')) {
                // 点击删除
                _index = target.parentNode.getAttribute('data-index');
                if (_index && onDeleteRef && onDeleteRef.current) onDeleteRef.current(e, list[_index].src, [list[_index]], Number(_index));
              }

            case 14:
            case "end":
              return _context.stop();
          }
        }
      }, _callee);
    }));
    return _handleClick.apply(this, arguments);
  }

  var fileRef = useRef(null);

  function handleFileChange(_x2) {
    return _handleFileChange.apply(this, arguments);
  } // 图片加载完成


  function _handleFileChange() {
    _handleFileChange = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(event) {
      var e;
      return _regeneratorRuntime.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              e = event.nativeEvent;
              if (type === 'video') e.targetType = 'video';
              if (onChooseRef && onChooseRef.current) onChooseRef.current(e);
              e.stopPropagation();

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

  function load(e) {
    var target = e.target;
    target.parentNode.setAttribute('data-complete', '1');
  } // 图片加载失败


  function error(e) {
    var target = e.target;
    target.parentNode.setAttribute('data-complete', '0');
  }

  return /*#__PURE__*/React.createElement("div", _extends({
    ref: ref
  }, others, {
    className: "photos" + (others.className ? ' ' + others.className : ''),
    onClick: handleClick
  }), list && list.length > 0 && list.map(function (item, index) {
    return /*#__PURE__*/React.createElement("div", {
      key: index,
      "data-index": index,
      className: "photos-item" + (item.className ? ' ' + item.className : ''),
      style: Object.assign({
        backgroundImage: item.thumb ? "url(" + item.thumb + ")" : 'initial'
      }, item.style || {}),
      "data-complete": !item.thumb ? "null" : ''
    }, item.thumb && /*#__PURE__*/React.createElement("img", {
      className: "photos-item-img",
      src: item.thumb,
      alt: "",
      onLoad: load,
      onError: error
    }), /*#__PURE__*/React.createElement("div", {
      className: "photos-item-error"
    }), /*#__PURE__*/React.createElement("div", {
      className: "photos-item-load"
    }), onDelete && /*#__PURE__*/React.createElement("div", {
      className: "photos-delete"
    }, /*#__PURE__*/React.createElement("div", {
      className: "photos-delete-icon"
    })), item.children);
  }), onChoose && /*#__PURE__*/React.createElement("div", {
    className: "photos-item photos-upload"
  }, /*#__PURE__*/React.createElement("div", {
    className: "photos-upload-icon" + (type === 'video' ? ' video' : '')
  }), type === 'video' && Bridge.platform !== 'wq' && Bridge.platform !== 'waiqin' && /*#__PURE__*/React.createElement("input", {
    ref: fileRef,
    type: "file",
    className: "photos-upload-file-video",
    name: "uploadVideo",
    onChange: handleFileChange,
    accept: "video/*",
    capture: "camcorder"
  }), type !== 'video' && (!navigator.userAgent.toLowerCase().match(/applewebkit.*mobile.*/) || isBrowser) && /*#__PURE__*/React.createElement("input", {
    ref: fileRef,
    type: "file",
    className: "photos-upload-file-photo",
    name: "uploadPhoto",
    onChange: handleFileChange,
    accept: "image/jpg,image/jpeg,image/png,image/gif,image/bmp"
  }), upload && upload, uploading && /*#__PURE__*/React.createElement("div", {
    className: "photos-upload-loading"
  }, /*#__PURE__*/React.createElement("div", {
    className: "photos-upload-loading-icon"
  }))), typeof previewCurrent === 'number' && /*#__PURE__*/React.createElement(Preview, {
    onHide: function onHide() {
      return setPreviewCurrent(null);
    },
    list: list // 需要预览的资源列表{src: '图片或视频的地址', type: 'video|image, 默认image', thumb: '封面地址'}
    ,
    current: previewCurrent
  }));
});
export default Photos;