import React, { useState } from 'react';
import { Table, Tooltip } from 'antd';
import { Resizable } from 'react-resizable';
import ResizeObserver from 'rc-resize-observer';

import { isSzseEnv } from '../../../../util';
import { dispatch } from '../../../../model'; 

import './SuggestTable.less';

const ResizeableHeaderCell = props => {
  const { onResize, width, onClick, ...restProps } = props;

  if (!width) {
    return <th {...restProps} />;
  }

  return (
    <Resizable
      width={width}
      height={0}
      handle={
        <span
          className="react-resizable-handle"
          onClick={(e) => {
            e.stopPropagation();
          }}
        />
      }
      onResize={onResize}
      draggableOpts={{ enableUserSelectHack: false }}
    >
      <th
        onClick={onClick}
        {...restProps}
      />
    </Resizable>
  );
};

const SourceComponent = (props) => {
  const { data, onClick, name } = props;

  const moreSourceComponent = <div style={{ maxWidth: 400, maxHeight: 300, overflow: 'auto' }}>
  {
    (data||[]).map((source, index) => {
      return (
        <div 
          className='pointer'
          key={index}
          style={{
            textDecoration: 'underline',
          }}
          onClick={(e) => {
            e.stopPropagation();
            onClick && onClick(source.sourceId, name);
          }}
        >
        {source.sourcePath||''}
        </div>
      );
    })
  }
  </div>;

  return (
    <Tooltip 
      title={moreSourceComponent}
      overlayClassName='tooltip-common'
    >
      <a 
        href='#' 
        onClick={(e) => {
          e.stopPropagation();
          onClick && onClick(data[0].sourceId, name);
        }}
      >
      {
        (data||[]).length>0 && <span>{data[0].sourcePath||''}</span>
      }
      </a>
    </Tooltip>
  );
}

const SuggestTable = (props) => {

  const { suggests, onSelect } = props;
  const [ tableWidth, setTableWidth ] = useState(0);
  
  const cols = [
    {
      title: '中文名称',
      dataIndex: 'cnName',
      width: isSzseEnv?360:160,
      ellipsis: true,
      render: (text, _, __) => {
        return (
          <Tooltip title={text||''}>
            <span>{text||''}</span>
          </Tooltip>
        )
      }
    },
    {
      title: '英文名称',
      dataIndex: 'name',
      width: isSzseEnv?360:160,
      ellipsis: true,
      render: (text, _, __) => {
        return (
          <Tooltip title={text||''}>
            <span>{text||''}</span>
          </Tooltip>
        )
      }
    },
    {
      title: '业务含义',
      dataIndex: 'remark',
      width: isSzseEnv?360:160,
      ellipsis: true,
      render: (text, _, __) => {
        return (
          <Tooltip title={text||''}>
            <span>{text||''}</span>
          </Tooltip>
        )
      }
    },
    {
      title: '匹配度',
      dataIndex: 'score',
      width: 100,
      render: (_, record, index) => {
        return (
          <React.Fragment>
            <span style={{ color: '#f50' }}>{`${record.recommendedStats?.score}%`}</span>
            { index===0 && <span style={{ color: '#f50' }}> 推荐</span> }
          </React.Fragment>
        );
      }
    },
    {
      title: '使用次数',
      dataIndex: 'referencesCount',
      width: 80,
      ellipsis: true,
      render: (_, record) => {
        return (
          <span>{record.recommendedStats?.referencesCount}</span>
        );
      }
    },
    {
      title: '来源',
      dataIndex: 'source',
      ellipsis: true,
      render: (_, record) => {
        return (
          <SourceComponent data={record.recommendedStats?.sourceInfos||[]} name={record.name||''} onClick={sourceOnClick} />
        );
      }
    },
  ];

  const [ columns, setColumns ] = useState(cols);

  const sourceOnClick = (id, name) => {
    const timestamp = new Date().getTime();

    const tempArray = id.split('=');

    if (tempArray.length>=3) {

      dispatch({
        type: 'datamodel.getParent',
        payload: {
          id
        },
        callback: data => {
          window.open(`/center-home/metadetail?mid=${encodeURIComponent(data._id)}&action=metadetail&type=detail&manager=false&activekey=1&name=${encodeURIComponent(name||'')}`);
        }
      })
    } else {
      window.open(`/center-home/menu/datastandard?id=${id}&timestamp=${timestamp}`);
    }
  }

  const onTableSelect = (record, selected, selectedRows, nativeEvent) => {
    onSelect && onSelect(record);
  }

  const handleResize = index => (e, { size }) => {
    const nextColumns = [...columns];
    nextColumns[index] = {
      ...nextColumns[index],
      width: size.width,
    };

    setColumns(nextColumns);
  };

  const mergedColumns = () => {
    return (
      columns.map((column, index) => { 
        return {
          ...column,
          onHeaderCell: column => ({
            width: column.width,
            onResize: handleResize(index),
          }),
        };
      })
    );
  }

  const rowSelection = {
    type: 'radio',
    onSelect: onTableSelect,
  };

  return (
    <div className='suggest-table'>
      <ResizeObserver
        onResize={({ width }) => {

          if (tableWidth !== width) {
            setTableWidth(width);
            let newColumns = [...cols];

            newColumns.forEach((column, index) => { 
              if (!column.width) {
                const rowWidth = (cols.reduce((preVal, col) => (col.width?col.width:0) + preVal, 0)) + 50;
                
                if (width > rowWidth) {
                  column.width = (width-rowWidth)>200?(width-rowWidth):200;        
                } else {
                  column.width = 200;
                }
              }
            });

            setColumns(newColumns);
          }
        }}
      >
        <Table
          rowSelection={rowSelection}
          dataSource={suggests||[]}
          pagination={false}
          loading={false}
          rowKey='iid'
          rowClassName={(record, index) => {
            return 'pointer';
          }}
          components={{
            header: {
              cell: ResizeableHeaderCell,
            }
          }}
          columns={mergedColumns()}
          onRow={(record, index) => {
            return {
              onClick: (e) => {
                onSelect && onSelect(record);
              }
            }
          }}
        />
      </ResizeObserver>
    </div>
  );
}

export default SuggestTable;