/** @format */

import * as React from 'react';
import {Input, Popconfirm,notification,Switch, Row, Col} from 'antd';
import Highlighter from "react-highlight-words";
import {ColumnProps} from 'antd/es/table';
import {PaginationProps} from 'antd/es/pagination';
import Button from '../../../../components/button';
import Table from '../../../../components/table';
import Result from '../../../../components/result';
import {encodeBase64} from '../../../../utils/base64';
import message from '../../../../components/message';
import AlertSet from '../../../../components/alertSetting';
import {useBaseApiList,BaseApiRecordProps} from "../../../../service/baseApi"
import {
    
    usePutInterfaceEnable,
    usePutInterfaceReport,
    useDelete,
    useUpdateAlertSet,

} from '../../../../service/interface';
const {Search} = Input;
const Enable = (props: {id: number; checked: boolean}) => {
    const [state, requestData] = usePutInterfaceEnable({
        checked: props.checked,
    });
    const handleChange = (checked: boolean) => {
        requestData(props.id, checked).then(error=>{
          if(error) return message.error(error)
        })
    };
    return <Switch checked={state.checked} loading={state.loading} onChange={handleChange} />;
};

const Report = (props: {id: number; isReport: boolean}) => {
    const [state, requestData] = usePutInterfaceReport({
        isReport: props.isReport,
    });
    const handleChange = (isReport: boolean) => {
        requestData(props.id, isReport);
    };
    return <Switch checked={state.isReport} loading={state.loading} onChange={handleChange} />;
};

interface AlertSetState {
    visible: boolean;
    name?: string;
    id?: number;
    values?: BaseApiRecordProps;
}

