/** @format */
import * as React from 'react';
import {addId} from '../utils/operation';

import {
    GET_BASE_API_INFO,
    POST_BASEAPI_ONLINE_QUERY,
    POST_BASEAPI_MULTIPLE_QUERY,
    PUT_BASE_API_INFO,
    POST_BASE_API_INFO,
    GET_MERCNAT_BASEAPI_LIST,
    GET_BASE_API_LIST,
} from '../const/path';
import Axios from '../utils/xhr';

export interface ReciveBaseApiRecordProps {
    api_id: number;
    api_name: string;
    api_type: string;
    enable: boolean;
    is_show: boolean;
    method: string;
    operation_time: string;
    request_param: string;
    router: string;
    threshold_fail_rate: number;
    threshold_norecord_rate: number;
    threshold_timeout: number;
    rate_limit: number;
    warning_enable: boolean;
}
export interface BaseApiRecordProps extends ReciveBaseApiRecordProps {
    index: number;
    id: number;
    key: number;
    label: string;
    value: number;
}
interface BaseApiListState {
    loading: boolean;
    dataSource: BaseApiRecordProps[];
    total: number;
    error: null | string;
    deepData: BaseApiListParams;
}
interface BaseApiListParams {
    page_number?: number;
    search?: string;
    api_type?: 0 | 1;
    is_all?: boolean;
    page_size?: number;
    merchant_id?: number | '';
}
/**
 * 获取base api list（带有商户详细信息 应用于商户列表）
 */
export const useBaseApiList = () => {
    const [state, setState] = React.useState<BaseApiListState>({
        loading: false,
        dataSource: [],
        deepData: {
            page_size: 10,
            page_number: 1,
            search: '',
            is_all: false,
            api_type: 0,
        },
        total: 0,
        error: null,
    });
    const requestData = (params?: Partial<BaseApiListParams>) => {
        const combineParams = {...state.deepData, ...params};
        setState(preState => ({...preState, loading: true, deepData: combineParams}));
        Axios({
            url: GET_BASE_API_LIST,
            params: combineParams,
        })
            .then(({code, data, msg}) => {
                if (code === 0) {
                    if (!data.base_api_item_list) {
                        data.base_api_item_list = [];
                    }
                    const basePage = (data.page_number - 1) * data.page_size + 1;
                    setState(preState => ({
                        ...preState,
                        loading: false,
                        total: data.total,
                        dataSource: data.base_api_item_list.map((element: ReciveBaseApiRecordProps, index: number) => {
                            return {
                                ...element,
                                id: element.api_id,
                                index: basePage + index,
                                key: element.api_id,
                                value: element.api_id,
                                label: element.api_name,
                            };
                        }),
                    }));
                } else {
                    setState(preState => ({...preState, loading: false, error: msg}));
                }
            })
            .catch(error => {
                setState(preState => ({...preState, loading: false, error: error.message}));
            });
    };

    return [state, requestData, setState] as const;
};
interface MerchantBaseApiListParams {
    api_type?: 0 | 1;
    is_all?: boolean;
    merchant_id: number | '' | string;
    only_base_api?: boolean;
}
interface MerchantBaseApiListState {
    loading: boolean;
    error: null;
    deepData: MerchantBaseApiListParams;
    dataSource: any[];
}
/**
 * 获取商户下的baseApi list(和商户双向影响 应用于下拉选择框)
 */
export const useMerchantBaseApiList = () => {
    const [state, setState] = React.useState<MerchantBaseApiListState>({
        loading: false,
        error: null,
        dataSource: [],
        deepData: {
            api_type: 0,
            is_all: true,
            merchant_id: '',
        },
    });
    const requestData = (params?: MerchantBaseApiListParams) => {
        const combineParams = {...state.deepData, ...params};
        setState(preState => ({...preState, loading: true, error: null, deepData: combineParams}));
        Axios({
            url: GET_MERCNAT_BASEAPI_LIST,
            params: {only_base_api: true, ...combineParams},
        })
            .then(({code, msg, data}) => {
                if (code === 0) {
                    data.merchant_base_api_list = data.merchant_base_api_list || [];
                    setState(preState => ({
                        ...preState,
                        loading: false,
                        dataSource: data.merchant_base_api_list.map((element: any, index: number) => {
                            return {
                                ...element,
                                key: combineParams.only_base_api ? element.api_id : index,
                                value: combineParams.only_base_api ? element.api_id : index,
                                id: element.api_id,
                            };
                        }),
                    }));
                } else {
                    setState(preState => ({...preState, loading: false, error: msg}));
                }
            })
            .catch(error => {
                setState(preState => ({...preState, loading: false, error: error.message}));
            });
    };
    return [state, requestData] as const;
};

interface InfoProps {
    comment: string;
    error_code: string[];
    method: string;
    name: string;
    request_param: any[];
    response_param: any[];
    router: string;
    type: number;
}
interface InfoState {
    loading: boolean;
    error: null | string;
    data: InfoProps;
}

/**
 * 接口列表-接口信息
 */

