/** @format */

import * as React from 'react';
import {ColumnProps} from 'antd/es/table';
import {Progress, Typography, Row, Col, Divider, Spin} from 'antd';
import moment, {Moment} from 'moment';
import 'antd/es/date-picker/locale/zh_CN';
import ResultAnalysis from './resultAnalysisModal';
import ProvideAnalysis from './provideAnalysisModal';
import Search, {SearchItemProps} from '../../../../components/search/search';
import Button from '../../../../components/button';
import MerchantSelect from '../../../../components/select/merchant';
import BaseApiSelect from '../../../../components/select/baseApiSelect';
import RangePicker from '../../../../components/datePicker/rangePicker';
import Table from '../../../../components/table';
import {useMerchantStatisticsReportOnLine, useInterfaceStatisticsDetail} from '../../../../service/merchant';
import {PaginationProps} from 'antd/es/pagination';
import ReportTask from '../components/export-task/merchant';
import ViewTask from '../../components/view-task';

const {Title} = Typography;
const startTime = moment('00:00:00', 'HH:mm:ss');
const endTime = moment('23:59:59', 'HH:mm:ss');
interface SearchColumnsProps {
    merchant_id: number | '';
    api_id: number | '';
    time: [Moment, Moment];
}
const reportMerchant: React.FC = props => {
    //获取商户统计报表
    const [merchantState, requestMerchantData] = useMerchantStatisticsReportOnLine({
        page_number: 1,
        merchant_id: '',
        api_id: '',
        start_timestamp: startTime.unix(),
        end_timestamp: endTime.unix(),
    });
    //获取接口统计详情
    const [interfaceState, requestInterfaceData] = useInterfaceStatisticsDetail({
        merchant_id: '',
        api_id: '',
        start_timestamp: startTime.unix(),
        end_timestamp: endTime.unix(),
    });
    const handleChangeReportTable = ({current}: PaginationProps) => {
        requestMerchantData({page_number: current});
    };
    const tableColumns: ColumnProps<any>[] = React.useMemo(() => {
        return [
            {
                title: '序号',
                key: 'index',
                width: 80,
                dataIndex: 'index',
            },
            {
                title: '接口',
                key: 'api_name',
                dataIndex: 'api_name',
            },
            {
                title: '总调用',
                children: [
                    {
                        title: '调用量',
                        key: 'total',
                        align: 'right',
                        dataIndex: 'total',
                    },
                    {
                        title: '有效量',
                        align: 'right',
                        key: 'valid',
                        dataIndex: 'valid',
                    },
                    {
                        title: '有效占比',
                        key: 'valid_rate',
                        align: 'right',
                        width: 100,
                        dataIndex: 'valid_rate',
                    },
                ],
            },
            {
                title: '有效调用',
                children: [
                    {
                        title: '成功量',
                        key: 'success',
                        align: 'right',
                        dataIndex: 'success',
                        render: text => {
                            return text || text == 0 ? text : '--';
                        },
                    },
                    {
                        title: '成功占比',
                        key: 'success_rate',
                        align: 'right',
                        dataIndex: 'success_rate',
                        render: text => {
                            return text || text == 0 ? text : '--';
                        },
                    },
                    {
                        title: '查得量',
                        key: 'query',
                        align: 'right',
                        dataIndex: 'query',
                        render: text => {
                            return text || text == 0 ? text : '--';
                        },
                    },
                    {
                        title: '查得占比',
                        key: 'query_rate',
                        align: 'right',
                        dataIndex: 'query_rate',
                        render: text => {
                            return text || text == 0 ? text : '--';
                        },
                    },
                    {
                        title: '复用量',
                        align: 'right',
                        key: 'reuse',
                        dataIndex: 'reuse',
                        render: text => {
                            return text || text == 0 ? text : '--';
                        },
                    },
                    {
                        title: '复用占比',
                        align: 'right',
                        key: 'reuse_rate',
                        dataIndex: 'reuse_rate',
                        render: text => {
                            return text || text == 0 ? text : '--';
                        },
                    },
                ],
            },
        ];
    }, []);
    const analysisColumns: ColumnProps<any>[] = [
        {
            title: '指标',
            key: 'name',
            dataIndex: 'name',
            render: text => {
                return text || '--';
            },
        },
        {
            title: '数量',
            key: 'count',
            dataIndex: 'count',
            render: text => {
                return text || text === 0 ? text : '--';
            },
        },
        {
            title: '占比',
            key: 'rate',
            dataIndex: 'rate',
            render: text => {
                return text || '--';
            },
        },
    ];
    //接口统计详情
    const [InterfaceDependState, setInterfaceDependState] = React.useState<{
        api_id: number | '';
        merchant_id: '' | number;
    }>({
        merchant_id: '',
        api_id: '',
    });
    const handleResetInterface = () => {
        setInterfaceDependState(preState => ({...preState, api_id: '', merchant_id: ''}));
    };

    const InterfaceSearchColumns = React.useMemo(() => {
        const columns: SearchItemProps[] = [
            {
                key: 'merchant_id',

                component: (
                    <MerchantSelect
                        data_api_id={InterfaceDependState.api_id}
                        onChange={id =>
                            setInterfaceDependState(preState => ({...preState, merchant_id: id as number | ''}))
                        }
                    />
                ),
            },
            {
                key: 'api_id',

                component: (
                    <BaseApiSelect
                        merchant_id={InterfaceDependState.merchant_id}
                        onChange={id => setInterfaceDependState(preState => ({...preState, api_id: id as number | ''}))}
                    />
                ),
            },
            {
                key: 'time',
                options: {
                    initialValue: [startTime, endTime],
                },
                col: {
                    lg: 10,
                    xxl: 6,
                },
                component: <RangePicker showTime />,
            },
        ];
        return columns;
    }, [InterfaceDependState]);

    //商户统计报表
    const [reportDependState, setReportDependState] = React.useState<{
        api_id: number | '';
        merchant_id: '' | number;
    }>({
        merchant_id: '',
        api_id: '',
    });
    const handleResetReport = () => {
        setReportDependState(preState => ({...preState, api_id: '', merchant_id: ''}));
    };
    const reportSearchColumns = React.useMemo(() => {
        const columns: SearchItemProps[] = [
            {
                key: 'merchant_id',
                component: (
                    <MerchantSelect
                        data_api_id={reportDependState.api_id}
                        onChange={id =>
                            setReportDependState(preState => ({...preState, merchant_id: id as number | ''}))
                        }
                    />
                ),
            },
            {
                key: 'api_id',

                component: (
                    <BaseApiSelect
                        merchant_id={reportDependState.merchant_id}
                        onChange={id => setReportDependState(preState => ({...preState, api_id: id as number | ''}))}
                    />
                ),
            },
            {
                key: 'time',
                options: {
                    initialValue: [startTime, endTime],
                },
                col: {
                    xxl: 6,
                    lg: 10,
                },
                component: <RangePicker showTime />,
            },
        ];
        return columns;
    }, [reportDependState]);
    const handleSearchMerchant = (values: SearchColumnsProps) => {
        requestMerchantData({
            page_number: 1,
            merchant_id: values.merchant_id || '',
            api_id: values.api_id || '',
            end_timestamp: values.time[1].unix(),
            start_timestamp: values.time[0].unix(),
        });
    };
    const handleSearchInterfaceReport = (values: SearchColumnsProps) => {
        requestInterfaceData({
            merchant_id: values.merchant_id,
            api_id: values.api_id,
            end_timestamp: values.time[1].unix(),
            start_timestamp: values.time[0].unix(),
        });
    };
    return (
        <>
            <Title level={4}>接口统计详情</Title>
            <Search
                handleReset={handleResetInterface}
                disabled={interfaceState.loading}
                preRender={{
                    col: {
                        lg: 6,
                        xxl: 4,
                    },
                    render: (
                        <>
                            <ResultAnalysis>
                                <Button type='primary' style={{marginRight: 15}}>
                                    结果分析
                                </Button>
                            </ResultAnalysis>
                            <ProvideAnalysis>
                                <Button>数据源分析</Button>
                            </ProvideAnalysis>
                        </>
                    ),
                }}
                algin='start'
                handleSubmit={handleSearchInterfaceReport}
                dataSource={InterfaceSearchColumns}
            />
            <Spin spinning={interfaceState.loading}>
                <Row gutter={24} justify='center' type='flex' align='middle' style={{textAlign: 'center'}}>
                    <Col span={8}>
                        <h4>有效查询情况</h4>
                        <Progress type='circle' percent={interfaceState.dataSource.valid.success_rate} />
                        <Row gutter={24} justify='center' type='flex' align='middle' style={{marginTop: 15}}>
                            {[
                                {title: '有效量', value: interfaceState.dataSource.valid.count},
                                {title: '成功占比', value: interfaceState.dataSource.valid.success_rate + '%'},
                                {title: '异常占比', value: interfaceState.dataSource.valid.fail_rate + '%'},
                            ].map((element, index) => {
                                return (
                                    <Col span={6} key={index}>
                                        <p>{element.value}</p>
                                        <span>{element.title}</span>
                                    </Col>
                                );
                            })}
                        </Row>
                    </Col>
                    <Col span={8}>
                        <h4>复用情况</h4>
                        <Row>
                            <Progress type='circle' percent={interfaceState.dataSource.reuse.reuse_rate} />
                        </Row>
                        <Row gutter={24} justify='center' type='flex' align='middle' style={{marginTop: 15}}>
                            {[
                                {title: '复用量', value: interfaceState.dataSource.reuse.count},
                                {title: '复用占比', value: interfaceState.dataSource.reuse.reuse_rate + '%'},
                            ].map((element, index) => {
                                return (
                                    <Col span={6} key={index}>
                                        <p>{element.value}</p>
                                        <span>{element.title}</span>
                                    </Col>
                                );
                            })}
                        </Row>
                    </Col>
                    <Col span={8}>
                        <Table
                            rowKey='id'
                            columns={analysisColumns}
                            bordered={false}
                            dataSource={interfaceState.dataSource.tableList}
                            scroll={{x: false}}
                        />
                    </Col>
                </Row>
            </Spin>

            <Divider />
            <div>
                <Title level={4}>商户统计报表</Title>
                <Search
                    handleReset={handleResetReport}
                    preRender={{
                        col: {
                            lg: 6,
                            xxl: 4,
                        },
                        render: (
                            <>
                                <ReportTask>
                                    <Button type='primary' style={{marginRight: 15}}>
                                        导出任务
                                    </Button>
                                </ReportTask>
                                <ViewTask export_type={0}>
                                    <Button>查看任务</Button>
                                </ViewTask>
                            </>
                        ),
                    }}
                    algin='start'
                    handleSubmit={handleSearchMerchant}
                    dataSource={reportSearchColumns}
                    disabled={merchantState.loading}
                />
                <Table
                    rowKey='id'
                    loading={merchantState.loading}
                    dataSource={merchantState.dataSource}
                    columns={tableColumns}
                    onChange={handleChangeReportTable}
                    pagination={{total: merchantState.total, current: merchantState.deepData.page_number}}
                />
            </div>
        </>
    );
};
export default reportMerchant;
