/** @format */

import * as React from 'react';
import {LOGIN_PATH} from '../const/path';
import Axios from '../utils/xhr';
import {setLocalStorage} from '../utils/webStorage';

interface loginParams {
    username: string;
    password: string;
}
const useLogin = () => {
    const [loading, setState] = React.useState({
        loading: false,
        error: null,
    });
    const requestData = (params: loginParams) => {
        setState(preState => ({...preState, loading: true, error: null}));
        return (
            Axios({
                url: LOGIN_PATH,
                method: 'PUT',
                data: {
                    admin_name: params.username,
                    admin_passwd: params.password,
                },
            })
                //这里需要改res类型
                .then(({code, data, msg}) => {
                    if (code === 0) {
                        setLocalStorage('userinfo', {...data, userName: params.username});
                        setState(preState => ({...preState, loading: false}));
                    } else {
                        setState(preState => ({...preState, loading: false, error: msg}));
                        return msg;
                    }
                })
                .catch(error => {
                    setState(preState => ({...preState, loading: false, error: error.message}));
                    return error.message;
                })
        );
    };
    return [loading, requestData] as const;
};
export default useLogin;
