/** @format */

import * as React from 'react';
import moment from 'moment';
import {defaultColors} from '../../../const/status';
import {getRandomColor} from '../../../utils/operation';
import {ColumnProps} from 'antd/es/table';
import {Row, Col, Alert, Spin, Badge} from 'antd';
import Table from '../../../components/table';
import {useMechantResult} from '../../../service/dashbordMerchant';
import MerchantSelect from '../../../components/select/merchant';
import BaseApiSelect from '../../../components/select/baseApiSelect';
import RangePicker from '../../../components/datePicker/rangePicker';
import Search from '../../../components/search/search';
import {Chart, Geom, Axis, Tooltip, Coord, Guide} from 'bizcharts';
const DataSet = require('@antv/data-set');
const {DataView} = DataSet;
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(),
        colors: defaultColors,
    });
    const [resultState, requestResult] = useMechantResult();
    const handleReset = () => {
        setDependState(preState => ({...preState, merchant_id: '', baseApi_id: ''}));
    };

    const handleSearch = (values: any) => {
        setState(preState => ({...preState, nowTime: getNowTimw()}));
        requestResult({
            today_end_timestamp: state.nowTime.unix(),
            api_id: values.interface || '',
            merchant_id: values.merchant || '',
            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;
    }, []);
    const dv = new DataView();
    dv.source(resultState.dataSource).transform({
        type: 'percent',
        field: 'count',
        dimension: 'code',
        as: 'percent',
    });
    const [dependState, setDependState] = React.useState<{merchant_id: number | ''; baseApi_id: number | ''}>({
        merchant_id: '',
        baseApi_id: '',
    });
    return (
        <div>
            <Alert message={'数据统计截止统计:' + state.nowTime.format('YYYY-MM-DD HH:mm:ss')} type='info' />

            <Search
                algin='start'
                disabled={!dependState.baseApi_id || resultState.loading}
                handleReset={handleReset}
                handleSubmit={handleSearch}
                dataSource={[
                    {
                        key: 'merchant',
                        component: (
                            <MerchantSelect
                                api_ids={dependState.baseApi_id}
                                onChange={id => {
                                    if(!id){
                                        handleReset()
                                        return
                                    }
                                    setDependState(preState => ({...preState, merchant_id: id as number | ''}))
                                }}
                            />
                        ),
                    },
                    {
                        key: 'interface',
                        component: (
                            <BaseApiSelect
                                onChange={id => {
                                    setDependState(preState => ({...preState, baseApi_id: id as number | ''}));
                                }}
                                merchant_id={dependState.merchant_id}
                            />
                        ),
                    },
                    {
                        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 type='flex' justify='space-between'>
                    <Col span={9}>
                        <Chart height={400} data={dv} forceFit>
                            <Coord type={'theta'} radius={0.9} innerRadius={0.6} />
                            <Axis name='percent' />
                            <Tooltip showTitle title='code' />
                            <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="display: flex;justify-content: space-between;align-items: center;text-align: center;">
                                      <div >
                                        <span>${resultState.valid}</span>
                                        <br>
                                          有效调用
                                      </div>
                                    <div style="padding:0 10em;">
                                      <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={[
                                    'filesName*percent*count',
                                    (item, percent, count) => {
                                        return {
                                            name: item,
                                            value: `调用次数:${count}次`,
                                        };
                                    },
                                ]}
                            />
                        </Chart>
                    </Col>
                    <Col span={9}>
                        <Table
                            size='small'
                            bordered={false}
                            pagination={false}
                            rowKey='id'
                            columns={columns}
                            dataSource={resultState.dataSource}
                            scroll={{y: 400, x: false}}
                        />
                    </Col>
                </Row>
            </Spin>
        </div>
    );
};
export default Result;
