import React, {Component} from 'react'
|
import PropTypes from 'prop-types'
|
import { is, fromJS } from 'immutable'
|
import { Chart, registerShape } from '@antv/g2'
|
import { Spin, 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 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'
|
|
registerShape('point', 'pointer', {
|
draw(cfg, container) {
|
const group = container.addGroup({});
|
// 获取极坐标系下画布中心点
|
const center = this.parsePoint({ x: 0, y: 0 });
|
// 绘制指针
|
group.addShape('line', {
|
attrs: {
|
x1: center.x,
|
y1: center.y,
|
x2: cfg.x,
|
y2: cfg.y,
|
stroke: cfg.color,
|
lineWidth: 5,
|
lineCap: 'round',
|
},
|
});
|
group.addShape('circle', {
|
attrs: {
|
x: center.x,
|
y: center.y,
|
r: 9.75,
|
stroke: cfg.color,
|
lineWidth: 4.5,
|
fill: '#fff',
|
},
|
});
|
return group;
|
},
|
})
|
|
registerShape('point', 'hidden', {
|
draw(cfg, container) {
|
return container.addGroup({})
|
}
|
})
|
|
class DashboardChart extends Component {
|
static propTpyes = {
|
data: PropTypes.array, // 统一查询数据
|
config: PropTypes.object, // 组件配置信息
|
mainSearch: PropTypes.any, // 外层搜索条件
|
}
|
|
state = {
|
BID: '', // 上级ID
|
config: null, // 图表配置信息
|
loading: false, // 数据加载状态
|
chartId: Utils.getuuid(), // 图表Id
|
title: '', // 组件标题
|
sync: false, // 是否统一请求数据
|
plot: null, // 图表设置
|
data: {}, // 数据
|
chart: null
|
}
|
|
UNSAFE_componentWillMount () {
|
const { config, data, initdata } = this.props
|
let _config = fromJS(config).toJS()
|
|
let _data = null
|
let _sync = _config.setting.sync === 'true'
|
|
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 || ''
|
}
|
|
if (_sync && data) {
|
_data = data[config.dataName] || []
|
_sync = false
|
} else if (_sync && initdata) {
|
_data = initdata || []
|
_sync = false
|
}
|
|
if (_config.subtype === 'ratioboard') {
|
_data = _data || []
|
} else {
|
if (_data && Array.isArray(_data)) {
|
_data = _data[0] || {}
|
} else {
|
_data = {}
|
}
|
}
|
|
_config.plot.height = Utils.getHeight(_config.plot.height)
|
_config.style.height = 'auto'
|
_config.style.minHeight = _config.plot.height
|
|
this.setState({
|
config: _config,
|
data: _data,
|
BID: BID || '',
|
arr_field: _config.columns.map(col => col.field).join(','),
|
plot: _config.plot,
|
sync: _sync,
|
title: config.plot.title
|
}, () => {
|
if (config.setting.sync !== 'true' && config.setting.onload === 'true') {
|
setTimeout(() => {
|
this.loadData()
|
}, _config.setting.delay || 0)
|
} else if (config.setting.sync === 'true') {
|
this.handleData()
|
}
|
})
|
}
|
|
/**
|
* @description 图表数据更新,刷新内容
|
*/
|
UNSAFE_componentWillReceiveProps (nextProps) {
|
const { sync, config } = this.state
|
|
if (sync && !is(fromJS(this.props.data), fromJS(nextProps.data))) {
|
let _data = null
|
|
if (config.subtype === 'ratioboard') {
|
_data = []
|
if (nextProps.data && nextProps.data[config.dataName]) {
|
_data = nextProps.data[config.dataName] || []
|
}
|
} else {
|
_data = {}
|
if (nextProps.data && nextProps.data[config.dataName]) {
|
_data = nextProps.data[config.dataName] || {}
|
}
|
if (_data.hasOwnProperty(config.plot.valueField)) {
|
_data.value = _data[config.plot.valueField]
|
}
|
}
|
|
this.setState({sync: false, data: _data}, () => {
|
this.handleData()
|
})
|
} else if (config.setting.useMSearch && nextProps.mainSearch && !is(fromJS(this.props.mainSearch), fromJS(nextProps.mainSearch))) {
|
this.setState({}, () => {
|
this.loadData()
|
})
|
}
|
}
|
|
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)
|
|
if (config.timer) {
|
this.timer = new TimerTask()
|
this.timer.init(config.uuid, config.timer, config.timerRepeats, () => {
|
this.loadData(true)
|
})
|
}
|
}
|
|
/**
|
* @description 组件销毁,清除state更新,清除快捷键设置
|
*/
|
componentWillUnmount () {
|
this.setState = () => {
|
return
|
}
|
MKEmitter.removeListener('reloadData', this.reloadData)
|
MKEmitter.removeListener('resetSelectLine', this.resetParentParam)
|
|
this.timer && this.timer.stop()
|
}
|
|
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()
|
})
|
}
|
}
|
|
handleData = () => {
|
let _element = document.getElementById(this.state.chartId)
|
if (_element) {
|
_element.innerHTML = ''
|
}
|
this.viewrender()
|
}
|
|
async loadData (hastimer) {
|
const { mainSearch } = this.props
|
const { config, arr_field, BID } = this.state
|
|
if (config.setting.supModule && !BID) { // BID 不存在时,不做查询
|
this.setState({
|
data: {}
|
}, () => {
|
this.handleData()
|
})
|
return
|
}
|
|
let searches = config.setting.useMSearch && mainSearch ? mainSearch : []
|
|
let requireFields = searches.filter(item => item.required && item.value === '')
|
if (requireFields.length > 0) {
|
return
|
}
|
|
if (!hastimer) {
|
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) {
|
let data = null
|
if (config.subtype === 'ratioboard') {
|
data = result.data || []
|
} else {
|
data = {}
|
if (result.data && result.data[0] && result.data[0].hasOwnProperty(config.plot.valueField)) {
|
data.value = result.data[0][config.plot.valueField]
|
}
|
}
|
let reset = true
|
|
if (hastimer && is(fromJS(data), fromJS(this.state.data))) {
|
reset = false
|
}
|
|
this.setState({
|
data,
|
loading: false
|
}, () => {
|
if (!reset) return
|
this.handleData()
|
})
|
} else {
|
this.setState({
|
loading: false
|
})
|
this.timer && this.timer.stop()
|
|
if (result.ErrCode === 'N') {
|
Modal.error({
|
title: result.message,
|
})
|
} else {
|
notification.error({
|
top: 92,
|
message: result.message,
|
duration: 10
|
})
|
}
|
}
|
}
|
|
viewrender = () => {
|
const { config } = this.state
|
if (config.subtype === 'ratioboard') {
|
this.ratioboardrender()
|
} else {
|
this.dashboardrender()
|
}
|
}
|
|
getratiodata = () => {
|
const { data, plot } = this.state
|
|
let colors = {}
|
if (plot.colors && plot.colors.length > 0) {
|
plot.colors.forEach(item => {
|
colors[item.tick] = item.color
|
})
|
}
|
|
return data.map(item => {
|
let val = +item[plot.valueField]
|
let type = item[plot.labelField] || ''
|
if (isNaN(val)) {
|
val = 0
|
}
|
return {
|
type: type,
|
value: val,
|
$percent: val / plot.maxValue,
|
$color: colors[type] || '#1890ff'
|
}
|
})
|
}
|
|
ratioboardrender = () => {
|
const { plot, chartId } = this.state
|
const data = this.getratiodata()
|
|
const chart = new Chart({
|
container: chartId,
|
autoFit: true,
|
height: plot.height
|
})
|
|
chart.data(data)
|
chart.coordinate('polar', {
|
startAngle: -Math.PI / 2,
|
endAngle: 3 * Math.PI / 2,
|
radius: (plot.radius || 75) / 100
|
})
|
chart.scale('$percent', {
|
min: 0,
|
max: 1,
|
tickInterval: 1,
|
})
|
chart.axis(false)
|
chart.facet('rect', {
|
fields: ['type'],
|
showTitle: false,
|
eachView: function eachView(view, facet) {
|
const data = facet.data[0]
|
|
view.point().position('').shape('hidden')
|
|
view.annotation().arc({
|
top: false,
|
start: [0, 1],
|
end: [0.9999, 1],
|
style: {
|
stroke: plot.backColor,
|
lineWidth: 10
|
}
|
})
|
|
let _tick = data.$percent
|
if (_tick >= 1) {
|
_tick = 0.9999
|
}
|
|
view.annotation().arc({
|
start: [0, 1],
|
end: [_tick, 1],
|
style: {
|
stroke: data.$color,
|
lineWidth: 10,
|
}
|
})
|
// 仪表盘信息
|
let text = ''
|
if (plot.percent === 'true') {
|
text = +(data.$percent * 100).toFixed(2) + '%'
|
} else {
|
text = data.value
|
}
|
|
view.annotation().text({
|
position: ['50%', '45%'],
|
content: data.type,
|
style: {
|
fontSize: plot.fontSize * 0.8,
|
fill: plot.labelColor,
|
fontWeight: 300,
|
textAlign: 'center'
|
},
|
offsetX: 0
|
})
|
view.annotation().text({
|
position: ['50%', '55%'],
|
content: text,
|
style: {
|
fontSize: plot.fontSize,
|
fill: plot.labelColor,
|
fontWeight: 500,
|
textAlign: 'center'
|
},
|
offsetX: 0,
|
offsetY: 10
|
})
|
}
|
})
|
chart.render()
|
|
this.setState({chart})
|
}
|
|
/**
|
* @description 仪表盘渲染
|
*/
|
dashboardrender = () => {
|
const { plot, chartId, data } = this.state
|
|
let _data = fromJS(data).toJS()
|
|
if (_data.hasOwnProperty('value')) {
|
if (_data.value === '' || _data.value === null) {
|
delete _data.value
|
} else {
|
_data.value = +_data.value
|
|
if (isNaN(_data.value)) {
|
delete _data.value
|
} else if (_data.value > plot.maxValue) {
|
_data.value = plot.maxValue
|
}
|
}
|
}
|
|
const chart = new Chart({
|
container: chartId,
|
autoFit: true,
|
height: plot.height,
|
padding: [0, 0, 0, 0],
|
})
|
chart.data([_data])
|
chart.scale('value', {
|
min: 0,
|
max: plot.maxValue,
|
tickInterval: plot.tickInterval,
|
})
|
chart.coordinate('polar', {
|
startAngle: (-9 / 8) * Math.PI,
|
endAngle: (1 / 8) * Math.PI,
|
radius: 0.75,
|
})
|
|
chart.axis('1', false)
|
chart.axis('value', {
|
line: null,
|
label: {
|
offset: -36,
|
style: {
|
fontSize: 18,
|
fill: plot.tickColor,
|
textAlign: 'center',
|
textBaseline: 'middle',
|
},
|
},
|
tickLine: {
|
length: -24,
|
style: {
|
stroke: plot.tickColor
|
}
|
},
|
grid: null,
|
})
|
chart.legend(false)
|
chart.tooltip(false)
|
chart
|
.point()
|
.position('value*1')
|
.shape('pointer')
|
.color('value', (val) => {
|
if (!val && val !== 0) return 'transparent'
|
let _color = '#1890FF'
|
if (plot.colors && plot.colors.length > 0) {
|
_color = plot.colors[plot.colors.length - 1].color || '#1890FF'
|
plot.colors.some(item => {
|
if (item.tick > val) {
|
_color = item.color
|
return true
|
}
|
return false
|
})
|
}
|
return _color
|
})
|
.animate({
|
appear: {
|
animation: 'fade-in'
|
}
|
})
|
|
// 绘制仪表盘背景
|
chart.annotation().arc({
|
top: false,
|
start: [0, 1],
|
end: [plot.maxValue, 1],
|
style: {
|
stroke: '#CBCBCB',
|
lineWidth: 18,
|
lineDash: null,
|
},
|
})
|
|
if (!plot.colors || plot.colors.length === 0) {
|
chart.annotation().arc({
|
start: [0, 1],
|
end: [plot.maxValue, 1],
|
style: {
|
stroke: '#1890FF',
|
lineWidth: 18,
|
lineDash: null,
|
},
|
})
|
} else {
|
let start = 0
|
plot.colors.forEach(item => {
|
chart.annotation().arc({
|
start: [start, 1],
|
end: [item.tick, 1],
|
style: {
|
stroke: item.color,
|
lineWidth: 18,
|
lineDash: null,
|
},
|
})
|
start = item.tick
|
})
|
}
|
|
if (plot.label) {
|
chart.annotation().text({
|
position: ['50%', '85%'],
|
content: plot.label,
|
style: {
|
fontSize: 20,
|
fill: plot.labelColor,
|
textAlign: 'center',
|
},
|
})
|
}
|
|
if (data.hasOwnProperty('value')) {
|
let val = data.value
|
if (plot.percent !== 'false' && plot.maxValue) {
|
val = +(val / plot.maxValue * 100).toFixed(2) + ' %'
|
}
|
|
chart.annotation().text({
|
position: ['50%', '90%'],
|
content: val,
|
style: {
|
fontSize: 36,
|
fill: plot.labelColor,
|
textAlign: 'center',
|
},
|
offsetY: 15,
|
})
|
}
|
|
chart.render()
|
|
this.setState({chart})
|
}
|
|
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 } = this.state
|
|
return (
|
<div className="custom-dashboard-plot-box" id={'anchor' + config.uuid} style={config.style}>
|
{loading ?
|
<div className="loading-mask">
|
<div className="ant-spin-blur"></div>
|
<Spin />
|
</div> : null
|
}
|
<NormalHeader config={config} />
|
<div className="canvas-wrap">
|
{config.plot.download === 'enable' && this.state.chart ? <DownloadOutlined onClick={this.downloadImage} className="system-color download"/> : null}
|
<div className="canvas" id={this.state.chartId}></div>
|
</div>
|
</div>
|
)
|
}
|
}
|
|
export default DashboardChart
|