/** @format */
import * as React from 'react';
import {reduceRate, formatNumer} from '../utils/operation';
import {
    GET_DASHBORAD_MERCHANT_SERVERCONSUME,
    GET_MERCHANT_REPORT,
    GET_OVERVIEW_DATA,
    GET_MERCHANT_REVENUE,
    GET_MERCHANT_FAIL,
    GET_MERCHANT_TREND,
    GET_MERCHANT_RESULT,
    GET_MERCHANT_COST,
    GET_MERCHANT_MONITOR,
} from '../const/path';
import Axios from '../utils/xhr';
const page_size = 10;

interface DataOverviewRecordProps {
    key: string;
    name: string;
    today: number;
    yesterday: number;
    week: number;
    month: number;
}
interface DataOverviewState {
    loading: boolean;
    error: null | string;
    dataSource: DataOverviewRecordProps[];
    deepData: DataOverviewParams;
}
interface DataOverviewParams {
    api_id?: number | '';
    today_end_timestamp: number;
}
/**
 * 商户-服务概况-数据概况
 */

export const useDataOverview = () => {
    const [state, setState] = React.useState<DataOverviewState>({
        loading: false,
        dataSource: [],
        error: null,
        deepData: {
            api_id: '',
            today_end_timestamp: 0,
        },
    });
    const requestData = (parmas?: Partial<DataOverviewParams>) => {
        const combineParams = {...state.deepData, ...parmas};
        setState(preState => ({...preState, loading: true, error: null, deepData: combineParams}));
        Axios({
            url: GET_OVERVIEW_DATA,
            params: combineParams,
        })
            .then(({code, data, msg}) => {
                if (code === 0) {
                    setState(preState => ({
                        ...preState,
                        loading: false,
                        error: null,
                        dataSource: [
                            {
                                key: '1',
                                name: '有效查询',
                                today: data.today.valid,
                                yesterday: data.yesterday.valid,
                                week: data.week.valid,
                                month: data.month.valid,
                            },
                            {
                                key: '2',
                                name: '计费查次',
                                today: data.today.charge,
                                yesterday: data.yesterday.charge,
                                week: data.week.charge,
                                month: data.month.charge,
                            },
                            {
                                key: '3',
                                name: '平台输出',
                                today:
                                    data.today.valid === 0 || data.today.resue === 0
                                        ? `${formatNumer(data.today.resue)}(0%)`
                                        : `${formatNumer(data.today.resue)}(${reduceRate(
                                              data.today.resue / data.today.valid,
                                          )})`,
                                yesterday:
                                    data.yesterday.valid === 0 || data.yesterday.resue === 0
                                        ? `${formatNumer(data.yesterday.resue)}(0%)`
                                        : `${formatNumer(data.yesterday.resue)}(${reduceRate(
                                              data.yesterday.resue / data.yesterday.valid,
                                          )})`,
                                week:
                                    data.week.valid === 0 || data.week.resue == 0
                                        ? `${formatNumer(data.week.resue)}(0%)`
                                        : `${formatNumer(data.week.resue)}(${reduceRate(
                                              data.week.resue / data.week.valid,
                                          )})`,
                                month:
                                    data.month.valid === 0 || data.month.resue === 0
                                        ? `${formatNumer(data.month.resue)}(0%)`
                                        : `${formatNumer(data.month.resue)}(${reduceRate(
                                              data.month.resue / data.month.valid,
                                          )})`,
                            },
                            {
                                key: '4',
                                name: '异常调用',
                                today: data.today.fail,
                                yesterday: data.yesterday.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 RequestRankParamsProps {
    page_number: number;
    time_type: number;
    today_end_timestamp: number;
    page_size?: number;
}

interface ReciveConsumeRecordProps {
    charge: number;
    merchant_name: string;
    detail: ReciveConsumeRecordDetailProps[];
}
interface ReciveConsumeRecordDetailProps {
    api_name: string;
    charge: number;
    charge_rate: string;
    rate: string;
    valid: number;
}
export interface ConsumeRecordDetailProps {
    id: number;
    api_name: string;
    charge: number;
    charge_rate: string;
    rate: string;
    valid: number;
    filesName: string;
    value: string;
}
export interface ConsumeRecordProps {
    id: number;
    charge: number;
    merchant_name: string;
    detail: ConsumeRecordDetailProps[];
}
interface ConsumeState {
    loading: boolean;
    deepData: RequestRankParamsProps;
    total: 0;
    dataSource: ConsumeRecordProps[];
    error: null;
}
/**
 * 商户-服务概况-商户消费排行
 */
export const useMerchantConsume = (params: RequestRankParamsProps) => {
    const [state, setState] = React.useState<ConsumeState>({
        loading: false,
        deepData: {
            page_number: 1,
            time_type: 0,
            today_end_timestamp: 0,
            page_size,
        },
        error: null,
        total: 0,
        dataSource: [],
    });
    const requestData = (params?: Partial<RequestRankParamsProps>) => {
        const combineParams = {...state.deepData, ...params};
        setState(preState => ({...preState, loading: true, error: null, deepData: combineParams}));
        Axios({
            url: GET_DASHBORAD_MERCHANT_SERVERCONSUME,
            params: combineParams,
        })
            .then(({code, msg, data}) => {
                if (code === 0) {
                    if (!data.infos) {
                        data.infos = [];
                    }
                    setState(preState => ({
                        ...preState,
                        ...params,
                        loading: false,
                        total: data.total,
                        dataSource: data.infos.map((element: ReciveConsumeRecordProps, index: number) => {
                            element.detail = element.detail || [];
                            return {
                                name: element.merchant_name,
                                value: element.charge,
                                id: index,
                                detail: element.detail.map((item, index) => {
                                    return {...item, id: index, filesName: item.api_name, value: item.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 ReciveRevenueRecordProps {
    api_name: string;
    charge: number;
    detail: ReciveRevenueRecordDetailProps[];
}
interface ReciveRevenueRecordDetailProps {
    charge: number;
    merchant_name: string;
    rate: string;
    valid: number;
}
export interface RevenueRecordProps {
    api_name: string;
    charge: number;
    id: number;
    detail: RevenueRecordDetailProps[];
}
export interface RevenueRecordDetailProps {
    charge: number;
    merchant_name: string;
    rate: string;
    valid: number;
    id: number;
    filesName: string;
    value: number;
}
interface RevenueState {
    loading: boolean;
    dataSource: RevenueRecordProps[];
    error: null;
    total: number;
    deepData: RequestRankParamsProps;
}
/**
 * 服务营收排行
 */
export const useRevenue = (params: RequestRankParamsProps) => {
    const [state, setState] = React.useState<RevenueState>({
        loading: false,
        dataSource: [],
        error: null,
        total: 0,
        deepData: {
            page_size,
            page_number: 1,
            time_type: 0,
            today_end_timestamp: 0,
        },
    });
    const requestData = (params?: Partial<RequestRankParamsProps>) => {
        const combineParams = {...state.deepData, ...params};
        setState(preState => ({...preState, loading: true, error: null, deepData: combineParams}));
        Axios({
            url: GET_MERCHANT_REVENUE,
            params: combineParams,
        })
            .then(({code, msg, data}) => {
                if (code === 0) {
                    if (!data.infos) {
                        data.infos = [];
                    }
                    setState(preState => ({
                        ...preState,
                        loading: false,
                        error: null,
                        total: data.total,
                        dataSource: data.infos.map((element: ReciveRevenueRecordProps, index: number) => {
                            element.detail = element.detail || [];
                            return {
                                ...element,
                                id: index,
                                detail: element.detail.map((item, index) => {
                                    return {
                                        ...item,
                                        id: index,
                                        filesName: item.merchant_name,
                                        value: item.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 ReciveFailRecordProps {
    api_name: string;
    fail: number;
    detail: ReciveFailDetailProps[];
}
interface ReciveFailDetailProps {
    code: number;
    fail: number;
    msg: string;
    rate: string;
}
export interface FailRecordProps {
    api_name: string;
    fail: number;
    id: number;
    detail: FailDetailProps[];
}
export interface FailDetailProps {
    code: number;
    fail: number;
    msg: string;
    rate: string;
    id: number;
    filesName: string;
    value: number;
}
interface FaileState {
    loading: boolean;
    dataSource: FailRecordProps[];
    error: null;
    total: number;
    deepData: RequestRankParamsProps;
}

/**
 * 服务异常排行
 */
export const useServerFail = (params: RequestRankParamsProps) => {
    const [state, setState] = React.useState<FaileState>({
        loading: false,
        dataSource: [],
        error: null,
        total: 0,
        deepData: {
            page_number: 1,
            time_type: 0,
            today_end_timestamp: 0,
            page_size,
        },
    });
    const serverfaile = (params?: Partial<RequestRankParamsProps>) => {
        const combineParams = {...state.deepData, ...params};
        setState(preState => ({
            ...preState,
            loading: true,
            deepData: combineParams,
            error: null,
        }));
        Axios({
            url: GET_MERCHANT_FAIL,
            params: combineParams,
        })
            .then(({code, msg, data}) => {
                if (code === 0) {
                    if (!data.infos) {
                        data.infos = [];
                    }
                    setState(preState => ({
                        ...preState,
                        ...params,
                        deepData: {
                            ...preState.deepData,
                            ...params,
                        },
                        total: data.total,
                        loading: false,
                        dataSource: data.infos.map((element: ReciveFailRecordProps, index: number) => {
                            element.detail = element.detail || [];
                            return {
                                ...element,
                                id: index,
                                detail: element.detail.map((item, index) => {
                                    return {...item, id: index, filesName: item.code.toString(), value: item.fail};
                                }),
                            };
                        }),
                    }));
                } else {
                    setState(preState => ({...preState, loading: false, error: msg}));
                }
            })
            .catch(error => {
                setState(preState => ({...preState, loading: false, error: error.message}));
            });
    };
    return [state, serverfaile] as const;
};

interface InfoRecordProps {
    charge: number;
    date: string;
    total: number;
}
interface MerchantTrendSumProps {
    max: number;
    min: number;
    avg: number;
    current: number;
    desc: string;
}
interface MerchantTrendState {
    loading: boolean;
    error: null | string;
    dataSource: MerchantTrendSumProps[];
    charge_avg: number;
    total_avg: number;
    infos: InfoRecordProps[];
}
interface RequestTrendParams {
    today_end_timestamp: number;
    merchant_id: number | string;
    api_id: number;
    start_timestamp: number;
    end_timestamp: number;
    time_type: 0 | 1;
}

export interface HistoryReportItemProps {
    api_name: string;
    date: string;
    merchant_name: string;
    total: number;
    valid: number;
    charge: number;
    charge_rate: string;
    reuse: number;
    reuse_rate: string;
    fail: number;
    fail_rate: string;
    avg_elapsed: string;
}
interface MerchantHistoryReportParams {
    api_id: string;
    merchant_id: number | string;
    start_timestamp: number;
    end_timestamp: number;
    today_end_timestamp: number;
    is_all?: boolean;
}
interface ImerchantHistoryState {
    loading: boolean;
    error: null;
    dataSource: HistoryReportItemProps[];
    deepData: MerchantHistoryReportParams;
    total: number;
    sums?: HistoryReportItemProps;
}
/**
 * 仪表盘-商户-统计报表
 */
export const useReport = (baseParams: MerchantHistoryReportParams) => {
    const [state, setState] = React.useState<ImerchantHistoryState>({
        loading: false,
        error: null,
        dataSource: [],
        sums: {
            index: '合计',
        },
        deepData: {
            is_all: true,
            api_id: '',
            merchant_id: '',
            start_timestamp: 0,
            end_timestamp: 0,
            today_end_timestamp: 0,
            ...baseParams,
        },
        total: 0,
    });
    const requestData = (params?: Partial<MerchantHistoryReportParams>) => {
        const combineParams = {...state.deepData, ...params};
        setState(preState => ({...preState, loading: true, error: null, deepData: combineParams}));
        Axios({
            url: GET_MERCHANT_REPORT,
            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: HistoryReportItemProps, index: number) => {
                            return {
                                ...element,
                                index: index + 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;
};
/**
 * 获取仪表盘-商户-用量趋势
 */

export const useMerchantTrend = () => {
    const [state, setState] = React.useState<MerchantTrendState>({
        loading: false,
        error: null,
        dataSource: [],
        charge_avg: 0,
        total_avg: 0,
        infos: [],
    });
    const requestData = (params: RequestTrendParams) => {
        setState(preState => ({...preState, loading: true, error: null}));
        Axios({
            url: GET_MERCHANT_TREND,
            params: params,
        })
            .then(({code, msg, data}) => {
                if (code === 0) {
                    if (!data.infos) {
                        data.infos = [];
                    }
                    setState(preState => ({
                        ...preState,
                        loading: false,
                        infos: data.infos,
                        total_avg: data.last_stage_total_avg,
                        charge_avg: data.last_stage_charge_avg,
                        dataSource: [
                            {
                                max: data.total_max,
                                min: data.total_min,
                                avg: data.total_avg,
                                current: data.total_current,
                                desc: '有效量',
                                id: 1,
                            },
                            {
                                max: data.charge_max,
                                min: data.charge_min,
                                avg: data.charge_avg,
                                current: data.charge_current,
                                desc: '计费量',
                                id: 2,
                            },
                        ],
                    }));
                } else {
                    setState(preState => ({...preState, loading: false, error: msg}));
                }
            })
            .catch(error => {
                setState(preState => ({...preState, loading: false, error: error.message}));
            });
    };
    return [state, requestData] as const;
};

interface ReciveResultRecordProps {
    code: string;
    count: number;
    msg: string;
}
interface ResultRecordProps extends ReciveResultRecordProps {
    rate: string;
    id: number;
}
interface ResultState {
    loading: boolean;
    error: null | string;
    dataSource: ResultRecordProps[];
    total: number;
    charge: number;
    valid: number;
    fail: number;
}
interface RequestResultParams {
    today_end_timestamp: number;
    merchant_id: number | string;
    api_id: number;
    start_timestamp: number;
    end_timestamp: number;
}
/**
 * 仪表盘-商户-结果分析
 */
export const useMechantResult = () => {
    const [state, setState] = React.useState<ResultState>({
        loading: false,
        error: null,
        dataSource: [],
        total: 0,
        valid: 0,
        charge: 0,
        fail: 0,
    });
    const requestData = (params: RequestResultParams) => {
        setState(preState => ({...preState, loading: true, error: null}));
        Axios({
            url: GET_MERCHANT_RESULT,
            params: params,
        })
            .then(
                ({
                    code,
                    msg,
                    data,
                }: {
                    code: number;
                    msg: string;
                    data: {
                        api_code_total: number;
                        api_fail: number;
                        api_charge: number;
                        api_valid: number;
                        api_code_list: ReciveResultRecordProps[];
                    };
                }) => {
                    if (code === 0) {
                        if (!data.api_code_list) {
                            data.api_code_list = [];
                        }
                        setState(preState => ({
                            ...preState,
                            loading: false,
                            charge: data.api_charge,
                            fail: data.api_fail,
                            valid: data.api_valid,
                            total: data.api_code_total,
                            dataSource: data.api_code_list.map((element, index: number) => {
                                return {
                                    ...element,
                                    id: index,
                                    rate: reduceRate(element.count / data.api_code_total),
                                };
                            }),
                        }));
                    } else {
                        setState(preState => ({...preState, loading: false, error: msg}));
                    }
                },
            )
            .catch(error => {
                setState(preState => ({...preState, loading: false, error: error.message}));
            });
    };
    return [state, requestData] as const;
};
interface AcciveCostRecordProps {
    charge: number;
    count: number;
    provider_api_name: string;
    provider_name: string;
}
interface CostRecordProps extends AcciveCostRecordProps {
    id: number;
}
interface CostState {
    loading: boolean;
    error: null | string;
    dataSource: CostRecordProps[];
    merchant_sum_charge: number;
    total: number;
}

/**
 * 仪表盘-商户-成本分析
 */
export const useCost = () => {
    const [state, setState] = React.useState<CostState>({
        loading: false,
        error: null,
        dataSource: [],
        merchant_sum_charge: 0,
        total: 0,
    });
    const requestData = (params: RequestResultParams) => {
        setState(preState => ({...preState, loading: true}));
        Axios({url: GET_MERCHANT_COST, params: params})
            .then(
                ({
                    code,
                    msg,
                    data,
                }: {
                    code: number;
                    msg: string;
                    data: {
                        infos: CostRecordProps[];
                        merchant_sum_charge: number;
                        provider_sum_charge: number;
                    };
                }) => {
                    if (code === 0) {
                        data.infos = data.infos || [];
                        setState(preState => ({
                            ...preState,
                            loading: false,
                            total: data.provider_sum_charge,
                            merchant_sum_charge: data.merchant_sum_charge,
                            dataSource: data.infos.map((element, index) => {
                                return {
                                    ...element,
                                    id: index,
                                    name: `${element.provider_name}(${element.provider_api_name})`,
                                    rate: reduceRate(element.count / data.provider_sum_charge),
                                };
                            }),
                        }));
                    } else {
                        setState(preState => ({...preState, loading: false, error: msg}));
                    }
                },
            )
            .catch(error => {
                setState(error.message);
            });
    };
    return [state, requestData] as const;
};
interface ReceiveMonitorRecordProps {
    avg_elapsed: number;
    fail_count: number;
    timestamp_minute: number;
}
interface MonitorRecordProps extends ReceiveMonitorRecordProps {
    date: string;
}
interface MonitorState {
    loading: boolean;
    error: null | string;
    dataSource: MonitorRecordProps[];
}
/**
 * 仪表盘-商户-性能监控-接口耗时
 */
export const useMerchantMonitor = () => {
    const [state, setState] = React.useState<MonitorState>({
        loading: false,
        error: null,
        dataSource: [],
    });
    const requestData = (params: RequestResultParams) => {
        setState(preState => ({...preState, loading: true, error: null}));
        Axios({url: GET_MERCHANT_MONITOR, params})
            .then(({code, msg, data = []}: {code: number; msg: string; data: ReceiveMonitorRecordProps[]}) => {
                if (code === 0) {
                    data = data || [];
                    setState(preState => ({
                        ...preState,
                        loading: false,
                        dataSource: data.map(element => {
                            const time = new Date(element.timestamp_minute * 1000);
                            return {
                                ...element,
                                date: params.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;
};
