/** @format */

import * as React from 'react';
import {Popconfirm, Row,Badge,notification} from 'antd';
import {ColumnProps} from 'antd/es/table';
import {PaginationProps} from 'antd/es/pagination';
import message from "../../../components/message"
import Result from '../../../components/result';
import Table from '../../../components/table';
import CreateApi from "./components/createApi"
import AlertSetComponent, {AlertFormDataProps} from '../../../components/alertSetting';
import {useFusingApi, usePutApi, useUpdateFusingApi} from "../../../service/provideApi"
import UpdateComponent from "./components/providerApiForm"
import {EnableType} from '../../../const/status';
import {decodeBase64} from '../../../utils/base64';
import {formatNumer} from '../../../utils/operation';
import FusingApiForm from './components/fusingApiForm';

import {useSourceApiList, useDeleteSourceApi,usePutSourceApi, SourceApiRecordProps} from '../../../service/provideApi';
import Button from '../../../components/button';

interface AlertSetModalState {
    visible: boolean;
    values?: AlertFormDataProps;
    id?: number;
    name?:string 
}
interface UpdateModalState {
  visible: boolean;
  values?: SourceApiRecordProps;
  id?: number;
  name?:string 
}

const SourceApiPage: React.FC = () => {
    const name = new URLSearchParams(decodeBase64(location.search.slice(1))).get('name')
    const id = Number(new URLSearchParams(decodeBase64(location.search.slice(1))).get('id'));
    const [alertSetModalState, setAlertModalState] = React.useState<AlertSetModalState>({
        visible: false,
    });
    const [updateApiModalState,setUpdateApiModalState]=React.useState<UpdateModalState>({
      visible:false,
    })
    const [fusingModalVisible,setFusingModalVisible]=React.useState<UpdateModalState>({
      visible:false,
    })
    const [updateState,requestUpdate]=usePutApi()
    const [fusingApi, requestApiFusing] = useFusingApi()
    const [updateFusingApi,requestFusingApiUpdate] = useUpdateFusingApi()
    const [listState, requestList] = useSourceApiList({
        page_number: 1,
        provider_id: id,
    });
    const [putAlertSetState,requestPutAlertSet]=usePutSourceApi()
    const [deleteState, requestDelete] = useDeleteSourceApi();
    const handleUpdateAlertSetModalVisible = (visible: boolean, values?: SourceApiRecordProps) => {
        setAlertModalState({visible, values,id:values?.id,name:values?.thirdpart_api_name});
    };
    const [fusingConfig, setFusingConfig] = React.useState<any>()

    const handleFusingModalVisible = (visible: boolean, values?: any)=>{
      requestApiFusing(values.provider_api_code)
      setFusingConfig(values)
      setFusingModalVisible({visible})
    }

    const handleSubmitFusingApi = (body: any) => {
      requestFusingApiUpdate(body).then((error: any)=>{
        if(error){
          return notification.error({
            description:error,
            message:'保存失败!'
          })
        }
        setFusingModalVisible({visible:false})
      })
    }

    const handleSubmitUpdate=(values:any)=>{
      requestUpdate({
        ...values,
        provider_id:id,
        provider_api_id:updateApiModalState.id,
      }).then(error=>{
        if(error){
          return notification.error({
            description:error,
            message:`${updateApiModalState.name}更新失败!`
          })
        }
        handleUpdateApiModalVisible()
        requestList()
      })
    }

    //请求预警设置
    const handleSubmitApiAlertSet=(values:AlertFormDataProps)=>{
      if(alertSetModalState.id){
        requestPutAlertSet({
          ...values,
          id:alertSetModalState.id
        }).then(error=>{
          if(error){
            return notification.error({
              description:error,
              message:`${alertSetModalState.name}预警设置失败!`
            })
          }
          handleUpdateAlertSetModalVisible(false)
          onOk()
        })
      }
    }
    //修改Api 弹窗状态
    const handleUpdateApiModalVisible=(visible=false,values?:SourceApiRecordProps)=>{
      setUpdateApiModalState({visible,values,id:values?.id,name:values?.thirdpart_api_name})
    }
    //删除
    const handleDelete = (record: SourceApiRecordProps) => {
        requestDelete(record.id).then(error => {
            if (!error) {
                return requestList();
            }
            return message.error(error);
        });
    };
    const onOk=()=>{
      requestList();
    }
    const handleRetry = () => {
        requestList();
    };
    const handleChangeTable = ({current}: PaginationProps) => {
        requestList({page_number: current});
    };
   
    const tableColumns = React.useMemo(() => {
        const columns: ColumnProps<SourceApiRecordProps>[] = [
            {
                key: 'index',
                title: '序号',
                dataIndex: 'index',
                width: 80,
            },
            {
                key: 'thirdpart_api_name',
                title: '接口',
                dataIndex: 'thirdpart_api_name',
            },
            {
                key: 'thirdpart_api_router',
                title: '接口路径',
                dataIndex: 'thirdpart_api_router',
            },
            {
                key: 'cost',
                title: '单价(￥)',
                dataIndex: 'cost',
                align: 'right',
                width: 120,
            },
            {
                key: 'count',
                title: '日调用量上限(即查)',
                dataIndex: 'count',
                align: 'right',
                width: 200,
                render: text => {
                    return formatNumer(text);
                },
            },
            {
                key: 'state',
                title: '状态',
                dataIndex: 'state',
                width: 120,
                render: text => {
                    return <Badge color={text===1?"green":"yellow"} text={EnableType[text]}></Badge>
                },
            },
            {
                key: 'opertion',
                title: '操作',
                width: 280,
                render: (_, record) => {
                    return (
                        <>
                            <Button type='link' onClick={() => handleUpdateApiModalVisible(true, record)}>
                                修改
                            </Button>
                            <Button type='link' onClick={() => handleUpdateAlertSetModalVisible(true, record)}>
                                预警
                            </Button>
                            <Button type='link' onClick={() => handleFusingModalVisible(true, record)}>
                                熔断
                            </Button>
                            <Popconfirm
                                title={`确认删除-${record.thirdpart_api_name}?`}
                                okText='确认'
                                cancelText='取消'
                                okType='danger'
                                onConfirm={() => handleDelete(record)}
                            >
                                <Button type='link' loading={deleteState.loading}>删除</Button>
                            </Popconfirm>
                        </>
                    );
                },
            },
        ];
        return columns;
    }, []);

    return (
        <>
            
            <Row type='flex' justify='end' style={{marginBottom: 15}}>
            <CreateApi onOk={onOk}>
               <Button type='primary'>
                    添加
                </Button>
            </CreateApi>
            </Row>
            <Result error={listState.error} onRetry={handleRetry}>
                <Table
                    rowKey='id'
                    loading={listState.loading}
                    onChange={handleChangeTable}
                    columns={tableColumns}
                    pagination={{
                        total: listState.total,
                        current:listState.deepData.page_number
                    }}
                    dataSource={listState.dataSource}
                />
            </Result>
            {
              alertSetModalState.values ?
              <AlertSetComponent
                visible={alertSetModalState.visible}
                values={alertSetModalState.values}
                name={alertSetModalState.name}
                onSubmit={handleSubmitApiAlertSet}
                loading={putAlertSetState.loading}
                onCancel={()=>handleUpdateAlertSetModalVisible(false)}
              />
              :null
            }
              <FusingApiForm
                name={name}
                config={fusingConfig} 
                values={fusingApi.dataSource}
                visible={fusingModalVisible.visible}
                onSubmit={handleSubmitFusingApi}
                onCancel={()=>setFusingModalVisible({visible:false})}
                loading={updateFusingApi.loading}
              />
            {
              !!updateApiModalState.values? 
              <UpdateComponent 
                  onSubmit={handleSubmitUpdate}
                  title={`数据源设置--${updateApiModalState.name}`} 
                  values={updateApiModalState.values} 
                  onCancel={()=>handleUpdateApiModalVisible(false)} 
                  visible={updateApiModalState.visible}
                  type="update"
                  loading={updateState.loading}
                />
              :null
            }
           
        </>
    );
};
export default SourceApiPage;
