import React, {useState} from 'react'
import style from './style.module.css'
import http from '../../http'
import {setToken} from '../../http'
import {history} from '../../router.config'
import { encodeStr } from "../../util/pass"
import { Base64 } from "js-base64"

function Login() {
  let [user, setUser] = useState('');
  let [psw, setPsw] = useState('');

  const submission = async () => {
    console.log('?????', encodeStr(Base64.encode(psw)))
    const { data: {code, data, msg} } = await http({ 
      method: 'POST',
      url: '/admin/login', 
      data: {
        username: user, 
        password: encodeStr(Base64.encode(psw))
      }
    })
    
    // let {status, data, message} = (await http.post('/login', {params: {username: user, password: psw}})).data
    if (code === 0) {
      sessionStorage.setItem('userName', data.user.realName)
      setToken(data.token)
      history.replace('/scene')
    } else {
      alert(msg)
    }
  }

  return (
    <div className={style.layer}>
      <h1>登录</h1>
      <div>
        <label htmlFor="user">用户名</label>
        <input type="text" name="user" value={user} onChange={ev => setUser(ev.target.value)}/>
      </div>
      <div>
        <label htmlFor="psw">密码</label>
        <input type="password" name="psw" value={psw} onChange={ev => setPsw(ev.target.value)}/>
      </div>
      <div>
        <span className={style.button} onClick={submission}>登录</span>
      </div>
    </div>
  )
}

export default Login