import React,{ useState, useEffect, useRef, useContext, useMemo } from "react";
import { Button, Pagination, Space, Modal, Input, Table, Tooltip, Checkbox, Typography, Dropdown, Menu, Divider, Select } from "antd";
import classNames from 'classnames';
import { Resizable } from 'react-resizable';
import ResizeObserver from 'rc-resize-observer';
import { useContextMenu, Menu as RcMenu, Item as RcItem } from "react-contexify";
import LocalStorage from 'local-storage';

import FilterElementModal from './FilterElementModal';
import AssetMount from '../../AssetRecycle/Component/AssetMount';
import ImportAssetDrawer from './ImportAssetDrawer';
import AssetEdit from './AddAssetModel';
import AssetDetailDrawer from "./AssetDetailDrawer";
import { dispatch, dispatchLatestHomepage } from '../../../../model';
import { showMessage, showNotifaction, getQueryParam, inputWidth, isSzseEnv } from '../../../../util';
import { AnchorId, AnchorDirId, AnchorTimestamp, AssetBrowseReference, AssetManageReference, AssetRecycleReference, ResourceBrowseReference } from '../../../../util/constant';
import { FullScreenSvg, CancelFullScreenSvg } from './AssetSvg';
import AssetDeleteModal from './AssetDeleteModal';
import { AppContext, appId } from "../../../../App";
import StartFlowModal from "./StartFlow";
import TagColumnConnect from "../../Tag";

import "./AssetTable.less";
import 'react-contexify/dist/ReactContexify.css';
import { getTemplateType } from "../../../../util/axios";
import { UserItem } from "./AssetAction";

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

