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('请输入正确的手机号！');
      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('请输入手机号!'),
          {
            validator: validatePhone,
            message: '请输入正确的手机号',
          },
        ]}
      >
        <Input
          placeholder="请输入手机号"
          prefix="+86"
          maxLength={11}
          className={styles.txt}
          allowClear
        />
      </FormItem>
      <FormItem label="" name="code" rules={[getDefaultRule('请输入验证码!')]}>
        <Row>
          <Col span={16}>
            <Input placeholder="请输入验证码" maxLength={6} className={styles.txt} allowClear />
          </Col>
          <Col span={8}>
            <Button type="primary" onClick={onGetCaptcha} className={styles.btnCode}>
              {second > 0 ? second : '获取验证码'}
            </Button>
          </Col>
        </Row>
      </FormItem>
      <Button
        type="primary"
        htmlType="submit"
        size="large"
        className={styles.btnSubmit}
        loading={props.submitting}
      >
        登录
      </Button>
    </Form>
  );
};

export default LoginSMS;
