import React, { useState, useEffect, useRef, useContext, useMemo } from "react";
import { Tooltip, Modal, Pagination, Typography, Space, Menu, Dropdown, Row, Col, Divider } from 'antd';
import { DownOutlined, UpOutlined, UnorderedListOutlined } from '@ant-design/icons';
import copy from "copy-to-clipboard";  
import SmoothScroll from 'smooth-scroll';
import classnames from 'classnames';
import { Resizable } from 'react-resizable';
import { useContextMenu, Menu as RcMenu, Item as RcItem } from "react-contexify";
import ResizeObserver from 'rc-resize-observer';
import ServiceDetail from './ServiceDetailModal';
import SampleModal from './SampleModal';
import ExchangeOwnerModal from './ExchangeOwner';
import Table from '../../ResizeableTable';

import { dispatch } from '../../../../model'; 
import { showMessage, getQueryParam, paginate, isSzseEnv, formatDate, getDataModelerRole } from '../../../../util';
import { AnchorId, AnchorTimestamp, Action, CatalogId, ModelerId, DataModelerRoleReader } from '../../../../util/constant';
import { AppContext } from "../../../../App";
import SelectUser from "./SelectUsers";
// import Tag from "../../Tag";

import './ModelTable.less';
import 'react-contexify/dist/ReactContexify.css';

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