//资产项
export const AssetItem = (props) => {
  const { metadata } = props;
  const app = useContext(AppContext);

  let content = '';
  if (typeof metadata==='string') {
    content = metadata;
  } else {
    (metadata?.columnItems||[]).forEach((item, index) => {
      content += ((index===0)?'':',') + (((item.metadataColumnCnName||'')!=='')?(item.metadataColumnCnName||''):(item.metadataColumnName||''));
    })
  }

  const cols = [
    {
      title: '序号',
      dataIndex: 'key',
      render: (text, record, index) => {
        return (index+1).toString();
      },
      width: 60,
      ellipsis: true,
    },
    {
      title: '名称',
      width: 160,
      dataIndex: 'metadataColumnCnName',
      editable: true,
      ellipsis: true,
    },
    {
      title: '技术ID(英文名称)',
      width: 160,
      dataIndex: 'metadataColumnName',
      editable: true,
      ellipsis: true,
    },
  ];

  return (
    <Tooltip 
      overlayClassName='tooltip-common'
      title={(typeof metadata==='string') ? (content||'') : <div style={{ width: 500, maxHeight: 300, overflow: 'auto' }}>
        <Table 
          dataSource={metadata?.columnItems||[]}
          columns={cols}
          loading={false}
          pagination={false}
          size='small'
        />
      </div>}
    >
      <Text ellipsis={true}>
      {
        (typeof metadata==='string') ? (content||'') : <a onClick={(e) => {
          e?.stopPropagation()
          app?.setGlobalState?.({
            message: 'data-govern-show-metadata-message',
            data: metadata
          })
        }}>
          { metadata?.tableEnName??metadata?.tableCnName }
        </a>
      }
      </Text>
    </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 AssetTable = (props) => {
  console.log('AssetTableProps',props);
  
  const { className, nodeId, nodeType, nodeLevel, elementsChanged, assetActionChanged, onSelect, onCountChange, reference = AssetManageReference, onFullScreenChange,myAssets } = props;

  const MENU_ID = 'asset-table';

  const { show } = useContextMenu({
    id: MENU_ID,
  });

  const [ loading, setLoading ] = useState(false);
  const [ columns, setColumns ] = useState([]);
  const [ realColumns, setRealColumns ] = useState([]);
  const [ assets, setAssets ] = useState([]);
  const [ total, setTotal ] = useState(0);
  const [ selectItem, setSelectItem ] = useState({});
  const [ contextMenuItem, setContextMenuItem ] = useState({});

  const [ checkedKeys, setCheckedKeys ] = useState([]);
  const [ importAssetVisible, setImportAssetVisible ] = useState(false);
  const [ filterElementVisible, setFilterElementVisible ] = useState(false);
  const [ assetEditVisible, setAssetEditVisible ] = useState(false);
  const [ assetDetailDrawerVisible, setAssetDetailDrawerVisible ] = useState(false);
  // const [ currentAssetId, setCurrentAssetId ] = useState('');
  const [ pagination, setPagination ] = useState( { pageNum: 1, pageSize: 20 } );
  const { pageNum, pageSize } = pagination;
  const [ keyword, setKeyword ] = useState('');
  const [ fullScreen, setFullScreen ] = useState(false);
  const [ recursive, setRecursive ] = useState(true);
  const [ fullSearch, setFullSearch ] = useState(false);
  const [ TableWidth, setTableWidth ] = useState(0);
  const [ compact, setCompact ] = useState(false);
  const [ assetDeleteModalVisible, setAssetDeleteModalVisible ] = useState(false);
  const [ startFlowModalVisible, setStartFlowModalVisible ] = useState(false);
  const [ users, setUsers ] = useState([]);
  const [ assetMountParam, setAssetMountParam ] = useState({
    visible: false,
    ids: undefined
  })
  const [loadingTemplates, setLoadingTemplates] = useState(false)
  const [templates, setTemplates] = useState()
  const [currentTemplateType, setTemplateType] = useState()
  const [sorter, setSorter] = useState()
  const [elements, setElements] = useState()
  const [mouseEnterKey,setMouseEnterKey] = useState(null)
  const [tableReload,setTableReload] = useState(null)

  const [ modal, contextHolder ] = Modal.useModal();
  const anchorId = getQueryParam(AnchorId, props?.location?.search);
  const timestamp = getQueryParam(AnchorTimestamp, props?.location?.search);
  const anchorDid = getQueryParam(AnchorDirId, props?.location?.search);

  const shouldScrollRef = useRef(false);
  const metadataIndexRef = useRef('');
  const remoteRelationRef = useRef(null);

  const mountRef = useRef(true)

  const app = useContext(AppContext)

  console.log(app)

  const actionCol = {
    title: '操作',
    dataIndex: 'action',
    width: 120,
    fixed: 'right',
    filter: false,
    render: (_, record) => {
      return (
        <Space size={5} split={<Divider type='vertical' style={{margin:0}} />}>
        {
          (reference===AssetManageReference||(reference===AssetBrowseReference&&record.hasPermission)) && <a onClick={(e) => {
            e.stopPropagation();
            handleItemClick('authorization', record);
          }}>授权</a>
        }
        {
          (reference===AssetManageReference||(reference===AssetBrowseReference&&record.hasPermission)) && <a onClick={(e) => {
            e.stopPropagation();
            setAssetMountParam({
              visible: true,
              ids: [record.id]
            });
          }}>变更目录</a>
        }
        </Space>
      )
    }
  }

  const tagColumns={
    title:"标签", 
    key:"tag",
    dataIndex:"tag",
    width:200,
    onCell:(record)=>{
        return ({ 
            onMouseEnter: (event) => {
                setMouseEnterKey(record._id);
            }, 
            onMouseLeave: (event) => {
                setMouseEnterKey(null);
            },
        })
    },
    render:(_,record)=>{
        const payload = {id:record.id,type:'dataAsset',reload:tableReload,creator:app.user?.userName}
        console.log('payload',payload)
        return (record._id===mouseEnterKey)?<TagColumnConnect {...{...payload,styleType:'complex'}}  />:<TagColumnConnect {...payload} />
    }
  }

  useEffect(() => {
    if (TableWidth>0 && columns.length>0 && (elements??[]).length>0) {
      const newColumns = [...columns??[]].map((column)=>{
        return ({...column,onCell:(record)=>{
          return({
            onClick: (e) => {
              setSelectItem(record);
              onSelect && onSelect(record?.id, record?.dirId);

              setAssetDetailDrawerVisible(true);
            },
          })
        }})
      });
      const currentWidth = (newColumns.reduce((preVal, col) => (col.width?col.width:0) + preVal, 0)) + 32.0;

      newColumns.forEach(column => {
        if (currentWidth < TableWidth) {
          column.width = (TableWidth - 32.0)/newColumns.length;
        }

        const index = (elements??[]).findIndex(item => item.name === column.title)

        if (index !== -1) {
          const tmp = (elements[index].optional??'').split(',')

          if ((tmp??[]).indexOf('用户列表')!==-1) {
            column.render = (text, record) => {
              return <UserItem readonly={true} value={text||''} users={users} multiple={elements[index].selectMode==='多选'} showTooltip={true} />
            } 
          }
        }
      })

      setRealColumns([...newColumns,tagColumns, <Column key='auto' />]);
    } else {
      setRealColumns([]);
    }

  }, [columns, TableWidth, elements, users, mouseEnterKey, tableReload])

  useEffect(() => {
    getUsers();
    if (reference === AssetRecycleReference) {
      getTemplates()
    }

    window?.addEventListener("storage", storageChange);

    return () => {
      window?.removeEventListener("storage", storageChange);
    }

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

  useEffect(() => {
    if (nodeId) {
      setSelectItem({});
      setCheckedKeys([]);
  
      if (shouldScrollRef.current === true) {
        if (remoteRelationRef.current) {
          getDataAssetLocationByRelation();
        } else {
          getDataAssetLocation();
        }
  
      } else {
        setPagination({ ...pagination, pageNum: 1 });
      }
    }
    //eslint-disable-next-line react-hooks/exhaustive-deps
  }, [ nodeId ])

  useEffect(() => {

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

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

  useEffect(() => {
    if (reference !== AssetRecycleReference && nodeId !== null) {
      getFilterElementsGroupThenGetDataAssets();
    } 
    //eslint-disable-next-line react-hooks/exhaustive-deps
  }, [ keyword, pagination, elementsChanged, assetActionChanged, recursive, fullSearch, sorter ])

  useEffect(() => {
    if (reference === AssetRecycleReference) {
      if (!mountRef.current) {
        getFilterElementsGroupThenGetDataAssets()
      }

      if (mountRef.current) {
        mountRef.current = false
      }
    }
    //eslint-disable-next-line react-hooks/exhaustive-deps
  }, [ keyword, pagination, elementsChanged ])

  const storageChange = (e) => {
    if (e.key === 'assetRelationOnClickEvent') {
      remoteRelationRef.current = e.relation;
      shouldScrollRef.current = true;
    } else if (e.key === 'assetPathOnClickEvent') {
      remoteRelationRef.current = {
        dataAssetId: e.id,
        dirId: e.dirId
      };  
      shouldScrollRef.current = true;
    } else if (e.key === 'assetTemplateChange') {
      getElements()
    }
  }

  const getTemplates = () => {
    setLoadingTemplates(true)
    dispatch({
      type: 'assetmanage.getTemplates',
      callback: data => {
        setLoadingTemplates(false)
        setTemplates(data)
        if ((data??[]).length > 0) {
          setTemplateType(data[0].type)
          LocalStorage.set(`templateType-${appId}`, data[0].type)
          let event = new Event('storage');
          event.key = 'assetTemplateChange';
          window?.dispatchEvent(event);

          getFilterElementsGroupThenGetDataAssets();
        }
      },
      error: () => {
        setLoadingTemplates(false)
      }
    })
  }

  const getElements = () => {
    dispatch({
      type: 'assetmanage.listElements',
      callback: data => {
        setElements(data)
      }
    })
  }

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

  const getDataAssetLocationByRelation = () => {
    setLoading(true);
    dispatch({
      type: 'assetmanage.getDataAssetLocation',
      payload: {
        dataAssetId: remoteRelationRef.current?.dataAssetId,
        dirId: remoteRelationRef.current?.dirId,
      },
      callback: data => {
        const anchorLocation = data.offset;
        const _pageNum = parseInt(anchorLocation/pageSize + ((anchorLocation%pageSize===0)?0:1));
        setPagination({ ...pagination, pageNum: _pageNum });
      },
      error: () => {
        setLoading(false);

        remoteRelationRef.current = null;
        setPagination({ ...pagination, pageNum: 1 });
      }
    });
  }

  const getDataAssetLocation = () => {
    setLoading(true);
    dispatch({
      type: 'assetmanage.getDataAssetLocation',
      payload: {
        dataAssetId: anchorId||'',
        dirId: anchorDid||'',
      },
      callback: data => {
        const anchorLocation = data.offset;
        const _pageNum = parseInt(anchorLocation/pageSize + ((anchorLocation%pageSize===0)?0:1));
        setPagination({ ...pagination, pageNum: _pageNum });
      },
      error: () => {
        setLoading(false);
        setPagination({ ...pagination, pageNum: 1 });
      }
    });
  }

  const changeCurrent = (page,size) => {
    setCheckedKeys([]);
    setPagination({ pageNum: page, pageSize: size });
  }

  const getFilterElementsGroupThenGetDataAssets = () => {
    setLoading(true);
    dispatch({
      type: 'assetmanage.listFilterElementsGroupByType',
      payload: {
        isAdmin: (reference===AssetManageReference)
      },
      callback: data => {
        let _columns = [];

        let index = 0, _metadataIndex = '';
        (data||[]).forEach(group => {
          (group.names||[]).forEach((name, i) => {

            index++;
            const params = {
              title: name,
              dataIndex: `element${index}`,
              ellipsis: true,
              width: 120,
              sorter: (reference !== AssetRecycleReference),
              render: (text, record) => {
                return (
                  <Tooltip title={text||''}>
                    <Text ellipsis={true}>
                    {text||''}
                    </Text>
                  </Tooltip>
                );
              }
            };

            if (name === '编号') {
              params.width = 60;
              // params.fixed = 'left';
            } else if (name === '中文名称') {
              params.width = isSzseEnv?230:160;
              // params.fixed = 'left';
            } else if (name === '英文名称') {
              params.width = isSzseEnv?224:160;
              // params.fixed = 'left';
              // params.render = (text, record) => {
              //   return (
              //     <Tooltip title={text||''}>
              //       <a onClick={()=>{detailAsset(record);}}>
              //       {text||''}
              //       </a>
              //     </Tooltip>
              //   );
              // }
            } else if (name === '资产项') {
              params.width = isSzseEnv?250:120;

              params.render = (metadata, _) => {
                return (
                  <AssetItem metadata={metadata} />
                );
              }

              _metadataIndex = `element${index}`;
            } else if (name === '资产目录路径') {
              params.render = (text, record) => {
                return (
                  <Tooltip title={text||''}>
                    <Text ellipsis={true}>
                      <a onClick={()=>{
                        let event = new Event('storage');
                        event.key = 'assetDirChangeEvent';
                        event.dirId = record.dirId||'';
                        window?.dispatchEvent(event);
                      }}>
                      {text||''}
                      </a>
                    </Text>
                  </Tooltip>
                );
              }
            }

            _columns.push(params);
          })
        })

        setAssets([]);

        setColumns(_columns);

        metadataIndexRef.current = _metadataIndex;

        getDataAssets(_metadataIndex);
      },
      error: () => {
        setLoading(false)
      }
    })
  }

  const getDataAssets = (projectIndex = metadataIndexRef.current) => {
    setLoading(true);

    let order = '';
    if (sorter?.order === 'ascend') {
      order ='asc'
    } else if (sorter?.order === 'descend') {
      order = 'desc'
    }

    let params = {
      dirId: nodeId,
      pageNum,
      pageSize,
      keyword: encodeURIComponent(keyword),
      orderName: sorter?.column?.title??'',
      order: order,
      filterByMyPermission: myAssets
    };

    if (reference !== AssetRecycleReference) {
      params.recursive = recursive;

      //全局搜索资产
      if (fullSearch) {
        params.dirId = '';
      }
    }

    let url = 'assetmanage.listDataAssetsByPage';
    if (reference===AssetRecycleReference) {
      url = 'assetmanage.listRecycleBinDataAssetsByPage';
    } else if ((reference===AssetBrowseReference|| reference===ResourceBrowseReference)) {
      params.checkPermission = true;

      if (nodeType === 'custom') {
        url = 'assetmanage.listDataAssetsByPersonalCustomType';
        if (reference === AssetBrowseReference) {
          params.resourceType = 'dataAsset';
        } else if (reference === ResourceBrowseReference) {
          params.resourceType = 'innerSource,outerSource';
        }
      }
    }

    dispatchLatestHomepage({
      type: url,
      payload: params,
      callback: data => {
        const _assets = [];

        (data.data||[]).forEach(asset => {

          let _asset = {...asset}, index = 0;
          (asset.elementValues||[]).forEach((elementValue) => {

            (elementValue.values||[]).forEach((value, i) => {

              index++;

              if (projectIndex === `element${index}`) {
                let metadata = {};
                try {

                  metadata = JSON.parse(value);
                  _asset['metadata'] = metadata;
                  _asset[`element${index}`] = metadata;
                } catch(error) {
                  metadata = value;
                  _asset['metadata'] = metadata;
                  _asset[`element${index}`] = metadata;
                }
              } else {
                _asset[`element${index}`] = value;
              }
            });
          })

          _assets.push(_asset);
        })
        
        setAssets(_assets);

        if (shouldScrollRef.current) {
          let scrollId = null;
          if (remoteRelationRef.current) {
            scrollId = remoteRelationRef.current.dataAssetId;
          } else {
            scrollId = anchorId;
          }

          shouldScrollRef.current = false;

          setTimeout(() => {
            var anchor = document.querySelector(`#data-asset-${scrollId}`);
            anchor?.scrollIntoView();
          }, 500)
        }

        // if (reference === AssetManageReference) {
        //   if (remoteRelationRef.current) {
        //     const index = _assets.findIndex((asset) => asset.id === remoteRelationRef.current.dataAssetId);

        //     remoteRelationRef.current = null;

        //     if (index === -1) {
        //       setSelectItem(_assets.length>0?_assets[0]:{});
        //       onSelect && onSelect(_assets.length>0?_assets[0].id:'', _assets.length>0?_assets[0].dirId:'');
        //     } else {
        //       setSelectItem(_assets[index]);
        //       onSelect && onSelect(_assets[index].id, _assets[index].dirId);
        //     }
        //   } else if ((selectItem?.id||'') !=='') {
        //     const index = _assets.findIndex((asset) => asset.id === selectItem?.id);
  
        //     if (index === -1) {
        //       setSelectItem(_assets.length>0?_assets[0]:{});
        //       onSelect && onSelect(_assets.length>0?_assets[0].id:'', _assets.length>0?_assets[0].dirId:'');
        //     }
        //   } else {
        //     setSelectItem(_assets.length>0?_assets[0]:{});
        //     onSelect && onSelect(_assets.length>0?_assets[0].id:'', _assets.length>0?_assets[0].dirId:'');
        //   }
        // }

        setTotal(data.total||0);
        onCountChange && onCountChange(data.total||0);
        setLoading(false);
      },
      error: () => {
        setLoading(false)
      }
    })
  }

  const onSearchInputChange = (value) => {
    setKeyword(value||'');
    setPagination({ ...pagination, pageNum: 1 });
  }

  const addAsset =()=>{
    setAssetEditVisible(true);
  }

  const onAssetEditCancel=(refresh = false) => {
    setAssetEditVisible(false);
    refresh && getDataAssets();
  }

  const onAssetMountCancel = (refresh = false) => {
    setAssetMountParam({
      visible: false,
      ids: undefined
    });

    if (refresh) {
      setCheckedKeys([]);
      getDataAssets();

      showMessage('success', (reference === AssetRecycleReference)?'挂载成功':'变更目录成功');
    }
  }

  const importAsset = () => {
    setImportAssetVisible(true);
  }

  const onFilterElementClick = () => {
    setFilterElementVisible(true);
  }

  const onRecursiveChange = (e) => {
    setRecursive(!e.target.checked);
  }

  const onFullSearchChange = (e) => {
    setFullSearch(e.target.checked);
  }

  const exportAsset = () => {
    if ((checkedKeys||[]).length === 0) {
      modal.confirm({
        title: '提示',
        content: '是否导出所有资产目录?',
        onOk: () => {
          window.open(`/api/dataassetmanager/dataAssetApi/exportByDataAssetIds?exportAll=true&templateType=${getTemplateType()}`);
        }
      })
    } else {
      window.open(`/api/dataassetmanager/dataAssetApi/exportByDataAssetIds?dataAssetIds=${checkedKeys.join(',')}&templateType=${getTemplateType()}`);
    }
  }

  const subscriptAsset = () => {
    if ((checkedKeys||[]).length === 0) return;
 
    modal.confirm({
      title: '提示',
      content: '是否确认订阅选中资产目录?',
      onOk: () => {
        let payload = {
          dataAssetIds: (checkedKeys||[]).join(','),
          env: app?.env?.domainId
        }

        dispatch({
          type: 'assetmanage.subs',
          payload,
          callback: () => {
            showMessage("success","订阅成功");
            setCheckedKeys([]);
          },
          error: () => {
          }
        })
      }
    })
  }

  // const detailAsset = (item)=>{
  //   setCurrentAssetId(item.id);
  //   window.open(`/center-home/asset-detail?id=${item.id}&dirId=${nodeId}`);
  // }

  const deleteAssets = () => {
    if ((checkedKeys||[]).length === 0) return;

    modal.confirm({
      title: '提示',
      content: '您确定要下线这些资产目录吗?',
      onOk: () => {
        let payload = {
          data: checkedKeys
        }

        dispatch({
          type: (reference===AssetManageReference)?'assetmanage.unloadDataAssetsFromAllDirs':'assetmanage.deleteDataAssets',
          payload,
          callback: () => {
            showMessage("success","下线成功");
            getDataAssets();
            setCheckedKeys([]);
          },
          error: () => {
          }
        })
      }
    })
  }

  const onImportAssetCancel = () => {
    setImportAssetVisible(false);
  }

  const onImportAssetSuccess = (tip = '') => {
    getDataAssets();

    // if ((tip||'') !== '') {
    //   showNotifaction('导入提示', tip, 5);
    // }
  }

  const onFilterElementModalCancel = (refresh = false) => {
    setFilterElementVisible(false);
    refresh && getFilterElementsGroupThenGetDataAssets();
  }

  const onAssetDetailDrawerCancel = (refresh = false) => {
    setAssetDetailDrawerVisible(false);
    refresh && getDataAssets();
  }

  const onBatchCatalogChangeBtnClick = () => {
    if ((checkedKeys||[]).length===0) return;
    
    setAssetMountParam({
      visible: true,
      ids: checkedKeys
    });
  }

  const onAssetDeleteModalCancel = () => {
    setAssetDeleteModalVisible(false);
  }

  const onAssetDeleteModalDelete = () => {
    setAssetDeleteModalVisible(false);

    const asssetIdsAndDirIds = [];

    (assets||[]).forEach(asset => {
      if (checkedKeys.indexOf(asset.id) !== -1) {
        asssetIdsAndDirIds.push({ dataAssetId: asset.id||'', dirId: asset.dirId||'' });
      }
    })

    let payload = {
      data: asssetIdsAndDirIds
    };

    dispatch({
      type: 'assetmanage.unloadDataAssets',
      payload,
      callback: () => {
        showMessage("success","删除成功");
        getDataAssets();
        setCheckedKeys([]);
      }
    })
  }

  const onAssetDeleteModalDeleteAll = () => {
    setAssetDeleteModalVisible(false);

    let payload = {
      data: checkedKeys
    };

    dispatch({
      type: 'assetmanage.unloadDataAssetsFromAllDirs',
      payload,
      callback: () => {
        showMessage("success","删除成功");
        getDataAssets();
        setCheckedKeys([]);
      }
    })
  }

  const recoveryAssets = () => {
    if ((checkedKeys||[]).length > 0) {
      modal.confirm({
        title: '提示',
        content: '您确定要恢复这些资产目录吗?',
        onOk: () => {
          let payload = {
            data: checkedKeys
          }
      
          dispatch({
            type: 'assetmanage.recoveryFromRecycleBin',
            payload,
            callback: () => {
              showMessage("success","恢复成功");
              getDataAssets();
              setCheckedKeys([]);
            }
          })
        }
      })
    }else{
      showMessage("warn","请选择资产目录");
    }
  }

  const onSelectChange = keys => {
    setCheckedKeys(keys);
  };

  const onFullScreenClick = () => {
    setFullScreen(!fullScreen);
    onFullScreenChange && onFullScreenChange(!fullScreen);
  }

  const onStartFlowClick = () => {
    setStartFlowModalVisible(true);
  }

  const onStartFlowModalCancel = (refresh = false) => {
    setStartFlowModalVisible(false);
    if (refresh) {
      setCheckedKeys([]);
    }
  }

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

    setRealColumns(nextColumns);
  };

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

  const handleItemClick = (id, record) => {
    if (id === 'uncombed') {
      modal.confirm({
        title: '提示',
        content: '是否将该条非资产目录的资源转为未梳理状态?',
        onOk: () => {
          dispatch({
            type: 'assetmanage.updateResourceState',
            payload: {
              params: {
                dataAssetId: record.id,
                resourceState: 'uncombed'
              }
            },
            callback: () => {
              LocalStorage.set('assetResourceChange', !(LocalStorage.get('assetResourceChange')||false));
              let event = new Event('storage');
              event.key = 'assetResourceChange';
              window?.dispatchEvent(event);
              
              getDataAssets();
            }
          });
        }
      });
    } else if (id === 'notRelatedAsset') {
      modal.confirm({
        title: '提示',
        content: '是否将该条未梳理的资源转为非资产目录?',
        onOk: () => {
          dispatch({
            type: 'assetmanage.updateResourceState',
            payload: {
              params: {
                dataAssetId: record.id,
                resourceState: 'notRelatedAsset'
              }
            },
            callback: () => {
              LocalStorage.set('assetResourceChange', !(LocalStorage.get('assetResourceChange')||false));
              let event = new Event('storage');
              event.key = 'assetResourceChange';
              window?.dispatchEvent(event);

              getDataAssets();
            }
          });
        }
      });
    } else if (id === 'authorization') {
      if (record.metadata?.metadataTableId) {
        app?.setGlobalState && app?.setGlobalState({
          message: 'data-govern-assets-admit',
          data: record
        })
      } else {
        showMessage("warn","该资产目录没有关联元数据信息");
      }
    }
  }

  const moreMenu = (
    <Menu>
      {
        // (reference===AssetManageReference) && 
        //   <Menu.Item disabled={(checkedKeys||[]).length===0}>
        //     <div className='text-center' onClick={onStartFlowClick}>
        //       申请
        //     </div>
        //   </Menu.Item>
      }
      {
        (reference!==AssetRecycleReference) && 
          <Menu.Item disabled={(checkedKeys||[]).length===0}>
            <div className='text-center' onClick={subscriptAsset}>
              订阅
            </div>
          </Menu.Item>
      }

      {
        (reference===AssetManageReference || reference===AssetRecycleReference) && <React.Fragment>
          <Menu.Item disabled={(checkedKeys||[]).length===0}>
            <div className='text-center' onClick={onBatchCatalogChangeBtnClick}>
            {(reference===AssetRecycleReference)?'挂载':'变更目录'}
            </div>
          </Menu.Item>
          {
            //自定义目录下的资产不允许新增 删除
            (nodeType!=='custom') && <Menu.Item disabled={(checkedKeys||[]).length===0}>
              <div className='text-center' onClick={deleteAssets}>
                删除
              </div>
            </Menu.Item>
          }
        </React.Fragment>
      }
      
      <Menu.Item>
        <div className='text-center' onClick={onFilterElementClick}>
          可见列设置
        </div>
      </Menu.Item>
    </Menu>
  );

  const rowSelection = {
    selectedRowKeys: checkedKeys,
    onChange: onSelectChange,
  };

  const classes = classNames('asset-list', className, {
    'asset-list-fullscreen': fullScreen,
  });  

  let scrollY = null;
  if ((assets||[]).length>0) {
    if (fullScreen) {
      scrollY = 'calc(100vh - 209px - 72px)';
    } else if (reference===AssetManageReference) {
      scrollY = 'calc(100vh - 209px - 72px)';
    } else if (reference===AssetBrowseReference ||reference===ResourceBrowseReference) {
      scrollY = 'calc(100vh - 209px - 72px)';
    } else if (reference===AssetRecycleReference) {
      scrollY = 'calc(100vh - 209px - 72px)';
    }
  }

  return(
    <div className={classes}> 
      <div
        className='flex p-3'
        style={{
          alignItems: 'center',
          justifyContent: 'space-between',
          borderBottom: '1px solid rgb(239, 239, 239)',
        }}
      > 
    <Space size={15}>
      {myAssets ? (
        // 当 myAssets 为 true 时，只显示可见列设置按钮
        <Button onClick={onFilterElementClick}>可见列设置</Button>
      ) : (
        // 当 myAssets 为 false 时，显示所有按钮
        <>
          { 
            //栏目和自定义目录 不允许新增资产
            // (reference===AssetManageReference && nodeLevel!==1 && nodeType!=='custom') && <Button onClick={addAsset}>新增</Button>
          }

          {
            reference === AssetRecycleReference && <Select 
              loading={loadingTemplates}
              value={currentTemplateType}
              onChange={(val) => {
                setTemplateType(val)
                LocalStorage.set(`templateType-${appId}`, val);
                let event = new Event('storage');
                event.key = 'assetTemplateChange';
                window?.dispatchEvent(event);

                setPagination({ ...pagination, pageNum: 1 });
              }}
              style={{ width: 100 }}
            >
            {
              (templates??[]).map((item, index) => <Select.Option key={index} value={item.type}>{item.name}</Select.Option>)
            }
            </Select>
          }

          { 
            (reference===AssetManageReference && nodeType!=='custom') && <Button onClick={importAsset}>导入</Button>
          }
          {
            (reference===AssetManageReference || reference===AssetRecycleReference) && 
              <Tooltip>
                <Button onClick={exportAsset} >导出</Button>
              </Tooltip>
          }

          {
            (compact && reference!==AssetRecycleReference) ? <Dropdown overlay={moreMenu} placement="bottomCenter"> 
              <Button>其他操作</Button>
            </Dropdown> : <React.Fragment>
              {
                (reference!==AssetRecycleReference) &&
                  <Tooltip title={(checkedKeys||[]).length===0?'请先选择资产目录':''}>
                    <Button onClick={subscriptAsset} disabled={(checkedKeys||[]).length===0} >订阅</Button>
                  </Tooltip>
              }

              {
                (reference===AssetManageReference || reference===AssetRecycleReference) && <React.Fragment>
                  <Tooltip title={(checkedKeys||[]).length===0?'请先选择资产目录':''}>
                    <Button onClick={onBatchCatalogChangeBtnClick} disabled={(checkedKeys||[]).length===0} >{(reference===AssetRecycleReference)?'挂载':'变更目录'}</Button>
                  </Tooltip>
                  {
                    (reference===AssetRecycleReference) && <Tooltip title={(checkedKeys||[]).length===0?'请先选择资产目录':''}>
                      <Button onClick={recoveryAssets} disabled={(checkedKeys||[]).length===0} >恢复</Button>
                    </Tooltip>
                  }
                  {
                    //自定义目录下的资产不允许删除
                    (nodeType!=='custom') && <Tooltip title={(checkedKeys||[]).length===0?'请先选择资产目录':''}>
                      <Button onClick={deleteAssets} disabled={(checkedKeys||[]).length===0} >下线</Button>
                    </Tooltip>
                  }
                </React.Fragment> 
              }
              <Button onClick={onFilterElementClick}>可见列设置</Button>
            </React.Fragment>
          }
        </>
      )}
    </Space>
    <Space>
      <Search 
        placeholder="请输入资产目录要素值" 
        allowClear 
        onSearch={onSearchInputChange} 
        enterButton
        style={{ width: inputWidth }}
      />
      {
        (reference!==AssetRecycleReference) && <Tooltip title={fullScreen?'取消全屏':'全屏'}>
          <Button onClick={onFullScreenClick} icon={fullScreen?<CancelFullScreenSvg style={{ width: 20, height: 20 }} />:<FullScreenSvg style={{ width: 20, height: 20 }} />} type='text'></Button>
        </Tooltip>
      }
    </Space>
      </div>
      <div
        className='p-3'
      >
        <ResizeObserver
          onResize={({ width }) => {
            setTableWidth(width);

            if (width < 1030 && !compact) {
              setCompact(true);
            } else if (width >= 1030 && compact) {
              setCompact(false);
            }
          }}
        >
          <Table
            rowSelection={rowSelection}
            components={{
              header: {
                cell: ResizeableHeaderCell,
              }
            }}
            onRow={(record) => {
              return {
                id: `data-asset-${record?.id}`,
                onContextMenu: event => {
                  // if ((reference===AssetManageReference||(reference===AssetBrowseReference&&record.hasPermission)) && (record.resourceState==='uncombed'||record.resourceState==='notRelatedAsset')) {
                  //   setContextMenuItem(record);
                  //   displayMenu(event);
                  // }
                },
              }
            }}
            rowClassName={(record, index) => {
              let classNames = [];
              // if (reference===AssetManageReference && (record.resourceState==='uncombed'||record.resourceState==='notRelatedAsset')) {
              //   classNames.push('cursor-contextmenu');
              // }

              if (record?.id===anchorId || record?.id===selectItem?.id) {
                classNames.push('yy-table-select-row');
              }

              return classNames.join(' ');
            }}
            loading={loading}
            columns={
              (realColumns||[]).map((column, index) => { 
                return {
                  ...column,
                  onHeaderCell: column => ({
                    width: column.width,
                    onResize: handleResize(index),
                  }),
                };
              })
            } 
            rowKey='id'
            dataSource={assets}
            pagination={false}
            size='default'
            scroll={{ y: scrollY }}
            onChange={(pagination, filters, sorter, extra) => {
              if (extra?.action === 'sort') {
                console.log('sorter', sorter)
                setSorter(sorter)
              }
            }}
          />
        </ResizeObserver>
      
        <Pagination
          className="text-center mt-3"
          showSizeChanger
          onChange={changeCurrent}
          onShowSizeChange={changeCurrent}
          current={pageNum}
          pageSize={pageSize}
          defaultCurrent={1}
          total={total}
          showTotal={total => `共 ${total} 条`}
        />
      </div> 

      <AssetEdit 
        visible={assetEditVisible}
        nodeId={nodeId}
        onCancel={onAssetEditCancel}
      />
      <ImportAssetDrawer 
        visible={importAssetVisible}
        nodeId={nodeId}
        onCancel={onImportAssetCancel}
        onSuccess={onImportAssetSuccess}
      />
      <AssetMount
        visible={ assetMountParam.visible }
        reference={reference}
        ids={ assetMountParam.ids }
        onCancel={ onAssetMountCancel }
        {...props}
      />
      <FilterElementModal
        type={(reference===AssetManageReference)?'admin': 'user'}
        reference={reference}
        visible={ filterElementVisible }
        onCancel={ onFilterElementModalCancel}
      />
      <AssetDetailDrawer 
        id={selectItem?.id}
        dirId={selectItem?.dirId}
        visible={assetDetailDrawerVisible}
        reference={reference}
        onCancel={onAssetDetailDrawerCancel}
      />
      <AssetDeleteModal 
        visible={assetDeleteModalVisible}
        onCancel={onAssetDeleteModalCancel}
        onDelete={onAssetDeleteModalDelete}
        onDeleteAll={onAssetDeleteModalDeleteAll}
      />
      <StartFlowModal
        visible={startFlowModalVisible}
        ids={checkedKeys||[]}
        onCancel={onStartFlowModalCancel}
      />
      <RcMenu id={MENU_ID}>
        {/* {
          (contextMenuItem.resourceState==='notRelatedAsset') && <RcItem id="uncombed" onClick={handleItemClick}>
            转为未梳理
          </RcItem>
        }
        {
          (contextMenuItem.resourceState==='uncombed') && <RcItem id="notRelatedAsset" onClick={handleItemClick}>
            转为非资产
          </RcItem>
        } */}
        {/* <RcItem id="authorization" onClick={handleItemClick}>
          授权
        </RcItem> */}
      </RcMenu>

      {contextHolder}
    </div>
  )
}

export default AssetTable;