import React, { useState, useEffect } from 'react';
import { Alert, notification } from 'antd';
import { OMSLogin } from '@/services/user/api';
import { gateWayConfig, GetGateWay } from '@/services/common/api';
import { AUTHORITY, USER_MODE } from '@/utils/constants';
import { appConnector } from '@/containers/App/store';
import { useHistory } from 'react-router-dom';
import sha1 from 'sha1';
import LoginForm from './components/Login';
import styles from './style.less';
import { setAuthority } from '@/utils/authority';
const { UserName, Password, Submit } = LoginForm;

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

const Login = props => {
  const { userLogin = {}, submitting, setAuth, setUserMode, setLoginName } = props;
  const { status, type: loginType } = userLogin;
  const history = useHistory();
  const [loading, setLoading] = useState(false);
  // const [autoLogin, setAutoLogin] = useState(true);
  const [type, setType] = useState('account');
  const handleSubmit = values => {
    /* eslint-disable no-console */
    console.log(values); // eg:{userName: "123", password: "123"}
    const { userName: loginName, password } = values;
    setLoading(true);
    OMSLogin(loginName, sha1(password).toUpperCase(), 'CivManage')
      .then(result => {
        const { msg } = result;

        if (result.data && result.data.pass) {
          const { userMode, token } = result.data;
          localStorage.setItem('token', token?.access_token || '');
          setUserMode(userMode);
          setLoginName(loginName);
          if (userMode === USER_MODE.SUPER || userMode === USER_MODE.ADMIN) {
            const authority = [AUTHORITY.LOGIN, AUTHORITY[userMode]];
            setAuthority(authority);
            setAuth(authority);
            sessionStorage.setItem('userType', AUTHORITY[userMode]);
            if (userMode === USER_MODE.SUPER) {
              history.push(`/solution`);
            } else {
              history.push(`/authority/user`);
            }
          }
          if (userMode === USER_MODE.COMMON) {
            // const authority = [AUTHORITY.LOGIN, AUTHORITY.COMMON];
            // setAuthority(authority);
            // setAuth(authority);
            // history.push(`/userCenter/UserManage`);
            notification.warning({
              message: msg || '没有权限！',
            });
          }
        } else {
          notification.warning({
            message: msg || '没有权限！',
          });
        }
        setLoading(false);
      })
      .catch(e => {
        setLoading(false);
        notification.error({
          message: e.message || '没有权限！',
        });
        console.error(e);
      });
  };

  const updateDicName = () => {
    GetGateWay()
      .then(res => {
        if (res.code === 0 && res.data) {
          localStorage.setItem('panda-publish', 'getway');
        } else {
          localStorage.setItem('panda-publish', '');
        }
      })
      .catch(err => {
        localStorage.setItem('panda-publish', '');
        console.error(err);
      });
  };
  useEffect(() => {
    updateDicName();
  }, []);

  return (
    <div className={styles.main}>
      <LoginForm activeKey={type} onTabChange={setType} onSubmit={handleSubmit}>
        {status === 'error' && loginType === 'account' && !submitting && (
          <LoginMessage content="账户或密码错误（admin/ant.design）" />
        )}
        <UserName
          name="userName"
          placeholder="请输入用户名"
          rules={[
            {
              required: true,
              message: '请输入用户名!',
            },
          ]}
        />
        <Password
          name="password"
          placeholder="请输入密码"
          rules={[
            {
              required: true,
              message: '请输入密码！',
            },
          ]}
        />
        <div>
          {/* <Checkbox
            checked={autoLogin}
            onChange={e => setAutoLogin(e.target.checked)}
          >
            自动登录
          </Checkbox> */}
          {/* <a
            style={{
              float: 'right',
            }}
          >
            忘记密码
          </a> */}
        </div>
        <Submit loading={loading}>登录</Submit>
      </LoginForm>
    </div>
  );
};

export default appConnector(Login);
