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 copy from "copy-to-clipboard";  
import produce from 'immer';

import MetadataInfo from './MetadataInfo';
import { dispatch } from '../../../../model';
import { highlightSearchContentByTerms, showMessage, paginate, isPostAsset } from '../../../../util';
import { AppContext, appId } from '../../../../App';
import Tag from '../../Tag';  
import Separate from './Separate';
import { AnchorId, AnchorDirId, AssetManageReference, AssetRecycleReference, AssetDraftReference, Action } from '../../../../util/constant';
import IndexCode from './IndexCode';
import Upload from './Upload';
import Table from '../../ResizeableTable';
import SubsribeButton from './subscribe-button';

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 RelationAssets from './asset-relation-assets';
import QuestionModalButton from './QuestionModalButton';
import MetaMatchStandard from './MetaMatchStandard';
import './AssetAction.less';
import { useGetStandardMatchByIds } from '@/hooks/standard';
import ImportActionComment from "./ImportActionComment"
import { useGetModalInfoAndAction } from '@/hooks/common';
import AssetsCompareModal from './AssetsCompareModal';
import TagCell, { TagSelectPopup } from './tag-help'
import MatchMetaInfo from './MatchMetaInfo';

const AssetAction = React.forwardRef(function (props, ref) {
  const { id, dirId, action, terms, onChange, reference, readonly = false, permissionId, catalog, template } = props;

  const [ currentAction, setCurrentAction ] = useState(action);
  const [ assetParams, setAssetParams ] = useState({ assets: {}, attributes: [] });
  const [ elements, setElements ] = 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 { assets, attributes } = 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 [loadingEditPermission, setLoadingEditPermission] = useState(false); 
  const [canEdit, setEdit] = useState(false);
  const [metadata, setMetadata] = useState(undefined);
  const [metadataColumnList, setMetadataColumnList] = useState(undefined);
  const [modifyMetadataColumnList, setModifyMetadataColumnList] = useState();
  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 [publishedAssetPaths, setPublishedAssetPaths] = useState([]);
  const [publishedAsset, setPublishedAsset] = useState();
  const [isStructured, setStructured] = useState();
  const [businessElements, setBusinessElements] = useState();
  const [businessColumns, setBusinessColumns] = useState();
  const [sqlinfo,setSqlInfo] = useState([])
  const [resoureTagMap, setResourceTagMap] = useState()

  const [loadingSaveAsDraft, setLoadingSaveAsDraft] = React.useState(false)
  const [needSaveAsDraft, setNeedSaveAsDraft] = React.useState()
  const [selectData,setSelectData] = useState({
    metadataId:'',
    metadataPath:''
  })

  const app = useContext(AppContext);
  const uploadRef = useRef(undefined);
  const [columnForm] = Form.useForm()
  const relationAssetsRef = useRef();
  const comparemodal = useGetModalInfoAndAction()

  const [form] = Form.useForm();

  useEffect(()=>{
    if(assets?.metadataId)
      setSelectData({metadataId:assets.metadataId,metadataPath:assets.metadataPath})
  },[assets])

  React.useImperativeHandle(ref, () => ({
    validate: async () => {
      // await form.validateFields();
      await columnForm?.validateFields();
    },
    getAsset: () => {
      const row = form?.getFieldsValue();
      const newElements = [...elements];
      (newElements||[]).forEach(element => {
        if (row.hasOwnProperty(element.name)) {
          element.value = row[element.name];
        }
      });

      const data = (action==='add') ? { elements: newElements } : { ...assets, elements: newElements };

      return {...data, businessRelations: relationAssetsRef.current?.assets, businessColumns: modifyMetadataColumnList};
    }
  }), [action, assets, form, elements, modifyMetadataColumnList])

  const columns = [
    {
      title: '技术ID(英文名称)',
      dataIndex: 'name',
      width: 160,
      ellipsis: true,
      render: (text, record, _) => {
        return (
          <Tooltip title={text||''}>
            <a onClick={() => {
              window.open(`/center-home/metadetail?mid=${record.metadataColumnId}&action=metadetail&type=detail&manager=true&activekey=1`)
            }}>
            {highlightSearchContentByTerms(text||'', terms)}
            </a>
          </Tooltip>
        );
      }
    },
    {
      title: '名称',
      dataIndex: 'cnName',
      // width: 200,
      ellipsis: true,
      render: (text, _) => highlightSearchContentByTerms(text||'', terms)
    },
    {
      title: '标注信息',
      dataIndex: 'annotation',
      ellipsis: true,
      render: (text, record) => {
        if(currentAction==='edit'){
          return <Form.Item name={record._id} style={{marginBottom:0}}>
            <Input  />
          </Form.Item>
        }else{
          return highlightSearchContentByTerms(text||'', terms)
        }
        
      }
    },
    {
      title: '类型',
      dataIndex: 'typeName',
      width: 100,
      ellipsis: true,
      render: (text, _) => highlightSearchContentByTerms(text||'', terms)
    },
    {
      title: '长度',
      dataIndex: 'size',
      width: 60,
      ellipsis: true,
    },
  ];

  const businessActionCol = {
    title: '操作',
    dataIndex: 'action',
    width: 80,
    render: (_, record, index) => {
      return <Button 
        size='small'
        onClick={() => {
          setModifyMetadataColumnList(prev => {
            const newModifyList = [...prev]
            newModifyList.splice(index, 1)

            return newModifyList
          })
        }}
      >
      删除
      </Button> 
    }
  }

  useEffect(() => {
    if (!readonly) {
      getSystems();
    }

    getUsers();
    getTreeData();
    getDepartments();
    if (action === 'add') {
      getElements();
    } else {
      if (id) {
        setPagination({...pagination, pageNum: 1});
        getAssetPaths();
        checkDataAssetEditable();
        getAsset();

      } else {
        setMetadataId('');
        setAssetParams({...assetParams, ...{assets: {}, attributes: []}});
        setCurrentAttribute();
      }
    }    
    //eslint-disable-next-line react-hooks/exhaustive-deps
  }, [id, dirId])

  useEffect(() => {
    if (assets?.templateType) {
      judgeNeedSaveAsDraft()
    }
  }, [assets])

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

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

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

  useEffect(() => {
    if ((businessElements??[]).length>0) {
      setBusinessColumns(
        (businessElements??[]).map(item => ({
          ...item,
          title: <span>
            {
              item.required==='是' && <span style={{
                marginRight: 4,
                color: '#ff4d4f',
              }}>*</span>
            }
            { item.name }
          </span>,
          dataIndex: item.enName,
          width:160,
          ellipsis: true,
          render: (text, record, index) => {
            let value = ''
            const _index = (record.columnElements??[]).findIndex(_item => item.id === _item.id)
            if (_index !== -1) {
              value = record.columnElements[_index].value
            }

            columnForm?.setFieldsValue({ [`column${item.enName}${index}`]: value })
            return (
              <Form.Item name={`column${item.enName}${index}`}
                rules={[{ required: (item.required==='是')?true:false, message: `请填写${item.enName}!` }]}
                style={{ marginBottom: 0 }}
              >
                <MetadataColumnEditableItem 
                  value={value} 
                  isEdit={currentAction!=='detail'} 
                  terms={terms} 
                  onChange={(e) => {
                    onMetadataColumnEditableItemChange(e.target.value, item.enName, index)
                  }} 
                />
              </Form.Item>
            )
          } 
        }))
      )
    }
  }, [businessElements, currentAction, terms, modifyMetadataColumnList])

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

  useEffect(() => {
    let _isStructured = template?.structedStateEnum==='structured'||assets?.structedState==='structured'

    setStructured(_isStructured)

    if (!_isStructured) {
      getBusinessColumns()
    }
  }, [assets, template])

  useEffect(() => {
    if (assets) {
      setMetadataColumnList(isStructured?assets.columns:assets.businessColumns)
      setModifyMetadataColumnList(isStructured?assets.columns:assets.businessColumns)
    }
  }, [assets, isStructured])

  const [tableData, total] = useMemo(() => {
    let currentMetadataColumnList = currentAction!=='detail' ? [...modifyMetadataColumnList||[]] : [...metadataColumnList||[]]

    return [paginate(currentMetadataColumnList, pageNum, pageSize), currentMetadataColumnList.length];
  }, [metadataColumnList, modifyMetadataColumnList, pagination, keyword, currentAction, assets])

  const resourceIds = useMemo(()=>{
    return tableData?.map((item)=>{
        return item.metadataColumnId
    })
  },[tableData])

  useEffect(()=>{
    if(tableData.length){
      getResourceTag()
    }
  },[tableData])
  const checkStandard=true
  const {standardmap} = useGetStandardMatchByIds({metadataIds:resourceIds,checkStandard})

  const standardmatch={
    title: '匹配标准',
    ellipsis:true,
    width:150,
    // resize:true,
    className: 'table-tag-cell',
    render:(_,record)=>{
        return <MetaMatchStandard id={record.metadataColumnId} isManager={false} item={standardmap[record.metadataColumnId]} />
    }
  }

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

    const getResourceTag = () => {
      console.log(tableData)
    const ids = (tableData??[]).map(item =>{
      return  item.id?item.id: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 cols = useMemo(() => {
    let newCols = []

    newCols = isStructured?[...columns]:[...businessColumns??[]]
    if (!isStructured && currentAction!=='detail') {
      newCols.push(businessActionCol)
    }
 
    return [...newCols,standardmatch,tagCol]
  }, [currentAction, isStructured, columns, businessColumns, businessActionCol])



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

  const getAssetPaths = () => {
    let payload = {
      dataAssetId: id,
    }
    if (reference === AssetDraftReference) {
      payload = {
        draftId: id,
      }
    }

    dispatch({
      type: (reference===AssetDraftReference)?'assetmanage.getDraftAssetPaths':'assetmanage.getAssetPaths',
      payload,
      callback: data => {
        setAssetPaths(data||[]);
      }
    });
  }

  const getPublishedAssetPaths = (id) => {
    dispatch({
      type: 'assetmanage.getAssetPaths',
      payload: {
        dataAssetId: id,
      },
      callback: data => {
        setPublishedAssetPaths(data)
      }
    });
  }

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

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

  const getBusinessColumns = () => {
    if (template?.type||assets?.templateType) {
      dispatch({
        type: 'assetmanage.listBusinessColumnElements',
        payload: {
          templateType: template?.type||assets?.templateType,
        },
        callback: (data) => {
          setBusinessElements(data)
        }
      })
    }
  }

  const getElements = () => {
    setLoading(true);
    dispatch({
      type: 'assetmanage.listElements',
      callback: (data) => {
        setLoading(false);
        const _attributes = Array.from(new Set((data??[]).map(item => item.type)));
        setElements(data);
        setAssetParams({ attributes: _attributes });
        if ((_attributes??[]).length > 0) {
          setCurrentAttribute(_attributes[0])
        }
      },
      error: () => {
        setLoading(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: 'pds.getDepartments',
      callback: (data) => {
        setLoadingDepartments(false);
        setDepartments(data);
      },
      error: () => {
        setLoadingDepartments(false);
      }
    })
  }

  const checkDataAssetEditable = () => {
    let params = {
      dataAssetId: id,
    }
    if (reference === AssetDraftReference) {
      params = {
        draftId: id,
      }
    }

    setLoadingEditPermission(true);
    dispatch({
      type: (reference===AssetDraftReference)?'assetmanage.checkDraftEditable':'assetmanage.checkDataAssetEditable',
      payload: {
        params
      },
      callback: value => {
        setLoadingEditPermission(false);
        setEdit(value==='true'?true:false);
      },
      error: () => {
        setLoadingEditPermission(false);
      }
    })
  }

  const judgeNeedSaveAsDraft = () => {
    setLoadingSaveAsDraft(true)
    dispatch({
      type: 'assetmanage.checkIsNeedSaveAsDraft',
      payload: {
        params: {
          templateType: assets?.templateType,
        }
      },
      callback: (data) => {
        setLoadingSaveAsDraft(false)
        setNeedSaveAsDraft((data==='true')?true:false)
      },
      error: () => {
        setLoadingSaveAsDraft(false)
      }
    })
  }

  const getAsset = () => {
    setLoading(true);

    let url = 'assetmanage.getDataAssetDetail';
    let payload = {
      dataAssetId: id,
      dirId: dirId,
      checkPermission: reference!==AssetManageReference
    };
    if (reference === AssetDraftReference) {
      url = 'assetmanage.getDraftDetail';
      payload = {
        params: {
          draftId: id,
        }
      };
    }

    dispatch({
      type: url,
      payload,
      callback: data => {
        setLoading(false);

        //资产草稿版本比对
        if (reference === AssetDraftReference && data?.dataAssetId && (data?.dirIds??[]).length > 0) {
          getPublishedAssetPaths(data?.dataAssetId)
          getPublishedAsset(data?.dataAssetId, data?.dirIds[0])
        }

        const metadataIndex = data?.elements?.findIndex(item => item.name === '资产项');

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

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

        const _attributes = Array.from(new Set((data?.elements??[]).map(item => item.type)))

        setAssetParams({ assets: data, attributes: _attributes });
        const sqls = (data.questionSqlPairs||[]).map((i,key)=>{
          return {...i,id:key}
        })
        setSqlInfo(sqls)
        let map = {};
        (data.columns||[]).forEach((i)=>{
          map[i._id] = i.annotation
        })
        columnForm.setFieldsValue(map)
        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 getPublishedAsset = (id, dirId) => {
    dispatch({
      type: 'assetmanage.getDataAssetDetail',
      payload: {
        dataAssetId: id,
        dirId: dirId,
        checkPermission: false
      },
      callback: data => {
        setPublishedAsset(data)
      }
    })
  }

  const onMetadataColumnEditableItemChange = (val, dataIndex, index) => {
    const _index = (pageNum-1)*pageSize + index;
    setModifyMetadataColumnList(
      produce(modifyMetadataColumnList, (draft) => {
        if ((draft??[]).length > _index) {
          const columnElements = draft[_index].columnElements
          const __index = (columnElements??[]).findIndex(item => item.enName === dataIndex)
          
          if (__index !== -1) {
            columnElements[__index].value = val
          }
        }
      })
    )
  }

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

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

  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=${assets?.templateType}&timestamp=${timestamp}`);
    } else {
      showMessage('warn', '资产目录类型不是资源也不是资产!');
    }
  
  }

  const onOk = async() => {
    try {
      // const row = await form?.validateFields();
      const row = form?.getFieldsValue();
      const formdata = await columnForm?.validateFields();

      const {columns} = assets
      
      const newElements = [...elements];
      (newElements||[]).forEach(element => {
        if (row.hasOwnProperty(element.name)) {
          element.value = row[element.name];
        }
      });

      const tempcolumns = (columns||[]).map((item)=>{
        return {...item,annotation:formdata[item._id]}
      })

      setConfirmLoading(true);

      if (reference === AssetDraftReference) {
        let data = action==='add' ? { elements: newElements } : { ...assets, elements: newElements }
        data = {...data,...selectData,columns:tempcolumns,questionSqlPairs:sqlinfo, businessRelations: relationAssetsRef.current?.assets, businessColumns: modifyMetadataColumnList}
        
        dispatch({
          type: 'assetmanage.updateDraft',
          payload: { 
            params: {
              isAdmin: true,
            },
            data,
          },
          callback: () => {
            setConfirmLoading(false);
            setCurrentAction('detail');
            getAsset();
            showMessage("success",(action==='add')?"新增成功":"修改成功");
            onChange && onChange();
          },
          error: () => {
            setConfirmLoading(false);
          }
        })
      } else {
        let params = {
          dirId,
          metadataId: selectData.metadataId??'',
          operation: 'change',
        }

        let data = action==='add' ? { elements: newElements } : { ...assets, elements: newElements }

        data = {...data,...selectData,columns:tempcolumns,questionSqlPairs:sqlinfo, businessRelations: relationAssetsRef.current?.assets, businessColumns: modifyMetadataColumnList}

        dispatch({
          type: needSaveAsDraft?'assetmanage.saveAsDraft':'assetmanage.addOrUpdateDataAsset',
          payload: { 
            params,
            data,
          },
          callback: () => {
            setConfirmLoading(false);
            setCurrentAction('detail');
            getAsset();
            showMessage("success",(action==='add')?"新增成功":"修改成功");
            onChange && onChange();
          },
          error: () => {
            setConfirmLoading(false);
          }
        })
      }
    } catch (errInfo) {
      console.log('Validate Failed:', errInfo);
      showMessage('warn', '请完成资产必填项')
    }
  }

  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 formItemLayout = {
  //   labelCol: {
  //     xs: { span: 24 },
  //     sm: { span: 5 },
  //   },
  //   wrapperCol: {
  //     xs: { span: 24 },
  //     sm: { span: 17 },
  //   },
  // };

  const elementEditComponent = (element) => {
    if (element.selectMode==='单选') {
      return (
        <Select 
          allowClear
          disabled={element.manualMaintain==='否'}
        >
        {
          element.optional?.split(',').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==='否'} defaultValue={element?.value || ''}/>;
  }

  const elementDetailComponent = (item, publishedItem) => {
    return <span>
      <Typography.Text>{highlightSearchContentByTerms(item.value||'', terms)}</Typography.Text>
      {
        publishedItem?.value && publishedItem?.value!==item.value && <Typography.Text className='ml-2' type='danger'><del>{publishedItem?.value}</del></Typography.Text>
      }
      </span>;
  }

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

  const shareAsset = () => {
    if ((assets?.dirIds??[]).length > 0) {
      copy(`${window.location.origin}/center-home/asset-detail?id=${id}&dirId=${assets?.dirIds[0]}&isDraft=${reference===AssetDraftReference}&catalog=${app?.env?.domainId||catalog||LocalStorage.get('assetsEnv')||''}`);
      showMessage('success', '已复制到剪贴板');
    } 
  }

  const onValuesChange = (changedValues, allValues) => {
    
  }

  return (
    <div
      className='flex asset-action'
      style={{
        height: '100%',
        flexDirection: 'column',
      }}
    >
      <Spin spinning={loading||loadingSaveAsDraft||loadingEditPermission}>
        {
          (action!=='add' && (id||'')!=='') && <div> 
            <div className='mb-3'>
              <Row gutter={10}>
                <Col flex='1 1 0' style={{ overflow: 'hidden' }}>
                  <span>资产目录路径: </span>
                  <span>
                  {
                    (assetPaths??[]).length > 0 && (
                      (reference===AssetDraftReference) ? <span>{assetPaths[0].dataAssetName||''}</span> : <a onClick={() => { jumpToPath(assetPaths[0]); }}>
                      {assetPaths[0].dataAssetName||''}
                    </a> )
                  }
                  {
                    (assetPaths??[]).length > 0 && (publishedAssetPaths??[]).length > 0 && assetPaths[0].dirId!==publishedAssetPaths[0].dirId && <Typography.Text className='ml-2 pointer' type='danger' onClick={() => { jumpToPath(publishedAssetPaths[0]) }}>
                      <del>{publishedAssetPaths[0].dataAssetName||''}</del>
                    </Typography.Text>
                  }
                  </span>
                </Col>
                <Col flex={0}>
                  <span>{`访问次数: ${assets?.visitCount??0}`}</span>
                </Col>
              </Row>
            </div>
          </div>  
        }
    
        <Form form={form} onValuesChange={onValuesChange}>
          <div className='flex mb-3' style={{ justifyContent: 'space-between', alignItems: 'center' }}>
            <Radio.Group buttonStyle='solid' value={currentAttribute} onChange={(e) => {
              setCurrentAttribute(e.target.value)
            }}>
            {
              (attributes??[]).map((item,key) => (
                <Radio.Button key={key} value={item}>{item}</Radio.Button>
              ))
            }
            </Radio.Group>
            {
              action!=='add' && <Space>
                {/* <QuestionModalButton list={sqlinfo} readOnly={currentAction==='detail'} setList={setSqlInfo} /> */}
                {
                  (!readonly && (reference===AssetManageReference||canEdit)) && <React.Fragment>
                    {
                      currentAction==='detail' ? (
                        <>
                          <Tooltip title={(assets?.existDraft)?'资产存在草稿箱中，不允许编辑':''}>
                            <Button onClick={onActionButtonClick} disabled={assets?.existDraft}>编辑</Button>
                          </Tooltip>
                        </>
                      ) : <React.Fragment>
                        <Button onClick={onCancelButtonClick}>取消</Button>
                        <Button loading={confirmLoading} onClick={onActionButtonClick}>{(reference===AssetDraftReference||!needSaveAsDraft)?'保存':'保存草稿'}</Button>
                      </React.Fragment>
                    }
                  </React.Fragment>
                }
                {
                  reference !== AssetRecycleReference && <Button onClick={shareAsset}>分享</Button>
                }
                 {
                  reference !== AssetDraftReference && reference !== AssetRecycleReference && <SubsribeButton id={assets?.id} appType='dataAssetManager' subType={assets?.templateType} env={app?.env?.domainId||catalog||LocalStorage.get('assetsEnv')}  />
                }
                {/* 
                {
                  !isPostAsset(assets?.templateType) && <Dropdown overlay={
                    <Menu onClick={({ key })=>{
                      if (metadata?.metadataTableId) {
                        app?.setGlobalState?.({
                          message: 'data-govern-show-metadata-relation',
                          data: { id: metadata?.metadataTableId, type: key } 
                        })
                      } else {
                        showMessage("warn","该资产目录没有关联元数据信息");
                      }
                    }}>
                      <Menu.Item key="lineage">血缘分析</Menu.Item>
                      <Menu.Item key="impact">影响分析</Menu.Item>
                      <Menu.Item key="lineage,impact">全链分析</Menu.Item>
                    </Menu>
                  }>
                    <Button>
                      <Space>
                          关系分析
                          <DownOutlined />
                      </Space>
                    </Button>
                  </Dropdown> 
                }    */}
              </Space>
            }
          </div>
          {
            attributes?.map((attribute, index) => {
              return <div key={index} style={{ display: (attribute===currentAttribute)?'':'none' }}>
                <Descriptions column={1} bordered>
                {
                  elements?.map((element, index) => {
                    if (element.type!==attribute || element.name === '资产项') return null;

                    const _index = (publishedAsset?.elements??[]).findIndex(item => item.name===element.name)
                    let publishedElement = null;
                    if (_index !== -1) {
                      publishedElement = publishedAsset?.elements[_index];
                    }

                    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') ? 
                        <div className='flex' style={{ alignItems: 'center' }}>
                          <div style={{ flex: 1 }}>
                            <Form.Item 
                              label=''
                              name={element.name}
                              rules={[{ required: element.required === '是' }]}    
                              style={{ marginBottom: 0 }} 
                            > 
                            { elementEditComponent(element) }                              
                            </Form.Item>
                          </div>
                          <div style={{ flex: '0 0 auto', marginLeft: 10, width: 16 }}>
                          {
                            element.interpretation ? 
                              <Tooltip placement="left" title={element.interpretation}>
                                <QuestionCircleOutlined style={{ fontSize: 16 }} />
                              </Tooltip> : <></>
                          }
                          </div>
                        </div>      
                        : <React.Fragment>
                        <div className='flex' style={{ alignItems: 'center' }}>
                          <div style={{ flex: 1 }}>
                          { elementDetailComponent(element, publishedElement) }
                          </div>
                          <div style={{ flex: '0 0 auto', marginLeft: 10, width: 16 }}>
                          {
                            element.interpretation && 
                              <Tooltip placement="left" title={element.interpretation}>
                                <QuestionCircleOutlined style={{ fontSize: 16 }} />
                              </Tooltip>
                          }
                          </div>
                        </div>  
                        </React.Fragment>
                      }
                      </Descriptions.Item>
                    )
                  })
                }
                </Descriptions>
              </div>
            })
          }
        </Form>

      </Spin>
      {
        assets?.structedState==='unStructured'&&(
          <MatchMetaInfo 
            item={assets} reference={reference} AssetDraftReference={AssetDraftReference} getAsset={getAsset} 
            dirId={dirId} metadataId={metadataId} needSaveAsDraft={needSaveAsDraft} currentAction={currentAction}
            selectData={selectData} setSelectData={setSelectData}
          />
        )
      }
      <div>
        <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',gap:10}}>
          <div style={{flex:1}}>
            <Divider orientation='left'>字段级资产目录信息</Divider>
          </div>
          
          {action!=='add'&&<Button size='small' onClick={()=>{comparemodal.openModal()}}>对比</Button>}
        </div>
        {
          isStructured ? 
          <Form form={columnForm}>
            <Table
              className='mt-3'
              columns={cols??[]} 
              rowKey='_id'
              dataSource={tableData||[]}
              pagination={{
                position: ['bottomCenter'],
                total,
                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 });
                },
              }} 
            /> 
          </Form>
          : <React.Fragment>
            <div className='flex' style={{ justifyContent: 'end' }}>
              {
                (currentAction !== 'detail') && <Button onClick={async () => {
                  try {
                    await columnForm?.validateFields()
                    setModifyMetadataColumnList(prev => {
                      return [{
                        columnElements: [...businessColumns??[]]
                      }, ...prev??[]]
                    })
                  } catch (errInfo) {

                  }
                }}>
                  新增
                </Button>
              }
            </div>
            
            <Form form={columnForm}>
              <Table
                className='mt-3'
                columns={cols??[]} 
                rowKey='_id'
                dataSource={tableData||[]}
                pagination={{
                  position: ['bottomCenter'],
                  total,
                  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 });
                  },
                }} 
              />
            </Form>
            
            <div>
              <Divider orientation='left'>关联资产</Divider>
              <RelationAssets 
                ref={relationAssetsRef} 
                reference={reference}  
                action={currentAction} 
                item={assets}
              />
            </div>
          </React.Fragment>
        }
      </div>
      <ImportActionComment modelerData={assets} />
      <AssetsCompareModal visible={comparemodal.visible} item={assets} onCancel={()=>{comparemodal.cancelModal()}} />
      {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 MetadataColumnEditableItem = ({ value, isEdit, terms, onChange }) => {
  return (
    <React.Fragment>
    {
      isEdit ? <Input size='small' 
        value={value} 
        onChange={(e) => { onChange?.(e) }} 
      /> : <span>
        {highlightSearchContentByTerms(value, terms)}
      </span>
    }
    </React.Fragment>
  )
}