/** @format */

import * as React from 'react';
import md5 from 'md5';
import Axios from '../utils/xhr';
import {
    GET_ORDER_MANGENT,
    PUT_MERCHANT_AUTH,
    GET_MERCHANT_LIST,
    GET_MERCHANT_LIST_WITH_DATAAPI,
    POST_INSERT_MERCHANT,
    PUT_CHNAGE_MERCHANT,
    GET_MERCHANT_REPORT_OnLine,
    GET_REPORT_MERCHANT_ONLINE,
    GET_MERCHANT_REVIEW_LIST,
} from '../const/path';

interface RequestMerchantListParams {
    merchant_id: number | ''; //商户id
    page_number: number; //当前页
    data_api_id: number | ''; //产品id
    status_code: number; //
    is_all?: boolean;
    page_size?: number;
    merchant_type: any;
    phone?: string;
    merchant_name?: string;
    start_time?: string;
    end_time?: string;
}

export interface ReciveMerchantProps {
    //基本信息
    id: number;
    auth_status: number;
    app_key: string;
    app_secret: string;
    name: string;
    phone: string;
    password: string;
    email: string;
    //商户信息
    merchant_name: string;
    social_code: string;
    merchant_parssword: string;
    memail: string;
    company_name: string;
    address: string;
    contact_name: string;
    contact_number: string;
    merchant_license: string;
    ip_whitelist: string;
    warning_enable: boolean;
    data_api_info: dataApiInfoProps[];
    is_http_code: number;
    merchant_type: any;
    create_time: string;
}
interface dataApiInfoProps {
    combo_type: number;
    data_api_name: string;
    left_count: number;
    left_day: number;
    status_code: number;
}
export interface MerchantRecordState extends ReciveMerchantProps {
    index: number;
}
interface MerchantState {
    loading: boolean;
    dataSource: Readonly<MerchantRecordState>[];
    total: number;
    error: null | string;
    deepData: RequestMerchantListParams;
}
/**
 * 获取商户列表(带有数据API)
 * 初次就会加载数据
 */
export const useMerchantListWithDataApi = (params: RequestMerchantListParams) => {
    const [state, setState] = React.useState<Readonly<MerchantState>>({
        loading: false,
        dataSource: [],
        deepData: {
            merchant_id: '',
            page_number: 1,
            merchant_type: '',
            data_api_id: '',
            status_code: 0,
            is_all: false,
            page_size: 10,
        },
        total: 0,
        error: null,
    });
    const requestData = (params?: Partial<RequestMerchantListParams>) => {
        setState(preState => {
            return {...preState, loading: true, error: null};
        });
        const combinationParams = {
            ...state.deepData,
            ...params,
        };
        Axios({
            url: GET_MERCHANT_LIST_WITH_DATAAPI,
            params: combinationParams,
        })
            .then(({code, data, msg}) => {
                if (code === 0) {
                    if (!data.merchant_list) {
                        data.merchant_list = [];
                    }
                    const baseSize = data.page_size * (data.page_number - 1);
                    setState(preState => {
                        return {
                            ...preState,
                            loading: false,
                            total: data.total,
                            deepData: combinationParams,
                            dataSource: data.merchant_list.map((element: ReciveMerchantProps, index: number) => {
                                return {
                                    ...element,
                                    index: baseSize + index + 1,
                                };
                            }),
                        };
                    });
                } else {
                    setState(preState => ({...preState, loading: false, error: msg, deepData: combinationParams}));
                }
            })
            .catch(error => {
                setState(preState => {
                    return {...preState, loading: false, error: error.message, deepData: combinationParams};
                });
            });
    };
    React.useEffect(() => {
        requestData(params);
    }, []);
    return [state, requestData] as const;
};
// 待审核商户列表
export const useMerchantReviewList = (params: RequestMerchantListParams) => {
    const [state, setState] = React.useState<Readonly<MerchantState>>({
        loading: false,
        dataSource: [],
        deepData: {
            merchant_id: '',
            page_number: 1,
            data_api_id: '',
            status_code: 0,
            is_all: false,
            page_size: 10,
            merchant_name: '',
            phone: '',
            start_time: '',
            end_time: '',
        },
        total: 0,
        error: null,
    });
    const requestData = (params?: Partial<RequestMerchantListParams>) => {
        setState(preState => {
            return {...preState, loading: true, error: null};
        });
        const combinationParams = {
            ...state.deepData,
            ...params,
        };
        Axios({
            url: GET_MERCHANT_REVIEW_LIST,
            params: combinationParams,
        })
            .then(({code, data, msg}) => {
                if (code === 0) {
                    if (!data.merchant_list) {
                        data.merchant_list = [];
                    }
                    const baseSize = data.page_size * (data.page_number - 1);
                    setState(preState => {
                        return {
                            ...preState,
                            loading: false,
                            total: data.total,
                            deepData: combinationParams,
                            dataSource: data.merchant_list.map((element: ReciveMerchantProps, index: number) => {
                                return {
                                    ...element,
                                    index: baseSize + index + 1,
                                };
                            }),
                        };
                    });
                } else {
                    setState(preState => ({...preState, loading: false, error: msg, deepData: combinationParams}));
                }
            })
            .catch(error => {
                setState(preState => {
                    return {...preState, loading: false, error: error.message, deepData: combinationParams};
                });
            });
    };
    React.useEffect(() => {
        requestData(params);
    }, []);
    return [state, requestData] as const;
};
interface merchantListParams {
    api_ids?: number | string; //baseApi id
    data_api_id?: number | ''; // dataApi id
    is_all?: boolean;
}
//转换出去的接口数据类型
export interface merchantProps {
    key: number;
    value: number;
    label: string;
    [propIndex: string]: any;
}
interface MerchantListState {
    loading: boolean;
    error: null;
    dataSource: merchantProps[];
    deepData: merchantListParams;
}

