import React, { useRef, useState } from 'react';
import { Form, Input, Row, Col, Button, message } from 'antd';
import { history } from 'umi';
import { apiSMSCaptcha, fakeAccountLogin } from '@/services/login';
import { getDefaultRule, validatePhone } from '@/utils/validator';
import localStorage from '@/utils/localStorage';
import sessionStorage from '@/utils/sessionStorage';
import styles from '../../style.less';

const FormItem = Form.Item;
const LoginSMS = props => {
  const refSearch = useRef(null);
  const [second, setSecond] = useState(0);
  const [form] = Form.useForm();

  const onFinish = async ({ phone, code }) => {
    const res = await fakeAccountLogin({
      username: phone,
      tenantId: 560761,
      source: 1,
      verifyType: 1,
      verifyCode: code,
    });
    if (res && +res.code === 2000) {
      localStorage.set('token', res.data.accessToken);
      localStorage.set('refreshtoken', res.data.refreshToken);
      localStorage.set('atExpire', res.data.atExpire);
      phone && sessionStorage.set('account', phone);
      history.replace('/');
    } else {
      message.error(res.msg);
    }
  };

  // 校验手机号
  const checkPhone = v => {
    const reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
    return !!v && reg.test(v);
  };

  const countTimer = () => {
    let time = 60;
    setSecond(time);
    const timer = setInterval(() => {
      setSecond(--time);
      if (time < 1) {
        clearInterval(timer);
      }
    }, 1000);
  };

  // 获取验证码
  const onGetCaptcha = async e => {
    const { phone } = form.getFieldsValue();
    if (!checkPhone(phone)) {
      message.error($t('phone.number.invalid'));
      return;
    }
    const res = await apiSMSCaptcha({
      phone,
      tenantId: 560761,
      source: 1,
    });
    if (res && +res.code === 2000) {
      countTimer();
    } else {
      message.error(res.msg);
    }
  };

  return (
    <Form onFinish={onFinish} form={form} ref={refSearch} name="horizontal_login" layout="inline">
      <FormItem
        label=""
        name="phone"
        rules={[
          getDefaultRule($t('phone.required')),
          {
            validator: validatePhone,
            message: $t('enter.valid.phone'),
          },
        ]}
      >
        <Input
          placeholder={$t('enter.phone.number')}
          prefix="+86"
          maxLength={11}
          className={styles.txt}
          allowClear
        />
      </FormItem>
      <FormItem label="" name="code" rules={[getDefaultRule($t('verification.code.required'))]}>
        <Row>
          <Col span={16}>
            <Input placeholder={$t('enter.verification.code')} maxLength={6} className={styles.txt} allowClear />
          </Col>
          <Col span={8}>
            <Button type="primary" onClick={onGetCaptcha} className={styles.btnCode}>
              {second > 0 ? second : $t('get.verification.code')}
            </Button>
          </Col>
        </Row>
      </FormItem>
      <Button
        type="primary"
        htmlType="submit"
        size="large"
        className={styles.btnSubmit}
        loading={props.submitting}
      >{$t('login')}</Button>
    </Form>
  );
};

export default LoginSMS;
