/** @format */

import * as React from 'react';
import {Popconfirm,notification } from 'antd';
import Highlighter from "react-highlight-words";
import Result from '../../../../components/result';
import Search from '../../../../components/search/search';
import {encodeBase64} from '../../../../utils/base64';
import message from '../../../../components/message';
import SelectType from '../../../../components/select/dataType';
import Input from '../../../../components/input';
import Button from '../../../../components/button';
import Table from '../../../../components/table';
import {ColumnProps} from 'antd/es/table';
import {PaginationProps} from 'antd/es/pagination';
import {DataType} from '../../../../const/status';
import CreateApiForm from './components/createApi';
import UpdateApiFrom, {formValuesProps} from './components/datApiForm';
import {useDataApiList,useUpdateDataAPi, useDeleteDataApi, useRelese, DataApiRecordProps} from '../../../../service/dataApi';


interface SearchColumnsProps {
  search:string;
  type:0|1
}

interface IUpdateApiModalState {
    id?: number;
    values?: formValuesProps;
    visible: boolean;
}
const DataAPI: React.FC = (props) => {
    const {history} = props;
    const [listState, requestList] = useDataApiList();
    React.useEffect(()=>{
      requestList({
        page_number: 1,
        data_api_type: '',
        search: '',
      })
    },[]);
    const [updateDataAPIState,requestUpdateDataApi]=useUpdateDataAPi()
    const [updateApiModalState, setUpdateApiModalState] = React.useState<IUpdateApiModalState>({
        visible: false,
    });
  
    //删除
    const [deleteState, requestDelete] = useDeleteDataApi();
   
    const handleDelete = (id: number) => {
        requestDelete(id).then(error => {
            if (!error) {
                return requestList();
            }
            return message.error(error);
        });
    };
    const handleSearch=(values:SearchColumnsProps)=>{
      requestList({
        page_number: 1,
        data_api_type: values.type||"",
        search: values.search||""
      })
    }
    //页码改变
    const handleChangeTable = (pagination: PaginationProps) => {
        const {current} = pagination;
        requestList({
            page_number: current,
        });
    };
    //重试
    const handleretry = () => {
        requestList();
    };
    //发布或者下线
    const [resleState, requestRelase] = useRelese();

    const handlePutRelase = (record:DataApiRecordProps) => {
      requestRelase({
        id:record.id,
        status:record.is_release?0:1
      }).then(error=>{
        if(error){
          const status=record.is_release?0:1;
          return notification.error({
            message:`${record.data_api_name}${status===0?"下线":"发布"}失败`,
            description:error,
           })
        }
         requestList()
      })

    };
    const handleUpdateApiModalVisble = (visible: boolean, record?: DataApiRecordProps) => {
        setUpdateApiModalState(preState => ({
            visible,
            values: record,
            id:record?.id,
        }));
    };
    //请求更新
    const handleSubmitUpdate=(values)=>{
      requestUpdateDataApi({
        ...values,
        data_api_id:updateApiModalState.id
      }).then(error=>{
        if(error){
          return notification.error({
            message:`更新${updateApiModalState.values?.data_api_name}失败!`,
            description:error
          })
        }
        handleUpdateApiModalVisble(false);
        requestList()
      })
    }
    const handleToQueryModo = (record: DataApiRecordProps) => {
        const path =
            '/home/dataServer/queryMode?' + encodeBase64('id=' + record.id + '&name=' + encodeURIComponent(record.data_api_name));
        history.push(path);
    };
    const tableColumns = React.useMemo(() => {
        const columns: ColumnProps<DataApiRecordProps>[] = [
            {
                key: 'index',
                title: '序号',
                dataIndex: 'index',
                width:80,
                fixed:'left'
            },
            {
                key: 'data_api_name',
                title: '数据API',
                width:360,
                dataIndex: 'data_api_name',
                fixed:'left',
                render: text => {
                  return text?<Highlighter 
                  textToHighlight={text} 
                  highlightStyle={{color:"#12C194"}}
                  searchWords={[listState.deepData.search||""]}></Highlighter> : '--';
              },
            },
            {
                key: 'data_api_type',
                title: '类别',
                render: (_, record) => {
                    return DataType[record.data_api_type]||"--";
                },
            },
            {
                key: 'version',
                title: '版本',
                dataIndex: 'version',
                width:100,
                render: text => {
                  return text || '--';
              },
            },
            {
                key: 'release_time',
                title: '上架时间',
                dataIndex: 'release_time',
                width:180,
                render: text => {
                  return text || '--';
              },
            },
            {
                key: 'opertion',
                title: '操作',
                width: 330,
                fixed:"right",
                render: (_, record) => {
                    return (
                        <>
                            <Button type="link" onClick={() => handleUpdateApiModalVisble(true, record)}>
                                基本设置
                            </Button>
                            <Button type="link" onClick={() => handleToQueryModo(record)}>
                                详细设置
                            </Button>
                            <Button loading={resleState.loading} type="link" onClick={() => handlePutRelase(record)}>
                                {record.is_release ? '下线' : '发布'}
                            </Button>
                            <Popconfirm
                                title={`是否确认删除(${record.data_api_name})`}
                                okType="danger"
                                okText="确认"
                                cancelText="取消"
                                onConfirm={() => handleDelete(record.id)}
                            >
                                <Button type="link" loading={deleteState.loading}>删除</Button>
                            </Popconfirm>
                        </>
                    );
                },
            },
        ];
        return columns;
    }, [listState.deepData]);

    const SearchColumns = React.useMemo(() => {
        const columns= [
            {
                key: 'search',
                options:{
                  initialValue:"",
                },
                component: <Input placeholder="请输入数据API名称" />,
            },
            {
                key: 'type',
                // options:{
                //   initialValue:0,
                // },
                component: (
                    <SelectType  isAll  />
                ),
            },
        ];
        return columns;
    }, []);
    return (
        <>
            <Search
                dataSource={SearchColumns}
                handleSubmit={handleSearch}
                disabled={listState.loading}
                extra={
                    <CreateApiForm onOk={()=>requestList()}>
                        <Button icon="folder-add" type="primary" >
                            添加
                        </Button>
                    </CreateApiForm>
                }
            />
            {
            !!updateApiModalState.values? 
            <UpdateApiFrom 
              title={`基本设置(${updateApiModalState.values.data_api_name})`} 
              values={updateApiModalState.values} 
              visible={updateApiModalState.visible} 
              onSubmit={handleSubmitUpdate}
              loading={updateDataAPIState.loading}
              onCancel={()=>handleUpdateApiModalVisble(false)} />
            :null
            }
            <Result error={listState.error} onRetry={handleretry}>
                <Table
                    onChange={handleChangeTable}
                    columns={tableColumns}
                    bordered
                    rowKey="id"
                    pagination={{
                        total: listState.total,
                        current:listState.deepData.page_number
                    }}
                    loading={listState.loading}
                    dataSource={listState.dataSource}
                />
            </Result>
        </>
    );
};
export default DataAPI;
