/**
 * 数据API相关的 逻辑请求
 * @format
 *  */

import * as React from 'react';
import Axios from '../utils/xhr';
import {addId} from '../utils/operation';

import {
    GET_DATA_API_LIST,
    DELETE_DATA_API_LIST,
    POST_DATA_API,
    PUT_DATA_API,
    PUT_DATA_API_RELEASE,
    GET_MERCHANT_DATA_API_BASE_API_LIST,
    GET_MERCHANT_DATAAPI_BASEAPI_INFO,
    GET_DATA_API_COMBO_LIST,
} from '../const/path';

interface ReciveDataApiRecordProps {
    data_api_name: string;
    data_api_type: number;
    data_api_desc: string;
    version: string;
    release_time: string;
    is_release: boolean;
    data_api_id: number;
}

export interface DataApiRecordProps extends ReciveDataApiRecordProps {
    index: number;
    id: number;
    value: number;
    key: number;
    label: string;
}

interface dataApiListParams {
    is_all?: boolean;
    page_size?: number;
    page_number?: number;
    search?: string;
    data_api_type?: number | string;
    merchant_id?: number | '';
}

interface DataApiListState {
    loading: boolean;
    error: null;
    deepData: dataApiListParams;
    total: number;
    dataSource: DataApiRecordProps[];
}

/**
 * 获取数据API列表
 */
export const useDataApiList = () => {
    const [state, setState] = React.useState<Readonly<DataApiListState>>({
        loading: false,
        error: null,
        deepData: {
            is_all: false,
            page_size: 10,
        },
        total: 0,
        dataSource: [],
    });
    const requestData = (params?: dataApiListParams) => {
        params = params || {};
        const combinationParams = {...state.deepData, ...params};
        setState(preState => ({...preState, loading: true, error: null, deepData: combinationParams}));
        Axios({
            url: GET_DATA_API_LIST,
            params: combinationParams,
        })
            .then(({code, msg, data}) => {
                if (code === 0) {
                    if (!data.data_apis) {
                        data.data_apis = [];
                    }
                    const basePage = (data.page_number - 1) * data.page_size + 1;
                    setState(preState => ({
                        ...preState,
                        loading: false,
                        total: data.total,
                        dataSource: data.data_apis.map((element: ReciveDataApiRecordProps, index: number) => {
                            return {
                                ...element,
                                index: basePage + index,
                                id: element.data_api_id,
                                value: element.data_api_id,
                                key: element.data_api_id,
                                label: element.data_api_name,
                            };
                        }),
                    }));
                } else {
                    setState(preState => ({...preState, loading: false, error: msg}));
                }
            })
            .catch(error => {
                setState(preState => ({...preState, loading: false, error: error.message}));
            });
    };
    return [state, requestData] as const;
};

/**
 * 删除数据API
 */
