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) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

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

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

import React, { useState } from 'react';
import { useField, observer } from '@formily/react';
import { Dialog, Drawer, Balloon } from '@alicloudfe/components';
import TeamixIcon from '@teamix/icon';
import { BaseItem } from '@teamix/formily';
import { usePrefixCls } from '@teamix/utils';

var useParentPattern = function useParentPattern() {
  var _field$parent, _field$form;

  var field = useField();
  return (field === null || field === void 0 ? void 0 : (_field$parent = field.parent) === null || _field$parent === void 0 ? void 0 : _field$parent.pattern) || (field === null || field === void 0 ? void 0 : (_field$form = field.form) === null || _field$form === void 0 ? void 0 : _field$form.pattern);
};

export var Editable = observer(function (props) {
  return null;
});

Editable.BaseBuilder = function (type) {
  return observer(function (_ref) {
    var props = _extends({}, _ref);

    var field = useField();
    var pattern = useParentPattern();

    var _useState = useState(false),
        _useState2 = _slicedToArray(_useState, 2),
        visible = _useState2[0],
        setVisible = _useState2[1];

    var prefixCls = usePrefixCls('formily-editable', {
      base: true
    });

    var onOk = /*#__PURE__*/function () {
      var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
        var errors;
        return regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                _context.prev = 0;
                _context.next = 3;
                return field.form.validate("".concat(field.address, ".*"));

              case 3:
                _context.prev = 3;
                errors = field.form.queryFeedbacks({
                  type: 'error',
                  address: "".concat(field.address, ".*")
                });

                if (!(errors === null || errors === void 0 ? void 0 : errors.length)) {
                  _context.next = 7;
                  break;
                }

                return _context.abrupt("return");

              case 7:
                setVisible(false);
                return _context.finish(3);

              case 9:
              case "end":
                return _context.stop();
            }
          }
        }, _callee, null, [[0,, 3, 9]]);
      }));

      return function onOk() {
        return _ref2.apply(this, arguments);
      };
    }();

    var onCancel = function onCancel() {
      setVisible(false);
    };

    var onOpen = function onOpen() {
      setVisible(true);
    };

    return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", {
      style: {
        display: 'inline-flex'
      },
      onClick: onOpen
    }, /*#__PURE__*/React.createElement(BaseItem, {
      className: prefixCls('trigger')
    }, /*#__PURE__*/React.createElement("div", {
      className: prefixCls('content')
    }, /*#__PURE__*/React.createElement("span", {
      className: prefixCls('preview')
    }, field.title), pattern === 'editable' && /*#__PURE__*/React.createElement(TeamixIcon, {
      className: prefixCls('edit-btn'),
      type: "form-line",
      size: "small"
    })))), /*#__PURE__*/React.createElement(type, _objectSpread(_objectSpread({
      title: field.title
    }, props), {}, {
      visible: visible,
      onOk: onOk,
      onCancel: onCancel,
      onClose: onCancel
    })));
  });
};

Editable.Popover = observer(function (_ref3) {
  var props = _extends({}, _ref3);

  var field = useField();
  var pattern = useParentPattern();

  var _useState3 = useState(false),
      _useState4 = _slicedToArray(_useState3, 2),
      visible = _useState4[0],
      setVisible = _useState4[1];

  var prefixCls = usePrefixCls('formily-editable', {
    base: true
  });

  var closePopover = /*#__PURE__*/function () {
    var _ref4 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() {
      var errors;
      return regeneratorRuntime.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              _context2.prev = 0;
              _context2.next = 3;
              return field.form.validate("".concat(field.address, ".*"));

            case 3:
              _context2.prev = 3;
              errors = field.form.queryFeedbacks({
                type: 'error',
                address: "".concat(field.address, ".*")
              });

              if (!(errors === null || errors === void 0 ? void 0 : errors.length)) {
                _context2.next = 7;
                break;
              }

              return _context2.abrupt("return");

            case 7:
              setVisible(false);
              return _context2.finish(3);

            case 9:
            case "end":
              return _context2.stop();
          }
        }
      }, _callee2, null, [[0,, 3, 9]]);
    }));

    return function closePopover() {
      return _ref4.apply(this, arguments);
    };
  }();

  var openPopover = function openPopover() {
    setVisible(true);
  };

  return /*#__PURE__*/React.createElement(Balloon, _objectSpread(_objectSpread({}, props), {}, {
    title: field.title,
    className: props.className,
    visible: visible,
    onVisibleChange: function onVisibleChange(visible) {
      if (visible) {
        openPopover();
      } else {
        closePopover();
      }
    },
    align: "t",
    triggerType: "click",
    closable: false,
    trigger: /*#__PURE__*/React.createElement("div", {
      style: {
        display: 'inline-flex'
      }
    }, /*#__PURE__*/React.createElement(BaseItem, {
      className: prefixCls('trigger')
    }, /*#__PURE__*/React.createElement("div", {
      className: prefixCls('content')
    }, /*#__PURE__*/React.createElement("span", {
      className: prefixCls('preview')
    }, props.title || field.title), pattern === 'editable' && /*#__PURE__*/React.createElement(TeamixIcon, {
      className: prefixCls('edit-btn'),
      type: "form-line",
      size: "small"
    }))))
  }), props.children);
});
Editable.Dialog = Editable.BaseBuilder(Dialog);
Editable.Drawer = Editable.BaseBuilder(Drawer);
var EditableDialog = Editable.Dialog;
var EditableDrawer = Editable.Drawer;
var EditablePopover = Editable.Popover;
export { EditableDialog, EditableDrawer, EditablePopover };