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

import {SelectValue} from 'antd/es/select';
import {RadioChangeEvent} from 'antd/es/radio';
import {Chart, Geom, Axis, Tooltip, Legend} from 'bizcharts';
import Result from '../../../components/result';
import Search, {SearchItemProps} from '../../../components/search/search';
import {useMonitor} 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 colors = ['#07c27f', '#ff9123'];
const startTime = moment('00:00:00', 'HH:mm:ss');
const endTime = moment('23:59:59', 'HH:mm:ss');
const getNowTime = () => {
    return moment();
};
interface SearchValue {
    provider_api_id: number;
    today_end_timestamp: number;
    start_timestamp: number;
    end_timestamp: number;
    time_type: 0 | 1;
}
interface IsearchState {
    timeType: 0 | 1;
    nowTime: Moment;
    disabled: boolean;
}
interface IMonitorSearchProps {
    name: string | React.ReactNode;
    onSearch: (values: SearchValue) => void;
    loading: boolean;
}
const MonitorSearch: React.FC<IMonitorSearchProps> = props => {
    const {name, onSearch, loading} = props;
    const [state, setState] = React.useState<IsearchState>({
        timeType: 0,
        nowTime: getNowTime(),
        disabled: true,
    });
    const handleChangeInterface = (interfaceValue: SelectValue) => {
        setState(preState => ({...preState, disabled: !interfaceValue}));
    };
    const handleSwitchTimeType = (e: RadioChangeEvent) => {
        setState(preState => ({...preState, timeType: e.target.value}));
    };
    const handelSearch = (values: any) => {
        setState(preState => ({...preState, nowTime: getNowTime()}));

        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();
        }
        onSearch({
            provider_api_id: values.provider_api_id,
            today_end_timestamp: state.nowTime.unix(),
            start_timestamp,
            end_timestamp,
            time_type: state.timeType,
        });
    };

    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
                      disabledDate={current => {
                          return (
                              !!current &&
                              (current > moment().endOf('day') ||
                                  current <
                                      moment()
                                          .subtract(2, 'month')
                                          .endOf('day'))
                          );
                      }}
                  />
              ),
              options: {
                  initialValue: startTime,
              },
          });
    return (
        <>
            <h3>{name}</h3>
            <Alert message={'数据统计截止统计:' + state.nowTime.format('YYYY-MM-DD HH:mm:ss')} type='info' />
            <SwitchTime onChange={handleSwitchTimeType} />
            <Search
                algin='start'
                disabled={state.disabled || loading}
                handleSubmit={handelSearch}
                dataSource={dataSource}
            />
        </>
    );
};

const MonitorFail: React.FC = () => {
    const [monitorState, requestMontior] = useMonitor();
    const handleSearch = (values: SearchValue) => {
        requestMontior(values);
    };
    return (
        <>
            <MonitorSearch loading={monitorState.loading} name='异常次数' onSearch={handleSearch} />

            <Spin spinning={monitorState.loading}>
                <Row>
                    <Result error={monitorState.error} onRetry={() => requestMontior()}>
                        <Chart height={400} data={monitorState.dataSource} forceFit>
                            <Legend name='fail_count' itemFormatter={() => '异常次数'} />
                            <Axis name='date' title={null} />
                            <Tooltip />
                            <Geom
                                type='line'
                                tooltip={[
                                    'date*fail_count',
                                    (time, sold) => {
                                        return {
                                            name: '异常次数',
                                            title: time,
                                            value: sold,
                                        };
                                    },
                                ]}
                                position='date*fail_count'
                                color={colors[1]}
                                size={2}
                                shape={'smooth'}
                            />
                        </Chart>
                    </Result>
                </Row>
            </Spin>
        </>
    );
};
const MonitorTimeConsuming: React.FC = () => {
    const [monitorState, requestMontior] = useMonitor();
    const handleSearch = (values: SearchValue) => {
        requestMontior(values);
    };
    return (
        <>
            <MonitorSearch loading={monitorState.loading} name='接口耗时' onSearch={handleSearch} />
            <Spin spinning={monitorState.loading}>
                <Result error={monitorState.error} onRetry={() => requestMontior()}>
                    <Row>
                        <Col span={22}>
                            <Chart height={400} data={monitorState.dataSource} forceFit>
                                <Legend name='avg_elapsed' itemFormatter={() => '接口耗时'} />
                                <Axis name='date' title={null} />
                                <Tooltip />
                                <Geom
                                    type='line'
                                    tooltip={[
                                        'date*avg_elapsed',
                                        (time, sold) => {
                                            return {
                                                name: '接口耗时',
                                                title: time,
                                                value: sold,
                                            };
                                        },
                                    ]}
                                    position='date*avg_elapsed'
                                    color={colors[1]}
                                    size={2}
                                    shape={'smooth'}
                                />
                            </Chart>
                        </Col>
                    </Row>
                </Result>
            </Spin>
        </>
    );
};

const monitor: React.FC = () => {
    return (
        <>
            <MonitorTimeConsuming />
            <MonitorFail />
        </>
    );
};
export default monitor;