export const useDeleteDataApi = () => {
    const [state, setState] = React.useState({
        loading: false,
        error: null,
    });
    const requestData = (id: number) => {
        setState(preState => ({...preState, loading: true, error: null}));
        return Axios({
            url: DELETE_DATA_API_LIST,
            method: 'DELETE',
            params: {
                data_api_id: id,
            },
        })
            .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 InsertDataApiParams {
    data_api_desc: string;
    data_api_name: string;
    data_api_type: number;
    version: string;
}

/**
 * 新增数据API
 */
export const useInsertApi = () => {
    const [state, setState] = React.useState({
        loading: false,
        error: null,
    });
    const requestData = (data: InsertDataApiParams) => {
        setState(preState => ({...preState, loading: true, error: null}));
        return Axios({
            url: POST_DATA_API,
            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 UpdateDataApiParams {
    data_api_desc: string;
    data_api_name: string;
    data_api_type: number;
    version: string;
    data_api_id: number;
}

/**
 * 更新数据Api 基本配置
 */
export const useUpdateDataAPi = () => {
    const [state, setState] = React.useState({
        loading: false,
        error: null,
    });
    const requestData = (data: UpdateDataApiParams) => {
        setState(preState => ({...preState, loading: true, error: null}));
        return Axios({
            url: PUT_DATA_API,
            method: 'PUT',
            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;
};
/**
 * 发布/下线 API
 */
export const useRelese = () => {
    const [state, setState] = React.useState({
        loading: false,
        error: null,
    });
    const requestData = (params: {id: number; status: 0 | 1}) => {
        setState(preState => ({...preState, loading: true, error: null}));
        return Axios({
            url: PUT_DATA_API_RELEASE + '/' + params.id,
            method: 'PUT',
            data: {
                status: params.status,
            },
        })
            .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;
};

// --------------------------dataApi 下面的baseaPI--------------------------------------
interface UpdateDataApiToBaseApiParams {
    count_code: number;
    count_type: 0 | 1;
    data_api_base_api_id: number;
    filters: {name: string; value: string}[];
    force_update: boolean;
    is_crypto: boolean;
    provider_group_list: any[];
    request_params: any[];
    response_params: any[];
    reuse_time: number;
    sale_name: string;
    minimal_time_consuming: number;
    random_percentage: number;
}

/**
 * 配置数据API 下面的base api
 */
export const useUpdateDataApiToBaseApiInfo = () => {
    const [state, setState] = React.useState({
        loading: false,
        error: null,
    });
    const requestData = (data: UpdateDataApiToBaseApiParams) => {
        setState(preState => ({...preState, loading: true, error: null}));
        return Axios({
            url: '/data_api/base_api',
            method: 'PUT',
            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: null}));
                return error;
            });
    };
    return [state, requestData] as const;
};

// -----------------------------获取商户下的数据Api下面的base Api---------------------------
interface ReciveMerchantDataApitoBaseApiListRecordProps {
    merchant_child_api_id: number;
    merchant_child_api_name: string;
    router: string;
}

interface MerchantDataApitoBaseApiListRecordProps extends ReciveMerchantDataApitoBaseApiListRecordProps {
    key: number;
    value: number;
    label: string;
}

interface MerchantDataApiToBaseApiListState {
    loading: boolean;
    error: null;
    dataSource: MerchantDataApitoBaseApiListRecordProps[];
}

/**
 * 获取商户下的数据Api 有哪些baseApi 组成
 */
export const useMerchantDataApiToBaseApiList = (id: number) => {
    const [state, setState] = React.useState<MerchantDataApiToBaseApiListState>({
        loading: false,
        dataSource: [],
        error: null,
    });
    const requestData = (id: number) => {
        setState(preState => ({...preState, loading: true}));
        Axios({
            url: GET_MERCHANT_DATA_API_BASE_API_LIST,
            params: {
                merchant_data_api_id: id,
            },
        })
            .then(({code, data, msg}) => {
                if (code === 0) {
                    if (!data.merchant_base_api_list) {
                        data.merchant_base_api_list = [];
                    }
                    setState(preState => ({
                        ...preState,
                        loading: false,
                        dataSource: data.merchant_base_api_list.map(
                            (element: ReciveMerchantDataApitoBaseApiListRecordProps) => {
                                return {
                                    ...element,
                                    key: element.merchant_child_api_id,
                                    value: element.merchant_child_api_id,
                                    label: `${element.merchant_child_api_name}(${element.router})`,
                                };
                            },
                        ),
                    }));
                } else {
                    setState(preState => ({...preState, loading: false, error: msg}));
                }
            })
            .catch(error => {
                setState(preState => ({...preState, loading: false, error: error.message}));
            });
    };
    React.useEffect(() => {
        requestData(id);
    }, []);
    return [state, requestData] as const;
};

interface ReciveoMerchantBaseApiInfo {
    count_type: string;
    timeout: number;
    force_update: boolean;
    reuse_time: number;
    is_crypto: boolean;
    response_param: any[];
    request_param: any[];
    merchant_provider_group_list: any[];
    count_code: string;
    filters: any[];
    is_raw_error_code: number;
    minimal_time_consuming: number;
    random_percentage: number;
    rate_limit: number;
}

interface MerchantDataApiToBaseApiInfoState {
    loading: boolean;
    dataSource: ReciveoMerchantBaseApiInfo;
}

/**
 * 获取商户下的数据Api 的baseApi 信息
 */
export const useMerchantDataApiToBaseApiInfo = () => {
    const [state, setState] = React.useState<MerchantDataApiToBaseApiInfoState>({
        loading: false,
        dataSource: {
            merchant_provider_group_list: [],
            request_param: [],
            response_param: [],
            count_type: '',
            timeout: 0,
            force_update: false,
            reuse_time: 0,
            is_raw_error_code: 0,
            is_crypto: false,
            count_code: '',
            filters: [],
            minimal_time_consuming: 0,
            random_percentage: 0,
            rate_limit: 0,
        },
    });
    const requestData = (id: number) => {
        setState(preState => ({...preState, loading: true}));
        Axios({
            url: GET_MERCHANT_DATAAPI_BASEAPI_INFO,
            params: {
                merchant_child_api_id: id,
            },
        }).then(({code, data}: {code: number; data: ReciveoMerchantBaseApiInfo}) => {
            if (code === 0) {
                data.merchant_provider_group_list = data.merchant_provider_group_list || [];
                setState({
                    loading: false,
                    dataSource: {
                        ...data,
                        request_param: addId(data.request_param, 'reuest'),
                        response_param: addId(data.response_param, 'response'),
                        minimal_time_consuming: data.minimal_time_consuming,
                        random_percentage: data.random_percentage,
                        filters: addId(data.filters, 'filter') || [],
                        merchant_provider_group_list: data.merchant_provider_group_list.map(
                            (element: any, index: number) => ({
                                ...element,
                                id: index,
                                merchant_provider_api_list: element.merchant_provider_api_list.map(
                                    (item: any, idx: number) => ({
                                        ...item,
                                        index: idx + 1,
                                        id: idx,
                                    }),
                                ),
                            }),
                        ),
                    },
                });
            }
        });
    };
    return [state, requestData] as const;
};

interface UpdateMerchantBaseApiParams extends ReciveoMerchantBaseApiInfo {
    merchant_child_api_id: number;
    merchantId: number;
}

/**
 * 更新商户下的 dataApi 下面的baseApi info
 */
export const useUpdateMerchantDataApiToBaseApiinfo = () => {
    const [state, setState] = React.useState({
        loading: false,
        error: null,
    });
    const requestData = (data: UpdateMerchantBaseApiParams) => {
        const {merchantId, ...rest} = data;
        setState(preState => ({...preState, loading: true, error: null}));
        return Axios({
            url: '/merchant_api/merchant_base_api/' + merchantId,
            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;
};

interface ReciveComboRecordProps {
    combo_id: number;
    combo_desc: string;
}

interface ComboRecordProps extends ReciveComboRecordProps {
    id: number;
    key: number;
    value: number;
    label: string;
}

interface ComboListState {
    loading: boolean;
    error: null;
    dataSource: any[];
}

/**
 * 获取 数据API 的价格套餐
 */
export const useDataApiComboList = () => {
    const [state, setState] = React.useState<ComboListState>({
        loading: false,
        error: null,
        dataSource: [],
    });
    const requestData = (query_type_id: number) => {
        setState(preState => ({...preState, loading: true, error: null}));
        Axios({
            url: GET_DATA_API_COMBO_LIST,
            params: {
                query_type_id: query_type_id,
            },
        })
            .then(({code, data, msg}) => {
                if (code === 0) {
                    data.combo_list = data.combo_list || [];
                    setState(preState => ({
                        ...preState,
                        loading: false,
                        dataSource: data.combo_list.map((element: ComboRecordProps, index: number) => {
                            return {
                                ...element,
                                index: index + 1,
                                id: element.combo_id,
                                key: element.combo_id,
                                value: element.combo_id,
                                label: element.combo_desc,
                            };
                        }),
                    }));
                } else {
                    setState(preState => ({...preState, loading: false, error: msg}));
                }
            })
            .catch(error => {
                setState(preState => ({...preState, loading: false, error: error.message}));
            });
    };
    return [state, requestData] as const;
};

/**
 * 数据API 配置价格体系
 */
