/** @format */

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

interface LoggingListProps {
    page_num?: number;
    page_size?: number;
    search?: string;
}
export interface LoggingItemProps {
    before: string;
    created_at: string;
    func: string;
    id: number;
    modules: string;
    name: string;
    user: string;
}
interface LoggingState {
    loading: boolean;
    dataSource: LoggingItemProps[];
    error: null | string;
    total: number;
    deepData: LoggingListProps;
}

/**
 * 日志记录
 */
export const useLoggingList = (params: LoggingListProps) => {
    const [state, setState] = React.useState<LoggingState>({
        loading: false,
        dataSource: [],
        error: null,
        total: 0,
        deepData: {
            page_num: 1,
            page_size: 10,
            search: '',
        },
    });
    const requestData = (params: LoggingListProps) => {
        const combineParams = {...state.deepData, ...params};
        setState(prevState => ({...prevState, loading: true, deepData: combineParams}));
        Axios({
            url: GET_Logging_LIST,
            params: combineParams,
        })
            .then(({code, data, msg}) => {
                if (code === 0) {
                    const baseIndex = (data.page_number - 1) * data.page_size;
                    if (!data.list) {
                        data.list = [];
                    }
                    setState(prevState => ({
                        ...prevState,
                        loading: false,
                        total: data.total,
                        dataSource: data.list.map((item: LoggingItemProps, idx: number) => {
                            return {
                                ...item,
                                index: baseIndex + idx + 1,
                            };
                        }),
                    }));
                } else {
                    setState(prevState => ({...prevState, loading: false, error: msg}));
                    // 跳入访问出错页面
                }
            })
            .catch(error => {
                setState(prevState => ({...prevState, loading: false, error: error}));
            });
    };
    React.useEffect(() => {
        requestData(params);
    }, []);
    return [state, requestData] as const;
};
