"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault")["default"];
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));
var _regeneratorRuntime2 = _interopRequireDefault(require("@babel/runtime/helpers/regeneratorRuntime"));
var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof"));
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
var _objectSpread3 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));
var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
var _react = _interopRequireDefault(require("react"));
var _r2g7rm = _interopRequireDefault(require("./assets/r2g7rm.jpg"));
var _documentTitle = _interopRequireDefault(require("@uiw-admin/document-title"));
var _uiw = require("uiw");
var _request = require("@kkt/request");
var _jsxRuntime = require("react/jsx-runtime");
var _excluded = ["name", "required", "labelFor"],
  _excluded2 = ["title"];
var Login = function Login(props) {
  var _props$align = props.align,
    align = _props$align === void 0 ? 'center' : _props$align,
    _props$classNameWarp = props.classNameWarp,
    classNameWarp = _props$classNameWarp === void 0 ? '' : _props$classNameWarp,
    _props$styleWarp = props.styleWarp,
    styleWarp = _props$styleWarp === void 0 ? {} : _props$styleWarp,
    _props$classNameBody = props.classNameBody,
    classNameBody = _props$classNameBody === void 0 ? '' : _props$classNameBody,
    _props$styleBody = props.styleBody,
    styleBody = _props$styleBody === void 0 ? {} : _props$styleBody,
    _props$footer = props.footer,
    footer = _props$footer === void 0 ? true : _props$footer,
    _props$bg = props.bg,
    bg = _props$bg === void 0 ? _r2g7rm["default"] : _props$bg,
    _props$logo = props.logo,
    logo = _props$logo === void 0 ? _r2g7rm["default"] : _props$logo,
    children = props.children,
    _props$projectName = props.projectName,
    projectName = _props$projectName === void 0 ? 'UIW Admin' : _props$projectName,
    _props$onSuccess = props.onSuccess,
    _onSuccess = _props$onSuccess === void 0 ? function () {
      return null;
    } : _props$onSuccess,
    _props$btnProps = props.btnProps,
    btnProps = _props$btnProps === void 0 ? {} : _props$btnProps,
    api = props.api,
    onBefore = props.onBefore,
    requestConfig = props.requestConfig,
    buttons = props.buttons,
    saveField = props.saveField,
    fields = props.fields,
    _props$isDefaultField = props.isDefaultFields,
    isDefaultFields = _props$isDefaultField === void 0 ? true : _props$isDefaultField,
    defaultFieldsConfig = props.defaultFieldsConfig,
    _props$styleContainer = props.styleContainer,
    styleContainer = _props$styleContainer === void 0 ? {} : _props$styleContainer;
  var _ref = saveField || {},
    _ref$userName = _ref.userName,
    userName = _ref$userName === void 0 ? 'username' : _ref$userName,
    _ref$passWord = _ref.passWord,
    passWord = _ref$passWord === void 0 ? 'password' : _ref$passWord;
  var userNameLabel = ((defaultFieldsConfig || {})['userName'] || {})['label'] || '账号';
  var passWordLabel = ((defaultFieldsConfig || {})['passWord'] || {})['label'] || '密码';
  userName = ((defaultFieldsConfig || {})['userName'] || {})['name'] || userName;
  passWord = ((defaultFieldsConfig || {})['passWord'] || {})['name'] || passWord;
  var _React$useState = _react["default"].useState(),
    _React$useState2 = (0, _slicedToArray2["default"])(_React$useState, 2),
    store = _React$useState2[0],
    setStore = _React$useState2[1];
  var _useReactMutation = (0, _request.useReactMutation)((0, _objectSpread3["default"])((0, _objectSpread3["default"])({
      url: api,
      method: 'POST'
    }, requestConfig), {}, {
      mutationKey: ['login'],
      onSuccess: function onSuccess(res) {
        return _onSuccess(res, store);
      },
      onError: function onError() {
        return _onSuccess(undefined, store);
      }
    })),
    mutateAsync = _useReactMutation.mutateAsync,
    isLoading = _useReactMutation.isLoading;
  var defaultFields = [(0, _objectSpread3["default"])({
    name: userName,
    label: "".concat(userNameLabel),
    labelFor: userName,
    required: true,
    children: /*#__PURE__*/(0, _jsxRuntime.jsx)("input", {
      type: "text",
      disabled: !!isLoading,
      id: userName,
      placeholder: "\u8BF7\u8F93\u5165".concat(userNameLabel),
      className: "form-field"
    })
  }, (defaultFieldsConfig === null || defaultFieldsConfig === void 0 ? void 0 : defaultFieldsConfig.userName) || {}), (0, _objectSpread3["default"])({
    name: passWord,
    label: "".concat(passWordLabel),
    labelFor: passWord,
    required: true,
    children: /*#__PURE__*/(0, _jsxRuntime.jsx)("input", {
      disabled: !!isLoading,
      id: passWord,
      type: "password",
      placeholder: "\u8BF7\u8F93\u5165".concat(passWordLabel),
      className: "form-field"
    })
  }, (defaultFieldsConfig === null || defaultFieldsConfig === void 0 ? void 0 : defaultFieldsConfig.passWord) || {})];
  var fieldArr = defaultFields;
  if (fields && Array.isArray(fields)) {
    if (isDefaultFields) {
      fieldArr = defaultFields.concat(fields);
    } else {
      fieldArr = fields;
    }
  }
  var FooterRender = _react["default"].useMemo(function () {
    if (footer === false || footer === '') {
      return null;
    } else if (footer === true) {
      return /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
        className: "copyright-footer",
        children: "\u7248\u6743\u6240\u6709 copyright \xA9 2022 uiw admin"
      });
    }
    return footer;
  }, []);
  return /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
    className: "uiw-loayout-login",
    style: (0, _objectSpread3["default"])({
      background: "url(".concat(bg, ")")
    }, styleContainer),
    children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_documentTitle["default"], {
      title: projectName
    }), /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
      style: styleWarp,
      className: "uiw-loayout-login-warp ".concat(classNameWarp, " uiw-loayout-login-warp-").concat(align),
      children: /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
        className: "uiw-loayout-login-body ".concat(classNameBody),
        style: styleBody,
        children: [logo && /*#__PURE__*/(0, _jsxRuntime.jsx)("img", {
          className: "logo",
          src: logo
        }), projectName && /*#__PURE__*/(0, _jsxRuntime.jsx)("span", {
          className: "uiw-title",
          children: projectName
        }), children ? children : /*#__PURE__*/(0, _jsxRuntime.jsx)(_uiw.Form, {
          resetOnSubmit: false,
          onSubmit: /*#__PURE__*/function () {
            var _ref3 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/(0, _regeneratorRuntime2["default"])().mark(function _callee(_ref2) {
              var current, errorObj, err, result;
              return (0, _regeneratorRuntime2["default"])().wrap(function _callee$(_context) {
                while (1) switch (_context.prev = _context.next) {
                  case 0:
                    current = _ref2.current;
                    errorObj = {};
                    fieldArr.forEach(function (item) {
                      if (item.verification && typeof item.verification === 'function') {
                        var result = item.verification(current[item.name], current);
                        if (typeof result === 'string' && result) {
                          errorObj[item.name] = result;
                        }
                      } else if (item.required && !current[item.name]) {
                        errorObj[item.name] = "".concat(item.label, "\u4E0D\u80FD\u4E3A\u7A7A");
                      }
                    });
                    if (!(Object.keys(errorObj).length > 0)) {
                      _context.next = 9;
                      break;
                    }
                    err = new Error();
                    err.filed = errorObj;
                    throw err;
                  case 9:
                    if (!(typeof onBefore === 'function')) {
                      _context.next = 18;
                      break;
                    }
                    result = onBefore(current);
                    if (!((0, _typeof2["default"])(result) === 'object')) {
                      _context.next = 16;
                      break;
                    }
                    setStore((0, _objectSpread3["default"])((0, _objectSpread3["default"])((0, _objectSpread3["default"])({}, current), result || {}), {}, {
                      swr_Rest_Time: new Date().getTime()
                    }));
                    _context.next = 15;
                    return mutateAsync((0, _objectSpread3["default"])((0, _objectSpread3["default"])({}, current), result || {}));
                  case 15:
                    return _context.abrupt("return");
                  case 16:
                    if (result) {
                      _context.next = 18;
                      break;
                    }
                    return _context.abrupt("return");
                  case 18:
                    setStore((0, _objectSpread3["default"])((0, _objectSpread3["default"])({}, current), {}, {
                      swr_Rest_Time: new Date().getTime()
                    }));
                    _context.next = 21;
                    return mutateAsync((0, _objectSpread3["default"])({}, current));
                  case 21:
                  case "end":
                    return _context.stop();
                }
              }, _callee);
            }));
            return function (_x) {
              return _ref3.apply(this, arguments);
            };
          }(),
          onSubmitError: function onSubmitError(error) {
            if (error.filed) {
              return (0, _objectSpread3["default"])({}, error.filed);
            }
            return null;
          },
          fields: fieldArr.reduce(function (pre, current) {
            if (!current || current && !current.name) {
              return (0, _objectSpread3["default"])({}, pre);
            }
            var name = current.name,
              required = current.required,
              labelFor = current.labelFor,
              rest = (0, _objectWithoutProperties2["default"])(current, _excluded);
            return (0, _objectSpread3["default"])((0, _objectSpread3["default"])({}, pre), {}, (0, _defineProperty2["default"])({}, name, (0, _objectSpread3["default"])({
              labelFor: name || labelFor
            }, rest)));
          }, {}),
          children: function children(_ref4) {
            var _ref4$fields = _ref4.fields,
              fields = _ref4$fields === void 0 ? {} : _ref4$fields,
              canSubmit = _ref4.canSubmit;
            var disabled = typeof canSubmit === 'function' ? canSubmit() : undefined;
            return /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
              children: [fieldArr.map(function (item, index) {
                return /*#__PURE__*/(0, _jsxRuntime.jsx)(_uiw.Row, {
                  children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_uiw.Col, {
                    children: fields[item.name]
                  })
                }, index);
              }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_uiw.Row, {
                children: buttons && buttons.length > 0 ? buttons.map(function (item, idx) {
                  var title = item.title,
                    rest = (0, _objectWithoutProperties2["default"])(item, _excluded2);
                  return /*#__PURE__*/(0, _jsxRuntime.jsx)(_uiw.Button, (0, _objectSpread3["default"])((0, _objectSpread3["default"])({
                    loading: !!isLoading && item.htmlType === 'submit',
                    disabled: !disabled,
                    className: "btns",
                    type: "danger"
                  }, rest), {}, {
                    children: title
                  }), idx);
                }) : /*#__PURE__*/(0, _jsxRuntime.jsx)(_uiw.Button, (0, _objectSpread3["default"])((0, _objectSpread3["default"])({
                  disabled: !disabled,
                  loading: !!isLoading,
                  className: "btns",
                  block: true,
                  style: {
                    marginTop: 20,
                    height: 44
                  },
                  htmlType: "submit",
                  type: "dark"
                }, btnProps), {}, {
                  children: "\u767B\u5F55"
                }))
              })]
            });
          }
        })]
      })
    }), FooterRender]
  });
};
var LoginPage = function LoginPage(props) {
  return /*#__PURE__*/(0, _jsxRuntime.jsx)(_request.QueryClientProvider, {
    client: _request.queryClient,
    children: /*#__PURE__*/(0, _jsxRuntime.jsx)(Login, (0, _objectSpread3["default"])({}, props))
  });
};
var _default = LoginPage;
exports["default"] = _default;
module.exports = exports.default;