/**
 * 搜索商户列表(仅包括自身信息)
 * 如果要传id 代表要搜索带有这个接口得商户
 */
export const userMerchantList = () => {
    const [state, setState] = React.useState<MerchantListState>({
        loading: false,
        error: null,
        dataSource: [],
        deepData: {
            is_all: true,
        },
    });
    const requesData = (params: merchantListParams) => {
        const combineParams = {...state.deepData, ...params};
        setState(preState => ({...preState, loading: true, error: null, deepData: combineParams}));
        Axios({
            url: GET_MERCHANT_LIST,
            params: combineParams,
        })
            .then(({code, data, msg}) => {
                if (code === 0) {
                    data.merchant_list = data.merchant_list || [];
                    setState(preState => ({
                        ...preState,
                        loading: false,
                        dataSource: data.merchant_list.map((element: any) => {
                            return {
                                ...element,
                                value: element.merchant_id,
                                key: element.merchant_id,
                                label: element.merchant.merchant_name,
                            };
                        }),
                    }));
                } else {
                    setState(preState => ({...preState, loading: false, error: msg}));
                }
            })
            .catch(error => {
                setState(preState => ({...preState, loading: false, error: error.message}));
            });
    };

    return [state, requesData] as const;
};

/**
 * 新增商户
 */
export const useInsertMerchant = () => {
    const [state, setState] = React.useState({
        loading: false,
        error: null,
    });
    const requestData = (params: ReciveMerchantProps) => {
        setState(preState => ({...preState, loading: true, error: null}));
        return Axios({
            url: POST_INSERT_MERCHANT,
            method: 'POST',
            data: transformData(params),
        })
            .then(({code, msg}) => {
                if (code === 0) {
                    setState({
                        loading: false,
                        error: null,
                    });
                } else {
                    setState({
                        loading: false,
                        error: msg,
                    });
                    return msg;
                }
            })
            .catch(error => {
                setState({
                    loading: false,
                    error: error.message,
                });
                return error.message;
            });
    };
    return [state, requestData] as const;
};

/**
 * 商户信息修改
 */
export const useUpdateMerchant = () => {
    const [state, setState] = React.useState({
        loading: false,
        error: null,
    });
    const requestData = (params: ReciveMerchantProps) => {
        setState(preState => ({...preState, loading: true, error: null}));
        return Axios({
            url: PUT_CHNAGE_MERCHANT,
            method: 'PUT',
            params: {
                merchant_id: params.id,
            },
            data: transformData(params),
        })
            .then(({code, msg}) => {
                if (code === 0) {
                    setState({
                        loading: false,
                        error: null,
                    });
                } else {
                    setState({
                        loading: false,
                        error: msg,
                    });
                    return msg;
                }
            })
            .catch(error => {
                setState({
                    loading: false,
                    error: error.message,
                });
                return error.message;
            });
    };
    return [state, requestData] as const;
};
/**
 * 商户认证
 */
