import React, { useState } from "react";
import { Redirect } from "react-router-dom";
import { Form, Icon, Input, Button, message, Spin,Modal} from "antd";
import { connect } from "react-redux";
import DocumentTitle from "react-document-title";
import "./index.less";
import { login, getUserInfo,setUserInfo} from "@/store/actions";
// import encryption from '../../utils/crypto';
// import axios from "axios";

const getQueryVariable=(variable)=>{

       let query = window.location.hash.substring(1);
      //  console.log({query});
      //  console.log(query.split("?"));
       if(query.split("?")[1]){
          
          let vars = ((query.split("?")[1]).split("&"));
          // console.log({vars});
          for (let i=0;i<vars.length;i++) {
                  let pair = vars[i].split("=");
                  if(pair[0] == variable){return pair[1];}
          }
       }
       
       return false;
}


/**
 * 
 * @param {*} props 
 * @returns 
 */
const Login = (props) => {
  const { form, token, login, getUserInfo } = props;
  const { getFieldDecorator } = form;

  const [loading, setLoading] = useState(false);

  // console.log({form});

  const handleLogin = (username, password,hospSign) => {
    //登录完成后 发送请求 调用接口获取用户信息
    console.log('开始登录');
    setLoading(true);
    login(
      username,
      password,
      hospSign
    )
      .then((data) => {
        console.log({'登录返回':data});
        message.success("登录成功");
        localStorage.setItem("userInfo",JSON.stringify(data));  
        handleUserInfo(data);
      })
      .catch((error) => {
        setLoading(false);
        // console.log({error});
        // const {msg} = error;
        // Modal.confirm({
        //   title: "错误111",
        //   content:msg,
        //   okText: "确定",
        //   cancelText: "取消",
        //   onOk() {
        //     // window.location.reload();
        //     form.resetFields();
        //   },
        //   onCancel() {
        //     console.log("Cancel");
        //   },
        // });
      });
  };

  // 获取用户信息

  const handleUserInfo = (data) => {
    getUserInfo(data);
  };

  const handleSubmit = (event) => {
    // 阻止事件的默认行为
    event.preventDefault();

    // 对所有表单字段进行检验
    form.validateFields((err, values) => {
      // 检验成功
      if (!err) {
        const { username, password } = values;
        const hospSign = getQueryVariable('hospSign');
        localStorage.removeItem('hospSign');
        localStorage.setItem('hospSign',JSON.stringify(hospSign));
        handleLogin(username,password,hospSign);
      } else {
        console.log("检验失败!");
      }
    });
  };

  if (token) {
    return <Redirect to="/dashboard" />;
  }
  return (
    <DocumentTitle title={"用户登录"}>
      <div className="login-container">
        
        <Form onSubmit={handleSubmit} className="content">
          <div className="title">
            <h2>用户登录</h2>
          </div>
          <Spin spinning={loading} tip="登录中...">
            <Form.Item>
              {getFieldDecorator("username", {
                rules: [
                  {
                    required: true,
                    whitespace: true,
                    message: "请输入用户名",
                  },
                ],
              })(
                <Input
                  prefix={
                    <Icon type="user" style={{ color: "rgba(0,0,0,.25)" }} />
                  }
                  placeholder="用户名"
                />
              )}
            </Form.Item>
            <Form.Item>
              {getFieldDecorator("password", {
                rules: [
                  {
                    required: true,
                    whitespace: true,
                    message: "请输入密码",
                  },
                ],
              })(
                <Input
                  prefix={
                    <Icon type="lock" style={{ color: "rgba(0,0,0,.25)" }} />
                  }
                  type="password"
                  placeholder="密码"
                />
              )}
            </Form.Item>
            <Form.Item>
              <Button
                type="primary"
                htmlType="submit"
                className="login-form-button"
              >
                登录 ^_^
              </Button>
            </Form.Item>
            {/* <Form.Item>
              <span>账号 : admin 密码 : 随便填</span>
              <br />
              <span>账号 : editor 密码 : 随便填</span>
              <br />
              <span>账号 : guest 密码 : 随便填</span>
            </Form.Item> */}
          </Spin>
        </Form>
      </div>
    </DocumentTitle>
  );
};

const WrapLogin = Form.create()(Login);



export default connect((state) => state.user, { login, getUserInfo })(
  WrapLogin
);

