import React, { useEffect, useState, useContext, useMemo, useRef } from 'react';
import { Form, Spin, Input, Descriptions, Space, Button, Tooltip, Select, Cascader, Radio, Divider, Typography, Modal, Row, Col, Pagination, Dropdown, Menu, message } from 'antd';
import { DownOutlined, UpOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import LocalStorage from 'local-storage';
import { useDebounceEffect } from 'ahooks';

import MetadataInfo from './MetadataInfo';
import { dispatch } from '../../../../model';
import { highlightSearchContentByTerms, showMessage, paginate } from '../../../../util';
import { AppContext, appId } from '../../../../App';
import Tag from '../../Tag';  
import Separate from './Separate';
import AssetTagModal from './AssetTagModal';
import { AnchorId, AnchorDirId, AssetManageReference } from '../../../../util/constant';
import IndexCode from './IndexCode';
// import Upload from './Upload';
import Table from '../../ResizeableTable';

import { CancelSvg, EditSvg, SaveSvg, FullScreenSvg, CancelFullScreenSvg } from './AssetSvg';
// import SelectUser from '../../Model/Component/SelectUsers';
// import SelectFilter from '../../Model/Component/SelectFilter';
import { checkDataAssetEditable } from '../../../../service/dataassetmanager';
import download from '../../../../util/download';
import SelectStandard from './SelectStandard';
import AttributeMaintain from './AttributeMaintain';

import './AssetAction.less';

const AssetAction = (props) => {
  const { id, dirId, draftId,action, terms, onChange, reference, form, onMetadataChange, onElementsChange, readonly = false, permissionId ,templateType} = props;

  const [ currentAction, setCurrentAction ] = useState(action);
  const [ assetParams, setAssetParams ] = useState({ assets: {}, attributes: [], attributesFoldMap: {} });
  const [ elements, setElements ] = useState([]);
  const [ wholeElements, setWholeElements ] = useState([]);
  const [currentAttribute, setCurrentAttribute] = useState();
  const [ metadataId, setMetadataId ] = useState('');
  const [ loading, setLoading ] = useState(false);
  const [ confirmLoading, setConfirmLoading ] = useState(false);
  const [ fullScreen, setFullScreen ] = useState(false);
  const [ assetPaths, setAssetPaths ] = useState([]);
  const [ resourceRelations, setResourceRelations ] = useState([]);
  const { assets, attributes, attributesFoldMap } = assetParams;
  const [ assetTagModalVisible, setAssetTagModalVisible ] = useState(false);
  const [ selectTag, setSelectTag ] = useState({});
  const [ systems, setSystems] = useState([]);
  const [ loadingSystems, setLoadingSystems ] = useState(false); 
  const [ users, setUsers ] = useState([]);
  const [ loadingUsers, setLoadingUsers ] = useState(false);
  const [ departments, setDepartments ] = useState([]);
  const [ loadingDepartments, setLoadingDepartments ] = useState(false);
  const [ treeData, setTreeData ] = useState([]);
  const [ treeDataMap, setTreeDataMap ] = useState(undefined);
  const [currentDomainGroup, setCurrentDomainGroup] = useState(undefined);
  const [currentBussinessDomain, setCurrentBussinessDomain] = useState(undefined);
  const [canEdit, setEdit] = useState(false);
  const [saveAsDraft, setSaveAsDraft] = useState(false);
  const [isExist, setIsExist] = useState(false);
  const [metadata, setMetadata] = useState(undefined);
  const [loadingMetadataColumnList, setLoadingMetadataColumnList] = useState(false);
  const [metadataColumnList, setMetadataColumnList] = useState(undefined);
  const [selectStandardParam, setSelectStandardParam] = useState({ visible: false, id: undefined });
  const [attributeMaintainParam, setAttributeMaintainParam] = useState({  
    visible: false,
    metadataId: undefined
  });
  const [ pagination, setPagination ] = useState({ pageNum: 1, pageSize: 20 });
  const { pageNum, pageSize } = pagination;
  const [modal, contextHolder] = Modal.useModal();
  const [permissions, setPermissions] = useState(undefined);
  const [keyword, setKeyword] = useState('');
  const [standardList, setStandardList] = useState(undefined);

  const app = useContext(AppContext);
  const uploadRef = useRef(undefined);

  const columns = [
    {
      title: '技术ID(英文名称)',
      dataIndex: 'name',
      width: 160,
      ellipsis: true,
      render: (text, record, _) => {
        return (
          <Tooltip title={text||''}>
            <a onClick={() => {
              app?.setGlobalState?.({
                message: 'data-govern-metadata-column-detail',
                data: {
                  id: record._id
                }
              })
            }}>
            {highlightSearchContentByTerms(text||'', terms)}
            </a>
          </Tooltip>
        );
      }
    },
    {
      title: '名称',
      dataIndex: 'cnName',
      // width: 200,
      ellipsis: true,
      render: (text, _) => highlightSearchContentByTerms(text||'', terms)
    },
    // {
    //   title: '是否有权限',
    //   dataIndex: 'permission',
    //   width: 100,
    //   ellipsis: true,
    //   render: (_, record) => {
    //     const index = (permissions||[]).findIndex(item => item.columnMetadataId===record._id);
    //     if (index!==-1) {
    //       return permissions[index].visible === 'Y' ? '是':'否';
    //     }
  
    //     return '否';
    //   }
    // },
    {
      title: '备注信息',
      dataIndex: 'remarks',
      ellipsis: true,
      render: (text, _) => highlightSearchContentByTerms(text||'', terms)
    },
    {
      title: '类型',
      dataIndex: 'typeName',
      width: 100,
      ellipsis: true,
      render: (text, _) => highlightSearchContentByTerms(text||'', terms)
    },
    {
      title: '长度',
      dataIndex: 'size',
      width: 60,
      ellipsis: true,
    },
    {
      title: '关联标准',
      dataIndex: 'standard',
      ellipsis: true,
      render: (_, record) => {
        return <AppContext.Consumer>
        {
          appValue => <a onClick={() => {
            appValue?.setGlobalState && appValue?.setGlobalState({
              message: 'data-govern-show-index-detail-message',
              data: { id: record.standard?.standardId } 
            })
          }}>
            <span>{record.standard?.standardName}</span>
          </a>
        }
        </AppContext.Consumer>
      }
    },
  ];

  useEffect(() => {
    console.log('props',AssetManageReference,props);
    getSystems();
    getUsers();
    getTreeData();
    getDepartments();
    if (action === 'add') {
      // getElements();
    } else {
      setCurrentAction('detail');
      if(draftId){
        setPagination({...pagination, pageNum: 1});
        getElements();
        getDraftData()
      }
      else if ((id||'')!=='') {
        setPagination({...pagination, pageNum: 1});
        getElements();
        getAssetPaths();
        getResourceRelations();
        checkDataAssetEditable();
        checkIsNeedSaveAsDraftDataAsset()
        getAsset();
        
      } else {
        setMetadataId('');
        setAssetParams({...assetParams, ...{assets: {}, attributes: []}});
        setCurrentAttribute();
        getElements();
      }
    }    
    //eslint-disable-next-line react-hooks/exhaustive-deps
  }, [id, dirId])

  useEffect(() => {
    if (permissionId) {
      getPermission();
    }
  }, [permissionId, app?.env])

  const domains = useMemo(() => {
    if (currentDomainGroup && treeDataMap) {
      return treeDataMap[currentDomainGroup];
    }

    return [];
  }, [currentDomainGroup, treeDataMap])

  const businessData = useMemo(() => {
    if (currentDomainGroup && currentBussinessDomain && treeDataMap) {
      const currentLevel2Data = treeDataMap[currentDomainGroup];

      const index = (currentLevel2Data||[]).findIndex(item => item.text === currentBussinessDomain);
      if (index !== -1) {
        return currentLevel2Data[index].children;
      }
    }

    return [];
  }, [currentDomainGroup, currentBussinessDomain, treeDataMap])

  const tableData = useMemo(() => { 
    if (metadataColumnList) {
      const newMetadataColumnList = [];

      metadataColumnList.filter(item => {
        return (
          !keyword
          || (item.name??'').indexOf(keyword)!==-1
          || (item.cnName??'').indexOf(keyword)!==-1
        )
      }).forEach(item => {
        const index = (standardList??[]).findIndex(_item => _item.metadataId === item._id);
        let newItem = {...item};
        if (index !== -1) {
          newItem.standard = standardList[index];
        }

        newMetadataColumnList.push(newItem);
      });

      return paginate(newMetadataColumnList, pageNum, pageSize);
    }

    return [];
  }, [metadataColumnList, standardList, pagination, keyword])

  const getPermission = () => {
    // dispatch({
    //   type: 'assetmanage.getPermission',
    //   payload: {
    //     permissionId,
    //     env: app?.env?.domainId||LocalStorage.get('assetsEnv')
    //   },
    //   callback: data => {
    //     setPermissions(data.columnPermissions);
    //   }
    // });
  }

  const getAssetPaths = () => {
    dispatch({
      type: 'assetmanage.getAssetPaths',
      payload: {
        dataAssetId: id,
      },
      callback: data => {
        setAssetPaths(data||[]);
      }
    });
  }

  const getSystems = () => {
    setLoadingSystems(true);
    dispatch({
      type: 'assetmanage.getSystems',
      payload: {
        env: app?.env?.domainId||LocalStorage.get('assetsEnv'),
      },
      callback: data => {
        setLoadingSystems(false);
        setSystems(data||[])
      },
      error: () => {
        setLoadingSystems(false);
      }
    });
  }

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

  const getTreeData = () => {
    dispatch({
      type: 'assetmanage.queryAllDirectoryAsTree',
      callback: (data) => {
        setTreeData(data);

        const newTreeDataMap = {};
        data?.forEach(item => {
          newTreeDataMap[item.text] = item.children;
        })
        setTreeDataMap(newTreeDataMap);
      }
    })
  }

  const getDepartments = () => {
    setLoadingDepartments(true);
    dispatch({
      type: 'user.getMcclDepartments',
      callback: (data) => {
        setLoadingDepartments(false);
        setDepartments(data);
      },
      error: () => {
        setLoadingDepartments(false);
      }
    })
  }

  const getResourceRelations = () => {
    dispatch({
      type: 'assetmanage.getResourceRelations',
      payload: {
        dataAssetId: id,
      },
      callback: data => {
        setResourceRelations(data||[]);
      }
    });
  }

  const getElements = ( cb = null ) => {
    const tempinfo = {}
    if(templateType){
      tempinfo.templateType =templateType
    }
    dispatch({
      type: (currentAction==='add')?'assetmanage.listElementsAndFillValue':'assetmanage.listElements',
      payload: (currentAction==='add')?{
        params: {
          dirId,
          ...tempinfo
        }
      }:{
        params:{
          ...tempinfo
        }
      },
      callback: data => {
        setWholeElements(data||[]);
      }
    })
  }

  const getUserElements = () => {
    setLoading(true);
    dispatch({
      type: 'assetmanage.listUserElements',
      callback: data => {
        setLoading(false);
        getAsset(data||[]);
      },
      error: () => {
        setLoading(false);
      }
    })
  }

  const checkDataAssetEditable = () => {
    dispatch({
      type: 'assetmanage.checkDataAssetEditable',
      payload: {
        params: {
          dataAssetId: id,
        }
      },
      callback: value => {
        setEdit(value==='true'?true:false);
      }
    })
  }

  // 判断当前模版内容操作需不需要保存为草稿
  const checkIsNeedSaveAsDraftDataAsset = () => {
    dispatch({
      type: 'assetmanage.checkIsNeedSaveAsDraftDataAsset',
      payload: {
        params: {
          templateType
        }
      },
      callback: value => {
        setSaveAsDraft(value);
      }
    })
  }

  const getAsset = (userElements=null) => {
    setLoading(true);
    dispatch({
      type: 'assetmanage.getDataAssetDetail',
      payload: {
        dataAssetId: id,
        dirId: dirId,
        checkPermission: reference!==AssetManageReference
      },
      callback: data => {
        setLoading(false);
        setIsExist(data?.existDraft)
        const metadataIndex = data?.elements?.findIndex(item => item.name === '资产项');

        if (metadataIndex !== -1) {
          let metadataValue = data?.elements[metadataIndex].value;
          try {
            setMetadata(JSON.parse(metadataValue));
            getMetadataAttributes();
            getMetadataStandardList();
          } catch(error) {
          
          }
        }

        if (userElements) {
          const userElementIds = [];
          (userElements||[]).forEach(element => {
            userElementIds.push(element?.id);
          });

          const filterElements = (data?.elements||[]).filter(element => userElementIds.indexOf(element?.id) !== -1);

          data = { ...data, elements: filterElements };
        }

        setElements(data?.elements||[]);
        onElementsChange && onElementsChange(data?.elements||[]);

        setMetadataId(data?.metadataId||'');
        onMetadataChange && onMetadataChange(data?.metadataId||'');

        const _attributes = [];
        (data?.elements||[]).forEach(element => {
          if (_attributes.indexOf(element.type) === -1) {
            _attributes.push(element.type||'');
          }
        })

        let newAttributesFoldMap = {...attributesFoldMap};
        (_attributes||[]).forEach(attribute => {
          if (newAttributesFoldMap[attribute]===undefined || newAttributesFoldMap[attribute]===null) {
            newAttributesFoldMap[attribute] = true;
          }
        })

        setAssetParams({ assets: data, attributes: _attributes, attributesFoldMap: newAttributesFoldMap });
        if ((_attributes??[]).length > 0) {
          setCurrentAttribute(_attributes[0])
        }

        let _fieldsValue = {};
        (data.elements||[]).forEach(element => {
          _fieldsValue[element.name] = element.value||'';
          if (element.name === '主题域分组') {
            setCurrentDomainGroup(element.value);
          } else if (element.name === '主题域') {
            setCurrentBussinessDomain(element.value);
          }
        })

        form?.setFieldsValue(_fieldsValue);
      },
      error: () => {
        setLoading(false);
      }
    })
  }

  // 获取草稿数据
  const getDraftData = (userElements=null) => {
    setLoading(true);
    dispatch({
      type: 'assetmanage.getDraftDataAssetDetail',
      payload: {
        params: {
          draftId
        }
      },
      callback: data => {
        setLoading(false);
        setIsExist(data?.existDraft)
        const metadataIndex = data?.elements?.findIndex(item => item.name === '资产项');

        if (metadataIndex !== -1) {
          let metadataValue = data?.elements[metadataIndex].value;
          try {
            setMetadata(JSON.parse(metadataValue));
            getMetadataAttributes();
            getMetadataStandardList();
          } catch(error) {
          
          }
        }

        if (userElements) {
          const userElementIds = [];
          (userElements||[]).forEach(element => {
            userElementIds.push(element?.id);
          });

          const filterElements = (data?.elements||[]).filter(element => userElementIds.indexOf(element?.id) !== -1);

          data = { ...data, elements: filterElements };
        }

        setElements(data?.elements||[]);
        onElementsChange && onElementsChange(data?.elements||[]);

        setMetadataId(data?.metadataId||'');
        onMetadataChange && onMetadataChange(data?.metadataId||'');

        const _attributes = [];
        (data?.elements||[]).forEach(element => {
          if (_attributes.indexOf(element.type) === -1) {
            _attributes.push(element.type||'');
          }
        })

        let newAttributesFoldMap = {...attributesFoldMap};
        (_attributes||[]).forEach(attribute => {
          if (newAttributesFoldMap[attribute]===undefined || newAttributesFoldMap[attribute]===null) {
            newAttributesFoldMap[attribute] = true;
          }
        })

        setAssetParams({ assets: data, attributes: _attributes, attributesFoldMap: newAttributesFoldMap });
        if ((_attributes??[]).length > 0) {
          setCurrentAttribute(_attributes[0])
        }

        let _fieldsValue = {};
        (data.elements||[]).forEach(element => {
          _fieldsValue[element.name] = element.value||'';
          if (element.name === '主题域分组') {
            setCurrentDomainGroup(element.value);
          } else if (element.name === '主题域') {
            setCurrentBussinessDomain(element.value);
          }
        })

        form?.setFieldsValue(_fieldsValue);
      },
      error: () => {
        setLoading(false);
      }
    })
  }

  const getMetadataAttributes = () => {
    setMetadata(prevMetadata => {
      const ids = prevMetadata?.columnItems.map(item => item.metadataColumnId);

      if ((ids||[]).length > 0) {
        setLoadingMetadataColumnList(true);
        dispatch({
          type: 'assetmanage.getMetadataAttributes',
          payload: {
            data: ids,
            params: {
              catalog: app?.env?.domainId||LocalStorage.get('assetsEnv'),
            }
          },
          callback: data => {
            setLoadingMetadataColumnList(false);

            const newData = [...data||[]];
            if (prevMetadata?.metadataTableId?.toLowerCase().indexOf('query') !== -1) {
              newData.forEach(item => {
                item.typeName = item.datatype;
                item.size = item.length;
              });
            }

            setMetadataColumnList(newData);
          },
          error: () => {
            setLoadingMetadataColumnList(false);
          }
        });
      }

      return prevMetadata
    })
  }

  const onCancelButtonClick = () => {
    setCurrentAction('detail');
    getAsset();
  }

  const onActionButtonClick = () => {
    if (currentAction === 'detail') {
      setCurrentAction('edit');
    } else if (currentAction === 'edit') {
      onOk();
    }
  }

  const onAuthorizationButtonClick = () => {
    if (assets?.metadataId) {
      app?.setGlobalState && app?.setGlobalState({
        message: 'data-govern-assets-admit',
        data: assets
      })
    } else {
      showMessage("warn","该资产目录没有关联元数据信息");
    }
  }

  const jumpToPath = (item) => {
    const timestamp = new Date().getTime();

    if (item.resourceType==='innerSource'||item.resourceType==='outerSource') {
      window.open(`/center-home/menu/asset-resource-browse?${AnchorId}=${item?.dataAssetId}&${AnchorDirId}=${item?.dirId}&timestamp=${timestamp}`);
    } else if (item.resourceType==='dataAsset') {
      window.open(`/center-home/menu/asset-browse?${AnchorId}=${item?.dataAssetId}&${AnchorDirId}=${item?.dirId}&templateType=${LocalStorage.get(`templateType-${appId}`)}&timestamp=${timestamp}`);
    } else {
      showMessage('warn', '资产目录类型不是资源也不是资产!');
    }
  
  }

  const jumpToRelation = (relation) => {
    const timestamp = new Date().getTime();

    if (relation.resourceType==='innerSource'||relation.resourceType==='outerSource') {
      window.open(`/center-home/menu/asset-resource-browse?${AnchorId}=${relation?.dataAssetId}&${AnchorDirId}=${relation?.dirId}&timestamp=${timestamp}`);
    } else if (relation.resourceType==='dataAsset') {
      window.open(`/center-home/menu/asset-browse?${AnchorId}=${relation?.dataAssetId}&${AnchorDirId}=${relation?.dirId}&timestamp=${timestamp}`);
    } else {
      showMessage('warn', '资产目录类型不是资源也不是资产!');
    }
  }

  const onOk = async() => {
    try {
      const row = await form?.validateFields();
      const newElements = [...elements];
      (newElements||[]).forEach(element => {
        if (row.hasOwnProperty(element.name)) {
          element.value = row[element.name];
        }
      });

      const params = {
        dirId,
      }

      if ((metadataId||'')!=='') {
        params.metadataId = metadataId;
      }
      setConfirmLoading(true);

      // 请求完成后的操作
      const afterRequest = (getData) => {
        setConfirmLoading(false);
        setCurrentAction('detail');
        getData()
        showMessage("success",(action==='add')?"新增成功":"修改成功");
        onChange && onChange();
      }

      if(draftId){ //资产草稿内的直接更新
          dispatch({
          type: 'assetmanage.updateDraftDataAsset',
          payload: {
            data:{ ...assets, elements: newElements } 
          },
          callback: () => {
            afterRequest(getDraftData);
          },
          error: () => {
            setConfirmLoading(false);
          }
        })
      }
      else if(saveAsDraft){ //资产管理内的资产要求保存为草稿
        dispatch({
          type: 'assetmanage.saveAsDraftDataAsset',
          payload: {
            params: {
              operation:'change'
            },
            data:{ ...assets, elements: newElements } 
          },
          callback: () => {
            afterRequest(getAsset);
          },
          error: () => {
            setConfirmLoading(false);
          }
        })
      }else{ //资产管理内的资产不要求保存为草稿则直接保存
        dispatch({
          type: 'assetmanage.checkCodeIsExist',
          payload: { 
            data: action==='add' ? { elements: newElements } : { ...assets, elements: newElements } 
          },
          callback: isExist => {
            if (isExist === 'true') {
              setConfirmLoading(false);
              showMessage('warn', '已存在相同的资产目录编号,请重新输入');
            } else {
              dispatch({
                type: 'assetmanage.addOrUpdateDataAsset',
                payload: { 
                  params,
                  data: action==='add' ? { elements: newElements } : { ...assets, elements: newElements } 
                },
                callback: () => {
                  afterRequest(getAsset);
                },
                error: () => {
                  setConfirmLoading(false);
                }
              })
            }
          },
          error: () => {
            setConfirmLoading(false);
          }
        })
        }
    } catch (errInfo) {
      showMessage('warn', '请完成资产必填项')
    }
  }

  // const onFoldButtonClick = (attribute, fold) => {
  //   let newAttributesFoldMap = {...attributesFoldMap};
  //   newAttributesFoldMap[attribute] = fold;

  //   setAssetParams({...assetParams, attributesFoldMap: newAttributesFoldMap});
  // }

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

   //选中元数据后 内容回填.
   const fillElementValueBeforeCreate = (mid = metadataId) => {
    dispatch({
      type: 'assetmanage.fillElementValueBeforeCreate',
      payload: {
        params: {
          metadataIds: mid
        }
      },
      callback: data => {
        let _fieldsValue = {};
        (data||[]).forEach(element => {
          _fieldsValue[element.name] = element.value;
        })

        form?.setFieldsValue(_fieldsValue);
      }
    })
  }

  const onAssetTag = (value) => {
    setSelectTag(value);
    setAssetTagModalVisible(true);
  }

  const onAssetTagModalCancel = (refresh = false) => {
    setAssetTagModalVisible(false);

    if (refresh) {
      getResourceRelations();

      let event = new Event('storage');
      event.key = 'tagChange';
      window?.dispatchEvent(event);
    }
  }

  // const formItemLayout = {
  //   labelCol: {
  //     xs: { span: 24 },
  //     sm: { span: 5 },
  //   },
  //   wrapperCol: {
  //     xs: { span: 24 },
  //     sm: { span: 17 },
  //   },
  // };

  const elementEditComponent = (element) => {
    if (element.name==='资产项') return <MetadataInfo />;

    if (element.name === '数据源系统') {
      return (
        <Select 
          allowClear
          loading={loadingSystems}
          disabled={element.manualMaintain==='否'}
        >
        {
          systems?.map((system, index) => {
            return <Select.Option key={index} value={system.scopeName}>
            {system.scopeName}
            </Select.Option>
          })
        }
        </Select>
      )
    }

    if (element.name === '主题域分组') {
      return (
        <Select 
          allowClear
          disabled={element.manualMaintain==='否'}
        >
        {
          treeData?.map((item, index) => {
            return <Select.Option key={index} value={item.text}>
            {item.text}
            </Select.Option>
          })
        }
        </Select>
      )
    }

    if (element.name === '主题域') {
      return (
        <Select 
          allowClear
          disabled={element.manualMaintain==='否'}
        >
        {
          domains?.map((item, index) => {
            return <Select.Option key={index} value={item.text}>
            {item.text}
            </Select.Option>
          })
        }
        </Select>
      )
    }

    if (element.name === '业务对象') {
      return (
        <Select 
          allowClear
          disabled={element.manualMaintain==='否'}
        >
        {
          businessData?.map((item, index) => {
            return <Select.Option key={index} value={item.text}>
            {item.text}
            </Select.Option>
          })
        }
        </Select>
      )
    }

    if (element.selectMode==='单选' || element.selectMode==='多选') {
      const tmp = (element.optional??'').split(',')

      if ((tmp??[]).indexOf('部门列表')!==-1) {
        return <DepartmentItem loading={loadingDepartments} departments={departments} multiple={element.selectMode==='多选'} /> 
      }
  
      if ((tmp??[]).indexOf('用户列表')!==-1) {
        return <UserItem loading={loadingUsers} users={users} multiple={element.selectMode==='多选'} />  
      }
    }

    if (element.selectMode==='单选') {
      const tmp = (element.optional??'').split(',')

      return (
        <Select 
          allowClear
          disabled={element.manualMaintain==='否'}
        >
        {
          tmp?.map((value, index) => {
            return <Select.Option key={index} value={value}>
            {value}
            </Select.Option>
          })
        }
        </Select>
      )
    }

    if (element.selectMode==='多选') return <MultipleSelect element={element}/>;

    return <Input disabled={element.manualMaintain==='否'} />;
  }

  const elementDetailComponent = (item) => {
    if (item.name === '资产项') {
      return <MetadataInfo config={false} value={item.value||''} terms={terms} />;
    }

    if (item.name === '指标标准编码') {
      return <IndexCode value={item.value||''} terms={terms} />;
    }

    if (item.selectMode==='单选' || item.selectMode==='多选') {
      const tmp = (item.optional??'').split(',')

      if ((tmp??[]).indexOf('用户列表')!==-1) {
        return <UserItem readonly={true} value={item.value||''} loading={loadingUsers} users={users} multiple={item.selectMode==='多选'} />  
      }
    }

    return <span className='text-color'>{highlightSearchContentByTerms(item.value||'', terms)}</span>;
  }

  const onExportClick = () => {
    dispatch({
      type: 'assetmanage.exportMetadataAttributes',
      payload: { 
        responseType: 'blob', 
        params: {  
          tableId: metadata?.metadataTableId
        } 
      },
      callback: (res) => {
        download(res);
      }
    })
  }

  // const onAttributeMaintainCancel = () => {
  //   setAttributeMaintainParam({visible: false, metadataId: undefined});
  // }

  // const onAttributeMaintainChange = (catalogId) => {
  //   if (catalogId === '1') {
  //     setPagination({...pagination, pageNum: 1});
  //     getMetadataAttributes();
  //   } else {
  //     getMetadataStandardList();
  //   }
  // }

  const getMetadataStandardList = () => {
    setMetadata(prevMetadata => {
      if (prevMetadata?.metadataTableId) {
        dispatch({
          type: 'assetmanage.getMetadataStandardList',
          payload: {
            data: {
              parentMetadataId: prevMetadata?.metadataTableId,
            },
            params: {
              page: 1,
              size: 999999
            }
          },
          callback: data => {
            setStandardList(data?.content);
          },
        });
      }

      return prevMetadata;
    })
  }

  const onValuesChange = (changedValues, allValues) => {
    if (changedValues.hasOwnProperty('主题域分组')) {
      setCurrentDomainGroup(changedValues['主题域分组']);
      form.setFieldsValue({'主题域': '', '业务对象': ''});
    } else if (changedValues.hasOwnProperty('主题域')) {
      setCurrentBussinessDomain(changedValues['主题域']);
      form.setFieldsValue({'业务对象': ''});
    }
  }

  return (
    <div
      className='flex asset-action'
      style={{
        height: '100%',
        flexDirection: 'column',
      }}
    >
      {
        (!readonly && (reference===AssetManageReference||canEdit||draftId)) && <div className='flex' style={{ justifyContent: 'right' }}>
          <Space>
            {
              currentAction==='detail' ? <Tooltip title={isExist?'资产存在草稿箱中，不允许编辑':''}><Button type='primary' disabled={isExist} onClick={onActionButtonClick}>编辑</Button></Tooltip> : <React.Fragment>
                <Button type='primary' onClick={onCancelButtonClick}>取消</Button>
                {saveAsDraft?<Button type='primary' onClick={onActionButtonClick}>保存为草稿</Button>:
                  <Button type='primary' onClick={onActionButtonClick}>保存</Button>}
              </React.Fragment>
            }
            {/* <Button type='primary' onClick={onAuthorizationButtonClick}>授权</Button> */}
          </Space>
        </div>  
      }
      {
        (action!=='add' && (id||'')!=='') && <div> 
          <div className='pl-common py-compact-common'>
            <Descriptions column={1}>
              <Descriptions.Item 
                label={<div className='title-text' style={{ textAlign: 'right', width: 90 }}>资产目录路径</div>} 
                style={{ paddingBottom: 0 }}
              >
                <div className='flex' style={{ flexDirection: 'column' }}>
                {
                  (assetPaths||[]).map((item, key) => {
                    return (
                      <a key={key} onClick={() => { jumpToPath(item); }}>
                        <span>{item?.dataAssetName||''}</span>
                      </a>                        
                    );
                  })
                }
                </div>
              </Descriptions.Item>
              {/* <Descriptions.Item label={<div className='title-text' style={{ textAlign: 'right', width: 90 }}>资产目录标签</div>} style={{ paddingBottom: 15 }}>
                <AppContext.Consumer>
                {
                  value => {
                    return (currentAction==='add'||currentAction==='edit')?<Tag styleType='complex' id={id} creator={value?.user?.userName||''} onAssetTag={onAssetTag} />:<Tag id={id} creator={value?.user?.userName||''} />
                  } 
                }
                </AppContext.Consumer>
              </Descriptions.Item> */}
              {/* <Descriptions.Item 
                label={<div className='title-text' style={{ textAlign: 'right', width: 80 }}>关联关系</div>} 
                style={{ paddingBottom: 0 }}
              >
                <div className='flex' style={{ flexDirection: 'column' }}>
                {
                  (resourceRelations||[]).map((item, key) => {
                    return (
                      <a key={key} onClick={() => { jumpToRelation(item); }}>{item?.dataAssetName||''}</a>
                    );
                  })
                }
                </div>              
              </Descriptions.Item> */}
            </Descriptions>
          </div>
        </div>  
      }

      {/* <div
        style={{
          flex: 1,
          overflow: 'auto',
        }}
      > */}
        <Spin 
          spinning={loading}
        >
          <Form form={form} onValuesChange={onValuesChange}>
            <Radio.Group className='mb-3' value={currentAttribute} onChange={(e) => {
              setCurrentAttribute(e.target.value)
            }}>
            {
              (attributes??[]).map((item,key) => (
                <Radio.Button key={key} value={item}>{item}</Radio.Button>
              ))
            }
            </Radio.Group>
            {
              attributes?.map((attribute, index) => {
                return <div key={index} style={{ display: (attribute===currentAttribute)?'':'none' }}>
                  <Descriptions column={1} bordered>
                  {
                    wholeElements?.length>0 && elements?.map((element, index) => {
                      if (element.type!==attribute || element.name === '资产项') return null;

                      let interpretation = null;
                      const filterElements = wholeElements?.filter(_element => _element.id === element.id);
                      if (filterElements.length>0) {
                        interpretation = filterElements[0].interpretation;
                      }

                      return (
                        <Descriptions.Item 
                          key={index}
                          label={
                            <span>
                            {element.name}
                            {
                              (currentAction==='add'||currentAction==='edit') && (element.required === '是') && <span style={{ color: 'red' }}>*</span>
                            }
                            </span>
                          }
                          labelStyle={{ width: 180 }}
                        >
                        {
                          (currentAction==='add'||currentAction==='edit') ? 
                          <Row gutter={8} align='middle'>
                            <Col span={22}>
                              <Form.Item 
                                  label=''
                                  name={element.name}
                                  rules={[{ required: element.required === '是' }]}    
                                  style={{ marginBottom: 0 }} 
                                > 
                                {elementEditComponent(element)}                              
                                </Form.Item>
                            </Col>
                            {
                              interpretation &&  <Col span={2}>
                                <Tooltip placement="left" title={interpretation}>
                                  <QuestionCircleOutlined style={{ fontSize: 16 }} />
                                </Tooltip>
                              </Col>
                            }
                          </Row>      
                          : <React.Fragment>
                          <Row gutter={8} align='middle'>
                            <Col span={22}>
                            { elementDetailComponent(element) }
                            </Col>
                            {
                              interpretation &&  <Col span={2}>
                                <Tooltip placement="left" title={interpretation}>
                                  <QuestionCircleOutlined style={{ fontSize: 16 }} />
                                </Tooltip>
                              </Col>
                            }
                          </Row>  
                          </React.Fragment>
                        }
                        </Descriptions.Item>
                      )
                    })
                  }
                  </Descriptions>
                </div>
              })
            }
          </Form>

        </Spin>
      {/* </div>   */}
      
      <div>
      <Divider orientation='left'>字段级资产目录信息</Divider>
      </div>
    
      <Space style={{ marginLeft: 'auto' }}>
        {/* {
          (reference===AssetManageReference||canEdit) && <Button 
            type='primary' 
            onClick={() => {
              if (metadata?.metadataTableId) {
                setAttributeMaintainParam({ 
                  visible: true,
                  metadataId: metadata?.metadataTableId
                });
              } else {
                showMessage("warn","该资产目录没有关联元数据信息");
              }
            }}
          >
            字段级维护
          </Button>
        } */}
        {/* <Dropdown overlay={
          <Menu onClick={({ key })=>{
            if (key === 'lineage') {
              if (metadata?.metadataTableId) {
                app?.setGlobalState?.({
                  message: 'data-govern-show-metadata-relation',
                  data: { id: metadata?.metadataTableId, type: 'lineage' } 
                })
              } else {
                showMessage("warn","该资产目录没有关联元数据信息");
              }
            } else if (key === 'impact') {
              if (metadata?.metadataTableId) {
                app?.setGlobalState?.({
                  message: 'data-govern-show-metadata-relation',
                  data: { id: metadata?.metadataTableId, type: 'impact' } 
                })
              } else {
                showMessage("warn","该资产目录没有关联元数据信息");
              }
            }
          }}>
            <Menu.Item key="lineage">血缘分析</Menu.Item>
            <Menu.Item key="impact">影响分析</Menu.Item>
          </Menu>
        }>
          <Button>
            <Space>
                关系分析
                <DownOutlined />
            </Space>
          </Button>
        </Dropdown> */}
        <Input size="middle"
          placeholder="搜索中英文名称"
          value={keyword}
          bordered={true} allowClear
          style={{ width: 200 }}
          onChange={(e) => {
            setPagination({...paginate, pageNum: 1})
            setKeyword(e.target.value)
          }} />
        {/* {
          (reference===AssetManageReference||canEdit) && <Button type='primary' onClick={() => {
              uploadRef.current?.chooseFile()
            }}>导入</Button>
        } */}
        {/* <Button type='primary' onClick={() => {
          uploadRef.current?.chooseFile()
        }}>导入</Button>
        <Button type='primary' onClick={onExportClick}>导出</Button> */}
      </Space>
      
      <Table
        className='mt-3'
        loading={loadingMetadataColumnList}
        columns={permissionId?columns:columns.filter(item => item.dataIndex !== 'permission')} 
        rowKey='_id'
        dataSource={tableData||[]}
        pagination={{
          position: ['bottomLeft'],
          size: 'small',
          total: (metadataColumnList||[]).length,
          showTotal: (total) => `共${total}项`,
          showSizeChanger: true,
          current: pageNum,
          pageSize,
          onChange: (_pageNum, _pageSize) => {
            setPagination({ pageNum: _pageNum||1, pageSize: _pageSize || 20 });
          },
          onShowSizeChange: (_pageNum, _pageSize) => {
            setPagination({ pageNum: _pageNum||1, pageSize: _pageSize || 20 });
          },
        }} 
      />
      
      {/* <Upload ref={uploadRef} accept={'.xls,.xlsx'} upload={(files) => {
          dispatch({
            type: 'assetmanage.importMetadataAttributes',
            payload: { 
              fileList: [files[0]],
              params: {
                catalog: app?.env?.domainId||LocalStorage.get('assetsEnv'),
              }
            },
            callback: (data) => {
              getMetadataAttributes();
            },
            error: () => {
              
            }
          })
        }} /> */}

      {/* <AttributeMaintain 
        visible={attributeMaintainParam.visible}
        metadataId={attributeMaintainParam.metadataId}
        onCancel={onAttributeMaintainCancel}
        onChange={onAttributeMaintainChange}
      /> */}
      <AppContext.Consumer>
      {
        value => {
          return (
            <AssetTagModal
              visible={assetTagModalVisible}
              id={id}
              tag={selectTag}
              creator={value?.user?.userName||''}
              onCancel={onAssetTagModalCancel}
            />
          );
        } 
      }
      </AppContext.Consumer>
      {contextHolder}
    </div>
  )
}

export default AssetAction;


const MultipleSelect = ({ value = null, element, onChange }) => {

  const handleChange = (values) => {
    onChange?.(values?.join(','))
  }

  return (
    <Select 
      allowClear
      value={value?value?.split(','):[]}
      mode='multiple'
      disabled={element.manualMaintain==='否'}
      onChange={handleChange}
    >
    {
      element.optional?.split(',').map((value, index) => {
        return <Select.Option key={index} value={value}>
        {value}
        </Select.Option>
      })
    }
    </Select>
  )
}

const CascaderItem = ({ value = null, data, onChange, ...restProps }) => {

  const handleChange = (values) => {
    onChange?.((!values||values.length===0)?'':values[values.length-1]);
  }

  return (
    <Cascader 
      allowClear
      options={data}
      value={value?value.split('/'):undefined}
      onChange={handleChange}
      {...restProps}
    />
  )
}

const DepartmentItem = ({ loading, departments, value, onChange, multiple = false }) => {
  const [searchValue, setSearchValue] = React.useState()
  const [options, setOptions] = React.useState()

  useDebounceEffect(() => {
    setOptions(
      (departments??[])
        .filter(item => !searchValue || (item.organizationname??'').toLowerCase().indexOf(searchValue.toLowerCase())!==-1)
        .map(item => ({
          label: item.organizationname,
          value: item.organizationname,
        }))
    )
  }, [searchValue, departments], { wait: 300 })

  const currentValue = useMemo(() => {
    if (!value) return undefined

    if ((options??[]).length>0) {
      if (multiple) {
        return (value??'').split(',')
      } else {
        return value
      }
    }

    return undefined
  }, [value, options])

  return (
    <Select loading={loading} showSearch allowClear
      mode={multiple?'multiple':null}
      placeholder='请选择部门'
      value={currentValue}
      searchValue={searchValue}
      onSearch={(val) => {
        setSearchValue(val)
      }}
      onClear={() => {
        setSearchValue()
      }}
      filterOption={false}
      options={options}
      onChange={(val) => {
        if (multiple) {
          onChange?.((val??[]).toString())
        } else {
          onChange?.(val)
        }
      }}
    />
  )
}

export const UserItem = ({ loading, users, value, onChange, readonly=false, terms = [], multiple = false, showTooltip = false }) => {
  const [searchValue, setSearchValue] = React.useState()
  const [options, setOptions] = React.useState()

  const userInfo = React.useMemo(() => {
      if (value) {
        const tmp = (value??'').split(',')
        const newUserInfo = []
        tmp.map(item => {
          const index = (users??[]).findIndex(_item => _item.employeenumber === item)
          if (index !== -1) {
            const currentUser = users[index]
            newUserInfo.push(`${currentUser.employeenumber}(${currentUser.chinesename}/${currentUser.organizationname})`)
          }
        })
        
        return newUserInfo.toString()
      }

      return ''
  }, [value, users])

  useDebounceEffect(() => {
    setOptions(
      (users??[])
        .filter(item => !searchValue 
          || (item.employeenumber??'').toLowerCase().indexOf(searchValue.toLowerCase())!==-1 
          || (item.chinesename??'').toLowerCase().indexOf(searchValue.toLowerCase())!==-1
          || (item.organizationname??'').toLowerCase().indexOf(searchValue.toLowerCase())!==-1)
        .map(item => ({
          label: `${item.employeenumber}(${item.chinesename}/${item.organizationname})`,
          value: item.employeenumber,
        }))
    )
  }, [searchValue, users], { wait: 300 })

  const currentValue = useMemo(() => {
    if (!value) return undefined

    if ((options??[]).length>0) {
      if (multiple) {
        return (value??'').split(',')
      } else {
        return value
      }
    }

    return undefined
  }, [value, options])

  return (
      <React.Fragment>
      { 
          readonly ? <Tooltip title={showTooltip?userInfo:''}>
          <Typography.Text ellipsis={true}>
          {highlightSearchContentByTerms(userInfo, terms)}
          </Typography.Text>
          </Tooltip> : <Select loading={loading} showSearch allowClear
          placeholder='请选择用户'
          mode={multiple?'multiple':null}
          value={currentValue}
          searchValue={searchValue}
          onSearch={(val) => {
            setSearchValue(val)
          }}
          onClear={() => {
            setSearchValue()
          }}
          filterOption={false}
          options={options}
          onChange={(val) => {
            if (multiple) {
              onChange?.((val??[]).toString())
            } else {
              onChange?.(val)
            }
          }}
        />
      }
      </React.Fragment>
  )
} 