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 { encipher } from '@wisdom-utils/utils/lib/helpers';
import LoginForm from './components/Login';
import styles from './style.less';
import { SysConfiguration } from '@/services/userManage/api';
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 [pasType, setPasType] = useState('');

  useEffect(() => {
    passwordType();
  }, []);

  const passwordType = () => {
    SysConfiguration().then(res => {
      if (res.code === 0) {
        setPasType(res.data);
      }
    });
  };
  const handleSubmit = values => {
    /* eslint-disable no-console */
    console.log(values); // eg:{userName: "123", password: "123"}
    const { userName: loginName, password } = values;
    setLoading(true);
    OMSLogin(loginName, encipher(password, pasType ? pasType : '').toUpperCase(), 'CivManage')
      .then(result => {
        const { msg } = result;

        if (result.data && result.data.pass) {
          const { userMode, token, userName } = result.data;
          console.log(token);
          localStorage.setItem('token', token?.access_token || '');
          updateDicName();
          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]);
            sessionStorage.setItem('userName', userName);
            if (userMode === USER_MODE.SUPER) {
              // history.push(`/solution`);
              history.push(`/homePage`);
            } else {
              // history.push(`/authority/user`);
              history.push(`/homePage`);
            }
          }
          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');
          window.globalConfig = {
            ...window.globalConfig,
            access_token: localStorage.getItem('token'),
            hasGateWay: true,
            apiGatewayDomain: `${window.location.origin}${'/PandaCore/GateWay'}`,
          };
        } else {
          localStorage.setItem('panda-publish', '');
          window.globalConfig = {
            ...window.globalConfig,
            access_token: localStorage.getItem('token'),
            hasGateWay: false,
            apiGatewayDomain: `${window.location.origin}`,
          };
        }
      })
      .catch(err => {
        localStorage.setItem('panda-publish', '');
        console.error(err);
      });
  };

  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);
