/** @format */

import * as React from 'react';
import {ColumnProps} from 'antd/es/table';
import {Input, Popconfirm, Row, Col, notification} from 'antd';
import Highlighter from "react-highlight-words";
import {PaginationProps} from 'antd/es/pagination';
import Result from '../../../components/result';
import {encodeBase64} from '../../../utils/base64';
import message from '../../../components/message';
import {ProviderProps, useProviders, useDeleteSource,useChangeSource} from '../../../service/provider';
import CreateProvier from './components/createProvide';
import UpdateProvier, {formDataProps} from './components/provideForm';
import Button from '../../../components/button';
import Table from '../../../components/table';
const {Search} = Input;
interface UpdateProviderState {
    visible: boolean;
    values?: formDataProps;
    id?: number;
    name?:string
}
const dataSourcePage: React.FC = (props) => {
    const {history} = props;
    const [listState, requestList] = useProviders();
    React.useEffect(()=>{
      requestList({
        is_all:false,
        page_number:1
      })
    },[])
    
    const [deleteState, requestDelete] = useDeleteSource();
    const [changeState,requestUpdateProvider]=useChangeSource()
    const [UpdateState, setUpdateState] = React.useState<UpdateProviderState>({
        visible: false,
    });
    const handleRetry = () => {
      requestList();
    };
    const handleAddOk = () => {
      requestList();
    };
    
    const handleSearch = (searchContent: string) => {
      requestList({page_number: 1, search: searchContent});
    };
    const handleChangeTable = ({current}: PaginationProps) => {
      requestList({
            page_number: current,
        });
    };
    const handleUpdateVisible = (visible: boolean, values?: ProviderProps) => {
        setUpdateState({visible, values,id:values?.id,name:values?.platform_name});
    };
    const handleSubmitUpdate=(values:formDataProps)=>{
      if(UpdateState.id){
        requestUpdateProvider({
          platform_name: values.platform_name,
          platform_code: values.platform_code,
          contact: values.contact,
          email: values.email,
          provider_id:UpdateState.id
        }).then(error=>{
          if(error) return message.error(error);
          handleUpdateVisible(false)
          requestList()
        })
      }
     
    }
    //删除
    const handleDelete = (record: ProviderProps) => {
        requestDelete(record.provider_id).then((error: Error) => {
            if (error) {
              return notification.error({
                message:"删除数据源失败",
                description:error
              })
            }
            requestList();
        });
    };

    //跳转到API页面
    const handleToHrefApi = (record: ProviderProps) => {
        const search = encodeBase64('id=' + record.provider_id + '&name=' + encodeURIComponent(record.platform_name));
        history.push('/home/source/sourceApi?' + search);
    };
    const tableColumns = React.useMemo(() => {
        const columns: ColumnProps<ProviderProps>[] = [
            {
                key: 'name',
                title: '序号',
                width:80,
                dataIndex: 'index',
                fixed:"left"
            },
            {
                key: 'platform_name',
                title: '供应商',
                dataIndex: 'platform_name',
                fixed:"left",
                width:220,
                render: text => {
                    return text? <Highlighter  highlightStyle={{color:"#12C194"}}
                    searchWords={[listState.deepData.search||""]} textToHighlight={text}></Highlighter> : '--';
                },
            },
            {
                key: 'index',
                title: '联系方式',

                width:140,
                dataIndex: 'contact',
                render: text => {
                    return text || '--';
                },
            },
            {
                key: 'email',
                title: '邮箱',
                width:200,
                dataIndex: 'email',
                render: text => {
                    return text || '--';
                },
            },
            {
                key: 'cost',
                title: '花销(￥)',
                dataIndex: 'cost',
                align:"right",
                render: text => {
                    return text || '--';
                },
            },
            {
                key: 'create_time',
                title: '添加时间',
                dataIndex: 'create_time',
                width:180,
                render: text => {
                    return text || '--';
                },
            },
            {
                key: 'opertion',
                title: '操作',
                width: 220,
                fixed:"right",
                render: (_, record) => {
                    return (
                        <>
                            <Button type='link' onClick={() => handleUpdateVisible(true, record)}>
                                修改
                            </Button>
                            <Button type='link' onClick={() => handleToHrefApi(record)}>
                                API
                            </Button>
                            <Popconfirm
                                title={`确认删除${record.platform_name}?`}
                                onConfirm={() => handleDelete(record)}
                                okText='确认'
                                cancelText='取消'
                            >
                                <Button type='link' loading={deleteState.loading}>
                                    删除
                                </Button>
                            </Popconfirm>
                        </>
                    );
                },
            },
        ];
        return columns;
    }, [listState.deepData]);
    return (
        <>
        {
          UpdateState.values?<UpdateProvier loading={changeState.loading} values={UpdateState.values} title={`修改(${UpdateState.name})`} onSubmit={handleSubmitUpdate} visible={UpdateState.visible} onCancel={()=>handleUpdateVisible(false)} />:null
        }
            <Row  type='flex' justify='end' style={{marginBottom: 15}}>
                <Col xxl={4} lg={6}>
                    <Search placeholder='请输入供应商名称' onSearch={handleSearch} loading={listState.loading} enterButton />
                </Col>
                <Col xxl={1} offset={1} lg={2}>
                    <CreateProvier onOk={handleAddOk}>
                        <Button type='primary'>添加</Button>
                    </CreateProvier>
                </Col>
            </Row>
            <Result error={listState.error} onRetry={handleRetry}>
                <Table
                    onChange={handleChangeTable}
                    columns={tableColumns}
                    loading={listState.loading}
                    rowKey='id'
                    pagination={{
                        total: listState.total,
                        current:listState.deepData.page_number
                    }}
                    dataSource={listState.dataSource}
                />
            </Result>
        </>
    );
};
export default dataSourcePage;