const interfaceList: React.FC<any> = (props) => {
    const {history} = props
    const [baseApiListState, requestBaseApiList] = useBaseApiList();
    React.useEffect(()=>{
      requestBaseApiList({
        page_number: 1,
        search: '',
      })
    },[])
    const [deleteState, requestDelete] = useDelete();
    const [alertSetState, requestAlertSet] = useUpdateAlertSet();
    const [alertSetModalState, setAlertModalState] = React.useState<AlertSetState>({
        visible: false,
    });
    //表格搜索条件改变
    const handleChangeTable = ({current}: PaginationProps) => {
        requestBaseApiList({
            page_number: current,
        });
    };
    //重试
    const handleRetry = () => {
        requestBaseApiList();
    };
    const handleSearch = (value: string) => {
        requestBaseApiList({
            page_number: 1,
            search: value,
        });
    };
    //更新预警设置的弹窗
    const handleUpdateAlerSetVisible = (visible = false, record?: BaseApiRecordProps) => {
        setAlertModalState({visible, values: record,name:record?.api_name,id:record?.id});
    };
   
  //请求预警设置
  const handleSubmitAlertSet = (values: any) => {
    requestAlertSet({
      id:alertSetModalState.id as number,
      threshold_fail_rate:values.threshold_fail_rate,
      threshold_norecord_rate:values.threshold_norecord_rate,
      threshold_timeout:values.threshold_timeout,
      warning_enable:values.warning_enable,
      rate_limit:values.rate_limit,
    }).then(error=>{
      if(error){
        return notification.error({
          message:`${alertSetModalState.name}预警设置失败`,
          description:error,
        })
      }
      handleUpdateAlerSetVisible();
      requestBaseApiList()
    })
  };
    //跳转到编辑页面
    const handleToEdit = (record: BaseApiRecordProps) => {
        const path =
            '/home/dataServer/editInterface?' +
            encodeBase64('name=' + encodeURIComponent(record.api_name) + '&id=' + String(record.api_id));
        history.push(path);
    };
    //跳转到新增页面
    const handleToHrefAddInterface = () => {
        const path = '/home/dataServer/interfaceAdd';
        history.push(path);
    };
    const handleOk = (record: BaseApiRecordProps) => {
        requestDelete(record.api_id).then(error => {
          if(error){
            return notification.error({
              message:`${record.api_name}预警设置失败`,
              description:error,
            })
          } 
          handleRetry();
        });
    };
    //跳转到数据源
    const handleToSource = (record: BaseApiRecordProps) => {
        const path =
            '/home/dataServer/source?' + encodeBase64('name=' + encodeURIComponent(record.api_name)  + '&id=' + String(record.api_id));
        history.push(path);
    };
    const DataColumnProps = React.useMemo(() => {
        const columnProps: ColumnProps<BaseApiRecordProps>[] = [
            {
                title: '序号',
                key: 'index',
                dataIndex: 'index',
                width:80,
                fixed:"left"
            },
            {
                title: '接口名称',
                key: 'api_name',
                dataIndex: 'api_name',
                fixed:"left",
                width:200,
                render: text => {
                  return text?<Highlighter 
                  highlightStyle={{color:"#12C194"}}
                  searchWords={[baseApiListState.deepData.search||""]}
                  textToHighlight={text}></Highlighter>:"--"
              },
            },
            {
                title: '接口路径',
                key: 'router',
                dataIndex: 'router',
                render: text => {
                  return text || '--';
              },
            },
            {
                title: '操作时间',
                key: 'operation_time',
                dataIndex: 'operation_time',
                render: text => {
                  return text || '--';
              },
            },
            {
                title: '是否启用',
                key: 'enable',
                dataIndex: 'enable',
                render: (text, record) => {
                    return <Enable checked={text} id={record.api_id} />;
                },
            },
            {
                title: '是否开通报表',
                key: 'is_show',
                dataIndex: 'is_show',
                render: (text, record) => {
                    return <Report isReport={text} id={record.api_id} />;
                },
            },
            {
                title: '操作',
                fixed:"right",
                width:280,
                render: (_, record) => {
                    return (
                        <>
                            <Button type='link' onClick={() => handleToEdit(record)}>
                                编辑
                            </Button>
                            <Button type='link' onClick={() => handleToSource(record)}>
                                数据源
                            </Button>
                            <Button type='link' onClick={() => handleUpdateAlerSetVisible(true, record)}>
                                限制
                            </Button>
                            <Popconfirm
                                title={`是否删除   ${record.api_name}?`}
                                okText='是'
                                onConfirm={() => handleOk(record)}
                                cancelText='否'
                            >
                                <Button loading={deleteState.loading} size='small' type='link'>
                                    删除
                                </Button>
                            </Popconfirm>
                        </>
                    );
                },
            },
        ];
        return columnProps;
    }, [baseApiListState.deepData]);
    return (
        <>
            <Row type='flex' justify='end' style={{marginBottom: 15}}>
                <Col lg={6} xxl={4}>
                    <Search onSearch={handleSearch} loading={baseApiListState.loading} placeholder='请输入接口名称' enterButton='搜索' />
                </Col>
                <Col xxl={1} lg={2} offset={1}>
                    <Button type='primary' onClick={handleToHrefAddInterface}>
                        添加
                    </Button>
                </Col>
            </Row>
            {!!alertSetModalState.values && (
                <AlertSet
                    onSubmit={handleSubmitAlertSet}
                    error={alertSetState.error}
                    loading={alertSetState.loading}
                    name={alertSetModalState.name}
                    visible={alertSetModalState.visible}
                    values={alertSetModalState.values}
                    onCancel={() => handleUpdateAlerSetVisible(false)}
                />
            )}
            <Result error={baseApiListState.error} onRetry={handleRetry}>
                <Table
                    rowKey='api_id'
                    onChange={handleChangeTable}
                    pagination={{
                        total: baseApiListState.total,
                        current: baseApiListState.deepData.page_number,
                    }}
                    columns={DataColumnProps}
                    loading={baseApiListState.loading}
                    dataSource={baseApiListState.dataSource}
                />
            </Result>
        </>
    );
};
export default interfaceList;
