import _regeneratorRuntime from 'babel-runtime/regenerator';

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

function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }

import React, { forwardRef, useState } from 'react';
import Preview from './../Preview';
import Bridge from './../Bridge';

var Photos = forwardRef(function (_ref, ref) {
  // 点击整个photos容器
  var click = function () {
    var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(event) {
      var e, target, choose, 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 = 12;
                break;
              }

              // 点击添加
              choose = true;

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

              _context.next = 8;
              return beforeChoose();

            case 8:
              choose = _context.sent;

            case 9:
              if (choose && onChoose) onChoose(e);
              _context.next = 13;
              break;

            case 12:
              if (target.classList.contains('photos-item')) {
                // 点击照片
                index = target.getAttribute('data-index');

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

                if (_index && onDelete) onDelete(e, list[_index], Number(_index));
              }

            case 13:
            case 'end':
              return _context.stop();
          }
        }
      }, _callee, this);
    }));

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


  var fileChange = function () {
    var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(event) {
      var e, choose;
      return _regeneratorRuntime.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              e = event.nativeEvent;

              if (type === 'video') e.targetType = 'video';
              choose = true;

              if (!(typeof beforeChoose === 'function')) {
                _context2.next = 7;
                break;
              }

              _context2.next = 6;
              return beforeChoose();

            case 6:
              choose = _context2.sent;

            case 7:
              if (choose && onChoose) onChoose(e);
              e.stopPropagation();

            case 9:
            case 'end':
              return _context2.stop();
          }
        }
      }, _callee2, this);
    }));

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


  var type = _ref.type,
      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 === undefined ? true : _ref$preview,
      others = _objectWithoutProperties(_ref, ['type', 'list', 'upload', 'uploading', 'beforeChoose', 'onChoose', 'onDelete', 'onClick', 'preview']);

  var _useState = useState(null),
      previewCurrent = _useState[0],
      setPreviewCurrent = _useState[1];

  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 React.createElement(
    'div',
    _extends({
      ref: ref
    }, others, {
      className: 'photos' + (others.className ? ' ' + others.className : ''),
      onClick: click
    }),
    list && list.length > 0 && list.map(function (item, index) {
      return 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 && React.createElement('img', { className: 'photos-item-img', src: item.thumb, alt: '', onLoad: load, onError: error }),
        React.createElement('div', { className: 'photos-item-error' }),
        React.createElement('div', { className: 'photos-item-load' }),
        type === 'video' && React.createElement(
          'div',
          { className: 'photos-item-video' },
          React.createElement('div', { className: 'photos-item-video-icon' })
        ),
        onDelete && React.createElement(
          'div',
          { className: 'photos-delete' },
          React.createElement('div', { className: 'photos-delete-icon' })
        ),
        item.children
      );
    }),
    onChoose && React.createElement(
      'div',
      { className: 'photos-item photos-upload' },
      React.createElement('div', { className: 'photos-upload-icon' + (type === 'video' ? ' video' : '') }),
      type === 'video' && Bridge.platform !== 'wq' && Bridge.platform !== 'waiqin' && React.createElement('input', { type: 'file', name: 'uploadVideo', onChange: fileChange, accept: 'video/*', capture: 'camcorder' }),
      type !== 'video' && !navigator.userAgent.toLowerCase().match(/applewebkit.*mobile.*/) && React.createElement('input', { type: 'file', name: 'uploadPhoto', onChange: fileChange, accept: 'image/jpg,image/jpeg,image/png,image/gif,image/bmp' }),
      upload && upload,
      uploading && React.createElement(
        'div',
        { className: 'photos-upload-loading' },
        React.createElement('div', { className: 'photos-upload-loading-icon' })
      )
    ),
    typeof previewCurrent === 'number' && React.createElement(Preview, {
      onHide: function onHide() {
        return setPreviewCurrent(null);
      },
      list: list // 需要预览的资源列表{src: '图片或视频的地址', type: 'video|image, 默认image', thumb: '封面地址'}
      , current: previewCurrent
    })
  );
});

export default Photos;