/** @format */
import * as React from 'react';
import {
    GET_PROVIDE_OVIEDATA,
    GET_PROVIDE_COST_RANK,
    GET_PROVIDE_SERVER_FAIL,
    GET_PROVIDE_REPORT_OFFLINE,
    GET_PROVIDE_TREND,
    GET_PROVIDE_RESULT,
    GET_PROVIDE_MONITOR,
} from '../const/path';
import {reduceRate} from '../utils/operation';
import Axios from '../utils/xhr';
interface DataOviewParams {
    provider_api_id: number | '';
    today_end_timestamp: number;
}
interface DataOvieRecordProps {
    name: string;
    today: number;
    yesterday: number;
    week: number;
    month: number;
}
interface DataOviewState {
    loading: boolean;
    error: null;
    dataSource: DataOvieRecordProps[];
    deepData: DataOviewParams;
}
export const useDataOview = () => {
    const [state, setState] = React.useState<DataOviewState>({
        loading: false,
        error: null,
        dataSource: [],
        deepData: {
            provider_api_id: '',
            today_end_timestamp: 0,
        },
    });
    const requestData = (params?: Partial<DataOviewParams>) => {
        const combineParams = {...state.deepData, ...params};
        setState(preState => ({...preState, loading: true, error: null, deepData: combineParams}));
        Axios({url: GET_PROVIDE_OVIEDATA, params: combineParams})
            .then(({code, msg, data}) => {
                if (code === 0) {
                    setState(preState => ({
                        ...preState,
                        loading: false,
                        dataSource: [
                            {
                                name: '有效查询',
                                today: data.today.valid,
                                key: 'valid',
                                yesterday: data.yesterday.valid,
                                week: data.week.valid,
                                month: data.month.valid,
                            },
                            {
                                name: '计费查次',
                                today: data.today.charge,
                                yesterday: data.yesterday.charge,
                                week: data.week.charge,
                                key: 'charge',
                                month: data.month.charge,
                            },
                            {
                                name: '异常调用',
                                today: data.today.fail,
                                yesterday: data.yesterday.fail,
                                key: 'fail',
                                week: data.week.fail,
                                month: data.month.fail,
                            },
                        ],
                    }));
                } else {
                    setState(preState => ({...preState, loading: false, error: msg}));
                }
            })
            .catch(error => {
                setState(preState => ({...preState, loading: false, error: error.message}));
            });
    };
    return [state, requestData] as const;
};
interface CostParams {
    today_end_timestamp: number;
    page_size?: number;
    time_type: number;
    page_number: number;
}
interface CostState {
    loading: boolean;
    error: null;
    total: number;
    deepData: CostParams;
    dataSource: CostRecordProps[];
}
interface ReciveCostRecordProps {
    charge: number;
    provider_name: string;
    detail: ReciveCostRecordDetailProps[];
}
interface ReciveCostRecordDetailProps {
    charge: number;
    charge_rate: string;
    provider_api_name: string;
    rate: string;
    valid: number;
}
export interface CostRecordProps {
    charge: number;
    provider_name: string;
    detail: CostRecordDetailProps[];
    index: number;
    id: number;
}
export interface CostRecordDetailProps {
    charge: number;
    charge_rate: string;
    provider_api_name: string;
    rate: string;
    valid: number;
    id: number;
    index: number;
    filesName: string;
    value: number;
}

/**
 * 服务成本排行
 */
export const useServerCostRank = () => {
    const [state, setState] = React.useState<CostState>({
        loading: false,
        error: null,
        dataSource: [],
        total: 0,
        deepData: {
            today_end_timestamp: 0,
            page_size: 10,
            time_type: 0,
            page_number: 1,
        },
    });
    const requestData = (params?: Partial<CostParams>) => {
        const combineParams = {...state.deepData, ...params};
        setState(preState => ({...preState, loading: true, error: null, deepData: combineParams}));
        Axios({
            url: GET_PROVIDE_COST_RANK,
            params: combineParams,
        })
            .then(({code, msg, data}) => {
                if (code === 0) {
                    data.infos = data.infos || [];
                    const basePage = data.page_size * (data.page_number - 1) + 1;
                    setState(preState => ({
                        ...preState,
                        loading: false,
                        total: data.total,
                        dataSource: data.infos.map((element: ReciveCostRecordProps, index: number) => {
                            element.detail = element.detail || [];
                            return {
                                ...element,
                                detail: element.detail.map((item, idx) => {
                                    return {
                                        ...item,
                                        index: idx + 1,
                                        id: idx,
                                        filesName: item.provider_api_name,
                                        value: item.charge,
                                    };
                                }),
                                index: basePage + 1,
                                id: index,
                            };
                        }),
                    }));
                } else {
                    setState(preState => ({...preState, loading: false, error: msg}));
                }
            })
            .catch(error => {
                setState(preState => ({...preState, loading: false, error: error.message}));
            });
    };
    return [state, requestData] as const;
};
interface ServerFailParams {
    today_end_timestamp: number;
    page_size: number;
    time_type: number;
    page_number: number;
}
interface ReciveServerFailRecordProps {
    fail: number;
    provider_api_name: string;
    provider_name: string;
    detail: ReciveServerFailRecordDetailProps[];
}
interface ReciveServerFailRecordDetailProps {
    code: string;
    fail: number;
    msg: string;
    rate: string;
}

