// @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,
  Input,
  Select,
  Password,
  Phone,
  Captcha,
} from '@/components/form_items';

import BaseForm from '@/components/form';

import { orgTypeOptionConfigList } from '@/data';

import { phoneCheck } from '@/utils/phone';
import Agreement from '@/components/agreement';

const RegisterByEmailForm = (props) => {
  const [registerByEmailForm] = Form.useForm();

  const { isShowGoLogin } = props;

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

  const [formValues, setFormValues] = useState({});
  const [captchaEnable, setCaptchaEnable] = useState(false);
  const [lastTime, setLastTime] = useState();

  const handleFormFinish = (values) => {
    const payload = {
      username: values.username,
      captcha: values.captcha,
      phone: values.phone,
      password: values.password,
      customer: {
        name: values.orgName,
        type: values.orgType,
        service_id: values.orgId,
      },
    };
    if (props?.onFinish) {
      props.onFinish(payload);
    }
  };

  const handleValuesChange = useCallback(
    (changed, values) => {
      if (props?.errorInfo && props?.onClearErrorInfo) {
        props?.onClearErrorInfo();
      }
      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);
        }
      }
      setFormValues(values);
    },
    [formValues],
  );

  const handleCaptchaSend = async () => {
    try {
      let phone = formValues.area_code + formValues.phone;
      let data = await loginService.sendCaptchaByPhone({
        phone,
      });
      if (data?.error) {
        throw new Error(data?.msg);
      }
      setLastTime(() => new Date().getTime());
      message.success('验证码发送成功，请查收!');
    } catch (e) {
      throw e;
    }
  };

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

  return (
    <BaseForm
      className={styles.registerByBusinessForm}
      initialValues={initialValues}
      form={registerByEmailForm}
      name="registerByEmail"
      onFinish={handleFormFinish}
      onValuesChange={handleValuesChange}
    >
      <Input
        isShowMask
        name={'orgName'}
        placeholder={'请输入您所在机构的名称'}
        rules={[
          {
            required: true,
            message: '机构名称不为空',
          },
        ]}
      />

      <Select
        isShowMask={true}
        name={'orgType'}
        placeholder={'请选择您所在机构的类型'}
        optionList={orgTypeOptionConfigList}
        rules={[
          {
            required: true,
            message: '机构类型不为空',
          },
        ]}
      />

      <Input
        isShowMask
        name={'orgId'}
        placeholder={'请创建机构id'}
        rules={[
          {
            required: true,
            message: '机构id不为空',
          },
          () => ({
            validator: async (_, value) => {
              if (value) {
                const payload = { service_id: value };
                const result = await commonService.checkIsExistServiceId(
                  payload,
                );
                if (result?.data?.exists) {
                  return Promise.reject('机构id已存在');
                } else {
                  return Promise.resolve();
                }
              }
            },
          }),
        ]}
      />

      <Input
        isShowMask
        name={'username'}
        placeholder={'请输入您的姓名'}
        rules={[
          {
            required: true,
            message: '姓名不为空',
          },
        ]}
      />

      <Phone
        isShowMask={true}
        name={'phone'}
        placeholder={'请输入手机号'}
        rules={[
          () => ({
            validator: async (_, value) => {
              if (value) {
                const payload = { phone: `${formValues.area_code}${value}` };
                const result = await commonService.checkIsExistPhone(payload);
                if (result && result?.data?.isExist) {
                  setCaptchaEnable(false);
                  return Promise.reject('手机号已被占用,请更换号码');
                } else {
                  return Promise.resolve();
                }
              }
            },
          }),
        ]}
      />

      <Captcha
        isShowMask
        placeholder={'请输入验证码'}
        name={'captcha'}
        enable={captchaEnable}
        onSend={handleCaptchaSend}
        lastTime={lastTime}
        rules={[
          {
            required: true,
            message: '验证码不为空',
          },
        ]}
      />

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

      <Password
        isShowMask
        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>
      <div className={styles.agreementInfoGroup}>
        <Agreement />

        {isShowGoLogin ? (
          <div className={styles.goLoginGroup}>
            <span>已有账户</span>
            <a onClick={handleGoLoginGroup}>直接登录</a>
          </div>
        ) : null}
      </div>

      {props?.errorInfo ? (
        <div className={styles.errorInfoGroup}>{props?.errorInfo}</div>
      ) : null}
    </BaseForm>
  );
};

RegisterByEmailForm.defaultProps = {
  isShowGoLogin: true,
};

export default RegisterByEmailForm;
