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

import FilterColumnAction from './FilterColumnAction';

const { Title } = Typography;

export const defaultColumnTitles = ['英文名称','中文名称','数据项标准编码','数据项标准名称'];

const VersionCompareTable = (props) => {
  const { data, direction = 'left', selectedColumnTitles = defaultColumnTitles, onFilterChange } = props;
  const [columns, setColumns] = React.useState()

  React.useEffect(() => {
    const newColumns = [];
    for (const [index, item] of (data?.heads?.columnHead||[]).entries()) {
      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 (
            <Typography.Paragraph>
              <Tooltip title={attrValue?.value||''}>
                <Typography.Text className={stateClassName} ellipsis={true}>{attrValue?.value||''}</Typography.Text>
              </Tooltip>
            </Typography.Paragraph>
          );
        },
        width: (item==='序号')?60: 150,
        ellipsis: true,
        option: true,
      });
    }

    setColumns([...newColumns, {
      title: <FilterColumnAction columns={newColumns} defaultSelectedKeys={defaultColumnTitles} onChange={(val) => onFilterChange?.(val)} />,
      dataIndex: 'columnFilter',
      render: (_, record, index) => {
        return '';
      },
      width: 40,
      ellipsis: true,
      option: false
    }])
  }, [data])

  const _columns = React.useMemo(() => {
    return (columns??[]).filter(column => column.option===false || (selectedColumnTitles??[]).indexOf(column.title) !== -1)
   }, [selectedColumnTitles, columns])

  const tableData = React.useMemo(() => {
    const newTableData = [];
    let columnValue = (direction==='left') ? data?.leftValue?.columnValue : data?.rightValue?.columnValue;
    
    for (const item of columnValue??[]) {
      let newItem = {};
      for (const [index, _item] of item.entries()) {
        newItem[`column${index}`] = _item;
      }
      newTableData.push(newItem);
    }

    return newTableData
  }, [direction, data])

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

export default VersionCompareTable;