import React, { useEffect, useState } from 'react';
import { Modal, Button, Form, Input, Table, Tooltip, Typography } from 'antd';
import { dispatch } from '../../../../model';

const FC = (props) => {
  const {visible, service, onCancel} = props;
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState(undefined);
  const [cols, setCols] = useState([]);
  
  useEffect(() => {
    if (visible) {
      getSample();
    }
  }, [visible])

  const getSample = () => {
    setLoading(true)
    dispatch({
      type: 'pds.getSample',
      payload: { 
        params: {
          pdsDataServiceId: service?.id,
        }
      },
      callback: data => {
        setLoading(false);
        setData(data?.content||[]);

        const newCols = [];
        data?.headers?.forEach(item => {
          if (item) {
            newCols.push({
              title: item, 
              dataIndex: item, 
              width: 150, 
              ellipsis: true,
              render: (value, record) => <Tooltip title={value}>
                <Typography.Text ellipsis={true}>{value}</Typography.Text>
              </Tooltip>
            });
          }
        });
        setCols(newCols);
      },
      error: () => {
        setLoading(false);
      }
    });
  }

  const cancel = () => {
    setLoading(false);
    setData(undefined);
    onCancel?.();
  }

  const footer = [ 
    <Button
      key="0" 
      onClick={() => {cancel()}}
    >
    取消
    </Button>,
  ];

  return (
    <Modal 
      forceRender
      visible={visible}
      title={`${service?.name}的样本数据`}
      width={650}
      onCancel={() => {cancel()}}
      footer={footer}
    >
      <Table 
        loading={loading} 
        columns={cols} 
        dataSource={data||[]} 
        size='small'
        scroll={{ x: 600, y: 300 }}
        pagination={false}
      />
    </Modal>
  )
}

export default FC;