import React,{ useState, useEffect, useRef, useContext, useMemo } from "react";
import { Button, Pagination, Space, Modal, Input, Tooltip, Checkbox, Typography, Dropdown, Menu, Divider, Select, message, notification } 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 { Subject } from "rxjs";
import produce from 'immer'
import { useDebounceEffect } from 'ahooks'

import FilterElementModal from './FilterElementModal';
import AssetMount from '../../AssetRecycle/Component/AssetMount';
import ImportAssetDrawer from './ImportAssetDrawer';
import ImportBusinessColumn from './import-business-column';
import AddAsset from './add-asset';
import AssetDetailDrawer from "./AssetDetailDrawer";
import { dispatch, dispatchLatestHomepage } from '../../../../model';
import { showMessage, showNotifaction, getQueryParam, inputWidth, isSzseEnv, highlightSearchContentByTerms, isPostAsset, getAssetRange } 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 Table from '../../ResizeableTable';
import WorksheetModal from "./WorksheetModal";
import WorkbookDrawer from "./WorkbookDrawer";
import TagCell, { TagSelectPopup } from './tag-help'
import HistoryAndVersionDrawer from "./HistoryAndVersionDrawer";
import PermissionButton from '../../../../util/Component/PermissionButton'
import PermissionMenuItem from '../../../../util/Component/PermissionMenuItem'

import "./AssetTable.less";
import 'react-contexify/dist/ReactContexify.css';
import { getTemplateType } from "../../../../util/axios";
import { useGetModalInfoAndAction } from "@/hooks/common";
import AssetFlow from "./AssetFlow"
import { assetsActionManageService } from "@/services";

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

const operationMap = {
  historyVersion: '历史版本',
}

//资产项
export const AssetItem = (props) => {
  const { metadata, terms } = props;

  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}>
      {highlightSearchContentByTerms(content, terms, true)}
      </Text>
    </Tooltip>
  );
}

export const listSubject = new Subject();

