/** @format */

import * as React from 'react';
import moment, {Moment} from 'moment';
import {Badge, Modal, Row, Col} from 'antd';
import {ColumnProps} from 'antd/es/table';
import {PaginationProps} from 'antd/es/pagination';
import message from '../../../components/message';

import JsonView from '../../../components/jsonview';
import Table from '../../../components/table';
import Button from '../../../components/button';
import Input from '../../../components/input';
import Search, {SearchItemProps} from '../../../components/search/search';
import ProviderSelect from '../../../components/select/providerSelect';
import ProvideApiSelect from '../../../components/select/providerApi';
import StatusSelect from '../../../components/select/resultSelect';
import RangePicker from '../../../components/datePicker/rangePicker';
import Result from '../../../components/result';
import {useSourceCallLog, ReciveSourceLogProps} from '../../../service/controlPanel';
import TimeConsuming from './components/timeConsuming';
import LogExport from './components/logExport/providLogExport';
import LogExportList from '../components/view-task';
moment.locale('zh-cn');

const startTime = moment('00:00:00', 'HH:mm:ss');
const endTime = moment('23:59:59', 'HH:mm:ss');

interface SearchColumnsProps {
    provider_id: '' | number;
    provider_api_id: '' | number;
    raw_code:'',
    state: 0 | 1 | 2;
    request_param: string;
    search: string;
    time: [Moment, Moment];
    timeConsuming: {min: number | ''; max: number | ''};
}
const disabledDate = (current: Moment | undefined) => {
    return !!current && current > moment().endOf('day');
};
interface Istate {
    visible: boolean;
    values?: {
        request_params: string | object;
        response_params: string | object;
    };
    name?: string;
}
const sourceCallLog: React.FC = () => {
    const [state, setState] = React.useState<Istate>({
        visible: false,
    });
    const [logState, requestLog] = useSourceCallLog({
        page_number: 1,
        search: '',
        state: 0,
        request_param: '',
        raw_code:'',
        provider_id: '',
        provider_api_id: '',
        start_timestamp: startTime.unix(),
        end_timestamp: endTime.unix(),
        min: '',
        max: '',
    });
    const handleSubmit = (values: SearchColumnsProps) => {
        if (
            typeof values.timeConsuming.min === 'number' &&
            typeof values.timeConsuming.max === 'number' &&
            values.timeConsuming.min > values.timeConsuming.max
        ) {
            return message.error('最小耗时不能大于最大耗时!');
        }
        requestLog({
            page_number: 1,
            search: values.search,
            raw_code:values.raw_code,
            state: values.state,
            request_param: values.request_param,
            provider_id: values.provider_id,
            provider_api_id: values.provider_api_id,
            start_timestamp: values.time[0].unix(),
            end_timestamp: values.time[1].unix(),
            min: values.timeConsuming.min,
            max: values.timeConsuming.max,
        });
    };
    const handleUpdateModalVisible = (
        visible = false,
        values?: {request_params: string; response_params: string},
        name?: string,
    ) => {
        if (values) {
            const formatValues = {
                request_params: {},
                response_params: {},
            };

            if (!values.request_params) {
                formatValues.request_params = {};
            } else {
                try {
                    formatValues.request_params = JSON.parse(values.request_params);
                } catch (error) {
                    formatValues.request_params = values.request_params;
                }
            }
            if (!values.response_params) {
                formatValues.response_params = {};
            } else {
                try {
                    formatValues.response_params = JSON.parse(values.response_params);
                } catch (error) {
                    formatValues.response_params = values.response_params;
                }
            }
            setState(preState => ({...preState, visible, values: formatValues, name}));
            return;
        }
        setState(preState => ({...preState, visible, values, name}));
    };
    const handelChangeTable = ({current}: PaginationProps) => {
        requestLog({page_number: current});
    };
    const handleRetry = () => {
        requestLog();
    };
    const columns: ColumnProps<ReciveSourceLogProps>[] = [
        {
            title: '序号',
            dataIndex: 'index',
            key: 'index',
            width: 80,
        },
        {
            title: '供应商',
            dataIndex: 'provider_name',
            key: 'provider_name',
            render: text => {
                return text || '--';
            },
        },
        {
            title: '接口',
            dataIndex: 'provider_api_name',
            key: 'provider_api_name',
        },
        {
            title: '关键字',
            dataIndex: 'search',
            key: 'search',
            width: 160,
            render: text => {
                return text || '--';
            },
        },
        {
            title: '错误码',
            dataIndex: 'raw_code',
            key: 'raw_code',
            width: 110,
            render: text => {
                return text || '--';
            },
        },
        {
            title: '错误码含义',
            dataIndex: 'msg',
            key: 'msg',
            width: 180,
            render: text => {
                return text || '--';
            },
        },
        {
            title: '响应时长(s)',
            dataIndex: 'elapsed',
            key: 'elapsed',
            width: 120,
            render: text => {
                return text || '--';
            },
        },
        {
            title: '结果状态',
            dataIndex: 'state',
            key: 'state',
            width: 100,
            render: text => {
                return <Badge color={text ? 'green' : 'red'} text={text ? '成功' : '失败'} />;
            },
        },
        {
            title: '调用时间',
            dataIndex: 'create_time',
            key: 'create_time',
            width: 160,
            fixed: 'right',
            render: text => {
                return text || '--';
            },
        },
        {
            title: '参数内容',
            width: 100,
            dataIndex: 'params',
            key: 'params',
            fixed: 'right',
            render: (_, record) => {
                return (
                    <Button
                        type='link'
                        onClick={() => {
                            handleUpdateModalVisible(
                                true,
                                {
                                    request_params: record.request_params,
                                    response_params: record.response_params,
                                },
                                record.provider_name,
                            );
                        }}
                    >
                        查看
                    </Button>
                );
            },
        },
    ];
    const [dependState, setDependState] = React.useState<{provider_id: number | ''; provider_api_id: number | ''}>({
        provider_id: '',
        provider_api_id: '',
    });
    const handleReset = () => {
        setDependState(preState => ({...preState, provider_id: '', provider_api_id: ''}));
    };
    const SearchColumns = React.useMemo(() => {
        const columns: SearchItemProps[] = [
            {
                key: 'provider_id',

                component: (
                    <ProviderSelect
                        allowClear
                        provider_api_id={dependState.provider_api_id}
                        onChange={id => setDependState(preState => ({...preState, provider_id: id as number | ''}))}
                    />
                ),
            },
            {
                key: 'provider_api_id',

                component: (
                    <ProvideApiSelect
                        allowClear
                        provider_id={dependState.provider_id}
                        onChange={id => setDependState(preState => ({...preState, provider_api_id: id as number | ''}))}
                    />
                ),
            },
            {
                key: 'state',
                options: {
                    initialValue: 0,
                },
                col: {
                    xxl: 4,
                    lg: 3,
                },
                component: <StatusSelect />,
            },
            {
                key: 'request_param',

                component: <Input placeholder='请求参数/响应参数' />,
            },
            {
                key: 'search',

                component: <Input placeholder='关键字' />,
            },
            {
                key: 'time',
                col: {
                    lg: 10,
                    xxl: 6,
                },
                options: {
                    initialValue: [startTime, endTime],
                },
                component: (
                    <RangePicker disabledDate={disabledDate} showTime allowClear={false} format='YYYY-MM-DD HH:mm:ss' />
                ),
            },
            {
                key: 'raw_code',
                component: <Input placeholder='请输入CODE' />,
            },
            {
                key: 'timeConsuming',
                options: {
                    initialValue: {
                        min: '',
                        max: '',
                    },
                },
                component: <TimeConsuming />,
            },
        ];
        return columns;
    }, [dependState]);
    return (
        <>
            <Search
                disabled={logState.loading}
                handleReset={handleReset}
                algin='start'
                dataSource={SearchColumns}
                handleSubmit={handleSubmit}
                extra={
                    <>
                        <LogExport>
                            <Button>日志导出</Button>
                        </LogExport>
                        <LogExportList export_type={3} title='供应商日志导出列表'>
                            <Button style={{marginLeft: 15}}>日志列表</Button>
                        </LogExportList>
                    </>
                }
            />
            <Result error={logState.error} onRetry={handleRetry}>
                <Table
                    rowKey='id'
                    onChange={handelChangeTable}
                    pagination={{
                        total: logState.total,
                        showTotal: total => `共 ${total} 条记录`,
                        showQuickJumper: true,
                        current: logState.deepData.page_number,
                    }}
                    columns={columns}
                    dataSource={logState.dataSource}
                    loading={logState.loading}
                />
            </Result>
            {!!state.values ? (
                <Modal
                    onCancel={() => handleUpdateModalVisible(false)}
                    title={state.name}
                    visible={state.visible}
                    width={1000}
                    footer={null}
                >
                    <Row gutter={24}>
                        <Col span={12}>
                            <h3>请求参数</h3>
                            <JsonView keyWord={logState.deepData.request_param} src={state.values.request_params} />
                        </Col>
                        <Col span={12}>
                            <h3>响应参数</h3>
                            <JsonView keyWord={logState.deepData.request_param} src={state.values.response_params} />
                        </Col>
                    </Row>
                </Modal>
            ) : null}
        </>
    );
};
export default sourceCallLog;
