import { useEffect, useState } from 'react';
import { Typography, Tooltip, Table } from 'antd';

const { Text, Paragraph, Title } = Typography;

const VersionCompareIndex = (props) => {

  const { data, direction = 'left' } = props;
  const [ columns, setColumns ] = useState([]);
  const [ tableData, setTableData ] = useState([]);

  useEffect(() => {

    const newColumns = [];
    (data?.heads?.indexHead||[]).forEach((item, index) => {
      newColumns.push({
        title: item||'',
        dataIndex: `column${index}`,
        render: (attrValue, record, index) => {

          let stateClassName = '';
          if (attrValue?.state==='ADD' || attrValue?.state==='UPDATE') {
            stateClassName = 'add';
          } else if (attrValue?.state === 'DELETE') {
            stateClassName = 'delete';
          }

          return (
            <Paragraph>
              <Tooltip title={attrValue?.value||''}>
                <Text className={stateClassName} ellipsis={true}>{attrValue?.value||''}</Text>
              </Tooltip>
            </Paragraph>
          );
        },
        width: 60,
        ellipsis: true,
      });
    })

    setColumns(newColumns);

    const newTableData = [];
    let indexValue = [];
    if (direction==='left') {
      indexValue = data?.left?.indexValue||[];
    } else if (direction==='right') {
      indexValue = data?.right?.indexValue||[];
    }

    (indexValue||[]).forEach((attrItem) => {
      let newAttrItem = {};
      (attrItem||[]).forEach((item, index) => {
        newAttrItem[`column${index}`] = item;
      })
      newTableData.push(newAttrItem);
    })

    setTableData(newTableData);
    
    //eslint-disable-next-line react-hooks/exhaustive-deps
  }, [ data ])

  return (
    <div>
      <div className='my-3'>
        <Typography>
          <Title level={5}>数据表索引</Title>
        </Typography>
      </div>
      <Table
        columns={columns||[]}
        dataSource={tableData}
        pagination={false}
      />
    </div>
  );
}

export default VersionCompareIndex;