/** @format */

import * as React from 'react';
import {Input, Row, Col, Typography, Dropdown, Menu, Icon, Popconfirm} from 'antd';
import {PaginationProps} from 'antd/es/pagination';
import {ColumnProps} from 'antd/es/table';
import Limit from './components/limit';
import Button from '../../../components/button';
import Result from '../../../components/result';
import {interfaceStatus} from '../../../const/status';
import {formatNumer} from '../../../utils/operation';
import message from '../../../components/message';
import {encodeBase64, decodeBase64} from '../../../utils/base64';
import Table from '../../../components/table';
import Add from './components/addPermisson';
import {
    userMerchantDataApiByTime,
    useMerchantDataApiByQuoto,
    DataApiByTimeRecordProps,
    DataApiByQuotoRecordProps,
    useDeleteDataApi,
    useDataQueryDesc,
    ModifiableProps,
    useUpdateMerchantDataApiByLimit,
    TotalLimitParams,
    DayLimitParams,
} from '../../../service/permission';
import UpdateProductAlias from './components/updateProductAlias';
const {Search} = Input;
const {Title} = Typography;

interface LimitModalState {
    visible: boolean;
    name?: string;
    type?: 'time' | 'count';
    values?: ModifiableProps;
    id?: number;
}
const PermissionApi: React.FC = props => {
    const {history} = props;
    const merchantInfo = new URLSearchParams(decodeBase64(location.search.slice(1)));
    const id = Number(merchantInfo.get('id'));
    const name = merchantInfo.get('name');
    const [limitModalState, setLimitModalState] = React.useState<LimitModalState>({
        visible: false,
    });
    const [deletState, requestDelete] = useDeleteDataApi();
    const [descState, requestDesc] = useDataQueryDesc();
    const [updateLimitState, requestUpdate] = useUpdateMerchantDataApiByLimit();
    const [onTimeQuotaState, requestTimeQuota] = userMerchantDataApiByTime({
        merchant_id: id,
        page_number: 1,
        data_api_name: '',
    });
    const [quotoState, requestQuota] = useMerchantDataApiByQuoto({
        merchant_id: id,
        page_number: 1,
        data_api_name: '',
    });
    //更新 限额(次) 的弹窗状态
    const handleUpdateLimitModalVisible = (
        visible = false,
        values?: ModifiableProps,
        name?: string,
        type?: 'time' | 'count',
        id?: number,
    ) => {
        setLimitModalState({
            visible,
            values,
            name,
            type,
            id,
        });
    };
    //更新限额
    const handleSubmitUpdateLimit = (values: TotalLimitParams | DayLimitParams, type: 'time' | 'count') => {
        if (limitModalState.id) {
            requestUpdate(id, limitModalState.id, values).then(error => {
                if (error) return message.error(error);
                if (type === limitModalState.type) {
                    if (type === 'count') {
                        requestQuota();
                    } else {
                        requestTimeQuota();
                    }
                } else {
                    requestQuota();
                    requestTimeQuota();
                }
                handleUpdateLimitModalVisible(false);
            });
        }
    };
    const onSearchOntime = (value: string) => {
        requestTimeQuota({
            page_number: 1,
            data_api_name: value,
        });
    };
    const onSearchOuota = (value: string) => {
        requestQuota({
            page_number: 1,
            data_api_name: value,
        });
    };
    const handleChangeTimeQuota = ({current}: PaginationProps) => {
        requestTimeQuota({page_number: current});
    };
    const handleChangeQuota = ({current}: PaginationProps) => {
        requestQuota({page_number: current});
    };
    const handleHref = (record: DataApiByTimeRecordProps) => {
        history.push(
            '/home/merchant/interfaceSet?' +
                encodeBase64(
                    'id=' +
                        record.id +
                        '&merchantId=' +
                        id +
                        '&name=' +
                        encodeURIComponent(name + '--' + record.data_api_name),
                ),
        );
    };
    const handleDelete = (id: number, type: 'time' | 'quoto') => {
        requestDelete(id).then(error => {
            if (error) return message.error(error);
            if (type === 'quoto') {
                return requestQuota();
            }
            return requestTimeQuota();
        });
    };

    const handleViewDesc = (id: number, fileType: 0 | 1) => {
        requestDesc({
            merchant_data_api_id: id,
            file_type: fileType,
        }).then(([error, url]) => {
            if (error) return message.error(error);
            window.open(url);
        });
    };

    const refresh = () => {
        requestQuota();
        requestTimeQuota();
    }
    //按时的
    const tableOnlineColumns = React.useMemo(() => {
        const columns: ColumnProps<DataApiByTimeRecordProps>[] = [
            {
                key: 'index',
                title: '序号',
                dataIndex: 'index',
                width: 75,
                fixed: 'left',
            },
            {
                key: 'data_api_name',
                title: '数据API名称',
                dataIndex: 'data_api_name',
                width: 200,
                fixed: 'left',
            },
            {
                key: 'alias',
                title: '别名',
                dataIndex: 'alias',
                fixed: 'left',
                render: (_, record) => {
                    return <div>{record.alias? record.alias:'-'}</div>;
                },
            },
            {
                key: 'query_type_name',
                title: '查询方式',
                dataIndex: 'query_type_name',
                width: 100,
            },
            {
                key: 'day_count',
                title: '日调用量上限',
                dataIndex: 'day_count',
                align: 'right',
                width: 118,
                render: text => {
                    return formatNumer(text);
                },
            },
            {
                key: 'day_used_count',
                title: '今日用量',
                dataIndex: 'day_used_count',
                align: 'right',
                width: 100,
                render: text => {
                    return formatNumer(text);
                },
            },
            {
                key: 'day_remain_count',
                title: '今日余量',
                dataIndex: 'day_remain_count',
                align: 'right',
                width: 100,
                render: text => {
                    return formatNumer(text);
                },
            },
            {
                key: 'total_day',
                title: '天数上限',
                dataIndex: 'total_day',
                align: 'right',
                width: 100,
                render: text => {
                    return formatNumer(text);
                },
            },
            {
                key: 'effective_day',
                title: '剩余有效天数',
                dataIndex: 'effective_day',
                align: 'right',
                width: 118,
                render: text => {
                    return formatNumer(text);
                },
            },
            {
                key: 'status_code',
                title: '状态',
                dataIndex: 'status_code',
                width: 120,
                render: text => {
                    return interfaceStatus[text];
                },
            },
            {
                key: 'day_total_count',
                title: '日查量上限',
                dataIndex: 'day_total_count',
                align: 'right',
                width: 105,
                render: (_, record) => {
                    return formatNumer(record.modifiable.day_info.day_total_count);
                },
            },
            {
                key: 'remain_day_total_count',
                title: '今日余量(即查)',
                align: 'right',
                width: 128,
                render: (_, record) => {
                    return formatNumer(record.modifiable.day_info.remain_day_total_count);
                },
            },
            {
                key: 'use_time',
                title: '操作时间',
                dataIndex: 'use_time',
                width: 170,
            },
            {
                key: '',
                title: '操作',
                width: 325,
                fixed: 'right',

                render: (_, record) => {
                    return (
                        <>
                            <Button type='link' onClick={() => handleHref(record)}>
                                设置
                            </Button>
                            <UpdateProductAlias record={record} refresh={refresh}/>
                            <Dropdown
                                overlay={
                                    <Menu>
                                        <Menu.Item onClick={() => handleViewDesc(record.id, 0)}>
                                            <span>PDF</span>
                                        </Menu.Item>
                                        <Menu.Item onClick={() => handleViewDesc(record.id, 1)}>
                                            <span>WORD</span>
                                        </Menu.Item>
                                    </Menu>
                                }
                                placement='bottomLeft'
                            >
                                <Button type='link'>
                                    文档 <Icon type='down' />
                                </Button>
                            </Dropdown>
                            <Button
                                type='link'
                                disabled={record.is_free}
                                onClick={() =>
                                    handleUpdateLimitModalVisible(
                                        true,
                                        record.modifiable,
                                        record.data_api_name,
                                        'time',
                                        record.id,
                                    )
                                }
                            >
                                限额
                            </Button>
                            <Popconfirm title='是否确认删除该配额' onConfirm={() => handleDelete(record.id, 'time')}>
                                <Button type='link'>删除</Button>
                            </Popconfirm>
                        </>
                    );
                },
            },
        ];
        return columns;
    }, []);
    const QuotaColumns = React.useMemo(() => {
        const colums: ColumnProps<DataApiByQuotoRecordProps>[] = [
            {
                key: 'index',
                title: '序号',
                dataIndex: 'index',
                width: 80,
                fixed: 'left',
            },
            {
                key: 'data_api_name',
                title: '数据API名称',
                width: 200,
                dataIndex: 'data_api_name',
                fixed: 'left',
            },
            {
                key: 'alias',
                title: '别名',
                dataIndex: 'alias',
                fixed: 'left',
                render: (_, record) => {
                    return <div>{record.alias? record.alias:'-'}</div>;
                },
            },
            {
                key: 'query_type_name',
                title: '查询方式',
                dataIndex: 'query_type_name',
            },
            {
                key: 'total_count',
                title: '总调用上限',
                dataIndex: 'total_count',
                align: 'right',
                width: 110,
                render: text => {
                    return formatNumer(text);
                },
            },
            {
                key: 'used_count',
                title: '总用量',
                dataIndex: 'used_count',
                align: 'right',
                width: 95,
                render: text => {
                    return formatNumer(text);
                },
            },
            {
                key: 'remain_count',
                title: '总余量',
                dataIndex: 'remain_count',
                align: 'right',
                width: 100,
                render: text => {
                    return formatNumer(text);
                },
            },
            {
                key: 'day_count',
                title: '日调用上限',
                dataIndex: 'day_count',
                align: 'right',
                width: 107,
                render: text => {
                    return formatNumer(text);
                },
            },
            {
                key: 'day_total_count',
                title: '日即查量上限',
                align: 'right',
                width: 118,
                render: (_, record) => {
                    return formatNumer(record.modifiable.total_info.day_total_count);
                },
            },
            {
                key: 'remain_day_total_count',
                title: '今日余量(即查)',
                align: 'right',
                width: 128,
                render: (_, record) => {
                    return formatNumer(record.modifiable.total_info.remain_day_total_count);
                },
            },
            {
                key: 'status_code',
                title: '状态',
                dataIndex: 'status_code',
                width: 120,
                render: text => {
                    return interfaceStatus[text];
                },
            },
            {
                key: 'use_time',
                title: '操作时间',
                dataIndex: 'use_time',
                width: 170,
            },
            {
                key: 'opertion',
                width: 325,
                title: '操作',
                fixed: 'right',
                render: (_, record) => {
                    return (
                        <>
                            <Button type='link' onClick={() => handleHref(record)}>
                                设置
                            </Button>
                            <UpdateProductAlias record={record} refresh={refresh}/>
                            <Dropdown
                                overlay={
                                    <Menu>
                                        <Menu.Item onClick={() => handleViewDesc(record.id, 0)}>
                                            <span>PDF</span>
                                        </Menu.Item>
                                        <Menu.Item onClick={() => handleViewDesc(record.id, 1)}>
                                            <span>word</span>
                                        </Menu.Item>
                                    </Menu>
                                }
                                placement='bottomLeft'
                            >
                                <Button type='link'>
                                    文档 <Icon type='down' />
                                </Button>
                            </Dropdown>
                            <Button
                                type='link'
                                disabled={record.is_free}
                                onClick={() =>
                                    handleUpdateLimitModalVisible(
                                        true,
                                        record.modifiable,
                                        record.data_api_name,
                                        'count',
                                        record.id,
                                    )
                                }
                            >
                                限额
                            </Button>
                            <Popconfirm title='是否确认删除该配额' onConfirm={() => handleDelete(record.id, 'quoto')}>
                                <Button type='link'>删除</Button>
                            </Popconfirm>
                        </>
                    );
                },
            },
        ];
        return colums;
    }, []);
    return (
        <>
            <Row style={{textAlign: 'right', marginBottom: 15}}>
                <Add
                    onOk={() => {
                        requestTimeQuota();
                        requestQuota();
                    }}
                >
                    <Button type='primary' icon='plus'>
                        添加
                    </Button>
                </Add>
            </Row>

            {limitModalState.values ? (
                <Limit
                    loading={updateLimitState.loading}
                    type={limitModalState.type}
                    onSubmit={handleSubmitUpdateLimit}
                    values={limitModalState.values}
                    name={limitModalState.name}
                    visible={limitModalState.visible}
                    onCancle={() => handleUpdateLimitModalVisible(false)}
                />
            ) : null}

            <Row gutter={24} type='flex' justify='space-between' style={{marginBottom: 15}}>
                <Col span={3}>
                    <Title level={4}>按时配额</Title>
                </Col>
                <Col span={6}>
                    <Search placeholder='数据API名称' onSearch={onSearchOntime} enterButton />
                </Col>
            </Row>
            <Result error={onTimeQuotaState.error} onRetry={() => requestTimeQuota()}>
                <Table
                    pagination={{total: onTimeQuotaState.total}}
                    onChange={handleChangeTimeQuota}
                    loading={onTimeQuotaState.loading}
                    rowKey='id'
                    columns={tableOnlineColumns}
                    dataSource={onTimeQuotaState.dataSource}
                />
            </Result>

            <Row gutter={24} type='flex' justify='space-between' style={{marginBottom: 15, marginTop: 15}}>
                <Col span={3}>
                    <Title level={4}>按次配额</Title>
                </Col>
                <Col span={6}>
                    <Search placeholder='数据API名称' onSearch={onSearchOuota} enterButton />
                </Col>
            </Row>
            <Result error={quotoState.error} onRetry={() => requestQuota()}>
                <Table
                    onChange={handleChangeQuota}
                    pagination={{total: quotoState.total}}
                    loading={quotoState.loading}
                    rowKey='id'
                    columns={QuotaColumns}
                    dataSource={quotoState.dataSource}
                />
            </Result>
        </>
    );
};
export default PermissionApi;