const AssetTable = (props) => {

  const { className, nodeId, nodeType, nodeLevel, nodeAllowdLoadDataAsset, elementsChanged, assetActionChanged, onSelect, onCountChange, reference = AssetManageReference, onFullScreenChange, template } = props;
  
  const MENU_ID = 'asset-table';

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

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

  const [ checkedKeys, setCheckedKeys ] = useState([]);
  const [selectedRows, setSelectedRows] = React.useState([]);
  const [ importAssetVisible, setImportAssetVisible ] = useState(false);
  const [ filterElementVisible, setFilterElementVisible ] = useState(false);
  const [addAssetParams, setAddAssetParams] = useState({
    visible: 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 [importBusinessColumnParams, setImportBusinessColumnParams] = useState({
    visible: false
  })
  const [loadingTemplates, setLoadingTemplates] = useState(false)
  const [loadingElements, setLoadingElements] = useState(false)
  const [elements, setElements] = useState()
  const [currentElementId, setCurrentElementId] = useState()
  const [isDataKeyUser, setDataKeyUser] = useState() 
  const [reportTypes, setReportTypes] = useState()
  const [currentReport, setReport] = useState()
  const [worksheetModalVisible, setWorksheetModalVisible] = useState(false)
  const [workbookDrawerVisible, setWorkbookDrawerVisible] = useState(false)
  const [tagSelectPopupParams, setTagSelectPopupParams] = React.useState({
    visible: false,
    items: undefined
  })
  const [resoureTagMap, setResourceTagMap] = React.useState()
  const [historyAndVersionParams, setHistoryAndVersionParams] = React.useState({
    visible: false,
    id: undefined
  })
  const [permissions, setPermissions] = React.useState([])
  const [sorterParams, setSorterParams] = React.useState({
    sortField:'',
    sortDirection:''
  })

  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)

  const indexCol = {
    title: '序号',
    dataIndex: 'key',
    fixed: 'left',
    render: (text, record, index) => ((pagination.pageNum-1)*pagination.pageSize+index+1),
    width: 60,
    ellipsis: true,
    filter: false,
  }

  const tagCol = {
    title: '标签',
    dataIndex: 'tag',
    width: 360,
    className: 'table-tag-cell',
    render: (_, record) => <div onClick={(e) => e.stopPropagation()}>
      <TagCell 
        id={record.id}
        did={record.dirId}
        type='dataAsset'
        tags={resoureTagMap?.[record.id]}
        onChange={(val) => {
          setResourceTagMap((prevResourceTagMap) => {
            return produce(prevResourceTagMap||{}, (draft) => {
              draft[record.id] = val
            })
          })
        }}
      />
    </div>
  }

  const actionCol = {
    title: '操作',
    dataIndex: 'action',
    width: 60,
    fixed: 'right',
    filter: false,
    render: (_, record) => {
      return (
        <Space size={5} split={<Divider type='vertical' style={{margin:0}} />}>
        {
          ((record.allowButtons??[]).indexOf('authorize')!==-1) && <a onClick={(e) => {
            e.stopPropagation();
            app?.setGlobalState && app?.setGlobalState({
              message: 'data-govern-assets-admit',
              data: record
            })
          }}>授权</a>
        }
        {
          // (reference===AssetManageReference||(reference===AssetBrowseReference&&record.hasPermission)) && <a onClick={(e) => {
          //   e.stopPropagation();
          //   setAssetMountParam({
          //     visible: true,
          //     ids: [record.id]
          //   });
          // }}>变更目录</a>
        }
        </Space>
      )
    }
  }

  useEffect(() => {
    judgeDataKeyUser();
    getUsers();
    getReportTypes();

    const $list = listSubject.subscribe((val) => {
      if (val.msg === 'templateChange') {
        setCurrentElementId();
        getElements();
      }
    });
    window?.addEventListener("storage", storageChange);

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

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



  useEffect(() => {
    setSelectItem({});
    setCheckedKeys([]);
    setSelectedRows([]);
    if (nodeId) {  
      if (shouldScrollRef.current === true) {
        if (remoteRelationRef.current) {
          getDataAssetLocationByRelation();
        } else {
          getDataAssetLocation();
        }
  
      } else {
        setPagination({ ...pagination, pageNum: 1 });
      }
    } else {
      setAssets([])
      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])

  useDebounceEffect(() => {
    if (reference !== AssetRecycleReference&&(nodeId||nodeId===undefined)) {
      getFilterElementsGroupThenGetDataAssets();
    } 
    //eslint-disable-next-line react-hooks/exhaustive-deps
  }, [keyword, pagination, elementsChanged, assetActionChanged, recursive, fullSearch, currentElementId, nodeId], { wait: 350 })

  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 ])

  React.useEffect(() => {
    if (assets) {
      getResourceTag()
    }
  }, [assets])

  React.useEffect(() => {
    if (nodeId) {
      if (nodeType !== 'custom') {
        getPermissions()
      }
    }
  }, [nodeId, nodeType])

  const [addAble, importAble, exportAble, changeDirectoryAble, deleteAble, offlineAble, addTagAble, subscribeAble] = React.useMemo(() => {
    let [_addAble, _importAble, _exportAble, _changeDirectoryAble, _deleteAble, _offlineAble, _addTagAble, _subscribeAble] = [false, false, false, false, false, false, false, false]

    _addAble = (permissions??[]).findIndex(item => item==='add') !== -1

    if ((selectedRows??[]).length === 0) {
      _importAble = (permissions??[]).findIndex(item => item==='import') !== -1
      _exportAble = (permissions??[]).findIndex(item => item==='export') !== -1
    } else {
      let [allowImport, allowExport] = [true, true]
      for (const row of selectedRows??[]) {
        const importIndex = (row.allowButtons??[]).findIndex(item => item==='import')
        const exportIndex = (row.allowButtons??[]).findIndex(item => item==='export')
        if (importIndex === -1) {
          allowImport = false
        }
        if (exportIndex === -1) {
          allowExport = false
        }
      }

      _importAble = allowImport
      _exportAble = allowExport
    }

    let [allowChangeDirectory, allowDelete, allowOffline, allowAddTag, allowSubscribe] = [true, true, true, true, true]
    for (const row of selectedRows??[]) {
      const changeDirecotoryIndex = (row.allowButtons??[]).findIndex(item => item==='changeDir')
      const deleteIndex = (row.allowButtons??[]).findIndex(item => item==='delete')
      const offlineIndex = (row.allowButtons??[]).findIndex(item => item==='offline')
      const addTagIndex = (row.allowButtons??[]).findIndex(item => item==='addTag')
      const subscribeIndex = (row.allowButtons??[]).findIndex(item => item==='subscribe')
      if (changeDirecotoryIndex === -1) {
        allowChangeDirectory = false
      }
      if (deleteIndex === -1) {
        allowDelete = false
      }
      if (offlineIndex === -1) {
        allowOffline = false
      }
      if (addTagIndex === -1) {
        allowAddTag = false
      }
      if (subscribeIndex === -1) {
        allowSubscribe = false
      }
    }

    _changeDirectoryAble = allowChangeDirectory
    _deleteAble = allowDelete
    _offlineAble = allowOffline
    _addTagAble = allowAddTag
    _subscribeAble = allowSubscribe

    return [_addAble, _importAble, _exportAble, _changeDirectoryAble, _deleteAble, _offlineAble, _addTagAble, _subscribeAble]
  }, [permissions, selectedRows])

  
  // 直接使用数组作为数据源，添加key
  const realAssets = useMemo(()=>{
    let data = []
    assets?.map((asset) => {
      let temp = {}
      asset?.elementValuesWithoutTypeAttribute?.map((row,rowIndex)=>{
        const key = columns?.[rowIndex]?.dataIndex
        temp[key] = row
      })
      temp = {...asset,...temp}
      data.push(temp)
    });
    return data
  },[assets,columns])

  const menuData = React.useMemo(() => {
    const newMenuData = []
    for (const key of contextMenuItem?.allowButtons??[]) {
      if (operationMap[key]) {
        newMenuData.push(operationMap[key])
      }
    }
    return newMenuData
  }, [contextMenuItem])

  const questionModal = useGetModalInfoAndAction()

  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;
    }
  }

  const getPermissions = () => {
    dispatch({
      type: 'assetmanage.getPrivilegeByRangeAndDirId',
      payload: {
        range: getAssetRange(AssetManageReference),
        optionId: nodeId
      },
      callback: data => {
        setPermissions(data)
      }
    })
  }

  const judgeDataKeyUser = () => {
    dispatch({
      type: 'assetmanage.checkDataKeyUser',
      callback: (data) => {
        setDataKeyUser((data==='true')?true:false)
      }
    })
  }

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

  const getReportTypes = () => {
    dispatch({
      type: 'assetmanage.listSupportReportTypes',
      callback: data => {
        setReportTypes(data)
      }
    });
  }

  const getElements = () => {
    setLoadingElements(true);
    dispatch({
      type: 'assetmanage.listElements',
      callback: (data) => {
        setLoadingElements(false);
        setElements(data);
      },
      error: () => {
        setLoadingElements(false);
      }
    })
  }

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

  const changeCurrent = (page,size) => {
    setCheckedKeys([]);
    setSelectedRows([]);
    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 => {
            index++;
            const name = group.name
            const params = {
              title: name,
              dataIndex: group.enName,
              ellipsis: true,
              width: 150,
              sorter:true,
              render: (text, record) => {
                return (
                  <Tooltip title={text||''}>
                    <Text ellipsis={true}>
                    {highlightSearchContentByTerms(text, [keyword??''], true)}
                    </Text>
                  </Tooltip>
                );
              }
            };

            if (name === '编号') {
              params.width = 120;
              // params.fixed = 'left';
            } else if (name === '中文名称' || name === '岗位中文名') {
              params.width = isSzseEnv?230:160;
              // params.fixed = 'left';
            } else if (name === '英文名称' || 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} terms={[keyword??'']} />
                );
              }

              _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);
                      }}>
                      {highlightSearchContentByTerms(text, [keyword??''], true)}
                      </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 params = {
      queryElementId: currentElementId,
      dirId: nodeId,
      currentDirIsCustom: nodeType==='custom',
      pageNum,
      pageSize,
      ...sorterParams,
      range: getAssetRange(reference),
      keyword: encodeURIComponent(keyword)
    };

    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?.elementValuesWithoutTypeAttribute||[]).forEach((value) => {
              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 addAsset =()=>{
    setAddAssetParams({
      visible: true
    })
  }

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

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

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

  const importBusinessColumn = () => {
    setImportBusinessColumnParams({
      visible: 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: () => {
          const exportAll = checkedKeys?.length === 0 && !nodeId ? true : false
          const dirId = checkedKeys?.length === 0 && nodeId ? nodeId : ''
          window.open(`/api/dataassetmanager/dataAssetApi/exportByDataAssetIds?exportAll=${exportAll}&dirId=${dirId}&templateType=${getTemplateType()}&queryElementId=${currentElementId??''}&keyword=${encodeURIComponent(keyword??'')}`);
        }
      })
    } else {
      window.open(`/api/dataassetmanager/dataAssetApi/exportByDataAssetIds?dataAssetIds=${checkedKeys.join(',')}&templateType=${getTemplateType()}`);
    }
  }

  const exportAssetColumns = () => {
      modal.confirm({
        title: '提示',
        content: '是否导出资源目录字段?',
        async onOk(){
          // await assetsActionManageService.exportAssetsColumns({templateType:getTemplateType(),dataAssetIds:checkedKeys.join(',')})
          //window.open(`/api/dataassetmanager/dataAssetApi/exportByDataAssetIds?exportAll=true&templateType=${getTemplateType()}&queryElementId=${currentElementId??''}&keyword=${encodeURIComponent(keyword??'')}`);
          const exportAll = checkedKeys?.length === 0 && !nodeId ? true : false
          const dirId = checkedKeys?.length === 0 && nodeId ? nodeId : ''
          await assetsActionManageService.exportBusinessColumnsByDataAssetId({dirId,exportAll,templateType:getTemplateType(),dataAssetIds:checkedKeys.join(',')})
        }
      })
  }

  const subscriptAsset = () => {
    if ((checkedKeys||[]).length === 0) return;
 
    modal.confirm({
      title: '提示',
      content: '是否确认收藏选中的资产目录?',
      onOk: () => {
        dispatch({
          type: 'assetmanage.addSubscribe',
          payload: {
            params: {
              appType: 'dataAssetManager',
              subType: getTemplateType(),
              resourceIds: (checkedKeys??[]).toString(),
              env: app?.env?.domainId,
            }
          },
          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: 'assetmanage.deleteDataAssets',
          payload,
          callback: () => {
            showMessage("success","删除成功");
            getDataAssets();
            setCheckedKeys([]);
            setSelectedRows([]);
          },
          error: () => {
          }
        })
      }
    })
  }

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

    modal.confirm({
      title: '提示',
      content: '是否停用选中的资产目录?',
      onOk: () => {
        let payload = {
          data: checkedKeys
        }

        dispatch({
          type: 'assetmanage.offline',
          payload,
          callback: () => {
            showMessage("success","停用成功");
            getDataAssets();
            setCheckedKeys([]);
            setSelectedRows([]);
          },
          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([]);
        setSelectedRows([]);
      }
    })
  }

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

    let payload = {
      data: checkedKeys
    };

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

  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([]);
              setSelectedRows([]);
            }
          })
        }
      })
    }else{
      showMessage("warn","请选择资产目录");
    }
  }

  const onSelectChange = (selectedRowKeys, selectedRows) => {
    setCheckedKeys(selectedRowKeys);
    setSelectedRows(selectedRows);
  };

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

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

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

  const displayMenu = (event) => {
    show(event, {
      position: {
        x: event.clientX + 30,
        y: event.clientY - 10
      }
    })
  }

  const handleItemClick = ({ event, props, data, triggerEvent }) => {
    const key = event.currentTarget.id;

    if (key === '历史版本') {
      setHistoryAndVersionParams({
        visible: true,
        id: contextMenuItem?.id
      })
    }else if(key ==='发起问责'){
      questionModal.openModal([contextMenuItem])
    } 
  }

  const onBatchAddTagClick = () => {
    setTagSelectPopupParams({
      visible: true,
      items: (assets??[]).filter(item => (checkedKeys??[]).indexOf(item.id)!==-1).map(item => ({ 
        resourceId: item.id,
        catalogId: item.dirId,
        type: 'dataAsset',
      }))
    })
  }

  const getResourceTag = () => {
    const ids = (assets??[]).map(item => item.id)
    if (ids.length > 0) {
      dispatch({
        type: 'tag.getResourceTagIn',
        payload: {
          params: {
            resourceIds: ids,
            includeAll: true,
            includePrivate: true
          }
        },
        callback: data => {
          setResourceTagMap(data?.data)
        }
      });
    } else {
      setResourceTagMap()
    }
  }

  const onReportAnalyseClick = (val) => {
    if ((checkedKeys||[]).length === 0) {
      showMessage('warn', '请先选择资产');
    } else {
      setReport(val);
      setWorksheetModalVisible(true);
    }
  }

  const onReportWorkbookClick = (val) => {
    setReport(val);
    setWorkbookDrawerVisible(true);
  }

  const onMenuClick = ({ key }) => {
    if (key === 'offline') {
      offlineAssets()
    } else if (key === 'addTag') {
      onBatchAddTagClick()
    } else if (key === 'visibleColSetting') {
      onFilterElementClick()
    }else if(key==='questionwaring'){
      if(selectedRows.length){
        questionModal.openModal(selectedRows)
      }else{
        message.info("请选择资产")
      }
    }
  }

  const moreMenu = (
    <Menu onClick={onMenuClick}>
      <PermissionMenuItem 
        key='offline' 
        defaultPermission={offlineAble}
        disabled={(checkedKeys??[]).length===0}
        tip={(checkedKeys??[]).length===0?'请先选择资产':''}
      >
        <div className='text-center'>
          停用
        </div>
      </PermissionMenuItem>
      <PermissionMenuItem 
        key='addTag' 
        defaultPermission={addTagAble}
        disabled={(checkedKeys??[]).length===0}
        tip={(checkedKeys??[]).length===0?'请先选择资产':''}
      >
        <div className='text-center'>
          添加标签
        </div>
      </PermissionMenuItem>
      <Menu.Item key='questionwaring' 
      >
        <div className='text-center'>
          发起问责
        </div>
      </Menu.Item>
      <Menu.Item key='visibleColSetting' 
      >
        <div className='text-center'>
          可见列设置
        </div>
      </Menu.Item>
      {
        template?.structedStateEnum==='structured' && reportTypes?.map(item => 
          <React.Fragment key={item.code}>
            <Menu.Item disabled={(checkedKeys||[]).length===0}>
              <div className='text-center' onClick={() => { onReportAnalyseClick(item) }}>
                {`${item.name}自助分析`}
              </div>
            </Menu.Item>
            <Menu.Item>
              <div className='text-center' onClick={() => { onReportWorkbookClick(item)}}>
              {`${item.name}工作簿`}
              </div>
            </Menu.Item>
          </React.Fragment>
        )
      }
    </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 - 295px)';
    } else if (reference===AssetManageReference) {
      scrollY = 'calc(100vh - 295px)';
    } else if (reference===AssetBrowseReference ||reference===ResourceBrowseReference) {
      scrollY = 'calc(100vh - 295px)';
    } else if (reference===AssetRecycleReference) {
      scrollY = 'calc(100vh - 295px)';
    }
  }

   const handleTableChange = (pagination, filters, sorter) => {
    const temp = sorter?.order; // 或 'descend' 或 ''
    let sortDirection;
    if (temp === 'ascend') {
      sortDirection = 'ASC';
    } else if (temp === 'descend') {
      sortDirection = 'DESC';
    } else {
      sortDirection = ''; // 或者其他默认值
    }
    setSorterParams({
      sortField:sorter?.field,
      sortDirection
    })
  };

  useEffect(()=>{
  if(sorterParams.sortDirection||sorterParams.sortField) {
    getDataAssets()
  }
  },[sorterParams])

  return(
    <div className={classes}> 
      <div
        className='flex p-3'
        style={{
          alignItems: 'center',
          justifyContent: 'space-between',
          borderBottom: '1px solid rgb(239, 239, 239)',
        }}
      > 
        <Space>
          { 
            (((reference===AssetManageReference&&nodeType!=='custom')||isDataKeyUser) && template && template?.structedStateEnum!=='structured') && nodeId && <PermissionButton
              defaultPermission={addAble}
              onClick={addAsset}
            >
              新增
            </PermissionButton>
          }
          { 
            (reference===AssetManageReference && nodeType!=='custom') && <PermissionButton
              defaultPermission={importAble}
              onClick={importAsset}
            >
              导入
            </PermissionButton>
          }
          { 
            (reference===AssetManageReference && nodeType!=='custom' && template && template?.structedStateEnum!=='structured') && <PermissionButton
              defaultPermission={importAble}
              onClick={importBusinessColumn}
            >
              导入字段
            </PermissionButton>            
          }
          {
            (reference===AssetManageReference) && <PermissionButton
              defaultPermission={exportAble}
              onClick={exportAsset}
            >
              导出
            </PermissionButton>
          }
                    {
            (reference===AssetManageReference) && <PermissionButton
              defaultPermission={exportAble}
              onClick={exportAssetColumns}
            >
              导出字段
            </PermissionButton>
          }
          <PermissionButton
            defaultPermission={subscribeAble}
            onClick={subscriptAsset}
            tip={(checkedKeys||[]).length===0?'请先选择资产':''}
            disabled={(checkedKeys||[]).length===0}
          >
            收藏
          </PermissionButton>
          {
            reference===AssetManageReference && <PermissionButton 
              defaultPermission={changeDirectoryAble} 
              tip={(checkedKeys||[]).length===0?'请先选择资产':''}
              onClick={onBatchCatalogChangeBtnClick} 
              disabled={(checkedKeys||[]).length===0}
            >
              变更目录
            </PermissionButton>
          }
          {
            reference===AssetManageReference && <PermissionButton 
              defaultPermission={deleteAble} 
              tip={(checkedKeys||[]).length===0?'请先选择资产':''}
              onClick={deleteAssets} 
              disabled={(checkedKeys||[]).length===0}
            >
              删除
            </PermissionButton>
          }
          {
            reference===AssetBrowseReference && <Button onClick={onFilterElementClick}>可见列设置</Button>
          }
          {
            reference===AssetManageReference && <Dropdown overlay={moreMenu} placement="bottomCenter"> 
              <Button>其他操作</Button>
            </Dropdown>
          }
        </Space>
        <Space>
          {/* {
            (reference!==AssetRecycleReference) && <Checkbox onChange={onFullSearchChange} checked={fullSearch}>全部数据</Checkbox>
          } */}
          {
            (reference!==AssetRecycleReference) && <Select allowClear
              loading={loadingElements}
              value={currentElementId}
              placeholder='请选择搜索属性'
              onChange={(val) => {
                setCurrentElementId(val)
              }}
              style={{ width: 160 }}
            >
            {
              (elements??[]).map((item, index) => (
                <Select.Option key={item.id} value={item.id}>{item.name}</Select.Option>
              ))
            }
            </Select>
          }
          <Input size="middle"
            placeholder="请输入资产目录要素值"
            value={keyword} allowClear
            onChange={(e) => {
              setKeyword(e.target.value);
              setPagination({ ...pagination, pageNum: 1 });
            }} 
            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}
            onRow={(record) => {
              return {
                id: `data-asset-${record?.id}`,
                onClick: (e) => {
                  setSelectItem(record);
                  onSelect && onSelect(record?.id, record?.dirId);

                  setAssetDetailDrawerVisible(true);
                },
                onContextMenu: event => {
                  if (reference===AssetManageReference) {
                    let allowContextMenu = false

                    for (const key of (record.allowButtons??[])) {
                      if (operationMap[key]) {
                        allowContextMenu = true
                        break
                      }
                    }

                    if (allowContextMenu) {
                      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={reference===AssetManageReference?[indexCol, ...columns, tagCol]:[indexCol, ...columns]} 
            columns={reference===AssetManageReference?[indexCol, ...columns, tagCol, actionCol]:[indexCol, ...columns, actionCol]} 
            rowKey='id'
            dataSource={realAssets}
            pagination={false}
            onChange={handleTableChange}
            sortDirections={['ascend', 'descend','']}
            size='default'
            scroll={{ y: scrollY }}
          />
        </ResizeObserver>
      
        <Pagination
          className="text-center mt-3"
          showSizeChanger
          onChange={changeCurrent}
          onShowSizeChange={changeCurrent}
          current={pageNum}
          pageSize={pageSize}
          defaultCurrent={1}
          total={total}
          showTotal={total => `共 ${total} 条`}
        />
        <AssetFlow visible={questionModal.visible} onCancel={()=>{questionModal.cancelModal()}} item={questionModal.currentItem} />
      </div> 

      <AddAsset
        {...addAssetParams}
        nodeId={nodeId}
        template={template}
        onCancel={(refresh) => {
          setAddAssetParams({
            visible: false
          })

          refresh && getDataAssets()
        }}
      />
      <ImportAssetDrawer 
        visible={importAssetVisible}
        nodeId={nodeId}
        template={template}
        onCancel={onImportAssetCancel}
        onSuccess={onImportAssetSuccess}
      />
      <ImportBusinessColumn 
        {...importBusinessColumnParams}
        nodeId={nodeId}
        template={template}
        onCancel={() => {
          setImportBusinessColumnParams({
            visible: false
          })
        }}
        onSuccess={() => {
          setImportBusinessColumnParams({
            visible: false
          })

          getDataAssets()
        }}
      />
      <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}
      />
      <WorksheetModal 
        report={currentReport}
        visible={worksheetModalVisible}
        ids={checkedKeys}
        onCancel={() => {
          setWorksheetModalVisible(false);
        }}
      />

      <WorkbookDrawer
        report={currentReport}
        visible={workbookDrawerVisible}
        onCancel={() => {
          setWorkbookDrawerVisible(false);
        }}
      />
      <TagSelectPopup
        {...tagSelectPopupParams}
        type='dataAsset'
        onCancel={() => {
          setTagSelectPopupParams({
            visible: false,
            items: undefined
          })
        }}
        onChange={() => {
          getResourceTag()
        }}
      />
      <HistoryAndVersionDrawer 
        {...historyAndVersionParams}
        onCancel={() => {
          setHistoryAndVersionParams({
            visible: false,
            id: undefined,
          })
        }}
      />

      <RcMenu id={MENU_ID}>
        {
          menuData?.map((item,key) => (
            <RcItem key={key} id={item} onClick={handleItemClick}>
            {item}
            </RcItem>
          ))
        }
        <RcItem id={'发起问责'} onClick={handleItemClick}>
          发起问责
        </RcItem>
      </RcMenu>

      {contextHolder}
    </div>
  )
}

export default AssetTable;