政务数据资源中心(Government data Resource center) 03专项3期主要建设内容
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

376 lines
15 KiB

import React, { useEffect, useState } from 'react';
import { connect } from 'react-redux';
import { Spin, Table, Popconfirm, Button, Input, Row, Col } from 'antd';
import { ButtonGroup } from '$components';
import moment from 'moment';
import FileSaver from 'file-saver';
import MetadataDatabaseModal from '../components/metadataDatabaseModal';
import { ModelTypes } from '../constants/index';
import MetadataTagModal from '../components/metadataTagModal';
import MetadataResourceModal from '../components/metadataResourceModal';
import ReleaseModal from '../components/releaseModal';
const DatabaseTable = (props) => {
const { user, dispatch, actions, clientHeight, resourceCatalogId, resourceCatalogKey, isAdmin,
resourceCatalogPath, isRequesting, metadataModels, setView, tagList, metadataResourceApplications, params } = props;
const { metadataManagement } = actions;
const SortValues = { 'ascend': 'asc', 'descend': 'desc' };
const [tableData, setTableData] = useState([]);
const [tableDataCount, setTableDataCount] = useState(0);//Table数据
const [createAtSort, setCreateAtSort] = useState('descend');
const [keywords, setKeywords] = useState('');
const [limit, setLimit] = useState(10);
const [currentPage, setCurrentPage] = useState(1);
const [selectedRowKeys, setSelectedRowKeys] = useState([]);
const [selectedRows, setSelectedRows] = useState([]);
const [modalVisible, setModalVisible] = useState(false);
const [editData, setEditData] = useState({});
const [tagModalVisible, setTagModalVisible] = useState(false);
const [editTagData, setEditTagData] = useState({});
const [resourceModalVisible, setResourceModalVisible] = useState(false);
const [editResourceData, setEditResourceData] = useState({});
const [releaseModal, setReleaseModal] = useState(false);
useEffect(() => {
dispatch(metadataManagement.getTagList());
setCreateAtSort('descend');
onSearch('descend');
}, [resourceCatalogId]);
const initData = (query = {}) => {
dispatch(metadataManagement.getMetadataDatabases({ resourceId: params?.type == 'databases' ? params?.resourceId : null, catalog: resourceCatalogId, keywords, orderBy: 'createAt', ...query })).then(res => {
if (res.success) {
setTableData(res.payload.data.rows);
setTableDataCount(res.payload.data.count);
let resourceNames = [];
res.payload.data.rows.map(r => {
if (r.type === '表') {
resourceNames.push(r.name);
}
})
if (resourceNames.length)
dispatch(metadataManagement.getMetadataResourceApplications({ resourceNames: resourceNames.join(','), type: '库表' }))
}
})
}
const onView = (record) => {
setView({ path: '/' + resourceCatalogPath.join('/'), ...record });
}
const onEdit = (record) => {
dispatch(metadataManagement.getMetadataModels({ modelTypes: ModelTypes.join(',') })).then(res => {
if (res.success) {
setEditData({ title: '修改库表元数据', record: { path: '/' + resourceCatalogPath.join('/'), ...record, ...record.attributesParam } });
setModalVisible(true);
}
})
}
const confirmDelete = (id) => {
dispatch(metadataManagement.delMetadataDatabases(id)).then(res => {
if (res.success) {
onSearch(); setModalVisible(false);
}
});
}
const marking = (id) => {
dispatch(metadataManagement.getTagMetadata(id, 'database')).then(res => {
if (res.success) {
const obj = { tagSet: [], tags: [], id: id }
if (res.payload.data.length) {
const tagSetIds = res.payload.data.map(d => d.tagSet)
obj.tagSet = [...new Set(tagSetIds)];
obj.tags = res.payload.data.map(d => d.id);
}
setEditTagData({ record: obj });
setTagModalVisible(true);
}
})
}
const onConfirmTag = (values) => {
dispatch(metadataManagement.postTagMetadata({ database: editTagData.record.id, ...values })).then(res => {
if (res.success) {
onSearch(); setTagModalVisible(false);
}
});
}
const applyResources = (record) => {
setEditResourceData({ record: { resourceId: record.id, resourceName: record.name, applyBy: user.id, applyByName: user.name, resourceType: '库表' } });
setResourceModalVisible(true);
}
const servicePublication = (record) => {
console.log(record);
setEditData(record)
setReleaseModal(true)
}
const onConfirmResource = (values) => {
dispatch(metadataManagement.postMetadataResourceApplications({ resourceCatalogId, ...values })).then(res => {
if (res.success) {
onSearch(); setResourceModalVisible(false);
}
});
}
const onTableChange = (pagination, filters, sorter) => {
let limit = Number.parseInt(pagination.pageSize);
let offset = Number.parseInt(pagination.current) - 1;
setCurrentPage(pagination.current);
setLimit(limit);
let query = { offset, limit, orderDirection: SortValues[createAtSort] };
if (sorter.columnKey === 'createAt') {
query.orderDirection = SortValues[sorter.order];
setCreateAtSort(sorter.order);
}
setSelectedRowKeys([]);
setSelectedRows([]);
initData(query);
}
const columns = [
{
title: '名称',
dataIndex: 'name',
key: 'name',
width: '16%',
ellipsis: true
}, {
title: '代码',
dataIndex: 'code',
key: 'code',
width: '16%',
ellipsis: true
}, {
title: '元数据类型',
dataIndex: 'type',
key: 'type',
width: '10%'
}, {
title: '标签',
dataIndex: 'tags',
key: 'tags',
width: '18%',
ellipsis: true,
render: (text, record, index) => {
let tagName = record.tagDatabases.map(tagSet => tagSet.tag.name);
return tagName.join(',');
}
}, {
title: '创建者',
dataIndex: 'createBy',
key: 'createBy',
width: '14%',
render: (text, record, index) => {
return record.user.username
}
}, {
title: '创建时间',
dataIndex: 'createAt',
key: 'createAt',
width: '18%',
sortOrder: createAtSort,
sorter: (a, b) => moment(a.createAt).valueOf() - moment(b.createAt).valueOf(),
sortDirections: ['descend', 'ascend', 'descend'],
render: (text, record, index) => {
return moment(text).format('YYYY-MM-DD HH:mm:ss')
}
}, {
title: '操作',
dataIndex: 'action',
width: '8%',
render: (text, record) => {
let resourceApplicationsRecords = metadataResourceApplications.filter(ra =>
ra.applyBy == user.id && ra.resourceName === record.name && ra.resourceId == record.id);
return <ButtonGroup>
<a onClick={() => onView(record)}>查看</a>
{!isAdmin ? null :
<>
<a style={{ marginLeft: 10 }} onClick={() => onEdit(record)}>编辑</a>
<Popconfirm
title="是否确认删除该元数据?"
onConfirm={() => confirmDelete(record.id)}
> <a style={{ marginLeft: 10 }}>删除</a></Popconfirm>
{record.type === '表' ? <a style={{ marginLeft: 10 }} onClick={() => marking(record.id)}>打标</a> : null}
</>
}
{isAdmin ? null : record.type === '表' ? resourceApplicationsRecords.length === 0 ?
<a style={{ marginLeft: 10 }} onClick={() => applyResources(record)}>申请资源</a> :
<span style={{ marginLeft: 10, color: "#c0c0c0" }} title='已存在资源申请'>申请资源</span> : null}
{!isAdmin ? null :
record.type === '表' ?
<a style={{ marginLeft: 10 }} onClick={() => servicePublication(record)}>REST服务发布</a> : null
}
</ButtonGroup>
}
}];
const onSearch = (sort) => {
setSelectedRowKeys([]);
setSelectedRows([]);
setCurrentPage(1);
initData({ limit, offset: 0, orderDirection: SortValues[sort || createAtSort] });
}
const handleExport = (isAll = false) => {
let tableHeader = `<tr>`;
columns.filter(c => c.dataIndex != 'action').map(c => { tableHeader += `<th><div>${c.title}</div></th>`; });
tableHeader += '</tr>';
if (isAll) {
dispatch(metadataManagement.getMetadataDatabases({ catalog: resourceCatalogId })).then(res => {
if (res.success) {
handleExportTable(tableHeader, res.payload.data.rows);
}
})
} else {
let data = []
if (createAtSort === 'descend') {
data = selectedRows.sort((a, b) => moment(b.createAt).valueOf() - moment(a.createAt).valueOf());
} else {
data = selectedRows.sort((a, b) => moment(a.createAt).valueOf() - moment(b.createAt).valueOf());
}
handleExportTable(tableHeader, data);
}
}
const handleExportTable = (tableHeader, contentData) => {
let tableContent = '';
contentData.map(cd => {
tableContent += `<tr>`;
tableContent += `<th style="font-weight:600"><div>${cd.name}</div></th>`;
tableContent += `<th style="font-weight:600"><div>${cd.code}</div></th>`;
tableContent += `<th style="font-weight:600"><div>${cd.type}</div></th>`;
let tagName = cd.tagDatabases.map(tagSet => tagSet.tag.name);
tableContent += `<th style="font-weight:600"><div>${tagName.join(',')}</div></th>`;
tableContent += `<th style="font-weight:600"><div>${cd.user.username}</div></th>`;
tableContent += `<th style="font-weight:600"><div>${moment(cd.createAt).format('YYYY-MM-DD HH:mm:ss')}</div></th>`;
tableContent += `</tr>`;
})
let exportTable = `\uFEFF<table border="1">
${tableHeader}
${tableContent}
</table>`;
let tempStr = new Blob([exportTable], { type: 'text/plain;charset=utf-8' });
FileSaver.saveAs(tempStr, `库表元数据导出.xls`);
}
//新建、修改
const onConfirm = (values) => {
let obj = {}
if (editData.add) {
obj = { createBy: user.id, catalog: resourceCatalogId, catalogKey: resourceCatalogKey, ...values }
dispatch(metadataManagement.postMetadataDatabases(obj)).then(res => {
if (res.success) {
onSearch(); setModalVisible(false);
}
});
} else {
obj = { catalog: resourceCatalogId, catalogKey: resourceCatalogKey, ...values }
dispatch(metadataManagement.putMetadataDatabases(editData.record.id, obj)).then(res => {
if (res.success) {
onSearch(); setModalVisible(false);
}
});
}
}
return <Spin spinning={isRequesting}>
<Row style={{ marginBottom: 16 }}>
<Col span={12}>
{!isAdmin ? null : <>
<Button type='primary' onClick={() => {
dispatch(metadataManagement.getMetadataModels({ modelTypes: ModelTypes.join(',') })).then(res => {
if (res.success) {
setEditData({ add: true, title: '新建库表元数据', record: { path: '/' + resourceCatalogPath.join('/'), type: '目录' } });
setModalVisible(true);
}
})
}}>新建</Button>
{
tableDataCount == 0 ? <Button disabled={tableDataCount == 0} style={{ marginLeft: 16 }} onClick={() => handleExport()}>导出</Button> :
selectedRowKeys && selectedRowKeys.length ?
<Button disabled={tableDataCount == 0} style={{ marginLeft: 16 }} onClick={() => handleExport()}>导出</Button>
: <Popconfirm title={'是否导出全部?'} onConfirm={() => handleExport(true)} okText="确定" cancelText="取消">
<Button disabled={tableDataCount == 0} style={{ marginLeft: 16 }}> 导出</Button>
</Popconfirm>
}
</>}
</Col>
<Col span={12} style={{ display: 'flex', justifyContent: 'flex-end' }}>
<Input style={{ width: 220 }} placeholder="名称/代码/类型"
allowClear onPressEnter={onSearch} onChange={e => setKeywords(e.target.value || '')} />
<Button type='primary' style={{ marginLeft: 16 }} onClick={onSearch}>查询</Button>
</Col>
</Row >
<Table
scroll={{ y: clientHeight - 320 }}
rowKey='id'
columns={columns}
dataSource={tableData}
onChange={onTableChange}
pagination={{
current: currentPage,
pageSize: limit,
total: tableDataCount,
showSizeChanger: true,
// showQuickJumper: true,
showTotal: (total) => { return <span style={{ fontSize: 15 }}>{`${Math.ceil(total / limit)}页,${total}`}</span> },
}}
rowSelection={{
onChange: (selectedRowKeys, selectedRows) => {
setSelectedRowKeys(selectedRowKeys)
setSelectedRows(selectedRows);
},
selectedRowKeys: selectedRowKeys
}}
>
</Table>
{
modalVisible ?
<MetadataDatabaseModal
modelTypes={ModelTypes.filter(m => m === '目录')}
metadataModels={metadataModels}
editData={editData}
onCancel={() => setModalVisible(false)}
onConfirm={onConfirm} /> : ''
}
{
tagModalVisible ?
<MetadataTagModal
tagList={tagList}
editData={editTagData}
onCancel={() => setTagModalVisible(false)}
onConfirm={onConfirmTag} /> : ''
}
{
resourceModalVisible ?
<MetadataResourceModal
editData={editResourceData}
onCancel={() => setResourceModalVisible(false)}
onConfirm={onConfirmResource} /> : ''
}
{
releaseModal ?
<ReleaseModal
editData={editData}
onCancel={() => {
setReleaseModal(false)
setEditData({})
}}
onConfirm={() => {
}}
/>
: ''
}
</Spin >
}
function mapStateToProps(state) {
const { global, auth, metadataDatabases, metadataModels, tagList, tagMetadata, metadataResourceApplications } = state;
return {
user: auth.user,
actions: global.actions,
clientHeight: global.clientHeight,
isRequesting: metadataDatabases.isRequesting || metadataModels.isRequesting || tagList.isRequesting
|| tagMetadata.isRequesting || metadataResourceApplications.isRequesting,
metadataModels: metadataModels.data,
tagList: tagList.data || [],
metadataResourceApplications: metadataResourceApplications.data || []
};
}
export default connect(mapStateToProps)(DatabaseTable)