export interface ServerFailRecordProps {
    fail: number;
    provider_api_name: string;
    provider_name: string;
    detail: ServerFailRecordDetailProps[];
    index: number;
    id: number;
}
export interface ServerFailRecordDetailProps {
    code: string;
    fail: number;
    msg: string;
    rate: string;
    id: number;
    index: number;
    filesName: string;
    value: number;
}
interface ServerFailState {
    loading: boolean;
    error: null;
    dataSource: ServerFailRecordProps[];
    total: number;
    deepData: ServerFailParams;
}
/**
 * 服务异常排行
 */
export const useServerFail = () => {
    const [state, setState] = React.useState<ServerFailState>({
        loading: false,
        error: null,
        dataSource: [],
        total: 0,
        deepData: {
            today_end_timestamp: 0,
            page_size: 10,
            time_type: 0,
            page_number: 1,
        },
    });
    const requestData = (params?: Partial<ServerFailParams>) => {
        const combineParams = {...state.deepData, ...params};
        setState(preState => ({...preState, loading: true, error: null, deepData: combineParams}));
        Axios({
            url: GET_PROVIDE_SERVER_FAIL,
            params: combineParams,
        })
            .then(({code, msg, data}) => {
                if (code === 0) {
                    data.infos = data.infos || [];
                    setState(preState => ({
                        ...preState,
                        loading: false,
                        total: data.total,
                        dataSource: data.infos.map((element: ReciveServerFailRecordProps, index: number) => {
                            return {
                                ...element,
                                index: index + 1,
                                id: index,
                                detail: element.detail.map((item, index) => {
                                    return {
                                        ...item,
                                        index: index + 1,
                                        id: index,
                                        filesName: item.code,
                                        value: item.fail,
                                    };
                                }),
                            };
                        }),
                    }));
                } else {
                    setState(preState => ({...preState, loading: false, error: msg}));
                }
            })
            .catch(error => {
                setState(preState => ({...preState, loading: false, error: error.message}));
            });
    };
    return [state, requestData] as const;
};

interface ReciveReportRecordProps {
    avg_elapsed: string;
    charge: number;
    charge_rate: string;
    date: string;
    fail: number;
    fail_rate: string;
    provider_api_name: string;
    provider_name: string;
    query_no_record: number;
    query_no_record_rate: string;
    total: number;
}
export interface ReportRecordProps extends ReciveReportRecordProps {
    id: number;
    index: number;
}
interface ReportParams {
    is_all?: boolean;
    provider_api_id: number | '';
    start_timestamp: number;
    end_timestamp: number;
    today_end_timestamp: number;
}
interface ReportState {
    loading: boolean;
    error: null;
    deepData: ReportParams;
    dataSource: ReportRecordProps[];
    total: number;
    sums?: ReportRecordProps;
}
/**
 * 统计报表
 */
export const useReport = (params: ReportParams) => {
    const [state, setState] = React.useState<ReportState>({
        loading: false,
        error: null,
        deepData: {
            is_all: true,
            provider_api_id: '',
            start_timestamp: 0,
            end_timestamp: 0,
            today_end_timestamp: 0,
        },
        dataSource: [],
        total: 0,
    });
    const requestData = (params?: Partial<ReportParams>) => {
        const combineParams = {...state.deepData, ...params};
        setState(preState => ({...preState, loading: true, error: null, deepData: combineParams}));
        Axios({
            url: GET_PROVIDE_REPORT_OFFLINE,
            params: combineParams,
        })
            .then(({code, msg, data}) => {
                if (code === 0) {
                    if (!data.infos) {
                        data.infos = [];
                    }
                    setState(preState => ({
                        ...preState,
                        loading: false,
                        total: data.total,
                        sums: {...data.sum, index: '合计'},
                        dataSource: data.infos.map((element: ReciveReportRecordProps, index: number) => {
                            return {
                                ...element,
                                id: index,
                                index: index + 1,
                            };
                        }),
                    }));
                } else {
                    setState(preState => ({...preState, loading: false, error: msg}));
                }
            })
            .catch(error => {
                setState(preState => ({...preState, loading: false, error: error.message}));
            });
    };

    return [state, requestData] as const;
};
interface trendsParams {
    today_end_timestamp: number;
    provider_api_id: number;
    start_timestamp: number;
    end_timestamp: number;
    time_type: 0 | 1;
}
export interface TrendRecordProps {
    desc: string;
    max: number;
    min: number;
    avg: number;
    current: number;
    key: string;
}
interface TrendsState {
    loading: boolean;
    error: null;
    dataSource: TrendRecordProps[];
    deepData: trendsParams;
    infos: {
        charge: number;
        date: string;
        total: number;
    }[];
}
/**
 * 用量趋势
 */