export const useMerchantAuth = () => {
    const [state, setState] = React.useState({
        loading: false,
        error: null,
    });
    const requestData = (params: {id: number; state: 1 | 2}) => {
        setState({loading: true, error: null});
        return Axios({
            url: PUT_MERCHANT_AUTH,
            method: 'PUT',
            data: {
                merchant_id: params.id,
                state: params.state,
            },
        })
            .then(({code, msg}) => {
                if (code === 0) {
                    setState({loading: false, error: null});
                    return;
                } else {
                    setState({loading: false, error: msg});
                    return msg;
                }
            })
            .catch(error => {
                setState({loading: false, error: error.message});
                return error.message;
            });
    };
    return [state, requestData] as const;
};

//商户订单管理
interface ReciveOrderRecordProps {
    add_order_time: string;
    combo_type: string;
    data_api_name: string;
    order_id: number;
    price: number;
    query_type: string;
    status: number;
}
interface OrderRecordProps extends ReciveOrderRecordProps {
    id: number;
    index: number;
}
interface OrderParams {
    merchant_id: number | '';
    page_number: number;
    data_api_name: string;
    status_code: number;
    start_time?: string;
    end_time?: string;
}
interface OrderState {
    loading: boolean;
    error: null;
    total: number;
    dataSource: OrderRecordProps[];
    deepData: OrderParams;
}
/**
 * 查看商户的订单
 */
export const useOrderMangent = (params: OrderParams) => {
    const [state, setState] = React.useState<OrderState>({
        loading: false,
        error: null,
        deepData: {
            merchant_id: '',
            page_number: 1,
            data_api_name: '',
            status_code: 0,
            start_time: '',
            end_time: '',
        },
        dataSource: [],
        total: 0,
    });
    const requestData = (params?: Partial<OrderParams>) => {
        const combineParams = {...state.deepData, ...params};
        setState(preState => {
            return {...preState, loading: true, error: null};
        });
        Axios({
            url: GET_ORDER_MANGENT,
            params: combineParams,
        }).then(({code, data, msg}) => {
            if (code === 0) {
                const baseSize = data.page_size * (data.page_number - 1);
                if (!data.merchant_order_item_list) {
                    data.merchant_order_item_list = [];
                }
                setState(preState => {
                    return {
                        ...preState,
                        deepData: combineParams,
                        loading: false,
                        total: data.total,
                        dataSource: data.merchant_order_item_list.map(
                            (element: ReciveOrderRecordProps, index: number) => {
                                return {
                                    ...element,
                                    index: baseSize + index + 1,
                                    id: element.order_id,
                                };
                            },
                        ),
                    };
                });
            } else {
                setState(preState => ({...preState, loading: false, error: msg, deepData: combineParams}));
            }
        });
    };
    React.useEffect(() => {
        requestData(params);
    }, []);
    return [state, requestData] as const;
};

//将数据转换为后端需要的数据
const transformData = (params: ReciveMerchantProps) => {
    return {
        merchant_info: {
            merchant_name: params.merchant_name,
            social_code: params.social_code,
            password: params.merchant_parssword ? md5(params.merchant_parssword) : '',
            email: params.memail,
            company_name: params.company_name,
            address: params.address,
            contact_name: params.contact_name,
            contact_number: params.contact_number,
            merchant_license: params.merchant_license,
            ip_whitelist: params.ip_whitelist,
            warning_enable: params.warning_enable,
            is_http_code: params.is_http_code,
        },
        user_info: {
            name: params.name,
            phone: params.phone,
            password: params.password ? md5(params.password) : '',
            email: params.email,
        },
    };
};

interface MerchantStatisticsReportParams {
    page_size?: number;
    page_number: number;
    merchant_id: '' | number;
    api_id: '' | number;
    start_timestamp: number;
    end_timestamp: number;
}

export interface ReciveMerchantStatisticsReportOnLine {
    api_name: string;
    charge: number;
    charge_rate: string;
    date: string;
    elapsed: number;
    fail: number;
    fail_rate: string;
    query: number;
    query_rate: string;
    reuse: number;
    reuse_rate: string;
    total: number;
    valid: number;
    valid_rate: string;
}
export interface ImerchantStatisticsReportOnLineRecord extends ReciveMerchantStatisticsReportOnLine {
    index: number;
    id: number;
}
interface BaseState {
    loading: boolean;
    total: number;
    error: null | string;
}
interface MerchantStatisticsReportOnLineState extends BaseState {
    dataSource: ImerchantStatisticsReportOnLineRecord[];
    deepData: MerchantStatisticsReportParams;
}
/**
 * 获取商户统计报表(实时-控制面板)
 */
