/** @format */

import * as React from 'react';
import Axios from '../utils/xhr';
import {GET_ERROR_CODE_LIST} from '../const/path';
export interface ReciveErrorCodeRecordProps {
    code: number;
    id: number;
    msg: string;
}
export interface ErrorCodeRecordProps extends ReciveErrorCodeRecordProps {
    key: number;
    label: string;
    value: number;
}
interface ErrorCodeListState {
    loading: boolean;
    error: null;
    dataSource: ErrorCodeRecordProps[];
}
/**
 * 错误码获取
 */
export const useErrorCodeList = () => {
    const [state, setState] = React.useState<ErrorCodeListState>({
        loading: false,
        error: null,
        dataSource: [],
    });
    const requestData = () => {
        setState(preState => ({...preState, loading: true, error: null}));
        Axios({
            url: GET_ERROR_CODE_LIST,
            params: {
                is_all: true,
            },
        })
            .then(({code, msg, data}) => {
                if (code === 0) {
                    if (!data.error_code_list) {
                        data.error_code_list = [];
                    }
                    setState(preState => ({
                        ...preState,
                        loading: false,
                        dataSource: data.error_code_list.map((element: ReciveErrorCodeRecordProps) => {
                            return {
                                ...element,
                                key: element.id,
                                label: element.code + '-' + element.msg,
                                value: element.code,
                            };
                        }),
                    }));
                } else {
                    setState(preState => ({...preState, loading: false, error: msg}));
                }
            })
            .catch(error => {
                setState(preState => ({...preState, loading: false, error: error.message}));
            });
    };
    React.useEffect(() => {
        requestData();
    }, []);
    return [state, requestData] as const;
};
