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

import { dispatch } from '../../../../model'; 
import { isSzseEnv, formatDate, getDataModelerRole } from '../../../../util';
import { DataModelerRoleReader } from '../../../../util/constant';

// import Tag from "../../Tag";

import './ModelTable.less';

const { Text } = Typography;
const { Column } = Table;

const ModelNameColumn = (props) => {
  const { text, record, detailItem } = props;
  const [ data, setData ] = useState(record);

  const cols = [
    {
      title: '序号',
      dataIndex: 'key',
      render: (text, record, index) => {
        return (index+1).toString();
      },
      width: 60,
      ellipsis: true,
    },
    {
      title: '字段中文名称',
      width: 160,
      dataIndex: 'cnName',
      editable: true,
      ellipsis: true,
    },
    {
      title: '字段英文名称',
      width: 160,
      dataIndex: 'name',
      editable: true,
      ellipsis: true,
    },
  ];

  let _textComponent = <span style={{ color: '#000' }}>{text}</span>;
  if (data.digest) {
    _textComponent = <div style={{ width: 500, maxHeight: 300, overflow: 'auto' }}>
      <Table 
        rowKey='name'
        dataSource={data.digest.attributeDigests||[]}
        columns={cols}
        loading={false}
        pagination={false}
        size='small'
        rowClassName={(record, index) => {
          if (record?.primaryKey) {
            return 'primary-row';
          }

          return '';
        }}
      />
    </div>;
  }

  return (
    <Tooltip 
      title={_textComponent}
      overlayClassName='tooltip-common'
      onVisibleChange={(visible) => {
        if (visible && !record.digest) {
          dispatch({
            type: 'datamodel.getDataModelDigest',
            payload: {
              id: record.id
            },
            callback: _data => {
              record.digest = _data;
              setData({...record});
            }
          })
        }
      }}
    >
        <a onClick={()=>{detailItem(record);}}>
      {text||''}
      </a>
    </Tooltip>
  );
}

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 ExpandedModelTable = (props) => {

  const { onItemAction, onExpandedSelect, onExpandedChange, id = null, pid = null, checked, dataMap, onContextMenu, user, visibleColNames } = props;
  
  const [ tableWidth, setTableWidth ] = useState(0);
  const [ selectedRowKeys, setSelectedRowKeys ] = useState([]);
  const [ data, setData ] = useState([]);

  const [ columns, setColumns ] = useState([]);
  
  const cols = [
    {
      title: '模型名称',
      dataIndex: 'name',
      width: isSzseEnv?360:160,
      ellipsis: true,
      render: (text, record, index) => {
        return (<ModelNameColumn text={text} record={record} detailItem={detailItem} />);
      }
    },
    {
      title: '中文名称',
      dataIndex: 'cnName',
      width: isSzseEnv?420:160,
      ellipsis: true,
      render: (text, _, __) => {
        return (
          <Tooltip title={text||''}>
            <Text ellipsis={true}>{text||''}</Text>
          </Tooltip>
        )
      }
    },
    {
      title: '路径',
      dataIndex: 'path',
      width: 120,
      ellipsis: true,
      render: (text, _, __) => {
        return (
          <Tooltip title={text||''}>
            <Text ellipsis={true}>{text||''}</Text>
          </Tooltip>
        )
      }
    },
    {
      title: '状态',
      dataIndex: 'state',
      width: 100,
      ellipsis: true,
      render: (_, record) => {

        let color = '';
        if (record?.state?.id === '1') {
          color = '#DE7777';
        } else if (record?.state?.id === '2') {
          color = '#779BDE';
        } else if (record?.state?.id === '4') {
          color = '#77DEBF';
        }

        return (
          <span>
            <span style={{ display: 'inline-block', width: 10, height: 10, borderRadius: 5, marginRight: 5, backgroundColor: color  }}></span>
            <span>{record?.state?.cnName||''}</span>
          </span>
        );
      }
    },
    {
      title: '管理人',
      dataIndex: 'editor',
      width: 100,
      ellipsis: true,
    },
    {
      title: '版本号',
      dataIndex: 'modifiedTs',
      width: 170,
      ellipsis: true,
      render: (_,record) => {
        return `V_${formatDate(record.modifiedTs)}`;
      }
    },
    // {
    //   title: '标签',
    //   dataIndex: 'tag',
    //   width: 200,
    //   onCell: (record) => ({ 
    //     onMouseEnter: event => {
    //       setMouseEnterKey(record.id);
    //     }, 
    //     onMouseLeave: event => {
    //       setMouseEnterKey(null);
    //     },
    //   }),
    //   render: (_,record) => {
    //     return (
    //       record.id===mouseEnterKey?<Tag styleType='complex' id={record.id} />:<Tag id={record.id} />
    //     );
    //   }
    // },
    {
      title: '模型描述',
      dataIndex: 'remark',
      ellipsis: true,
      render: (text, _, __) => {
        return (
          <Tooltip title={text||''} overlayClassName='tooltip-common'>
            <Text ellipsis={true}>{text||''}</Text>
          </Tooltip>
        );
      }
    },
  ];

  useEffect(() => {
    setSelectedRowKeys(checked?[id]:[]);
    if (dataMap.has(id)) {
      setData([dataMap.get(id)]);
    } else {
      getCheckoutDataModel();
    }
    //eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  useEffect(() => {
    if (tableWidth>0) {
      let newColumns = [...cols];

      if ((visibleColNames||[]).length > 0) {
        newColumns = newColumns.filter(col => visibleColNames.indexOf(col.title)!==-1);
      }

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

      setColumns([ ...newColumns, <Column key='auto' />]);
    }
    //eslint-disable-next-line react-hooks/exhaustive-deps
  }, [ tableWidth, visibleColNames ])

  const getCheckoutDataModel = () => {
    dispatch({
      type: 'datamodel.getCheckoutDataModel',
      payload: {
        id: pid
      },
      callback: data => {
        setData(data?[data]:[]);
        onExpandedChange && onExpandedChange(id, data);
      }
    })
  }

  const detailItem = (record) => {
    onItemAction && onItemAction(record, 'detail', getDataModelerRole(user)===DataModelerRoleReader);
  }
  const onExpandedSelectChange = keys => {
    setSelectedRowKeys(keys);
    onExpandedSelect && onExpandedSelect(keys, data[0].id);
  };

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

    setColumns(nextColumns);
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: onExpandedSelectChange,
    hideSelectAll: true,
  };

  const mergedColumns = () => {
    let newColumns = [...columns];

    return (
      newColumns.map((col, index) => ({
        ...col,
        onHeaderCell: column => ({
          width: column.width,
          onResize: handleResize(index),
        }),
      }))
    );
  }

  const classes = classnames('model-table', {
    'model-table-sub': id
  });  

  return (
    <div className={classes}>
      <ResizeObserver
        onResize={({ width }) => {
          setTableWidth(width);
        }}
      >
        <Table
          rowSelection={rowSelection} 
          components={{
            header: {
              cell: ResizeableHeaderCell,
            }
          }}
          columns={mergedColumns()}
          rowKey={'id'}
          dataSource={data||[]}
          pagination={false}
          size='small'
          onRow={(record, index) => {
            return {
              onContextMenu: event => {
                onContextMenu && onContextMenu(event, record);
              },
            }
          }}
        />
      </ResizeObserver>
    </div>
  );
}

export default ExpandedModelTable;