/** @format */
import * as React from 'react';
import {SelectValue} from 'antd/es/select';
import {ColumnProps} from 'antd/es/table';
import {RadioChangeEvent} from 'antd/es/radio';
import {Table, Badge, Alert, Spin, Row, Col} from 'antd';
import moment, {Moment} from 'moment';
import {Chart, Geom, Axis, Tooltip, Legend, Guide} from 'bizcharts';

import {formatNumer} from '../../../utils/operation';
import Search, {SearchItemProps} from '../../../components/search/search';
import {useTrend, TrendRecordProps} from '../../../service/dashbordProvide';
import ProvideApiSelect from '../../../components/select/providerApi';
import RangePicker from '../../../components/datePicker/rangePicker';
import DatePicker from '../../../components/datePicker/datePicker';
import SwitchTime from '../components/switchTime';
const {Line} = Guide;
const colors = ['#07c27f', '#ff9123'];
const startTime = moment('00:00:00', 'HH:mm:ss').subtract(15, 'd');
const endTime = moment('23:59:59', 'HH:mm:ss');
const getNowTimw = () => {
    return moment();
};
const DataSet = require('@antv/data-set');
const ds = new DataSet();
interface Istate {
    timeType: 0 | 1;
    nowTime: Moment;
    disabled: boolean;
}

const usageTrend: React.FC = () => {
    const [state, setState] = React.useState<Istate>({
        timeType: 0,
        nowTime: getNowTimw(),
        disabled: true,
    });
    const [trendState, requestTrend] = useTrend();
    const handelSearch = (values: any) => {
        setState(preState => ({...preState, nowTime: getNowTimw()}));
        let start_timestamp, end_timestamp;
        //注意：如果时间类型是时，那么返回的时一天时间，需要手动转为当天的0点到23点50分59秒
        if (state.timeType === 0) {
            start_timestamp = values.dayTime[0].unix();
            end_timestamp = values.dayTime[1].unix();
        } else if (state.timeType === 1) {
            start_timestamp = values.dateTime
                .hour(0)
                .minute(0)
                .second(0)
                .unix();
            end_timestamp = values.dateTime
                .hour(23)
                .minute(59)
                .second(59)
                .unix();
        }
        requestTrend({
            provider_api_id: values.provider_api_id || '',
            today_end_timestamp: state.nowTime.unix(),
            start_timestamp,
            end_timestamp,
            time_type: state.timeType,
        });
    };
    const handleSwitchTimeType = (e: RadioChangeEvent) => {
        setState(preState => ({...preState, timeType: e.target.value}));
    };
    const handleChangeInterface = (interfaceValue: SelectValue) => {
        setState(preState => ({...preState, disabled: !interfaceValue}));
    };
    const dataSource: SearchItemProps[] = [
        {
            key: 'provider_api_id',
            component: (
                <ProvideApiSelect
                    provider_id=''
                    allowClear={true}
                    onChange={handleChangeInterface}
                    placeholder='请选择接口(必选)'
                />
            ),
        },
    ];
    !state.timeType
        ? dataSource.push({
              key: 'dayTime',
              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],
              },
          })
        : dataSource.push({
              key: 'dateTime',
              component: <DatePicker />,
              options: {
                  initialValue: endTime,
              },
          });
    const columns = React.useMemo(() => {
        const columns: ColumnProps<TrendRecordProps>[] = [
            {
                title: '最大用量',
                dataIndex: 'max',
                render: formatNumer,
            },
            {
                title: '最小用量',
                dataIndex: 'min',
                render: formatNumer,
            },
            {
                title: '平均用量',
                dataIndex: 'avg',
                render: formatNumer,
            },
            {
                title: '当前',
                dataIndex: 'current',
                render: formatNumer,
            },
            {
                title: null,
                dataIndex: 'desc',
                render: (text, _, index) => {
                    return <Badge color={colors[index]} text={text} />;
                },
            },
        ];
        return columns;
    }, []);
    const dv = ds.createView().source(trendState.infos);
    dv.transform({
        type: 'fold',
        fields: ['total', 'charge'], // 展开字段集
        key: 'key', // key字段
        value: 'value', // value字段
    });
    return (
        <>
            <Alert message={'数据统计截止统计:' + state.nowTime.format('YYYY-MM-DD HH:mm:ss')} type='info' />
            <SwitchTime onChange={handleSwitchTimeType} />
            <div>
                <Search
                    algin='start'
                    disabled={state.disabled || trendState.loading}
                    handleSubmit={handelSearch}
                    dataSource={dataSource}
                />
                <Spin spinning={trendState.loading}>
                    {state.timeType === 0 && (
                        <Table rowKey='key' columns={columns} dataSource={trendState.dataSource} pagination={false} />
                    )}
                    <Row>
                        <Col span={22}>
                            <Chart type='linear' scale={{type: 'cat', alias: '哈哈'}} height={400} data={dv} forceFit>
                                <Axis name='date' />
                                <Axis
                                    name='value'
                                    label={{
                                        formatter: val => `${val}`,
                                    }}
                                />
                                <Tooltip crosshairs={{type: 'y'}} />
                                <Geom
                                    tooltip={[
                                        'date*value*key',
                                        (time, value, key) => {
                                            return {
                                                name: key === 'charge' ? '计费量' : '有效量',
                                                title: time,
                                                value: value,
                                            };
                                        },
                                    ]}
                                    type='line'
                                    position='date*value'
                                    size={2}
                                    color={['key', colors]}
                                />
                            </Chart>
                        </Col>
                    </Row>
                </Spin>
            </div>
        </>
    );
};
export default usageTrend;
