/** @format */

import * as React from 'react';
import moment, {Moment} from 'moment';
import {ColumnProps} from 'antd/es/table';
import {PaginationProps} from 'antd/es/pagination';
import message from '../../../components/message';
import Search, {SearchItemProps} from '../../../components/search/search';
import Result from '../../../components/result';
import MerchantSelect from '../../../components/select/merchant';
import BaseApiSelect from '../../../components/select/baseApiSelect';
import ErrorCode from '../../../components/select/errorCode';
import StatusSelect from '../../../components/select/resultSelect';
import RangePicker from '../../../components/datePicker/rangePicker';
import Input from '../../../components/input';
import SourceContentModal from './components/modalSourceConent';
import ModalJsonView from './components/modalJsonView';
import Button from '../../../components/button';
import Table from '../../../components/table';
import {useControlMerchantLog} from '../../../service/controlPanel';
import TimeConsuming from './components/timeConsuming';
import MerchantLogExport from './components/logExport/merchantLogExport';
import ExportLogList 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');
const disabledDate = (current: Moment | undefined) => {
    return !!current && current > moment().endOf('day');
};

interface LogProps {
    index: number;
    merchant_name: string;
    api_name: string;
    search: string;
    id: number;
    code: number;
    msg: number;
    elapsed: number;
    is_reuse: boolean;
    state: boolean;
    create_time: string;
    response_params: string;
    request_params: string;
    origin_request: string;
    origin_response: string;
}
interface SearchColumnsProps {
    merchant_id: number | '';
    api_id: number | '';
    code: string;
    state: 0 | 1 | 2;
    request_param: string;
    search: string;
    time: [Moment, Moment];
    timeConsuming: {min: number | undefined; max: number | undefined};
}
interface Istate {
    merchant_id: number | '';
    api_id: number | '';
}

interface ModalState {
    visible: boolean;
    title?: string;
    data?: {title: string; src: null | object; keyWord: string | undefined}[];
}

