// @ts-nocheck
import React, { useState, useCallback } from 'react';
import { LocaleProvider, FM, FormattedMessage } from '@/locales';

import styles from './styles.less';

import { loginService, commonService, settingPwdService } from '@/service';

import { Form, Button, message } from 'antd4';

import {
  FormItemFactory,
  Phone,
  Email,
  Captcha,
  Password,
  UserName,
} from '@/components/form_items';

import BaseForm from '@/components/form';

import { phoneCheck } from '@/utils/phone';

import Agreement from '@/components/agreement';

const SettingPwdForm = (props) => {
  const [registerByEmailForm] = Form.useForm();
  const [loading, setLoading] = useState(false);

  const { type, isReset } = props;

  const initialValues = {
    area_code: '+86',
  };

  const email_pattern = /^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
  const [formValues, setFormValues] = useState({});
  const [captchaEnable, setCaptchaEnable] = useState(false);
  const [lastTime, setLastTime] = useState();
  const [formValidate, setFormValidate] = useState(false);

  const handleFormFinish = async (values) => {
    const payload = {
      code: values.captcha,
      password: values.password,
      kind: values.username.includes('@') ? 2 : 3,
      username: values.username.includes('@')
        ? values.username
        : `+86${values?.username}`,
    };
    if (values) {
      setLoading(true)
      const result = await settingPwdService.settingPwd(payload);
      setLoading(false)
      try {
        if (result?.error) {
          throw new Error(result?.msg);
        }
        message.success(`修改密码成功`);
        if (props?.onSuccess) {
          props.onSuccess();
        }
      } catch (e) {
        message.error(`修改密码失败`);
      }
    }
  };

  const handleValuesChange = (changed, values) => {
    if (values.username) {
      setCaptchaEnable(true);
    } else {
      setCaptchaEnable(false);
    }
    // if (type === 'phone') {
    //   if (changed.area_code || changed.phone) {
    //     let phone_enable = phoneCheck(values.area_code, values.phone);
    //     if (phone_enable && !captchaEnable) {
    //       setCaptchaEnable(true);
    //     } else if (!phone_enable && captchaEnable) {
    //       setCaptchaEnable(false);
    //     }
    //   }
    // } else {
    //   if (changed.email) {
    //     let email_enable = email_pattern.test(changed.email);
    //     if (email_enable && !captchaEnable) {
    //       setCaptchaEnable(true);
    //     } else if (!email_enable && captchaEnable) {
    //       setCaptchaEnable(false);
    //     }
    //   }
    // }
    setFormValues(values);
  };

  const handleCaptchaSend = async () => {
    const type = registerByEmailForm?.getFieldValue('username')?.includes('@')
      ? 'email'
      : 'phone';
    if (type === 'phone') {
      let phone = '+86' + formValues.username;
      // let phone = formValues.area_code + formValues.username;
      let data = await loginService.sendCaptchaByPhone({
        phone,
      });
      try {
        if (data?.error) {
          throw new Error(data?.msg);
        }
        setLastTime(new Date().getTime());
        message.success('验证码发送成功，请查收!');
      } catch (e) {
        if (e?.message === '60秒内不能发送多次验证码') {
          message.error(e?.message);
        } else {
          message.error('验证码发送失败，请稍候重试!');
        }  
      }
    } else {
      let email = formValues?.username;
      let data = await commonService.sendCaptchaByEmail({
        email,
      });
      try {
        if (data?.error) {
          throw new Error(data?.msg);
        }
        setLastTime(new Date().getTime());
        message.success('验证码发送成功，请查收!');
      } catch (e) {
        message.error('验证码发送失败，请稍候重试!');
        throw e;
      }
    }
  };
  return (
    <LocaleProvider {...props}>
      <div className={styles.setpwdContentGroup}>
        <div className={styles.headerGroup}>
          <div>
            <FM id="common.reset.pwd.btn" defaultMessage="Retrieve password" />
          </div>
        </div>
        <BaseForm
          initialValues={initialValues}
          form={registerByEmailForm}
          name="registerByEmail"
          onFinish={handleFormFinish}
          onValuesChange={handleValuesChange}
          onFieldsChange={(_, allFields) => {
            setFormValidate(
              allFields.every(
                ({ touched, errors }) => touched && errors?.length === 0,
              ),
            );
          }}
        >
          <UserName name={'username'} />

          <Captcha
            enable={captchaEnable}
            name={'captcha'}
            // placeholder={'请输入验证码'}
            onSend={handleCaptchaSend}
            lastTime={lastTime}
          />

          <Password
            name={'password'}
            // placeholder={'请输入密码'}
            // rules={[
            //   {
            //     required: true,
            //     message: '请输入密码',
            //   },
            // ]}
          />

          <Password
            name="confirm"
            dependencies={['password']}
            placeholder={FormattedMessage({
              id: 'common.reset.pwd.repeat.pwd.input.placement',
              defaultMessage: 'Please enter the password again',
            })}
            rules={[
              {
                required: true,
                message: FormattedMessage({
                  id: 'common.reset.pwd.repeat.pwd.input.placement',
                  defaultMessage: 'Please enter the password again',
                }),
              },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('password') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(
                    new Error(
                      FormattedMessage({
                        id: 'common.reset.pwd.repeat.pwd.input.noteq',
                        defaultMessage: 'The two passwords are inconsistent',
                      }),
                    ),
                  );
                },
              }),
            ]}
          />

          <Button type="primary" htmlType="submit" loading={loading} disabled={!formValidate}>
            <FM id="common.reset.confirm.title" defaultMessage="confirm" />
          </Button>
          <div className={styles.otherOption}>
            <a onClick={() => props?.onToLogin()}>
              <FM id="common.login.btn.title" defaultMessage="Login" />
            </a>
            <i />
            <a onClick={() => props?.onToSignup()}>
              <FM id="common.sign.up.account.btn" defaultMessage="Register" />
            </a>
          </div>
          {/* {!isReset ? (
        <div>
          <Agreement />
        </div>
      ) : null} */}
        </BaseForm>
      </div>
    </LocaleProvider>
  );
};

SettingPwdForm.defaultProps = {
  isReset: false,
};

export default SettingPwdForm;
