import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/objectWithoutPropertiesLoose";
import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
import _extends from "@babel/runtime/helpers/extends";
var _excluded = ["name", "required", "labelFor"],
  _excluded2 = ["title"];
import React from 'react';
import bgDefault from './assets/r2g7rm.jpg';
import DocumentTitle from '@uiw-admin/document-title';
import { Form, Row, Col, Button } from 'uiw';
import { QueryClientProvider, queryClient, useReactMutation } from '@kkt/request';
import './styles/index.css';
import { jsx as _jsx } from "react/jsx-runtime";
import { jsxs as _jsxs } from "react/jsx-runtime";
var Login = props => {
  var {
    align = 'center',
    classNameWarp = '',
    styleWarp = {},
    classNameBody = '',
    styleBody = {},
    footer = true,
    bg = bgDefault,
    logo = bgDefault,
    children,
    projectName = 'UIW Admin',
    onSuccess: _onSuccess = () => null,
    btnProps = {},
    api,
    onBefore,
    requestConfig,
    buttons,
    saveField,
    fields,
    isDefaultFields = true,
    defaultFieldsConfig,
    styleContainer = {}
  } = props;
  var {
    userName = 'username',
    passWord = 'password'
  } = saveField || {};
  var userNameLabel = ((defaultFieldsConfig || {})['userName'] || {})['label'] || '账号';
  var passWordLabel = ((defaultFieldsConfig || {})['passWord'] || {})['label'] || '密码';
  userName = ((defaultFieldsConfig || {})['userName'] || {})['name'] || userName;
  passWord = ((defaultFieldsConfig || {})['passWord'] || {})['name'] || passWord;
  var [store, setStore] = React.useState();
  var {
    mutateAsync,
    isLoading
  } = useReactMutation(_extends({
    url: api,
    method: 'POST'
  }, requestConfig, {
    mutationKey: ['login'],
    onSuccess: res => _onSuccess(res, store),
    onError: () => _onSuccess(undefined, store)
  }));
  var defaultFields = [_extends({
    name: userName,
    label: "" + userNameLabel,
    labelFor: userName,
    required: true,
    children: /*#__PURE__*/_jsx("input", {
      type: "text",
      disabled: !!isLoading,
      id: userName,
      placeholder: "\u8BF7\u8F93\u5165" + userNameLabel,
      className: "form-field"
    })
  }, (defaultFieldsConfig == null ? void 0 : defaultFieldsConfig.userName) || {}), _extends({
    name: passWord,
    label: "" + passWordLabel,
    labelFor: passWord,
    required: true,
    children: /*#__PURE__*/_jsx("input", {
      disabled: !!isLoading,
      id: passWord,
      type: "password",
      placeholder: "\u8BF7\u8F93\u5165" + passWordLabel,
      className: "form-field"
    })
  }, (defaultFieldsConfig == null ? void 0 : defaultFieldsConfig.passWord) || {})];
  var fieldArr = defaultFields;
  if (fields && Array.isArray(fields)) {
    if (isDefaultFields) {
      fieldArr = defaultFields.concat(fields);
    } else {
      fieldArr = fields;
    }
  }
  var FooterRender = React.useMemo(() => {
    if (footer === false || footer === '') {
      return null;
    } else if (footer === true) {
      return /*#__PURE__*/_jsx("div", {
        className: "copyright-footer",
        children: "\u7248\u6743\u6240\u6709 copyright \xA9 2022 uiw admin"
      });
    }
    return footer;
  }, []);
  return /*#__PURE__*/_jsxs("div", {
    className: "uiw-loayout-login",
    style: _extends({
      background: "url(" + bg + ")"
    }, styleContainer),
    children: [/*#__PURE__*/_jsx(DocumentTitle, {
      title: projectName
    }), /*#__PURE__*/_jsx("div", {
      style: styleWarp,
      className: "uiw-loayout-login-warp " + classNameWarp + " uiw-loayout-login-warp-" + align,
      children: /*#__PURE__*/_jsxs("div", {
        className: "uiw-loayout-login-body " + classNameBody,
        style: styleBody,
        children: [logo && /*#__PURE__*/_jsx("img", {
          className: "logo",
          src: logo
        }), projectName && /*#__PURE__*/_jsx("span", {
          className: "uiw-title",
          children: projectName
        }), children ? children : /*#__PURE__*/_jsx(Form, {
          resetOnSubmit: false,
          onSubmit: /*#__PURE__*/function () {
            var _ref2 = _asyncToGenerator(function* (_ref) {
              var {
                current
              } = _ref;
              var errorObj = {};
              fieldArr.forEach(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] = item.label + "\u4E0D\u80FD\u4E3A\u7A7A";
                }
              });
              if (Object.keys(errorObj).length > 0) {
                var err = new Error();
                err.filed = errorObj;
                throw err;
              } else {
                if (typeof onBefore === 'function') {
                  var result = onBefore(current);
                  if (typeof result === 'object') {
                    setStore(_extends({}, current, result || {}, {
                      swr_Rest_Time: new Date().getTime()
                    }));
                    yield mutateAsync(_extends({}, current, result || {}));
                    return;
                  }
                  if (!result) {
                    return;
                  }
                }
                setStore(_extends({}, current, {
                  swr_Rest_Time: new Date().getTime()
                }));
                yield mutateAsync(_extends({}, current));
              }
            });
            return function (_x) {
              return _ref2.apply(this, arguments);
            };
          }(),
          onSubmitError: error => {
            if (error.filed) {
              return _extends({}, error.filed);
            }
            return null;
          },
          fields: fieldArr.reduce((pre, current) => {
            if (!current || current && !current.name) {
              return _extends({}, pre);
            }
            var {
                name,
                labelFor
              } = current,
              rest = _objectWithoutPropertiesLoose(current, _excluded);
            return _extends({}, pre, {
              [name]: _extends({
                labelFor: name || labelFor
              }, rest)
            });
          }, {}),
          children: _ref3 => {
            var {
              fields = {},
              canSubmit
            } = _ref3;
            var disabled = typeof canSubmit === 'function' ? canSubmit() : undefined;
            return /*#__PURE__*/_jsxs("div", {
              children: [fieldArr.map((item, index) => {
                return /*#__PURE__*/_jsx(Row, {
                  children: /*#__PURE__*/_jsx(Col, {
                    children: fields[item.name]
                  })
                }, index);
              }), /*#__PURE__*/_jsx(Row, {
                children: buttons && buttons.length > 0 ? buttons.map((item, idx) => {
                  var {
                      title
                    } = item,
                    rest = _objectWithoutPropertiesLoose(item, _excluded2);
                  return /*#__PURE__*/_jsx(Button, _extends({
                    loading: !!isLoading && item.htmlType === 'submit',
                    disabled: !disabled,
                    className: "btns",
                    type: "danger"
                  }, rest, {
                    children: title
                  }), idx);
                }) : /*#__PURE__*/_jsx(Button, _extends({
                  disabled: !disabled,
                  loading: !!isLoading,
                  className: "btns",
                  block: true,
                  style: {
                    marginTop: 20,
                    height: 44
                  },
                  htmlType: "submit",
                  type: "dark"
                }, btnProps, {
                  children: "\u767B\u5F55"
                }))
              })]
            });
          }
        })]
      })
    }), FooterRender]
  });
};
var LoginPage = props => {
  return /*#__PURE__*/_jsx(QueryClientProvider, {
    client: queryClient,
    children: /*#__PURE__*/_jsx(Login, _extends({}, props))
  });
};
export default LoginPage;