/** @format */
import * as React from 'react';
import {Table, Badge, Alert, Spin, Row, Col} from 'antd';

import {SelectValue} from 'antd/es/select';
import {RadioChangeEvent} from 'antd/es/radio';
import {Chart, Geom, Axis, Tooltip, Legend, Guide, Label} from 'bizcharts';
import Search, {SearchItemProps} from '../../../components/search/search';
import {formatNumer} from '../../../utils/operation';

import {useMerchantTrend} from '../../../service/dashbordMerchant';
import MerchantSelect from '../../../components/select/merchant';
import BaseApiSelect from '../../../components/select/baseApiSelect';
import RangePicker from '../../../components/datePicker/rangePicker';
import DatePicker from '../../../components/datePicker/datePicker';
import SwitchTime from '../components/switchTime';
import moment, {Moment} from 'moment';
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] = useMerchantTrend();

    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({
            api_id: values.interface || '',
            merchant_id: values.merchant || '',
            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 = (baseApiId: SelectValue) => {
        setState(preState => ({...preState, disabled: !baseApiId}));
        setDependState(preState => ({...preState, api_ids: baseApiId as number | ''}));
    };
    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 dataSource: SearchItemProps[] = [
        {
            key: 'merchant',
            component: (
                <MerchantSelect
                    api_ids={dependState.api_ids}
                    onChange={id => {
                        if(!id){
                            handleReset()
                            return
                        }
                        setDependState(preState => ({...preState, merchant_id: id as number | ''}))
                    }}
                />
            ),
        },
        {
            key: 'interface',
            component: (
                <BaseApiSelect
                    allowClear={true}
                    merchant_id={dependState.merchant_id}
                    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(() => {
        return [
            {
                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: string, record: any, index: number) => {
                    return <Badge color={colors[index]} text={text} />;
                },
            },
        ];
    }, []);
    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} />

            <Search
                algin='start'
                disabled={state.disabled || trendState.loading}
                handleReset={handleReset}
                handleSubmit={handelSearch}
                dataSource={dataSource}
            />
            <Spin spinning={trendState.loading}>
                {state.timeType === 0 && (
                    <Table
                        rowKey='id'
                        bordered={false}
                        size='small'
                        columns={columns}
                        dataSource={trendState.dataSource}
                        pagination={false}
                    />
                )}
                <Row>
                    <Col span={22} offset={1}>
                        <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>
        </>
    );
};
export default usageTrend;