export const useBaseApiInfo = () => {
    const [state, setState] = React.useState<InfoState>({
        loading: false,
        error: null,
        data: {
            comment: '',
            error_code: [],
            method: '',
            name: '',
            request_param: [],
            response_param: [],
            router: '',
            type: 0,
        },
    });
    const requesData = (id: number) => {
        setState(preState => ({...preState, loading: true, error: null}));
        Axios({
            url: GET_BASE_API_INFO,
            params: {
                api_id: id,
            },
        })
            .then(({code, msg, data}) => {
                if (code === 0) {
                    data.response_param = data.response_param || [];
                    data.request_param = data.request_param || [];
                    data.error_code = data.error_code || [];
                    setState(preState => ({
                        ...preState,
                        loading: false,
                        error: null,
                        data: {
                            ...data,
                            error_code: data.error_code.map(element => Number(element)),
                            request_param: addId(data.request_param, 'base-request-api'),
                            response_param: addId(data.response_param, 'base-response-api'),
                        },
                    }));
                } else {
                    setState(preState => ({...preState, loading: false, error: msg}));
                }
            })
            .catch(error => {
                setState(preState => ({...preState, loading: false, error: error.message}));
            });
    };

    return [state, requesData] as const;
};
interface IputData extends InfoProps {
    id: number;
}
/**
 * 接口信息修改
 */
export const usePutBaseApi = () => {
    const [state, setState] = React.useState({
        loading: false,
        error: null,
    });
    const requestData = (data: IputData) => {
        const {id, ...rest} = data;
        setState(preState => ({...preState, loading: true, error: null}));
        return Axios({
            url: PUT_BASE_API_INFO + '/' + id,
            method: 'PUT',
            data: rest,
        })
            .then(({code, msg}) => {
                if (code === 0) {
                    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 [state, requestData] as const;
};

/**
 * 接口信息新增
 */
export const useBaseApiInsert = () => {
    const [state, setState] = React.useState({
        loading: false,
        error: null,
    });
    const requestData = (data: InfoProps) => {
        setState(preState => ({...preState, loading: true, error: null}));
        return Axios({
            url: POST_BASE_API_INFO,
            method: 'POST',
            data: data,
        })
            .then(({code, msg}) => {
                if (code === 0) {
                    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 [state, requestData] as const;
};

interface OnlineParams {
    app_key: string;
    app_secret: string;
    is_crypto: boolean;
    merchant_account: boolean;
    method: 'GET' | 'PUT' | 'DELETE' | 'POST';
    request_param: any[];
    router: string;
}

/**
 * 数据API在线查询
 */

export const useDataApiOnlineQuery = () => {
    const [state, setState] = React.useState({
        loading: false,
        error: null,
        deepData: {},
        data: null,
    });
    const requestData = (params?: OnlineParams) => {
        const combineParams = {...state.deepData, ...params};
        setState(preState => ({...preState, loading: true, error: null, deepData: combineParams}));
        Axios({
            url: POST_BASEAPI_ONLINE_QUERY,
            method: 'POST',
            data: combineParams,
        })
            .then(({code, msg, data}) => {
                if (code === 0) {
                    setState(preState => ({...preState, loading: false, data: JSON.parse(data)}));
                } else {
                    setState(preState => ({...preState, loading: false, error: msg}));
                }
            })
            .catch(error => {
                setState(preState => ({...preState, loading: false, error: error.message}));
            });
    };
    return [state, requestData] as const;
};

interface MultipleQueryParams {
    api_name: string;
    router: string;
    method: 'GET' | 'PUT' | 'DELETE' | 'POST';
    app_key: string;
    app_secret: string;
    is_crypto: boolean;
    merchant_account: boolean;
    multi_number: number;
}
/**
 * 对baseApi 创建 批量查询任务
 */
export const useDataApiMultipleQuery = () => {
    const [state, setState] = React.useState({
        loading: false,
        error: null,
    });
    const requestData = (params: MultipleQueryParams, file: File) => {
        setState(preState => ({...preState, loading: true, error: null}));
        const formData = new FormData();
        formData.append('file', file);
        return Axios({
            url: POST_BASEAPI_MULTIPLE_QUERY,
            method: 'POST',
            params: params,
            data: formData,
        })
            .then(({code, msg, data}) => {
                if (code === 0) {
                    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 [state, requestData] as const;
};
/**
 * base APi 过滤规则列表
 */
export const useParmasRuleList = () => {
    const [state, setState] = React.useState({loading: false, error: null, dataSource: []});
    const requestData = () => {
        setState(preState => ({...preState, loading: true, error: null}));

        Axios({url: '/data_api/param_filter_rules'})
            .then(({code, msg, rules}) => {
                if (code === 0) {
                    setState(preState => ({
                        ...preState,
                        loading: false,
                        dataSource: rules.map((element, index: number) => {
                            return {
                                ...element,
                                id: index,
                                value: element.rule_id,
                                key: element.rule_id,
                                label: `${element.rule_name}(${element.rule_desc})`,
                            };
                        }),
                    }));
                } else {
                    setState(preState => ({...preState, loading: false, error: msg}));
                }
            })
            .catch(error => {
                setState(preState => ({...preState, loading: false, error: error.message}));
            });
    };

    return [state, requestData] as const;
};
