// @ts-nocheck
import React, { useMemo } from 'react';
import styles from './styles.less';
import { message } from 'antd4';
import BaseModal from '@/Modal/base';
import { settingPwdService } from '@/service';
import { SettingPwdForm } from '../../component/form';

interface PropTypes {
  type: ['phone', 'email'];
  isReset: boolean;
  onBeforeSubmit: () => {};
  onSuccess: () => {};
  onFailed: () => {};
}

const SettingPwdModal = (props: PropTypes) => {
  const { type, isReset } = props;

  const handleSettingPwdSuccess = (values) => {
    if (props?.onSuccess) {
      props.onSuccess(values);
    }
  };

  const handleSettingPwdFailed = (errorInfo) => {
    if (props?.onFailed) {
      props.onFailed(errorInfo);
    }
  };

  const commonFormProps = {
    isShowMsg: true,
    onSuccess: handleSettingPwdSuccess,
    onFailed: handleSettingPwdFailed,
  };

  return (
    <BaseModal {...props}>
      <SettingPwdContent {...commonFormProps} isReset={isReset} type={type} />
    </BaseModal>
  );
};

SettingPwdModal.defaultProps = {
  type: 'phone',
  isReset: false,
  onBeforeSubmit: () => true,
  onSuccess: null,
  onFailed: null,
};

export default SettingPwdModal;

export const SettingPwdContent = (props) => {
  const { type, isReset } = props;

  const title = useMemo(() => {
    let title = '';
    if (isReset) {
      title = '修改';
    } else {
      title = '添加';
    }
    if (type === 'phone') {
      title += '手机密码';
    } else if (type === 'email') {
      title += '邮箱密码';
    }
    return title;
  }, [type]);

  const renderHeaderGroup = () => {
    return (
      <div className={styles.headerGroup}>
        <div>{title || '修改密码'}</div>
      </div>
    );
  };

  const handleFinish = async (values) => {
    if (values) {
      const result = await settingPwdService.settingPwd(values);
      try {
        if (result?.error) {
          throw new Error(result?.msg);
        }
        message.success(`${title}成功`);
        if (props?.onSuccess) {
          props.onSuccess();
        }
      } catch (e) {
        message.error(`${title}失败`);
      }
    }
  };

  return (
    <div className={styles.settingPwdContainer}>
      {/* 根据不同type不同标题 */}
      {renderHeaderGroup()}
      {/* 统一走设置密码的表单 */}
      <SettingPwdForm isReset={isReset} type={type} onFinish={handleFinish} />
    </div>
  );
};