export default () => {
    const [resultState, requestData] = useControlMerchantLog({
        state: 0,
        request_param: '',
        merchant_id: '',
        api_id: '',
        start_timestamp: startTime.unix(),
        end_timestamp: endTime.unix(),
        search: '',
        code: '',
        page_number: 1,
        min: '',
        max: '',
    });
    const [state, setState] = React.useState<Istate>({
        merchant_id: '',
        api_id: '',
    });
    const [jsonViewState, setJsonViewState] = React.useState<ModalState>({
        visible: false,
    });
    const [sourceState, setSourceState] = React.useState({
        id: 0,
        visible: false,
        name: '数据源内容',
        create_time: '',
    });

    const handlSubmit = (values: SearchColumnsProps) => {
        if (
            typeof values.timeConsuming.min === 'number' &&
            typeof values.timeConsuming.max === 'number' &&
            values.timeConsuming.min > values.timeConsuming.max
        ) {
            return message.error('最小耗时不能大于最大耗时!');
        }
        requestData({
            state: values.state,
            request_param: values.request_param,
            merchant_id: values.merchant_id,
            api_id: values.api_id,
            start_timestamp: values.time[0].unix(),
            end_timestamp: values.time[1].unix(),
            search: values.search,
            code: values.code,
            page_number: 1,
            min: values.timeConsuming.min,
            max: values.timeConsuming.max,
        });
    };
    //表格条件改变
    const handleChangeTable = ({current}: PaginationProps) => {
        requestData({page_number: current});
    };
    const handleRetry = () => {
        requestData();
    };
    const handleUpdateVisible = () => {
        setSourceState(preState => ({
            ...preState,
            visible: false,
        }));
    };
    //关闭弹窗
    const handleModalJsonViewVisible = (data: ModalState) => {
        setJsonViewState(data);
    };
    const handleReset = () => {
        setState(preState => ({...preState, merchant_id: '', api_id: ''}));
    };
    const tableColumns = React.useMemo(() => {
        const columns: ColumnProps<LogProps>[] = [
            {
                key: 'index',
                title: '序号',
                dataIndex: 'index',
                fixed: 'left',
                width: 80,
            },
            {
                key: 'merchant_name',
                title: '商户名',
                dataIndex: 'merchant_name',
                width: 180,
                fixed: 'left',
                render: text => {
                    return text || '--';
                },
            },
            {
                key: 'api_name',
                title: '接口',
                dataIndex: 'api_name',
                render: text => {
                    return text || '--';
                },
            },
            {
                key: 'search',
                title: '车牌/VIN/证件号',
                dataIndex: 'search',
                width: 169,
                render: text => {
                    return text || '--';
                },
            },

            {
                key: 'code',
                title: '错误码',
                dataIndex: 'code',
                render: text => {
                    return text === '' ? '--' : text;
                },
            },
            {
                key: 'msg',
                title: '错误码含义',
                dataIndex: 'msg',

                render: text => {
                    return <span style={{width: 200}}>{text || '--'}</span>;
                },
            },
            {
                key: 'elapsed',
                title: '响应时间(s)',
                dataIndex: 'elapsed',

                render: text => {
                    return text || '--';
                },
            },
            {
                key: 'is_reuse',
                title: '是否复用',
                dataIndex: 'is_reuse',
                render: text => {
                    return <span>{text ? '是' : '否'}</span>;
                },
            },
            {
                key: 'state',
                title: '结果状态',
                dataIndex: 'state',
                render: text => {
                    return <span>{text ? '成功' : '失败'}</span>;
                },
            },
            {
                key: 'create_time',
                title: '调用时间',
                dataIndex: 'create_time',
                fixed: 'right',
                render: text => {
                    return text || '--';
                },
            },
            {
                key: 'payload',
                title: '参数内容',
                dataIndex: 'create_time',
                width: 155,
                fixed: 'right',
                render: (_, record) => {
                    return (
                        <>
                            <Button
                                type='link'
                                onClick={() => {
                                    handleModalJsonViewVisible({
                                        visible: true,
                                        title: `日志(${record.api_name})`,
                                        data: [
                                            {
                                                title: '请求参数',
                                                src: record.request_params,
                                                keyWord: resultState.deepData.request_param,
                                            },
                                            {
                                                title: '响应参数',
                                                src: record.response_params,
                                                keyWord: resultState.deepData.request_param,
                                            },
                                        ],
                                    });
                                }}
                            >
                                日志
                            </Button>
                            <Button
                                type='link'
                                onClick={() => {
                                    handleModalJsonViewVisible({
                                        visible: true,
                                        title: `实际(${record.api_name})`,
                                        data: [
                                            {
                                                title: '请求参数',
                                                src: record.origin_request,
                                                keyWord: resultState.deepData.request_param,
                                            },
                                            {
                                                title: '响应参数',
                                                src: record.origin_response,
                                                keyWord: resultState.deepData.request_param,
                                            },
                                        ],
                                    });
                                }}
                            >
                                实际
                            </Button>
                        </>
                    );
                },
            },
            {
                key: 'sourceContent',
                title: '数据源内容',
                width: 110,
                fixed: 'right',
                render: (_, record) => {
                    return (
                        <Button
                            type='link'
                            onClick={() => {
                                let create_time = record.create_time;
                                const startTime = moment(resultState.deepData.start_timestamp * 1000);
                                const endTime = moment(resultState.deepData.end_timestamp * 1000);
                                if (startTime.isSame(endTime, 'D') && startTime.isSame(moment(), 'D')) {
                                    create_time = '';
                                }
                                setSourceState({
                                    visible: true,
                                    name: record.api_name,
                                    id: record.id,
                                    create_time,
                                });
                            }}
                        >
                            查看
                        </Button>
                    );
                },
            },
        ];
        return columns;
    }, [resultState.deepData]);

    const SearchColumns = React.useMemo(() => {
        const columns: SearchItemProps[] = [
            {
                key: 'merchant_id',
                component: (
                    <MerchantSelect
                        api_ids={state.api_id}
                        onChange={(merchant_id: any) => {
                            setState(preState => ({...preState, merchant_id}));
                        }}
                    />
                ),
            },
            {
                key: 'api_id',
                component: (
                    <BaseApiSelect
                        merchant_id={state.merchant_id}
                        onChange={(api_id: any) => setState(preState => ({...preState, api_id}))}
                    />
                ),
            },
            {
                key: 'code',
                component: <ErrorCode />,
            },
            {
                key: 'state',
                options: {
                    initialValue: 0,
                },
                col: {
                    lg: 3,
                },
                component: <StatusSelect />,
            },
            {
                key: 'request_param',
                options: {
                    initialValue: '',
                },
                component: <Input placeholder='请求参数/响应参数' />,
            },
            {
                key: 'search',
                options: {
                    initialValue: '',
                },
                component: <Input placeholder='车牌号/VIN/证件号' />,
            },
            {
                key: 'time',
                col: {
                    xxl: 6,
                    lg: 10,
                },
                options: {
                    initialValue: [startTime, endTime],
                },
                component: (
                    <RangePicker disabledDate={disabledDate} showTime allowClear={false} format='YYYY-MM-DD HH:mm:ss' />
                ),
            },
            {
                key: 'timeConsuming',
                col: {
                    xxl: 4,
                    lg: 6,
                },
                options: {
                    initialValue: {
                        min: undefined,
                        max: undefined,
                    },
                },
                component: <TimeConsuming />,
            },
        ];
        return columns;
    }, [state]);
    return (
        <div>
            <Search
                extra={
                    <>
                        <MerchantLogExport>
                            <Button>日志导出</Button>
                        </MerchantLogExport>
                        <ExportLogList export_type={2} title='商户日志导出列表'>
                            <Button style={{marginLeft: 15}}>日志列表</Button>
                        </ExportLogList>
                    </>
                }
                handleReset={handleReset}
                algin='start'
                handleSubmit={handlSubmit}
                dataSource={SearchColumns}
                disabled={resultState.loading}
            />
            {/* 参数内容 */}
            {jsonViewState.data || [].length ? (
                <ModalJsonView
                    title={jsonViewState.title}
                    data={jsonViewState.data}
                    visible={jsonViewState.visible}
                    onCancel={() => handleModalJsonViewVisible({visible: false})}
                />
            ) : null}
            {/* 数据源内容 */}
            {sourceState.visible ? (
                <SourceContentModal {...sourceState} handleUpdateVisible={handleUpdateVisible} />
            ) : null}

            <Result error={resultState.error} onRetry={handleRetry}>
                <Table
                    rowKey='id'
                    onChange={handleChangeTable}
                    columns={tableColumns}
                    loading={resultState.loading}
                    dataSource={resultState.dataSource}
                    pagination={{
                        total: resultState.total,
                        showQuickJumper: true,
                        showTotal: total => `共 ${total} 条记录`,
                        current: resultState.deepData.page_number,
                    }}
                />
            </Result>
        </div>
    );
};
