// @ts-nocheck
import React, { useState, useCallback } from 'react';
import styles from './styles.less';

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

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

import {
  FormItemFactory,
  Phone,
  Email,
  Captcha,
  Password,
} 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 { 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 [phoneLastTime, setPhoneLastTime] = useState();
  const [emailLastTime, setEmailLastTime] = useState();

  const handleFormFinish = (values) => {
    const payload = {
      code: values.captcha,
      password: values.password,
      kind: type === 'phone' ? 3 : 2,
      username:
        type === 'phone'
          ? `${values?.area_code}${values?.phone}`
          : values.email,
    };
    if (props?.onFinish) {
      props.onFinish(payload);
    }
  };

  const handleValuesChange = (changed, values) => {
    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 () => {
    if (type === 'phone') {
      let phone = formValues.area_code + formValues.phone;
      let data = await loginService.sendCaptchaByPhone({
        phone,
      });
      try {
        if (data?.error) {
          throw new Error(data?.msg);
        }
        setPhoneLastTime(new Date().getTime());
        message.success('验证码发送成功，请查收!');
      } catch (e) {
        if (e?.message === '60秒内不能发送多次验证码') {
          message.error(e?.message);
        } else {
          message.error('验证码发送失败，请稍候重试!');
        }
  
      }
    } else {
      let email = formValues?.email;
      let data = await commonService.sendCaptchaByEmail({
        email,
      });
      try {
        if (data?.error) {
          throw new Error(data?.msg);
        }
        setEmailLastTime(new Date().getTime());
        message.success('验证码发送成功，请查收!');
      } catch (e) {
        message.error('验证码发送失败，请稍候重试!');
        throw e;
      }
    }
  };

  return (
    <>
      <div className={styles.headerGroup}>
        <div>{title || '修改密码'}</div>
      </div>
      <BaseForm
        initialValues={initialValues}
        form={registerByEmailForm}
        name="registerByEmail"
        onFinish={handleFormFinish}
        onValuesChange={handleValuesChange}
      >
        {type === 'phone' ? (
          <Phone placeholder={'请输入手机号'} />
        ) : (
          <Email placeholder={'请输入邮箱'} />
        )}

        <Captcha
          enable={captchaEnable}
          name={'captcha'}
          placeholder={'请输入验证码'}
          onSend={handleCaptchaSend}
          lastTime={type === 'phone' ? phoneLastTime : emailLastTime}
        />

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

        <Password
          name="confirm"
          dependencies={['password']}
          placeholder={'请再次输入密码'}
          rules={[
            {
              required: true,
              message: '请再次输入密码',
            },
            ({ getFieldValue }) => ({
              validator(_, value) {
                if (!value || getFieldValue('password') === value) {
                  return Promise.resolve();
                }
                return Promise.reject(new Error('两次密码输入不一致'));
              },
            }),
          ]}
        />

        <Button type="primary" htmlType="submit">
          确认
        </Button>

        {!isReset ? (
          <div>
            <Agreement />
          </div>
        ) : null}
      </BaseForm>
    </>
  );
};

SettingPwdForm.defaultProps = {
  isReset: false,
};

export default SettingPwdForm;