export const useTrend = () => {
    const [state, setState] = React.useState<TrendsState>({
        loading: false,
        error: null,
        deepData: {
            today_end_timestamp: 0,
            provider_api_id: 0,
            start_timestamp: 0,
            end_timestamp: 0,
            time_type: 0,
        },
        infos: [],
        dataSource: [],
    });
    const requestData = (params?: Partial<trendsParams>) => {
        const combineParams = {...state.deepData, ...params};
        setState(preState => ({...preState, loading: true, error: null, deepData: combineParams}));
        Axios({
            url: GET_PROVIDE_TREND,
            params: combineParams,
        })
            .then(({code, msg, data}) => {
                if (code === 0) {
                    data.infos = data.infos || [];
                    setState(preState => ({
                        ...preState,
                        loading: false,
                        infos: data.infos,
                        dataSource: [
                            {
                                desc: '有效量',
                                max: data.total_max,
                                min: data.total_min,
                                avg: data.total_avg,
                                current: data.total_current,
                                key: 'valid',
                            },
                            {
                                desc: '计费量',
                                max: data.charge_max,
                                min: data.charge_min,
                                avg: data.charge_avg,
                                current: data.charge_current,
                                key: 'charge',
                            },
                        ],
                    }));
                } else {
                    setState(preState => ({...preState, loading: false, error: msg}));
                }
            })
            .catch(error => {
                setState(preState => ({...preState, loading: false, error: error.message}));
            });
    };
    return [state, requestData] as const;
};
interface ResultParams {
    today_end_timestamp: number;
    provider_api_id: number;
    start_timestamp: number;
    end_timestamp: number;
}
interface ResultState {
    loading: boolean;
    error: null;
    deepData: ResultParams;
    dataSource: {code: string; count: number; msg: string; index: number; id: number; rate: string}[];
    charge: number;
    fail: number;
    total: number;
}
/**
 * 结果分布
 */
export const useResult = () => {
    const [state, setState] = React.useState<ResultState>({
        loading: false,
        error: null,
        deepData: {
            today_end_timestamp: 0,
            provider_api_id: 0,
            start_timestamp: 0,
            end_timestamp: 0,
        },
        charge: 0,
        fail: 0,
        total: 0,
        dataSource: [],
    });
    const requestData = (params?: Partial<ResultParams>) => {
        const combineParams = {...state.deepData, ...params};
        setState(preState => ({...preState, loading: true, error: null}));
        Axios({url: GET_PROVIDE_RESULT, params: combineParams})
            .then(({code, msg, data}) => {
                if (code === 0) {
                    if (!data.provider_code_list) {
                        data.provider_code_list = [];
                    }
                    setState(preState => ({
                        ...preState,
                        loading: false,
                        charge: data.provider_charge,
                        fail: data.provider_fail,
                        total: data.provider_code_total,
                        dataSource: data.provider_code_list.map(
                            (element: {code: string; count: number; msg: string}, index: number) => {
                                return {
                                    ...element,
                                    id: index,
                                    rate: reduceRate(element.count / data.provider_code_total),
                                    index: index + 1,
                                };
                            },
                        ),
                    }));
                } else {
                    setState(preState => ({...preState, loading: false, error: msg}));
                }
            })
            .catch(error => {
                setState(preState => ({...preState, loading: false, error: error.message}));
            });
    };
    return [state, requestData] as const;
};
interface MonitorParams {
    today_end_timestamp: number;
    provider_api_id: number;
    start_timestamp: number;
    end_timestamp: number;
    time_type: 0 | 1;
}
interface MonitorState {
    loading: boolean;
    error: null;
    deepData: MonitorParams;
    dataSource: {avg_elapsed: number; fail_count: number; timestamp_minute: number}[];
}
/**
 * 性能监控-接口耗时/异常次数
 */
export const useMonitor = () => {
    const [state, setState] = React.useState<MonitorState>({
        loading: false,
        error: null,
        dataSource: [],
        deepData: {
            today_end_timestamp: 0,
            provider_api_id: 0,
            start_timestamp: 0,
            end_timestamp: 0,
            time_type: 0,
        },
    });
    const requestData = (params?: Partial<MonitorParams>) => {
        const combineParams = {...state.deepData, ...params};
        setState(preState => ({...preState, loading: true, error: null, deepData: combineParams}));
        Axios({
            url: GET_PROVIDE_MONITOR,
            params: combineParams,
        })
            .then(({code, msg, data}) => {
                if (code === 0) {
                    data = data || [];
                    setState(preState => ({
                        ...preState,
                        loading: false,
                        dataSource: data.map(
                            (element: {avg_elapsed: number; fail_count: number; timestamp_minute: number}) => {
                                const time = new Date(element.timestamp_minute * 1000);
                                return {
                                    ...element,
                                    date:
                                        combineParams.time_type === 0
                                            ? time.toLocaleDateString()
                                            : time.getHours() + ':00',
                                };
                            },
                        ),
                    }));
                } else {
                    setState(preState => ({...preState, loading: false, error: msg}));
                }
            })
            .catch(error => {
                setState(preState => ({...preState, loading: false, error: error.message}));
            });
    };
    return [state, requestData] as const;
};
