var _excluded = ["schema"],
    _excluded2 = ["schema", "useFieldValuesForRequest", "initialValues", "initialRequest", "formProps", "size", "onFinish", "beforeRequest", "formRef", "extendParams"];

function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(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 _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }

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

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

import React, { useState, useEffect, createRef, useMemo } from 'react';
import { useHistory } from 'react-router-dom';
import { Loading } from '@alicloudfe/components';
import ProForm, { createForm, formilyReactive } from '../form';
import { getTargetValue, resolveMaybePromiseMethod } from '@teamix/utils';
import { doRequest } from './request';
import useDialogAction from './dialog';
import { addContext } from './utils';
var toJS = formilyReactive.toJS;

function getDefaultFormPropsByDialogSize(size) {
  if (size === 'small') {
    return {
      layout: 'horizontal',
      labelCol: 6,
      wrapperCol: 18
    };
  }

  if (size === 'medium') {
    return {
      layout: 'horizontal',
      labelCol: 6,
      wrapperCol: 18
    };
  }

  if (size === 'large') {
    return {
      layout: 'horizontal',
      labelCol: 4,
      wrapperCol: 12
    };
  }

  return {
    layout: 'vertical',
    labelCol: 24,
    wrapperCol: 24
  };
}

function getSchemaAndFormProps(schema, formProps) {
  if (schema instanceof Array) {
    return _objectSpread({
      schema: schema
    }, formProps);
  }

  var formSchema = schema;
  return formSchema;
}

var DialogForm = function DialogForm(props) {
  var initialValues = props.initialValues,
      initialRequest = props.initialRequest,
      _props$size = props.size,
      size = _props$size === void 0 ? 'small' : _props$size,
      schema = props.schema,
      formProps = props.formProps,
      context = props.context,
      formRef = props.formRef,
      innerFormRef = props.innerFormRef,
      _props$validateFirst = props.validateFirst,
      validateFirst = _props$validateFirst === void 0 ? true : _props$validateFirst;
  var form = useMemo(function () {
    return createForm({
      initialValues: getTargetValue(initialValues, context),
      validateFirst: validateFirst
    });
  }, [validateFirst, initialValues, context]);

  var _useMemo = useMemo(function () {
    return getSchemaAndFormProps(schema, formProps);
  }, [schema, formProps]),
      formSchema = _useMemo.schema,
      others = _objectWithoutProperties(_useMemo, _excluded);

  var otherFormProps = useMemo(function () {
    return addContext(getTargetValue(others, context), context);
  }, [context, JSON.stringify(others)]);

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

  var history = useHistory();
  useEffect(function () {
    if (formRef) {
      formRef.current = form;
    }

    innerFormRef.current = form;

    if (initialRequest) {
      setLoading(true);
      doRequest(initialRequest, context, history).then(function (res) {
        form.setValues(res);
        setLoading(false);
      }).catch(function () {
        setLoading(false);
      });
    }
  }, []);
  return /*#__PURE__*/React.createElement(Loading, {
    visible: loading,
    style: {
      display: 'block'
    }
  }, /*#__PURE__*/React.createElement(ProForm, _objectSpread(_objectSpread({
    form: form,
    schema: formSchema
  }, getDefaultFormPropsByDialogSize(size)), otherFormProps)));
};

export function useDialogFormAction(action, context) {
  var schema = action.schema,
      _action$useFieldValue = action.useFieldValuesForRequest,
      useFieldValuesForRequest = _action$useFieldValue === void 0 ? true : _action$useFieldValue,
      initialValues = action.initialValues,
      initialRequest = action.initialRequest,
      _action$formProps = action.formProps,
      formProps = _action$formProps === void 0 ? {} : _action$formProps,
      _action$size = action.size,
      size = _action$size === void 0 ? 'small' : _action$size,
      _onFinish = action.onFinish,
      propsBeforeRequest = action.beforeRequest,
      propsFormRef = action.formRef,
      propsExtendParams = action.extendParams,
      others = _objectWithoutProperties(action, _excluded2);

  var innerFormRef = /*#__PURE__*/createRef();
  return useDialogAction(Object.assign({
    size: size,
    closeable: true,
    content: function content(contentContext) {
      var dialogFormProps = {
        initialValues: initialValues,
        initialRequest: initialRequest,
        schema: schema,
        size: size,
        formProps: formProps,
        context: contentContext
      };
      return /*#__PURE__*/React.createElement(DialogForm, _objectSpread({
        innerFormRef: innerFormRef,
        formRef: propsFormRef
      }, dialogFormProps));
    },
    extendParams: useFieldValuesForRequest ? ['{{fields}}', propsExtendParams] : propsExtendParams,
    beforeRequest: function beforeRequest(context) {
      return new Promise(function (resolve, reject) {
        innerFormRef.current.validate().then( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
          var _innerFormRef$current;

          var beforeRequestContext, fields, requestContext;
          return regeneratorRuntime.wrap(function _callee$(_context) {
            while (1) {
              switch (_context.prev = _context.next) {
                case 0:
                  fields = toJS((_innerFormRef$current = innerFormRef.current) === null || _innerFormRef$current === void 0 ? void 0 : _innerFormRef$current.values);

                  if (!propsBeforeRequest) {
                    _context.next = 14;
                    break;
                  }

                  _context.prev = 2;
                  _context.next = 5;
                  return resolveMaybePromiseMethod(propsBeforeRequest, _objectSpread(_objectSpread({}, context), {}, {
                    fields: fields
                  }));

                case 5:
                  beforeRequestContext = _context.sent;
                  _context.next = 11;
                  break;

                case 8:
                  _context.prev = 8;
                  _context.t0 = _context["catch"](2);
                  beforeRequestContext = false;

                case 11:
                  if (!(beforeRequestContext === false)) {
                    _context.next = 14;
                    break;
                  }

                  reject(false);
                  return _context.abrupt("return");

                case 14:
                  requestContext = Object.assign({
                    fields: fields
                  }, _typeof(beforeRequestContext) === 'object' ? beforeRequestContext : {});
                  resolve(requestContext);

                case 16:
                case "end":
                  return _context.stop();
              }
            }
          }, _callee, null, [[2, 8]]);
        }))).catch(function () {
          resolve(false);
        });
      });
    },
    onFinish: function onFinish() {
      var _innerFormRef$current2;

      _onFinish && _onFinish((_innerFormRef$current2 = innerFormRef.current) === null || _innerFormRef$current2 === void 0 ? void 0 : _innerFormRef$current2.values);
    }
  }, others), context, true);
}
export default useDialogFormAction;