/** @format */

import * as React from 'react';
import monent from 'moment';
import {PaginationProps} from 'antd/es/pagination';
import {ColumnProps, SorterResult} from 'antd/es/table';
import moment, {Moment} from 'moment';
import {Alert,Pagination} from 'antd';
import {CSVLink} from 'react-csv';
import Result from '../../../components/result';
import Button from '../../../components/button';
import Table from '../../../components/table';
import {formatNumer} from '../../../utils/operation';
import {useReport, ReportRecordProps} from '../../../service/dashbordProvide';
import Search, {SearchItemProps} from '../../../components/search/search';
import ProviderApiSelect from '../../../components/select/providerApi';
import RangePicker from '../../../components/datePicker/rangePicker';

const formatString = 'YYYY-MM-DD HH:mm:ss';

const getNowTime = (): Moment => {
    return monent();
};
const startTime = moment('00:00:00', 'HH:mm:ss');
const endTime = moment('23:59:59', 'HH:mm:ss');
interface SearchValesProps {
    provider_api_id: number | '';
    time: Moment[];
}
interface Istate {
    nowTime: Moment;
    dataSource: ReportRecordProps[];
    pageNumber:number;
    pageSize:number;
}
const Report: React.FC = () => {
    const [state, setState] = React.useState<Istate>({
        nowTime: getNowTime(),
        dataSource: [],
        pageNumber:1,
        pageSize:10,
    });
    const {nowTime} = state;
    const [reportState, requetReport] = useReport({
        provider_api_id: '',
        start_timestamp: startTime.unix(),
        end_timestamp: endTime.unix(),
        today_end_timestamp: state.nowTime.unix(),
    });
    React.useEffect(() => {
        setState(preState => ({
            ...preState,
            dataSource: reportState.dataSource
                .sort((pre, next) => {
                    new Date(pre.date);
                    return -(new Date(pre.date) - new Date(next.date));
                })
                .map((element, index) => {
                    return {
                        ...element,
                        index: index + 1,
                    };
                }),
        }));
    }, [reportState.dataSource]);
    const handleSearch = (values: SearchValesProps) => {
      setState(preState => ({...preState, nowTime: getNowTime(),pageNumber:1,
        pageSize:10,}));

        requetReport({
            provider_api_id: values.provider_api_id || '',
            start_timestamp: values.time[0].unix(),
            end_timestamp: values.time[1].unix(),
            today_end_timestamp: nowTime.unix(),
        });
    };


    const handleChangeTable = (
        pagination: PaginationProps,
        filters: Record<string | number | symbol, string[]>,
        sorter: SorterResult<any>,
    ) => {
        const {field, order} = sorter;
        setState(preState => ({
            ...preState,
            dataSource: preState.dataSource
                .sort((pre, next) => {
                    if (field === 'date') {
                        return order === 'ascend'
                            ? new Date(pre[field]) - new Date(next[field])
                            : -(new Date(pre[field]) - new Date(next[field]));
                    }
                    return order === 'ascend'
                        ? parseFloat(pre[field]) - parseFloat(next[field])
                        : -(parseFloat(pre[field]) - parseFloat(next[field]));
                })
                .map((element, index) => {
                    return {
                        ...element,
                        index: index + 1,
                    };
                }),
        }));
    };
    const SearchColumns = React.useMemo(() => {
        const columns: SearchItemProps[] = [
            {
                key: 'provider_api_id',
                component: <ProviderApiSelect provider_id='' />,
                options: {initialValue: undefined},
            },
            {
                key: 'time',
                col: {lg: 8, xxl: 4},
                component: <RangePicker />,
                options: {initialValue: [startTime, endTime]},
            },
        ];
        return columns;
    }, []);

    const tableColumns: ColumnProps<ReportRecordProps>[] = React.useMemo(() => {
        return [
            {
                title: '序号',
                dataIndex: 'index',
                width: 80,
            },
            {
                title: '日期',
                dataIndex: 'date',
                sorter: true,
                defaultSortOrder: 'descend',
                render: text => {
                    return text ? text : '--';
                },
            },
            {
                title: '客户',
                dataIndex: 'provider_name',
                render: text => {
                    return text ? text : '--';
                },
            },
            {
                title: '接口',
                dataIndex: 'provider_api_name',
                render: text => {
                    return text ? text : '--';
                },
            },
            {
                title: '查询数量',
                dataIndex: 'total',
                align: 'right',
                sorter: true,
                render: text => {
                  return text||text===0 ? formatNumer(text) : '--';
              },
            },

            {
                title: '计费查次',
                dataIndex: 'charge',
                align: 'right',
                sorter: true,
                render: text => {
                  return text||text===0 ? formatNumer(text) : '--';
              },
            },
            {
                title: '计费占比',
                dataIndex: 'charge_rate',
                align: 'right',
                sorter: true,
            },
            {
                title: '异常数量',
                dataIndex: 'fail',
                align: 'right',
                sorter: true,
                render: text => {
                  return text||text===0 ? formatNumer(text) : '--';
              },
            },
            {
                title: '异常占比',
                dataIndex: 'fail_rate',
                align: 'right',
                sorter: true,
            },
            {
                title: '耗时(s)',
                dataIndex: 'avg_elapsed',
                align: 'right',
                sorter: true,
            },
        ];
    }, []);
    const sliceStart=(state.pageNumber-1)*state.pageSize
    const sliceEnd=(state.pageNumber-1)*state.pageSize+state.pageSize

    const newDataSource=state.dataSource.length>0?state.dataSource.slice(sliceStart,sliceEnd).concat({id:"sum",index:"合计",date:"",provider_name:"",provider_api_name:"",total:reportState.sums?.total,charge:reportState.sums?.charge,charge_rate:reportState.sums?.charge_rate,fail:reportState.sums?.fail,fail_rate:reportState.sums?.fail_rate,avg_elapsed:reportState.sums?.avg_elapsed}):[]
    return (
        <div>
            <Alert message={'数据统计时间截止:' + nowTime.format(formatString)} />
            <Search
            disabled={reportState.loading}
                algin='start'
                extra={
                    <CSVLink
                        data={state.dataSource}
                        filename={'供应商统计报表.csv'}
                        headers={[
                            {label: '日期', key: 'date'},
                            {label: '客户', key: 'provider_name'},
                            {label: '接口', key: 'provider_api_name'},
                            {label: '查询数量', key: 'total'},
                            {label: '计费查次', key: 'charge'},
                            {label: '计费占比', key: 'charge_rate'},
                            {label: '异常数量', key: 'fail'},
                            {label: '异常占比', key: 'fail_rate'},
                            {label: '耗时(s)', key: 'avg_elapsed'},
                        ]}
                    >
                        <Button type='primary' icon='export'>
                            导出
                        </Button>
                    </CSVLink>
                }
                handleSubmit={handleSearch}
                dataSource={SearchColumns}
            />
            <Result error={reportState.error} onRetry={() => requetReport()}>
                <Table
                    rowKey='id'
                    dataSource={newDataSource}
                    columns={tableColumns}
                    loading={reportState.loading}
                    onChange={handleChangeTable}
                    pagination={false}
                />
                <Pagination 
                current={state.pageNumber}
                pageSize={state.pageSize}
                hideOnSinglePage={false} 
                showQuickJumper 
                pageSizeOptions={["10",'20', '30', '40', '50', '100']}  
                showSizeChanger 
                total={reportState.total} 
                onShowSizeChange={(current, size)=>setState(preState=>({...preState,pageNumber:current, pageSize:size}))}
                onChange={(page, pageSize)=>setState(preState=>({...preState,pageNumber:page,pageSize:pageSize}))}
                showTotal={(total)=>`总计${total}条记录`}>
                </Pagination>
            </Result>
        </div>
    );
};
export default Report;