export const useMerchantStatisticsReportOnLine = (params: {
    page_size?: number;
    page_number?: number;
    merchant_id?: number | '';
    api_id?: number | '';
    start_timestamp?: number;
    end_timestamp?: number;
}) => {
    const [state, setState] = React.useState({
        loading: false,
        total: 0,
        error: null,
        dataSource: [],
        deepData: {
            page_size: 10,
            page_number: 1,
            merchant_id: '',
            api_id: '',
            start_timestamp: '',
            end_timestamp: '',
        },
    });
    const requestData = (params: {
        page_size?: number;
        page_number?: number;
        merchant_id?: number | '';
        api_id?: number | '';
        start_timestamp?: number;
        end_timestamp?: number;
    }) => {
        const combinationParams = {...state.deepData, ...params};
        setState(preState => ({...preState, loading: true, error: null, deepData: combinationParams}));
        Axios({
            url: GET_MERCHANT_REPORT_OnLine,
            params: {
                ...state.deepData,
                ...params,
            },
        })
            .then(({code, msg, data}) => {
                if (code === 0) {
                    data.log_query_user_access_count = data.log_query_user_access_count || [];
                    const basePage = data.page_size * (data.page_number - 1) + 1;
                    setState(preState => ({
                        ...preState,
                        loading: false,
                        total: data.total,
                        dataSource: data.log_query_user_access_count.map(
                            (element: ReciveMerchantStatisticsReportOnLine, index: number) => {
                                return {
                                    ...element,
                                    index: basePage + index,
                                    id: basePage + index,
                                };
                            },
                        ),
                    }));
                } else {
                    setState(preState => ({...preState, loading: false, error: msg}));
                }
            })
            .catch(error => {
                setState(preState => ({...preState, loading: false, error: error.message}));
            });
    };
    React.useEffect(() => {
        requestData(params);
    }, []);
    return [state, requestData] as const;
};
interface InterfaceStatisticsDetailParams {
    merchant_id: number | '';
    api_id: number | '';
    start_timestamp: number;
    end_timestamp: number;
}

interface InterfaceStatisticsDetailState {
    loading: boolean;
    error: null;
    deepData: InterfaceStatisticsDetailParams;
    dataSource: {
        tableList: {name: string; count: number; rate: string; id: number}[];
        valid: {
            count: number;
            success_rate: number;
            fail_rate: string;
        };
        reuse: {
            count: number;
            reuse_rate: number;
        };
    };
}

/**
 * 获取接口统计详情(实时-控制面板-统计报表-商户查询统计)
 */
export const useInterfaceStatisticsDetail = (params: InterfaceStatisticsDetailParams) => {
    const [state, setState] = React.useState<InterfaceStatisticsDetailState>({
        loading: false,
        error: null,
        dataSource: {
            tableList: [],
            valid: {
                count: 0,
                success_rate: 0,
                fail_rate: '0',
            },
            reuse: {
                count: 0,
                reuse_rate: 0,
            },
        },
        deepData: params,
    });
    const requestData = (params?: Partial<InterfaceStatisticsDetailParams>) => {
        const combinationParams = {...state.deepData, ...params};
        setState(preState => ({...preState, loading: true, error: null, deepData: combinationParams}));

        Axios({
            url: GET_REPORT_MERCHANT_ONLINE,
            params: combinationParams,
        })
            .then(({code, msg, data}) => {
                if (code === 0) {
                    setState(preState => ({
                        ...preState,
                        loading: false,
                        dataSource: {
                            tableList: [
                                {
                                    name: '查得量',
                                    count: data.log_query_success_count.query,
                                    rate: (data.query_rate * 100).toFixed(2) + '%',
                                    id: 1,
                                },
                                {
                                    name: '查无量',
                                    count: data.log_query_success_count.un_query,
                                    rate: (data.un_query_rate * 100).toFixed(2) + '%',
                                    id: 2,
                                },
                                {
                                    name: '数据源异常',
                                    count: data.log_query_fail_count.provider_fail,
                                    rate: (data.provider_fail_rate * 100).toFixed(2) + '%',
                                    id: 3,
                                },
                                {
                                    name: '平台异常',
                                    count: data.log_query_fail_count.service_fail,
                                    rate: (data.service_fail_rate * 100).toFixed(2) + '%',
                                    id: 4,
                                },
                            ],
                            valid: {
                                count: data.total,
                                success_rate: data.success_rate * 100,
                                fail_rate: (data.fail_rate * 100).toFixed(2),
                            },
                            reuse: {
                                count: data.log_query_success_count.reuse,
                                reuse_rate: parseInt(String(data.reuse_rate * 100)),
                            },
                        },
                    }));
                } else {
                    setState(preState => ({...preState, loading: false, error: msg}));
                }
            })
            .catch(error => {
                setState(preState => ({...preState, loading: false, error: error.message}));
            });
    };
    React.useEffect(() => {
        requestData(params);
    }, []);
    return [state, requestData] as const;
};

