import { Alert, Col, Form, Input, Row, Image, message } from 'antd';
import React, { useEffect, useState } from 'react';
import { connect, Dispatch, history } from 'umi';
import { refreshTokenApi, ZjfakeAccountLogin, getPassword } from '@/services/login';
import LoginForm from './components/Login';
import styles from './style.less';
import { ConnectState } from '@/models/connect';
import logo from '../../../assets/logo.svg';
import cookie from 'react-cookies';
import moment from 'moment';

const { Tab, UserName, Password, Submit } = LoginForm;

interface LoginProps {
  dispatch: Dispatch;
  submitting?: boolean;
}

const LoginMessage: React.FC<{
  content: string;
}> = ({ content }) => (
  <Alert
    style={{
      marginBottom: 24,
    }}
    message={content}
    type="error"
    showIcon
  />
);

const Login: React.FC<LoginProps> = (props) => {
  const { userLogin = {}, submitting } = props;
  const { status, type: loginType } = userLogin;
  const [type, setType] = useState<string>('account');
  const [dis, disSet] = useState<boolean>(false);
  const [imgUrl, setImgUrl] = useState<any>('');
  const [tmpToken, setTmpToken] = useState<any>('');
  const remainingTime = 3 //刷新token的剩余时间，单位小时

  const genRandomString = (len: number) => {
    const text = 'abcdefghijklmnopqrstuvwxyz0123456789';
    const rdmIndex = (text: string | any[]) => (Math.random() * text.length) | 0;
    let rdmString = '';
    for (; rdmString.length < len; rdmString += text.charAt(rdmIndex(text)));
    return rdmString;
  };
  const changeCaptcha = () => {
    let tmpToken = genRandomString(16);
    let url = '/api/auth/captcha?token=' + tmpToken;
    setTmpToken(tmpToken);
    setImgUrl(url);
  };
  useEffect(() => {
    cookie.remove('mall3_token');
    sessionStorage.clear();
    changeCaptcha();
  }, []);

  //登录刷新Token方法
  const refreshToken = async (data: any) => {
    const params = {
      grant_type: "refresh_token",
      refresh_token: data?.refreshToken?.value,
      client_id: REACT_APP_CLIENT_KEY,
      client_secret: REACT_APP_CLIENT_SECRET,
    }
    const header = {
      clientId: REACT_APP_CLIENT_KEY,
    }
    await refreshTokenApi(params, header).then(res => {
      if (res?.success == true) {
        sessionStorage.setItem('Authorization', res?.data?.value);
        // sessionStorage.setItem('refreshToken', res?.data?.refreshToken.value);
        sessionStorage.setItem('scope', res?.data?.scope);
        history.push('/redirect');
      }
    })
  }

  const handleSubmit = async (values: any) => {
    if (START_ENV == 'sim' || START_ENV == 'PROD') {
      let code = {
        code: values.userCode
      }
      await getPassword({ ...code }).then((res) => {
        if (res?.data) {

          disSet(true);
          ZjfakeAccountLogin({ ...values, tmpToken }).then((res) => {
            if (res?.success) {
              if (moment(res?.data?.expiration).diff(moment(), 'hours') < remainingTime) {
                refreshToken(res?.data)
              } else {
                sessionStorage.setItem('Authorization', res?.data?.value);
                // sessionStorage.setItem('refreshToken', res?.data?.refreshToken.value);
                sessionStorage.setItem('scope', res?.data?.scope);
                history.push('/redirect');
              }
            }
            changeCaptcha();
            disSet(false);
          });

        } else {
          message.error('口令不正确，请重新输入')
        }
      })
    } else {
      disSet(true);
      await ZjfakeAccountLogin({ ...values, tmpToken }).then((res) => {
        if (res?.success) {
          if (moment(res?.data?.expiration).diff(moment(), 'hours') < remainingTime) {
            refreshToken(res?.data)
          } else {
            sessionStorage.setItem('Authorization', res?.data?.value);
            // sessionStorage.setItem('refreshToken', res?.data?.refreshToken.value);
            sessionStorage.setItem('scope', res?.data?.scope);
            history.push('/redirect');
          }
        }
        changeCaptcha();
        disSet(false);
      });
    }
  };

  return (
    <div className={styles.main}>
      <div style={{ textAlign: 'center', fontSize: '18px', fontWeight: 700 }}>
        <img
          src={logo}
          alt=""
          style={{ width: '60px', height: '60px', marginRight: '10px', color: '#b30000' }}
        />
        专家库登录
      </div>
      <LoginForm activeKey={type} onTabChange={setType} onSubmit={handleSubmit}>
        <Tab key="account" tab="账号密码登录">
          {status === 'error' && loginType === 'account' && !submitting && (
            <LoginMessage content="账号或密码错误" />
          )}
          {
            START_ENV == 'sim' || START_ENV == 'PROD' ?
              <Row>
                <Col span={24}>
                  <Form.Item name="userCode" rules={[{ required: true, message: '请输入口令' }]}>
                    <Input size='large' placeholder="请输入口令" />
                  </Form.Item>
                </Col>
              </Row> : null
          }
          <UserName
            name="userName"
            placeholder="请输入账号"
            rules={[
              {
                required: true,
                message: '请输入账号',
              },
            ]}
          />
          <Password
            name="password"
            placeholder="请输入密码"
            rules={[
              {
                required: true,
                message: '请输入密码',
              },
            ]}
          />
        </Tab>
        <Row>
          <Col span={12}>
            <Form.Item name="captcha" rules={[{ required: true, message: '请输入验证码' }]}>
              <Input size='large' placeholder="验证码" />
            </Form.Item>
          </Col>
          <Col span={12} style={{ lineHeight: '33.11px' }}>
            <Image src={imgUrl} preview={false} onClick={() => changeCaptcha()} />
          </Col>
        </Row>
        <Submit loading={submitting} disabled={dis}>
          登录
        </Submit>
      </LoginForm>
    </div>
  );
};

export default connect(({ login, loading }: ConnectState) => ({
  userLogin: login,
  submitting: loading.effects['login/login'],
}))(Login);
