// @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 { Input, Select, 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 BindOrgInfoForm = (props) => {
  const {
    isShowUserName,
    isShowPhoneGroup,
    isShowOrgInfoGroup,
    userInfo,
    orgInfo,
  } = props;

  const [registerByEmailForm] = Form.useForm();

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

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

  const handleFormFinish = (values) => {
    const payload = {
      ...userInfo,
      customer: orgInfo,
    };
    if (isShowPhoneGroup) {
      payload.captcha = values.captcha;
      payload.phone = values.phone;
    }
    if (isShowOrgInfoGroup) {
      payload.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) {
      message.error('验证码发送失败，请稍候重试!');
      throw e;
    }
  };

  const renderPhoneInfoGroup = () => {
    return (
      <React.Fragment>
        <Phone
          isShowMask={true}
          name={'phone'}
          placeholder={'请输入手机号'}
          rules={[
            () => ({
              validator: async (_, value) => {
                if (!isShowPhoneGroup) {
                  return Promise.resolve();
                }
                if (value && isShowPhoneGroup) {
                  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
          placeholder={'请输入验证码'}
          name={'captcha'}
          enable={captchaEnable}
          onSend={handleCaptchaSend}
          lastTime={lastTime}
          rules={[
            {
              required: true,
              message: '验证码不为空',
            },
          ]}
        />
      </React.Fragment>
    );
  };

  const renderOrgInfoGroup = () => {
    return (
      <React.Fragment>
        <Input
          name={'orgName'}
          placeholder={'请输入您所在机构的名称'}
          rules={[
            {
              required: true,
              message: '机构名称不为空',
            },
          ]}
        />

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

        <Input
          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();
                  }
                }
              },
            }),
          ]}
        />
      </React.Fragment>
    );
  };

  return (
    <BaseForm
      className={styles.bindOrgInfoForm}
      initialValues={initialValues}
      form={registerByEmailForm}
      name="bindOrgInfo"
      onFinish={handleFormFinish}
      onValuesChange={handleValuesChange}
    >
      {/* 机构信息group */}
      {isShowOrgInfoGroup ? renderOrgInfoGroup() : null}

      {/* 是否显示用户姓名 */}
      {isShowUserName ? (
        <Input
          name={'username'}
          placeholder={'请输入您的姓名'}
          rules={[
            {
              required: true,
              message: '姓名不为空',
            },
          ]}
        />
      ) : null}

      {/* 是否显示绑定手机号信息 */}
      {isShowPhoneGroup ? renderPhoneInfoGroup() : null}

      <Button type="primary" htmlType="submit">
        确定
      </Button>
      <div className={styles.agreementGroup}>
        <Agreement />
      </div>

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

BindOrgInfoForm.defaultProps = {
  isShowPhoneGroup: true,
  isShowOrgInfoGroup: true,
  isShowUserName: false,
  userInfo: {},
  orgInfo: {},
};

export default BindOrgInfoForm;
