import React, {Component} from 'react'
|
import PropTypes from 'prop-types'
|
import { is, fromJS } from 'immutable'
|
import { Chart } from '@antv/g2'
|
import { Spin, Empty, notification, Modal } from 'antd'
|
import { DownloadOutlined } from '@ant-design/icons'
|
import moment from 'moment'
|
|
import Api from '@/api'
|
import Utils from '@/utils/utils.js'
|
import asyncBtnComponent from './asyncButtonComponent'
|
import UtilsDM from '@/utils/utils-datamanage.js'
|
import MKEmitter from '@/utils/events.js'
|
import TimerTask from '@/utils/timer-task.js'
|
import NormalHeader from '@/tabviews/custom/components/share/normalheader'
|
import './index.scss'
|
|
const ExcelOutButton = asyncBtnComponent(() => import('@/tabviews/zshare/actionList/exceloutbutton'))
|
const ExcelInButton = asyncBtnComponent(() => import('@/tabviews/zshare/actionList/excelInbutton'))
|
|
class ScatterChart extends Component {
|
static propTpyes = {
|
config: PropTypes.object
|
}
|
|
state = {
|
BID: '', // 主表ID
|
config: null, // 图表配置信息
|
empty: true, // 图表数据为空
|
loading: false, // 数据加载状态
|
chartId: Utils.getuuid(), // 图表Id
|
plot: null, // 图表设置
|
search: null, // 搜索条件
|
chart: null
|
}
|
|
data = []
|
loaded = false
|
|
UNSAFE_componentWillMount () {
|
const { config } = this.props
|
|
let _config = fromJS(config).toJS()
|
let BID = ''
|
let BData = ''
|
|
if (config.setting.supModule) {
|
BData = window.GLOB.CacheData.get(config.setting.supModule)
|
} else {
|
BData = window.GLOB.CacheData.get(config.$pageId)
|
}
|
if (BData) {
|
BID = BData.$BID || ''
|
}
|
|
_config.plot.height = Utils.getHeight(_config.plot.height)
|
_config.style.height = 'auto'
|
_config.style.minHeight = _config.plot.height + 30
|
|
if (_config.plot.title) {
|
_config.style.minHeight = _config.style.minHeight + 45
|
}
|
|
if (_config.setting.sync === 'true') {
|
_config.setting.onload = 'false'
|
|
if (window.GLOB.SyncData.has(_config.dataName)) {
|
this.data = window.GLOB.SyncData.get(_config.dataName) || []
|
|
if (_config.$cache) {
|
Api.writeCacheConfig(_config.uuid, fromJS(this.data).toJS())
|
}
|
|
_config.setting.sync = 'false'
|
|
this.loaded = true
|
|
window.GLOB.SyncData.delete(_config.dataName)
|
}
|
}
|
|
this.setState({
|
config: _config,
|
BID: BID || '',
|
empty: this.data.length === 0,
|
arr_field: _config.columns.map(col => col.field).join(','),
|
plot: _config.plot,
|
search: _config.$searches
|
})
|
}
|
|
shouldComponentUpdate (nextProps, nextState) {
|
return !is(fromJS(this.state), fromJS(nextState))
|
}
|
|
componentDidMount () {
|
const { config } = this.state
|
|
MKEmitter.addListener('reloadData', this.reloadData)
|
MKEmitter.addListener('resetSelectLine', this.resetParentParam)
|
MKEmitter.addListener('queryModuleParam', this.queryModuleParam)
|
MKEmitter.addListener('refreshByButtonResult', this.refreshByButtonResult)
|
|
if (config.setting.useMSearch) {
|
MKEmitter.addListener('searchRefresh', this.searchRefresh)
|
}
|
|
if (config.setting.sync === 'true') {
|
MKEmitter.addListener('transferSyncData', this.transferSyncData)
|
}
|
|
if (config.timer) {
|
this.timer = new TimerTask()
|
this.timer.init(config.uuid, config.timer, config.timerRepeats, () => {
|
this.loadData('timer')
|
})
|
}
|
|
this.initExec()
|
}
|
|
/**
|
* @description 组件销毁,清除state更新,清除快捷键设置
|
*/
|
componentWillUnmount () {
|
this.setState = () => {
|
return
|
}
|
MKEmitter.removeListener('reloadData', this.reloadData)
|
MKEmitter.removeListener('searchRefresh', this.searchRefresh)
|
MKEmitter.removeListener('resetSelectLine', this.resetParentParam)
|
MKEmitter.removeListener('queryModuleParam', this.queryModuleParam)
|
MKEmitter.removeListener('transferSyncData', this.transferSyncData)
|
MKEmitter.removeListener('refreshByButtonResult', this.refreshByButtonResult)
|
|
this.timer && this.timer.stop()
|
}
|
|
initExec = () => {
|
const { config } = this.state
|
|
if (config.$cache) {
|
if (config.$time) {
|
if (!this.loaded) {
|
Api.getLCacheConfig(config.uuid, config.$time).then(res => {
|
if (!res.valid && config.setting.onload === 'true') {
|
setTimeout(() => {
|
this.loadData('init')
|
}, config.setting.delay || 0)
|
}
|
|
if (!res.data || this.loaded) return
|
|
this.data = res.data
|
this.handleData()
|
|
this.setState({empty: res.data.length === 0})
|
})
|
} else {
|
this.handleData()
|
}
|
} else {
|
if (!this.loaded) {
|
Api.getLCacheConfig(config.uuid, 0).then(res => {
|
if (!res.data || this.loaded) return
|
|
this.data = res.data
|
this.handleData()
|
|
this.setState({empty: res.data.length === 0})
|
})
|
}
|
|
if (config.setting.onload === 'true') {
|
setTimeout(() => {
|
this.loadData('init')
|
}, config.setting.delay || 0)
|
} else if (this.loaded) {
|
this.handleData()
|
}
|
}
|
} else if (config.setting.onload === 'true') {
|
setTimeout(() => {
|
this.loadData()
|
}, config.setting.delay || 0)
|
} else if (this.loaded) {
|
this.handleData()
|
}
|
}
|
|
transferSyncData = (syncId) => {
|
const { config } = this.state
|
|
if (config.$syncId !== syncId) return
|
|
let _data = window.GLOB.SyncData.get(config.dataName) || []
|
|
if (config.$cache) {
|
Api.writeCacheConfig(config.uuid, fromJS(_data).toJS())
|
}
|
|
this.data = _data
|
this.handleData()
|
|
this.setState({empty: _data.length === 0})
|
|
this.loaded = true
|
|
window.GLOB.SyncData.delete(config.dataName)
|
|
MKEmitter.removeListener('transferSyncData', this.transferSyncData)
|
}
|
|
searchRefresh = (searchId) => {
|
const { config } = this.state
|
|
if (config.$searchId !== searchId) return
|
|
this.setState({}, () => {
|
this.loadData()
|
})
|
}
|
|
/**
|
* @description 按钮执行完成后页面刷新
|
* @param {*} menuId // 菜单Id
|
* @param {*} position // 刷新位置
|
* @param {*} btn // 执行的按钮
|
*/
|
refreshByButtonResult = (menuId, position, btn) => {
|
const { config, BID } = this.state
|
|
if (config.uuid !== menuId) return
|
|
if ((position === 'mainline' || position === 'popclose') && config.setting.supModule && BID) { // 刷新源组件时,附带刷新上级行与当前组件
|
MKEmitter.emit('reloadData', config.setting.supModule, BID)
|
} else {
|
this.loadData()
|
}
|
}
|
|
reloadData = (menuId) => {
|
const { config } = this.state
|
|
if (config.uuid !== menuId) return
|
|
this.loadData()
|
}
|
|
resetParentParam = (MenuID, id) => {
|
const { config } = this.state
|
|
if (!config.setting.supModule || config.setting.supModule !== MenuID) return
|
if (id !== this.state.BID || id !== '') {
|
this.setState({ BID: id }, () => {
|
this.loadData()
|
})
|
}
|
}
|
|
/**
|
* @description 导出Excel时,获取页面搜索排序等参数
|
*/
|
queryModuleParam = (menuId, callback) => {
|
const { arr_field, config, search } = this.state
|
|
if (config.uuid !== menuId) return
|
|
let searches = search ? fromJS(search).toJS() : []
|
if (config.setting.useMSearch) { // 主表搜索条件
|
let mainSearch = window.GLOB.SearchBox.get(config.$searchId) || []
|
let keys = config.$s_keys || []
|
mainSearch.forEach(item => {
|
if (keys.includes(item.key.toLowerCase())) return
|
|
searches.push(item)
|
})
|
}
|
|
callback({
|
arr_field: arr_field,
|
orderBy: config.setting.order || '',
|
search: searches,
|
menuName: config.name
|
})
|
}
|
|
/**
|
* @description 数据加载
|
*/
|
async loadData (type) {
|
const { config, arr_field, BID, search } = this.state
|
|
if (config.setting.supModule && !BID) { // BID 不存在时,不做查询
|
this.setState({ empty: true })
|
|
if (!is(fromJS(this.data), fromJS([]))) {
|
this.data = []
|
this.handleData()
|
}
|
|
this.loaded = true
|
return
|
}
|
|
let searches = search ? fromJS(search).toJS() : []
|
if (config.setting.useMSearch) { // 主表搜索条件
|
let mainSearch = window.GLOB.SearchBox.get(config.$searchId) || []
|
let keys = config.$s_keys || []
|
mainSearch.forEach(item => {
|
if (keys.includes(item.key.toLowerCase())) return
|
|
searches.push(item)
|
})
|
}
|
|
if (config.$s_req && searches.filter(item => item.required && item.value === '').length > 0) {
|
return
|
}
|
|
if (type !== 'timer') {
|
this.setState({
|
loading: true
|
})
|
}
|
|
let _orderBy = config.setting.order || ''
|
let param = UtilsDM.getQueryDataParams(config.setting, arr_field, searches, _orderBy, '', '', BID)
|
|
let result = await Api.genericInterface(param)
|
if (result.status) {
|
if (config.$cache && type === 'init') {
|
Api.writeCacheConfig(config.uuid, result.data || [])
|
}
|
this.loaded = true
|
|
this.setState({
|
empty: !result.data || result.data.length === 0,
|
loading: false
|
})
|
|
if (!is(fromJS(this.data), fromJS(result.data || []))) {
|
this.data = result.data || []
|
this.handleData()
|
}
|
|
if (config.timer && config.clearField && result.data && result.data[0]) {
|
let vals = (config.clearValue || '').split(',')
|
if (vals.includes(result.data[0][config.clearField])) {
|
this.timer && this.timer.stop()
|
}
|
}
|
if (result.message) {
|
if (result.ErrCode === 'Y') {
|
Modal.success({
|
title: result.message
|
})
|
} else if (result.ErrCode === 'S') {
|
notification.success({
|
top: 92,
|
message: result.message,
|
duration: 2
|
})
|
}
|
}
|
} else {
|
this.setState({
|
loading: false
|
})
|
this.timer && this.timer.stop()
|
|
if (!result.message) return
|
if (result.ErrCode === 'N') {
|
Modal.error({
|
title: result.message,
|
})
|
} else if (result.ErrCode !== '-2') {
|
notification.error({
|
top: 92,
|
message: result.message,
|
duration: 10
|
})
|
}
|
}
|
}
|
|
/**
|
* @description 数据预处理,统计数据需要重置
|
*/
|
handleData = () => {
|
let _element = document.getElementById(this.state.chartId)
|
if (_element) {
|
_element.innerHTML = ''
|
}
|
|
setTimeout(() => {
|
this.scatterrender()
|
}, 100)
|
}
|
|
/**
|
* @description 散点图渲染
|
*/
|
scatterrender = () => {
|
const { plot, chartId } = this.state
|
const chart = new Chart({
|
container: chartId,
|
autoFit: true,
|
height: plot.height
|
})
|
|
chart.data(this.data);
|
chart.scale({
|
[plot.Xaxis]: { nice: true },
|
[plot.Yaxis]: { nice: true },
|
})
|
|
chart.axis(plot.Xaxis, { label: { style: { fill: plot.color } } })
|
chart.axis(plot.Yaxis, { label: { style: { fill: plot.color } } })
|
chart.legend({
|
position: 'bottom',
|
itemName: { style: { fill: plot.color } }
|
})
|
|
if (plot.tooltip !== 'true') {
|
chart.tooltip(false)
|
} else {
|
chart.tooltip({
|
showTitle: false,
|
showCrosshairs: true,
|
crosshairs: {
|
type: 'xy',
|
}
|
})
|
}
|
|
chart
|
.point()
|
.position(`${plot.Xaxis}*${plot.Yaxis}`)
|
.color(plot.gender)
|
.shape(plot.shape)
|
.tooltip(`${plot.gender}*${plot.Xaxis}*${plot.Yaxis}`, (gender, height, weight) => {
|
return {
|
name: gender,
|
value: height + (plot.Xunit ? `(${plot.Xunit}), ` : ', ') + weight + (plot.Yunit ? `(${plot.Yunit})` : '')
|
};
|
})
|
.style({
|
fillOpacity: 0.85
|
})
|
if (plot.interaction && plot.interaction.length) {
|
plot.interaction.forEach(t => {
|
chart.interaction(t)
|
})
|
}
|
chart.render()
|
|
this.setState({chart})
|
}
|
|
refreshSearch = (list) => {
|
this.setState({search: list}, () => {
|
this.loadData()
|
})
|
}
|
|
downloadImage = () => {
|
const { chart, config } = this.state
|
const link = document.createElement('a');
|
const filename = `${config.name}${moment().format('YYYY-MM-DD HH_mm_ss')}.png`;
|
const canvas = chart.getCanvas();
|
canvas.get('timeline').stopAllAnimations();
|
|
setTimeout(() => {
|
const canvas = chart.getCanvas();
|
const canvasDom = canvas.get('el');
|
const dataURL = canvasDom.toDataURL('image/png');
|
|
if (window.Blob && window.URL) {
|
const arr = dataURL.split(',');
|
const mime = arr[0].match(/:(.*?);/)[1];
|
const bstr = atob(arr[1]);
|
let n = bstr.length;
|
const u8arr = new Uint8Array(n);
|
while (n--) {
|
u8arr[n] = bstr.charCodeAt(n);
|
}
|
const blobObj = new Blob([u8arr], { type: mime });
|
if (window.navigator.msSaveBlob) {
|
window.navigator.msSaveBlob(blobObj, filename);
|
} else {
|
link.addEventListener('click', () => {
|
link.download = filename;
|
link.href = window.URL.createObjectURL(blobObj);
|
});
|
}
|
}
|
const e = document.createEvent('MouseEvents');
|
e.initEvent('click', false, false);
|
link.dispatchEvent(e);
|
}, 16);
|
}
|
|
render() {
|
const { config, loading, empty, BID } = this.state
|
|
let style = {...config.style}
|
if (empty && config.plot.empty === 'hidden') {
|
style.opacity = 0
|
style.position = 'absolute'
|
style.zIndex = -1
|
style.width = '100%'
|
}
|
|
return (
|
<div className="custom-scatter-plot-box" id={'anchor' + config.uuid} style={style}>
|
{loading ?
|
<div className="loading-mask">
|
<div className="ant-spin-blur"></div>
|
<Spin />
|
</div> : null
|
}
|
<NormalHeader config={config} BID={BID} refresh={this.refreshSearch} />
|
<div className="canvas-wrap">
|
{config.plot.download === 'enable' && this.state.chart && !empty ? <DownloadOutlined onClick={this.downloadImage} className="system-color download"/> : null}
|
<div className={'chart-action' + (config.plot.download === 'enable' ? ' downable' : '')}>
|
{config.action.map(item => {
|
if (item.OpenType === 'excelOut') {
|
return (
|
<ExcelOutButton
|
key={item.uuid}
|
BID={BID}
|
btn={item}
|
show="icon"
|
setting={config.setting}
|
/>
|
)
|
} else {
|
return (
|
<ExcelInButton
|
key={item.uuid}
|
BID={BID}
|
btn={item}
|
show="icon"
|
setting={config.setting}
|
/>
|
)
|
}
|
})}
|
</div>
|
<div className={'canvas' + (empty ? ' empty' : '')} id={this.state.chartId}></div>
|
</div>
|
{empty ? <Empty description={false}/> : null}
|
</div>
|
)
|
}
|
}
|
|
export default ScatterChart
|