/** @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,Typography ,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, HistoryReportItemProps} from '../../../service/dashbordMerchant';
import Search, {SearchItemProps} from '../../../components/search/search';
import MerchantSelect from '../../../components/select/merchant';
import BaseApiSelect from '../../../components/select/baseApiSelect';
import RangePicker from '../../../components/datePicker/rangePicker';

const formatString = 'YYYY-MM-DD HH:mm:ss';
const { Text } = Typography;

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 {
    merchant_id: number | string;
    api_id: number[];
    time: Moment[];
}
interface Istate {
    nowTime: Moment;
    dataSource: HistoryReportItemProps[];
    pageSize:number;
    pageNumber:number
}
const Report: React.FC = () => {
    const [state, setState] = React.useState<Istate>({
        nowTime: getNowTime(),
        dataSource: [],
        pageSize:10,
        pageNumber:1,
    });
    const {nowTime} = state;
    const [reportState, requetReport] = useReport({
        start_timestamp: startTime.unix(),
        end_timestamp: endTime.unix(),
        today_end_timestamp: state.nowTime.unix(),
        api_id: '',
        merchant_id: '',
    });
    React.useEffect(() => {
        setState(preState => ({
            ...preState,
            dataSource: reportState.dataSource
                .sort((pre, next) => {
                    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(),pageSize:10,
          pageNumber:1,}));
        requetReport({
            merchant_id: values.merchant_id,
            api_id: values.api_id.toString(),
            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 [dependState, setDependState] = React.useState<{merchant_id: number | ''; api_ids: number[]}>({
        merchant_id: '',
        api_ids: [],
    });
    const handleReset = () => {
        setDependState(preState => ({...preState, merchant_id: '', api_ids: []}));
    };
    const SearchColumns = React.useMemo(() => {
        const columns: SearchItemProps[] = [
            {
                key: 'merchant_id',
                component: (
                    <MerchantSelect
                        merchantId={dependState.merchant_id}
                        api_ids={dependState.api_ids.toString()}
                        onChange={id => {
                            if(!id){
                                handleReset()
                                return
                            }
                            setDependState(preState => ({...preState, merchant_id: id as number | ''}))
                        }}
                    />
                ),
            },
            {
                key: 'api_id',
                col: {
                    xxl: 10,
                    lg: 18,
                },
                component: (
                    <BaseApiSelect
                        apiIds={dependState.api_ids}
                        mode='multiple'
                        merchant_id={dependState.merchant_id}
                        onChange={value => {
                            setDependState(preState => ({ ...preState, api_ids: value as number[] }));
                        }}/>
                ),
                options: {initialValue: []},
            },
            {
                key: 'time',
                col: {
                    lg: 8,
                    xxl: 5,
                },
                component: <RangePicker />,
                options: {initialValue: [startTime, endTime]},
            },
        ];
        return columns;
    }, [dependState]);

    const tableColumns: ColumnProps<HistoryReportItemProps>[] = React.useMemo(() => {
        return [
            {
                title: '序号',
                dataIndex: 'index',
                width: 80,
            },
            {
                title: '日期',
                dataIndex: 'date',
                sorter: true,
                defaultSortOrder: 'descend',
                render: text => {
                    return text || '--';
                },
            },
            {
                title: '客户',
                dataIndex: 'merchant_name',
                render: text => {
                    return text || '--';
                },
            },
            {
                title: '接口',
                dataIndex: 'api_name',
                render: text => {
                    return text || '--';
                },
            },
            {
                title: '查询数量',
                dataIndex: 'total',
                align: 'right',
                sorter: true,
                render: text => {
                    return text||text===0 ? formatNumer(text) : '--';
                },
            },
            {
                title: '有效查询',
                dataIndex: 'valid',
                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,
                render: text => {
                    return text || '--';
                },
            },
            {
                title: '平台输出',
                dataIndex: 'reuse',
                align: 'right',
                sorter: true,
                render: text => {
                    return text||text===0 ? formatNumer(text) : '--';
                },
            },
            {
                title: '平台输出占比',
                dataIndex: 'reuse_rate',
                align: 'right',
                sorter: true,
                render: text => {
                    return text || '--';
                },
            },
            {
                title: '异常数量',
                dataIndex: 'fail',
                align: 'right',
                sorter: true,
                render: text => {
                    return text||text===0 ? formatNumer(text) : '--';
                },
            },
            {
                title: '异常占比',
                dataIndex: 'fail_rate',
                align: 'right',
                sorter: true,
                render: text => {
                    return text || '--';
                },
            },
            {
                title: '耗时(s)',
                dataIndex: 'avg_elapsed',
                align: 'right',
                sorter: true,
                render: text => {
                    return text || '--';
                },
            },
        ];
    }, []);
    const sliceStart=(state.pageNumber-1)*state.pageSize
    const sliceEnd=(state.pageNumber-1)*state.pageSize+state.pageSize
    const newData=state.dataSource.length>0?state.dataSource.slice(sliceStart,sliceEnd).concat({id:"sum", index:"合计", date:"",merchant_name:"",total:reportState.sums?.total,valid:reportState.sums?.valid,charge:reportState.sums?.charge,charge_rate:reportState.sums?.charge_rate,reuse:reportState.sums?.reuse,reuse_rate:reportState.sums?.reuse_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: 'merchant_name'},
                            {label: '接口', key: 'api_name'},
                            {label: '查询数量', key: 'total'},
                            {label: '有效查询', key: 'valid'},
                            {label: '计费查次', key: 'charge'},
                            {label: '计费占比', key: 'charge_rate'},
                            {label: '平台输出', key: 'reuse'},
                            {label: '平台输出占比', key: 'reuse_rate'},
                            {label: '异常数量', key: 'fail'},
                            {label: '异常占比', key: 'fail_rate'},
                            {label: '耗时(s)', key: 'avg_elapsed'},
                        ]}
                    >
                        <Button type='primary' icon='export'>
                            导出
                        </Button>
                    </CSVLink>
                }
                handleReset={handleReset}
                handleSubmit={handleSearch}
                dataSource={SearchColumns}
            />
            <Table
                rowKey='id'
                dataSource={newData}
                columns={tableColumns}
                loading={reportState.loading}
                onChange={handleChangeTable}
                pagination={false}
            />
            <Pagination 
              current={state.pageNumber}
              pageSize={state.pageSize}
              showSizeChanger 
              pageSizeOptions={["10",'20', '30', '40', '50', '100']} 
              showTotal={total => `总计${total}条记录`} 
              hideOnSinglePage={false} 
              showQuickJumper 
              defaultCurrent={1} 
              total={reportState.total} 
              onShowSizeChange={(current, size)=>{setState(preState=>({...preState,pageSize:size,pageNumber:current}))}}
              onChange={(page, pageSize)=>{setState(preState=>({...preState,pageNumber:page,pageSize:pageSize}))}}
              />
        </div>
    );
};
export default Report;