interface ResultAnalysisParams {
    merchant_id: number | '';
    api_id: number;
    start_timestamp: number;
    end_timestamp: number;
    status: 0 | 1 | 2;
}
interface ResultState {
    loading: boolean;
    error: null;
    deepData: ResultAnalysisParams;
    dataSource: ResultRecordProps[];
}

interface ReciveResultRecordProps {
    code: number;
    count: number;
    msg: string;
}
export interface ResultRecordProps extends ReciveResultRecordProps {
    fildName: string;
    value: number;
}

/**
 * 控制面板 统计报表 商户 结果分析
 *
 */
export const useResultAnalysis = () => {
    const [state, setState] = React.useState<ResultState>({
        loading: false,
        error: null,
        dataSource: [],
        deepData: {
            merchant_id: '',
            status: 0,
            api_id: 0,
            start_timestamp: 0,
            end_timestamp: 0,
        },
    });
    const requestData = (params?: Partial<ResultAnalysisParams>) => {
        const combineParams = {...state.deepData, ...params};
        setState(preState => ({...preState, loading: true, error: null, deepData: combineParams}));
        Axios({
            url: '/access_log/access_log_interface_analyze',
            params: combineParams,
        })
            .then(({code, msg, data}) => {
                if (code === 0) {
                    data = data || [];
                    setState(preState => ({
                        ...preState,
                        loading: false,
                        dataSource: data.map((element: ReciveResultRecordProps) => {
                            return {
                                ...element,
                                fildName: element.code.toString(),
                                value: element.count,
                            };
                        }),
                    }));
                } else {
                    setState(preState => ({...preState, loading: false, error: msg}));
                }
            })
            .catch(error => {
                setState(preState => ({...preState, loading: false, error: error.message}));
            });
    };
    const clear = React.useCallback(() => {
        setState({
            loading: false,
            error: null,
            dataSource: [],
            deepData: {
                merchant_id: '',
                status: 0,
                api_id: 0,
                start_timestamp: 0,
                end_timestamp: 0,
            },
        });
    }, []);
    return [state, requestData, clear] as const;
};
interface ProvideAnalysisParams {
    merchant_id: number | '';
    api_id: number;
    start_timestamp: number;
    end_timestamp: number;
}
interface ReciveProvideRecordProps {
    count: number;
    provider_api_name: string;
    provider_name: string;
}
interface ProvideRecordProps extends ReciveProvideRecordProps {
    fildName: string;
    value: number;
}
interface ProvideAnalysisState {
    loading: boolean;
    error: null;
    deepData: ProvideAnalysisParams;
    dataSource: ProvideRecordProps[];
}
/**
 * 日志分析 统计报表 商户 数据源分析
 */
export const useMerchantProvideAnalysis = () => {
    const [state, setState] = React.useState<ProvideAnalysisState>({
        loading: false,
        error: null,
        deepData: {
            merchant_id: '',
            api_id: 0,
            start_timestamp: 0,
            end_timestamp: 0,
        },
        dataSource: [],
    });
    const requestData = (params?: Partial<ProvideAnalysisParams>) => {
        const combinationParams = {...state.deepData, ...params};
        setState(preState => ({...preState, loading: true, deepData: combinationParams, error: null}));
        Axios({
            url: '/access_log/third_party_analyze',
            params: combinationParams,
        })
            .then(({code, msg, data}) => {
                if (code === 0) {
                    data = data || [];
                    setState(preState => ({
                        ...preState,
                        loading: false,
                        dataSource: data.map((element: ReciveProvideRecordProps) => {
                            return {
                                ...element,
                                fildName: `${element.provider_api_name}(${element.provider_name})`,
                                value: element.count,
                            };
                        }),
                    }));
                } else {
                    setState(preState => ({...preState, loading: false, error: msg}));
                }
            })
            .catch(error => {
                setState(preState => ({...preState, loading: false, error: error.message}));
            });
    };
    const clear = React.useCallback(() => {
        setState({
            loading: false,
            error: null,
            deepData: {
                merchant_id: '',
                api_id: 0,
                start_timestamp: 0,
                end_timestamp: 0,
            },
            dataSource: [],
        });
    }, []);
    return [state, requestData, clear] as const;
};
