/** @format */

import * as React from 'react';
import {SelectValue} from 'antd/es/select';
import moment from 'moment';
import {defaultColors} from '../../../const/status';
import {getRandomColor} from '../../../utils/operation';
import {ColumnProps} from 'antd/es/table';
import {Row, Col, Table, Alert, Spin, Badge} from 'antd';
import {useResult} from '../../../service/dashbordProvide';
import ProviderApiSelect from '../../../components/select/providerApi';
import RangePicker from '../../../components/datePicker/rangePicker';
import Search from '../../../components/search/search';
import {Chart, Geom, Axis, Tooltip, Label, Coord, Guide} from 'bizcharts';
const DataSet = require('@antv/data-set');
const {DataView} = DataSet;
const dv = new DataView();
const {Html} = Guide;
const startTime = moment('00:00:00', 'HH:mm:ss');
const endTime = moment('23:59:59', 'HH:mm:ss');
const getNowTimw = () => {
    return moment();
};

const Result: React.FC = () => {
    const [state, setState] = React.useState({
        nowTime: getNowTimw(),
        disabled: true,
        colors: defaultColors,
    });
    const [resultState, requestResult] = useResult();
    const handleChangeInterface = (interfaceValue: SelectValue) => {
        setState(preState => ({...preState, disabled: !interfaceValue}));
    };
    const handleSearch = (values: any) => {
        setState(preState => ({...preState, nowTime: getNowTimw()}));

        requestResult({
            today_end_timestamp: state.nowTime.unix(),
            provider_api_id: values.provider_api_id,
            start_timestamp: values.time[0].unix(),
            end_timestamp: values.time[1].unix(),
        });
    };
    React.useEffect(() => {
        const colors = state.colors;
        while (colors.length < resultState.dataSource.length) {
            const createColor = getRandomColor();
            if (!colors.includes(createColor)) {
                colors.push(createColor);
            }
        }
        setState(preState => ({...preState, colors}));
    }, [resultState.dataSource]);
    const columns = React.useMemo(() => {
        const tableColunms: ColumnProps<any>[] = [
            {
                title: '结果编码',
                dataIndex: 'code',
                render: (text, _, index) => {
                    return <Badge color={state.colors[index]} text={text} />;
                },
            },
            {
                title: '编码含义',
                dataIndex: 'msg',
            },
            {
                title: '占比',
                dataIndex: 'rate',
                align: 'right',
            },
            {
                title: '调用次数',
                dataIndex: 'count',
                align: 'right',
            },
        ];
        return tableColunms;
    }, []);

    dv.source(resultState.dataSource).transform({
        type: 'percent',
        field: 'count',
        dimension: 'code',
        as: 'percent',
    });

    return (
        <div>
            <Alert message={'数据统计截止统计:' + state.nowTime.format('YYYY-MM-DD HH:mm:ss')} type='info' />

            <Search
                algin='start'
                disabled={state.disabled || resultState.loading}
                handleSubmit={handleSearch}
                dataSource={[
                    {
                        key: 'provider_api_id',
                        component: <ProviderApiSelect provider_id='' onChange={handleChangeInterface} />,
                    },
                    {
                        key: 'time',
                        col: {
                            xxl: 6,
                            lg: 8,
                        },
                        component: (
                            <RangePicker
                                disabledDate={current => {
                                    return (
                                        !!current &&
                                        (current > moment().endOf('day') ||
                                            current <
                                                moment()
                                                    .subtract(2, 'month')
                                                    .endOf('day'))
                                    );
                                }}
                            />
                        ),
                        options: {
                            initialValue: [startTime, endTime],
                        },
                    },
                ]}
            />
            <Spin spinning={resultState.loading}>
                <Row gutter={24}>
                    <Col span={10}>
                        <Chart height={400} data={dv} forceFit>
                            <Coord type={'theta'} radius={0.9} innerRadius={0.6} />
                            <Axis name='percent' />
                            <Tooltip showTitle={false} />
                            <Guide>
                                <Html
                                    position={['50%', '50%']}
                                    html={`<div style="color:#8c8c8c;font-size:1.16em;text-align: center;width: 10em;">${
                                        resultState.total
                                    }<br>总调用`}
                                    alignX='middle'
                                    alignY='middle'
                                />
                                <Html
                                    position={['50%', '120%']}
                                    html={`
                                    <div style="width:200px; display: flex;justify-content: space-between;align-items: center;text-align: center;">
                                    <div>
                                      <span>${resultState.charge}</span>
                                      <br>
                                        计费调用
                                    </div>
                                    <div>
                                      <span>${resultState.fail}</span>
                                      <br>
                                        异常调用
                                    </div>
                                    </div>
                                  `}
                                />
                            </Guide>

                            <Geom
                                type='intervalStack'
                                position='percent'
                                color={['code', state.colors]}
                                style={{
                                    lineWidth: 1,
                                    stroke: '#fff',
                                }}
                                tooltip={[
                                    'code*percent*count',
                                    (item, percent, count) => {
                                        return {
                                            name: item,
                                            value: `调用次数:${count}次`,
                                        };
                                    },
                                ]}
                            />
                        </Chart>
                    </Col>
                    <Col span={10} offset={4}>
                        <Table
                            scroll={{y: 400, x: false}}
                            pagination={false}
                            rowKey='id'
                            columns={columns}
                            dataSource={resultState.dataSource}
                        />
                    </Col>
                </Row>
            </Spin>
        </div>
    );
};
export default Result;
