// @ts-nocheck
import React, { useState } from 'react';
import styles from './styles.less';
import BaseModal from '../../base';
import { message } from 'antd4';

import { CommonLoginFormPropType } from '@/propType/form/loginForm';

import { RegisterByBusinessForm } from '../../component/form';

import { registerService } from '@/service';

import { errorCodeInfo } from '@/utils/errorInfo';

const RegisterAccountModal = (props: any) => {
  const handleRegisterSuccess = async (res) => {
    if (props?.onSuccess) {
      props.onSuccess(res);
    }
  };

  const handleRegisterFailed = (errInfo) => {
    if (props?.onFailed) {
      props.onFailed(errInfo);
    }
  };

  const commonFormProps: CommonLoginFormPropType = {
    isShowMsg: true,
    onBeforeSubmit: props?.onBeforeSubmit ? props?.onBeforeSubmit : () => true,
    onSuccess: handleRegisterSuccess,
    onFailed: handleRegisterFailed,
  };

  return (
    <BaseModal {...props} width={600}>
      <RegisterAccountContent {...commonFormProps} />
    </BaseModal>
  );
};

RegisterAccountModal.defaultProps = {
  visible: false,
  isShowModal: true,
};

export default RegisterAccountModal;

export const RegisterAccountContent = (props) => {
  const { isShowGoLogin } = props;

  const [errorInfo, setErrorInfo] = useState('');

  const handleFormFinish = async (values) => {
    if (values) {
      try {
        const result = await registerService.registerAccountByBusiness(values);
        if (result?.code === 0 && result?.message === 'success') {
          message.success('注册成功');
          if (props?.onSuccess) {
            props.onSuccess(result?.data);
          }
        } else {
          const errorInfo =
            errorCodeInfo.find((item) => item.code === result?.code)?.title ||
            '';
          setErrorInfo(errorInfo || '注册失败');
          throw new Error('注册失败');
        }
      } catch (e) {
        message.error('注册失败');
      }
    }
  };

  const handleClearErrorInfo = () => {
    setErrorInfo('');
  };

  const renderHeaderGroup = () => {
    return (
      <div className={styles.headerGroup}>
        <div>{'注册账户'}</div>
      </div>
    );
  };

  const handleGoLoginClick = () => {
    if (props?.onGoLoginClick) {
      props.onGoLoginClick();
    }
  };

  return (
    <div className={styles.registerBusinessContainer}>
      {renderHeaderGroup()}
      <RegisterByBusinessForm
        errorInfo={errorInfo}
        onClearErrorInfo={handleClearErrorInfo}
        onFinish={handleFormFinish}
        isShowGoLogin={isShowGoLogin}
        onGoLoginClick={handleGoLoginClick}
      />
    </div>
  );
};

RegisterAccountContent.defaultProps = {
  isShowGoLogin: false,
};