const actions = [
  { title: '编辑', key: 'edit' },
  { title: '删除', key: 'delete' },
  { title: 'URI复制', key: 'copyUri' },
  { title: '样本数据', key: 'sample' },
  { title: '历史版本', key: 'history' },
  { title: '授权', key: 'admit' },
  // { title: '申请', key: 'startFlow' },
  // { title: '下载Tableau tds', key: 'downloadTds' },
  // { title: '跳转至电子表格', key: 'smart' },
  { title: '更换管理', key: 'exchangeOwner' },
  { title: '拖拉创建字段', key: 'dragAttribute' },
  { title: '自定义sql创建字段', key: 'sqlAttribute' }
]

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 
        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: 'pds.getServiceDigest',
            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 ModelTable = (props) => {

  const { data, onChange, onItemAction, onSelect, onHistory, catalogId, keyword, onAutoCreateTable, offset = null, modelId = null, modelPid = null, view, selectModelerIds, onSubSelect, modelState, user, isOnlyEnding, visibleColNames } = props;

  const MENU_ID = (((modelId||'') !== '') ? `model-table-contextmenu-${modelId}` : 'model-table-contextmenu');

  const { show, hideAll } = useContextMenu({
    id: MENU_ID,
  });
  
  const [ tableWidth, setTableWidth ] = useState(0);
  const [ selectedRowKeys, setSelectedRowKeys ] = useState([]);
  const [ subSelectedRowKeys, setSubSelectedRowKeys ] = useState([]);
  // const [ mouseEnterKey, setMouseEnterKey ] = useState(null);
  const [ sortRule, setSortRule ] = useState(null); 
  const [ filterData, setFilterData ] = useState([]);
  const [ subData, setSubData ] = useState([]);
  const [ serviceDetailParams, setServiceDetailParams ] = useState({ visible: false, id: '' }) 
  const [ sampleParams, setSampleParams ] = useState({ visible: false, service: undefined });
  const [ exchangeOwnerParams, setExchangeOwnerParams ] = useState({ visible: false, id: undefined }); 
  const [attrs, setAttrs] = useState(undefined);

  const app = useContext(AppContext);

  const indexCol = {
    title: '序号',
    dataIndex: 'key',
    render: (text, record, index) => {
      return (index+1).toString();
    },
    width: 60,
    ellipsis: true,
    filter: false,
  }

  const fixedCols = [
    // {
    //   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,
      render: (editor, record) => {
        const user = users?.filter((user)=>user.pernr===editor);
        if (user && user.length > 0) {
          return <Tooltip title={user[0].nachn?`${user[0].nachn}(${user[0].pernr})`:user[0].pernr}>
            <Text ellipsis={true}>{user[0].nachn?`${user[0].nachn}(${user[0].pernr})`:user[0].pernr}</Text>
          </Tooltip>
        }
        return editor;
      }
    },
  ]

  const actionCol = {
    title: '操作',
    dataIndex: 'action',
    width: 240,
    fixed: 'right',
    filter: false,
    render: (_, record) => {
      const authActionTitles = [];
      if ((getDataModelerRole(user)!==DataModelerRoleReader) && view!=='grant' && !isOnlyEnding && (record.editable||record.permitCheckOut)) {
        authActionTitles.push('编辑');
      }
      if ((getDataModelerRole(user)!==DataModelerRoleReader) && view!=='grant'&& !isOnlyEnding && record.deletable) {
        authActionTitles.push('删除');
      }

      if (record.odata) {
        authActionTitles.push('URI复制');
      }

      authActionTitles.push('样本数据');
      authActionTitles.push('历史版本');

      if (getDataModelerRole(user)!==DataModelerRoleReader&& view!=='grant'&&record.grantable) {
        authActionTitles.push('授权');
      }

      // if (getDataModelerRole(user)!==DataModelerRoleReader && view!=='grant' && isOnlyEnding && !currentItem?.grantable) {
      //   authActionTitles.push('申请');
      // }

      if (getDataModelerRole(user)!==DataModelerRoleReader && view!=='grant' && record.supportChangeOwn) {
        authActionTitles.push('更换管理');
      }

      if (getDataModelerRole(user)!==DataModelerRoleReader && view!=='grant' && record.serviceDefinitionType === 'empty') {
        authActionTitles.push('拖拉创建字段');
        authActionTitles.push('自定义sql创建字段');
      }

      // if (getDataModelerRole(user)!==DataModelerRoleReader && view!=='grant' && !isOnlyEnding && record.supportODataDisable) {
      //   authActionTitles.push('下载Tableau tds');
      // }

      // if (getDataModelerRole(user)!==DataModelerRoleReader && view!=='grant' && record.supportSmartBIWebSpreadSheet) {
      //   authActionTitles.push('跳转至电子表格');
      // }
      
      const authActions = actions.filter(item => authActionTitles.indexOf(item.title) !== -1);

      if (getDataModelerRole(user)!==DataModelerRoleReader && view!=='grant') {
        record.state?.supportedActions?.forEach((item, index) => {
          authActions.push({ title: item.cnName, key: `action-${index}` });
        });
      }

      const haveMore = authActions.length > 3;
      const showActions = authActions.slice(0, 3);
      const hiddenActions = authActions.slice(3, authActions.length);

      return (
        <Space size={5} split={<Divider type='vertical' style={{margin:0}} />}>
        {
          showActions.map((item, index) => {
            return (
              <div key={index} style={{ width: 50 }}>
                <a 
                  onClick={() => {handleItemClick(item.key, record)}} 
                >{item.title}</a>
              </div>
            )
          })
        }
        {
          haveMore && <Dropdown overlay={
              <Menu onClick={({ key }) => {
                handleItemClick(key, record);
              }}>
              {
                hiddenActions.map((item, index) => {
                  return (
                    <Menu.Item key={item.key} >
                      <div style={{ textAlign: 'center' }}>
                      {item.title}
                      </div>
                    </Menu.Item>
                  )
                })
              }
              </Menu>
            } 
            placement="bottomLeft"
          >
            <UnorderedListOutlined className='default' style={{ fontSize:16,cursor:'pointer', marginLeft: 5 }} />
          </Dropdown>
        }
        </Space>
      )
    }
  }

  // const [ columns, setColumns ] = useState([]);
  // const [ includePathColumns, setIncludePathColumns ] = useState([]);
  const [ pagination, setPagination ] = useState( { pageNum: 1, pageSize: 20 } );
  const [ currentItem, setCurrentItem ] = useState(null);
  const { pageNum, pageSize } = pagination;
  const [ users, setUsers ] = useState([]);

  const [modal, contextHolder] = Modal.useModal();

  const anchorId = getQueryParam(AnchorId, props.location?.search);
  const anchorTimestamp = getQueryParam(AnchorTimestamp, props.location?.search);

  const shouldScrollRef = useRef(false);

  useEffect(() => {
    getUsers();
    getAttrs();
    
    if ((modelId||'') !== '') {
      window?.addEventListener("storage", modelEventChange);
    
      return () => {
        window?.removeEventListener("storage", modelEventChange);
      }
    } 
  
    //eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  useEffect(() => {

    if ((modelId||'') === '') {
      onSelect && onSelect([]);
      
      if ((keyword||'') === '') {
        if (offset !== null) {
          const _pageNum = parseInt(offset/pageSize + ((offset%pageSize===0)?0:1));
          setPagination({...pagination, pageNum: _pageNum });
        } else {
          setPagination({...pagination, pageNum: 1 });
        }
      } else {
        setPagination({...pagination, pageNum: 1 });
      }
    } else {
      getCheckoutDataModel();
    }
    //eslint-disable-next-line react-hooks/exhaustive-deps
  }, [ catalogId, keyword, offset, modelState ]);

  useEffect(() => {
    if ((selectModelerIds||[]).length === 0) {
      setSelectedRowKeys([]);
      setSubSelectedRowKeys([]);
    }
  }, [selectModelerIds])

  useEffect(() => {

    if ((anchorId||'') !== '') {
      shouldScrollRef.current = true;
    }

    //eslint-disable-next-line react-hooks/exhaustive-deps
  }, [anchorTimestamp])

  useEffect(() => {
    if (shouldScrollRef.current) {
      SmoothScroll('a[href*="#"]');

      const _id = getQueryParam(AnchorId, props.location.search);
      var scroll = new SmoothScroll();
      var anchor = document.querySelector(`#data-model-${_id}`);

      if (anchor) {
        scroll.animateScroll(anchor);
        shouldScrollRef.current = false;
      }
    }
  })

  useEffect(() => {

    const newData = [...data];
    if (sortRule) {
      if (sortRule.order === 'ascend') {
        newData.sort((item1, item2) => {

          if (sortRule.field === 'state') {
            return (item1[sortRule.field]?.cnName||'').localeCompare(item2[sortRule.field]?.cnName||'');
          } else if (sortRule.field === 'modifiedTs') {
            return formatDate(item1[sortRule.field]).localeCompare(formatDate(item2[sortRule.field]));
          }

          return item1[sortRule.field].localeCompare(item2[sortRule.field]);
        })
      } else if (sortRule.order === 'descend') {
        newData.sort((item1, item2) => {
          if (sortRule.field === 'state') {
            return (item2[sortRule.field]?.cnName||'').localeCompare(item1[sortRule.field]?.cnName||'');
          } else if (sortRule.field === 'modifiedTs') {
            return formatDate(item2[sortRule.field]).localeCompare(formatDate(item1[sortRule.field]));
          }

          return item2[sortRule.field].localeCompare(item1[sortRule.field]);
        })
      } 
    }

    const _data = paginate(newData||[], pageNum, pageSize);

    setFilterData(_data);

    //eslint-disable-next-line react-hooks/exhaustive-deps
  }, [data, pagination, sortRule])

  const handleItemClick = (id, record) => {
    if (id === 'edit') {
      if (record?.editable) {
        editItem(record);
      } else if (record?.permitCheckOut) {
        dispatch({
          type: 'pds.checkoutService',
          payload: {
            params: {
              id: record?.id
            }
          },
          callback: data => {
            onChange && onChange(); 
            editItem(data);         
          }
        })
      }
    } else if (id === 'delete') {
      deleteItem(record);
    } else if (id === 'sample') {
      setSampleParams({visible: true, service: record})
    } else if (id === 'history') {
      historyItem(record);
    } else if (id === 'copy') {
      window.open(`/data-govern/data-model-action?${Action}=add&${CatalogId}=${(view==='dir')?(catalogId||''):''}&${ModelerId}=${record.id}`);
    } else if (id === 'createTable') {
      deployAction(record);
    } else if (id.indexOf('action') !== -1) {
      const index = (id.split('-'))[1];
      const action = record?.state?.supportedActions[index];
      stateAction(record, action);
    } else if (id === 'admit') {
      app.openAdmit?.({ dirId: catalogId, service: record })
    } else if (id === 'enableOData') {
      startODataItem(record);
    } else if (id === 'disableOData') {
      disableODataItem(record);
    } else if (id === 'startFlow') {
      app.applyServer?.({ service: record });
    } else if (id === 'downloadTds') {
      window.open(`/api/pdataservice/pdsCURD/genTDS?id=${record?.id}`);
    } else if (id === 'checkout') {
      dispatch({
        type: 'pds.checkoutService',
        payload: {
          params: {
            id: record?.id
          }
        },
        callback: () => {
          showMessage('success', '检出成功');
          onChange && onChange();          
        }
      })
    } else if (id === 'smart') {
      dispatch({
        type: 'pds.getSmartBiUrl',
        payload: {
          url: record?.smartBiWebSpreadSheetEntry
        },
        callback: (data) => {
          window.open(data)
        }
      })
    } else if (id === 'exchangeOwner') {
      setExchangeOwnerParams({ visible: true, id: record?.id });
    } else if (id === 'offline') {
      offlineService(record);
    } else if (id === 'copyUri') {
      copy(record.odata);
      showMessage('success', 'URI复制成功');
    } else if (id === 'dragAttribute') {
      app?.editServer?.({ service: record, dirId: catalogId, type: id });
    } else if (id === 'sqlAttribute') {
      app?.editServer?.({ service: record, dirId: catalogId, type: id });
    }
  }

  const detailItem = (record) => {
    // onItemAction && onItemAction(record, 'detail', getDataModelerRole(user)===DataModelerRoleReader);
    app.openDetail?.({ service: record, isOnlyEnding })
    // setServiceDetailParams({ visible: true, id: record.id })
  }

  const columns = useMemo(() => {
    let newCols = [];
    attrs?.forEach(item => {
      let col = {
        title: item.name,
        dataIndex: item.key,
        ellipsis: true,
        width: 120,
        render: (_, record) => {
          return <Tooltip title={record.basicInfo ? record.basicInfo[item.key] : ''}>
            <Text ellipsis={true}>{record.basicInfo ? record.basicInfo[item.key] : ''}</Text>
          </Tooltip>
        }
      };

      if (item.key === 'name') {
        col.render = (text, record, index) => {
          return (<ModelNameColumn text={record.basicInfo?record.basicInfo[item.key]:''} record={record} detailItem={detailItem} />);
        }; 
      }

      if (item.userSelected === true) {
        col.render = (_, record) => {
          const user = users?.filter((user)=>(user.pernr===record.basicInfo?.[item.key]));
          if (user && user.length > 0) {
            return <Tooltip title={user[0].nachn?`${user[0].nachn}(${user[0].pernr})`:user[0].pernr}>
              <Text ellipsis={true}>{user[0].nachn?`${user[0].nachn}(${user[0].pernr})`:user[0].pernr}</Text>
            </Tooltip>
          }
          return record.basicInfo?.[item.key];
        };
      }

      newCols.push(col);
    });

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

    if (!modelId) {
      newCols = [indexCol, ...newCols, ...fixedCols, actionCol];
    } else {
      newCols = [...newCols, ...fixedCols, actionCol];
    }
 
    return newCols;
  }, [visibleColNames, attrs, indexCol, actionCol, modelId, detailItem, users])

  const modelEventChange = (e) => {
    if (e.key === 'modelChange') {
      getCheckoutDataModel();
    }
  }

  const getAttrs = () => {
    dispatch({
      type: 'pds.getAttrs',
      payload: {
        modelName: 'DataService'
      },
      callback: data => {
        setAttrs(data);
      },
      error: () => {

      }
    })
  }

  const getUsers = () => {
    dispatch({
      type: 'pds.getOwners',
      callback: (data) => {
        setUsers(data);
      }
    })
  }

  const getCheckoutDataModel = () => {
    dispatch({
      type: 'pds.getCheckoutService',
      payload: {
        id: modelPid
      },
      callback: data => {
        setSubData(data?[data]:[]);
      },
      error: () => {

      }
    })
  }

  // const getDataModel = () => {
  //   dispatch({
  //     type: 'datamodel.getDataModel',
  //     payload: {
  //       id: modelId
  //     },
  //     callback: data => {
  //       setSubData(data?[data]:[]);
  //     },
  //     error: () => {

  //     }
  //   })
  // }

  const editItem = (record) => {
    // onItemAction && onItemAction(record, 'edit');
    app.editServer?.({ dirId: catalogId, service: record })
  }

  const deployAction = (record) => {
    onAutoCreateTable && onAutoCreateTable(record);
  }

  const stateAction = (record, action) => {
    modal.confirm({
      title: '提示!',
      content: `您确定要${action.cnName||''}该服务吗?`,
      onOk: () => {
        dispatch({
          type: 'pds.nextState',
          payload: {
            pdsDataServiceId: record.id,
            actionId: action.id
          },
          callback: () => {
            showMessage('success', `服务${action.cnName||''}成功`);

            if ((modelId||'') === '') {
              onChange && onChange();

              const index = selectedRowKeys.findIndex((rowKey) => rowKey === record.id);
              if (index !== -1) {
                const newSelectedRowKeys = [...selectedRowKeys];
                newSelectedRowKeys.splice(index, 1);
                setSelectedRowKeys(newSelectedRowKeys);
                onSelect && onSelect(newSelectedRowKeys);
              }
            } else {
              if (action.id === '2') {
                onChange && onChange();
              } else {
                getCheckoutDataModel();
              }
            }
            
          }
        })
      }
    });
  }

  const deleteItem = (record) => {

    modal.confirm({
      title: '提示!',
      content: '您确定要删除该服务吗?',
      onOk: () => {
        dispatch({
          type: 'pds.deleteService',
          payload: {
            params: {
              id: record.id
            }
          },
          callback: () => {
            showMessage('success', '服务删除成功');
            onChange && onChange();

            if ((modelId||'') ==='') {
              const index = selectedRowKeys.findIndex((rowKey) => rowKey === record.id);
              if (index !== -1) {
                const newSelectedRowKeys = [...selectedRowKeys];
                newSelectedRowKeys.splice(index, 1);
                setSelectedRowKeys(newSelectedRowKeys);
                onSelect && onSelect(newSelectedRowKeys);
              }
            }
            
          }
        })
      }
    });
  }

  const historyItem = (record) => {
    onHistory && onHistory(record.id);
  }

  const startODataItem = (record) => {
    modal.confirm({
      title: '提示!',
      content: '您确定要启动该服务的OData吗?',
      onOk: () => {
        dispatch({
          type: 'pds.enableOData',
          payload: {
            params: {
              pdsDataServiceId: record.id
            }
          },
          callback: () => {
            showMessage('success', '启动成功');
            onChange && onChange();          
          }
        })
      }
    });
  }

  const disableODataItem = (record) => {
    modal.confirm({
      title: '提示!',
      content: '您确定要停用该服务的OData吗?',
      onOk: () => {
        dispatch({
          type: 'pds.disableOData',
          payload: {
            params: {
              pdsDataServiceId: record.id
            }
          },
          callback: () => {
            showMessage('success', '停用成功');
            onChange && onChange();          
          }
        })
      }
    });
  }

  const offlineService = (record) => {
    modal.confirm({
      title: '提示!',
      content: '您确定要下线该服务吗?',
      onOk: () => {
        dispatch({
          type: 'pds.offlineDataService',
          payload: {
            params: {
              id: record.id
            }
          },
          callback: () => {
            showMessage('success', '下线成功');
            onChange && onChange();          
          }
        })
      }
    });
  }

  const onSelectChange = keys => {
    setSelectedRowKeys(keys);

    if ((modelId||'') !== '') {
      onSubSelect && onSubSelect(keys, subData[0].id);
    } else {
      onSelect && onSelect([...subSelectedRowKeys, ...keys]);
    }
  };

  const onSubSelectChange = (keys, id) => {
    if ((keys||[]).length === 0) {
      const index = subSelectedRowKeys.findIndex((rowKey) => rowKey === id);
      const newSubSelectedRowKeys = [...subSelectedRowKeys];
      newSubSelectedRowKeys.splice(index, 1);
      setSubSelectedRowKeys(newSubSelectedRowKeys);
      onSelect && onSelect([...newSubSelectedRowKeys, ...selectedRowKeys]);
    } else {
      const newSubSelectedRowKeys = [...subSelectedRowKeys, id];
      onSelect && onSelect([...newSubSelectedRowKeys, ...selectedRowKeys]);
    }
  }

  const onTableChange = (pagination, filters, sorter, extra) => {
    if (sorter) {
      setSortRule(sorter);
    }
  }

  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
    hideSelectAll: (modelId||'') !=='',
  };

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

  let expandable = undefined;
  let needExpand = false;

  if (!modelId) {
    (filterData||[]).forEach(record => {
      if (record?.alreadyCheckedOut) {
        needExpand = true;
      }
    })

    if (needExpand) {
      expandable = {
        expandedRowRender: record => <ModelTable
          view={view} 
          modelId={record?.checkedOutId}
          modelPid={record?.id}
          onSubSelect={onSubSelectChange}
          {...props} 
        />,
        expandIcon: ({ expanded, onExpand, record }) => {
          if (!record?.alreadyCheckedOut) return null;

          return expanded ? <UpOutlined style={{ fontSize: 10 }} onClick={e => onExpand(record, e)} /> : <DownOutlined style={{ fontSize: 10 }} onClick={e => onExpand(record, e)} />
        },
        rowExpandable: record => {
          return record?.alreadyCheckedOut;
        }
      };
    }
  } else {
    expandable = {
      expandedRowRender: record => <></>,
      expandIcon: ({ expanded, onExpand, record }) => {
        return null;
      },
      rowExpandable: record => {
        return false;
      }
    }
  }

  const displayMenu = (e) => {
    show({
      event: e
    })
  }

  const onServiceDetailClose = () => {
    setServiceDetailParams({ visible: false, id: '' })
  }

  const onSampleClose = () => {
    setSampleParams({ visible: false, service: undefined });
  }

  const onExchangeOwnerClose = (refresh = false) => {
    setExchangeOwnerParams({ visible: false, id: undefined });

    refresh && onChange?.();
  }

  let disableEdit = false, disableDelete = false, editTip = '', deleteTip = '', editMenuTitle = '编辑';

  if (!currentItem?.editable && currentItem?.state?.id!=='4') {
    disableEdit = true;

    if (currentItem?.state?.id === '2') {
      editTip = '待发布的服务不允许编辑';
    }
  }

  // if (!currentItem?.permitCheckOut && currentItem?.state?.id==='4') {
  //   disableEdit = true;
  //   editTip = `${currentItem.holder||''}正在编辑中, 不允许再编辑`;
  //   editMenuTitle = `编辑(${currentItem.holder||''}正在编辑中)`;
  // }

  if (!currentItem?.deletable) {
    disableDelete = true;

    if (currentItem?.state?.id === '2') {
      deleteTip = '待发布的服务不允许删除';
    } else if (currentItem?.state?.id === '4') {
      deleteTip = '已发布的服务不允许删除';
    }
  }

  return (
    <div className={classes}>
      <Table
        rowSelection={view!=='grant'?rowSelection:undefined} 
        rowKey={'id'}
        extraColWidth={(modelId||needExpand)?85:32}
        columns={columns||[]}
        dataSource={modelId?(subData||[]):(filterData||[])}
        pagination={false}
        size={modelId?'small':'default'}
        // rowClassName={(record, index) => 'cursor-contextmenu'}
        onRow={(record, index) => {
          return {
            id: `data-model-${record?.id}`,
            style: { backgroundColor: (record?.id===anchorId)?'#e7f7ff':'transparent' },
            onContextMenu: event => {
              setCurrentItem(record);
              // displayMenu(event);
            },
          }
        }}
        scroll={{ y: modelId?null:((filterData||[]).length===0?null:'calc(100vh - 121px - 57px - 24px - 38px - 44px)') }}
        onChange={onTableChange}
        expandable={!isOnlyEnding ? expandable : undefined}
      />
      {
        !modelId && (data||[]).length>0 && <Pagination
          className="text-center mt-3"
          showSizeChanger
          showQuickJumper
          onChange={(_pageNum, _pageSize) => {
            setPagination({ pageNum: _pageNum, pageSize: _pageSize || 20 });
          }}
          onShowSizeChange={(_pageNum, _pageSize) => {
            setPagination({ pageNum: 1, pageSize: _pageSize });
          }}
          current={pageNum}
          pageSize={pageSize}
          defaultCurrent={1}
          total={(data||[]).length}
          pageSizeOptions={[10,20,50]}
          showTotal={total => `共 ${total} 条`}
        />
      }
      <RcMenu id={MENU_ID}>
        {/* {
          (getDataModelerRole(user)!==DataModelerRoleReader) && view!=='grant' && !isOnlyEnding && <RcItem id="edit" disabled={!currentItem?.editable&&!currentItem?.permitCheckOut} onClick={handleItemClick}>
            编辑
          </RcItem>
        }
        {
          (getDataModelerRole(user)!==DataModelerRoleReader) && view!=='grant'&& !isOnlyEnding && <RcItem id="delete" disabled={!currentItem?.deletable} onClick={handleItemClick}>
            <Tooltip title={deleteTip}>
              删除
            </Tooltip>
          </RcItem>
        }
        <RcItem id="sample" onClick={handleItemClick}>
          样本数据
        </RcItem>
        <RcItem id="history" onClick={handleItemClick}>
          历史版本
        </RcItem>
        {
          getDataModelerRole(user)!==DataModelerRoleReader && view!=='grant' && (currentItem?.state?.supportedActions||[]).length>0 && currentItem?.state?.supportedActions.map((item, index) => {
            return (
              <RcItem id={`action-${index}`} onClick={handleItemClick}>
              {item.cnName||''}
              </RcItem>
            );
          }) 
        }
        {
          getDataModelerRole(user)!==DataModelerRoleReader&& view!=='grant' && <RcItem id="admit" onClick={handleItemClick} disabled={!currentItem?.grantable}>
            授权
          </RcItem>
        }
        {
          getDataModelerRole(user)!==DataModelerRoleReader && view!=='grant' && isOnlyEnding && <RcItem id="startFlow" onClick={handleItemClick} disabled={currentItem?.grantable}>
          申请
          </RcItem>
        }
        {
          getDataModelerRole(user)!==DataModelerRoleReader && view!=='grant' && !isOnlyEnding && currentItem?.supportODataEnable && <RcItem id="enableOData" onClick={handleItemClick}>
          启动OData
          </RcItem>
        }
        {
          getDataModelerRole(user)!==DataModelerRoleReader && view!=='grant' && !isOnlyEnding && currentItem?.supportODataDisable && <RcItem id="disableOData" onClick={handleItemClick}>
          停用OData
          </RcItem>
        }
        {
          getDataModelerRole(user)!==DataModelerRoleReader && view!=='grant' && !isOnlyEnding && currentItem?.supportODataDisable && <RcItem id="downloadTds" onClick={handleItemClick}>
          下载Tableau tds
          </RcItem>
        }
        {
          getDataModelerRole(user)!==DataModelerRoleReader && view!=='grant' && currentItem?.supportSmartBIWebSpreadSheet && <RcItem id="smart" onClick={handleItemClick}>
          跳转至电子表格
          </RcItem>
        }
        {
          getDataModelerRole(user)!==DataModelerRoleReader && view!=='grant' && currentItem?.supportChangeOwn && <RcItem id="exchangeOwner" onClick={handleItemClick}>
          更换管理
          </RcItem>
        } */}

      </RcMenu>
      <ServiceDetail visible={serviceDetailParams.visible} id={serviceDetailParams.id} onClose={onServiceDetailClose} />
      <SampleModal visible={sampleParams.visible} service={sampleParams.service} onCancel={onSampleClose} />
      <ExchangeOwnerModal visible={exchangeOwnerParams.visible} id={exchangeOwnerParams.id} onCancel={onExchangeOwnerClose} />

      { contextHolder }
    </div>
  );
}

export default ModelTable;