index.vue 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  1. <template>
  2. <div
  3. v-loading="config.loading"
  4. element-loading-text="图表加载中"
  5. :element-loading-background="loadingBackground"
  6. style="width: 100%;height: 100%"
  7. class="bs-design-wrap bs-custom-component"
  8. :class="{'light-theme':customTheme === 'light','auto-theme':customTheme !=='light'}"
  9. >
  10. <div
  11. :id="chatId"
  12. style="width: 100%;height: 100%"
  13. />
  14. </div>
  15. </template>
  16. <script>
  17. import 'insert-css'
  18. import cloneDeep from 'lodash/cloneDeep'
  19. import linkageMixins from 'data-room-ui/js/mixins/linkageMixins'
  20. import commonMixins from 'data-room-ui/js/mixins/commonMixins'
  21. import { mapState, mapMutations } from 'vuex'
  22. import { settingToTheme } from 'data-room-ui/js/utils/themeFormatting'
  23. import _ from 'lodash'
  24. import * as echarts from 'echarts'
  25. import CloneDeep from 'lodash-es/cloneDeep'
  26. export default {
  27. name: 'EchartsCustomComponent',
  28. mixins: [commonMixins, linkageMixins],
  29. props: {
  30. config: {
  31. type: Object,
  32. default: () => ({})
  33. }
  34. },
  35. data () {
  36. return {
  37. chart: null,
  38. hasData: false
  39. }
  40. },
  41. computed: {
  42. ...mapState('bigScreen', {
  43. pageInfo: state => state.pageInfo,
  44. customTheme: state => state.pageInfo.pageConfig.customTheme,
  45. activeCode: state => state.activeCode
  46. }),
  47. chatId () {
  48. let prefix = 'chart_'
  49. if (this.$route.path === window?.BS_CONFIG?.routers?.previewUrl) {
  50. prefix = 'preview_chart_'
  51. }
  52. if (this.$route.path === window?.BS_CONFIG?.routers?.designUrl) {
  53. prefix = 'design_chart_'
  54. }
  55. if (this.$route.path === window?.BS_CONFIG?.routers?.pageListUrl) {
  56. prefix = 'management_chart_'
  57. }
  58. return prefix + this.config.code
  59. }
  60. },
  61. created () {
  62. },
  63. watch: {
  64. // 监听主题变化手动触发组件配置更新
  65. 'config.option.theme': {
  66. handler (val) {
  67. if (val) {
  68. this.changeStyle(this.config, true)
  69. }
  70. }
  71. },
  72. 'config.w': {
  73. handler (val) {
  74. if (val) {
  75. const chartDom = document.getElementById(this.chatId)
  76. this.observeChart(chartDom, this.chart, this.config.option)
  77. }
  78. }
  79. },
  80. 'config.h': {
  81. handler (val) {
  82. if (val) {
  83. const chartDom = document.getElementById(this.chatId)
  84. this.observeChart(chartDom, this.chart, this.config.option)
  85. }
  86. }
  87. }
  88. },
  89. mounted () {
  90. },
  91. beforeDestroy () {
  92. if (this.chart) {
  93. this.chart.dispose()
  94. }
  95. },
  96. methods: {
  97. ...mapMutations('bigScreen', ['changeChartConfig', 'changeActiveItemConfig', 'changeChartLoading']),
  98. chartInit () {
  99. let config = this.config
  100. // key和code相等,说明是一进来刷新,调用list接口
  101. if (this.config.code === this.config.key || this.isPreview) {
  102. // 改变样式
  103. config = this.changeStyle(config)
  104. // 改变数据
  105. config.loading = true
  106. this.changeChartLoading(config)
  107. this.changeDataByCode(config).then((res) => {
  108. // 初始化图表
  109. config.loading = false
  110. this.changeChartLoading(config)
  111. this.newChart(res)
  112. }).catch(() => {
  113. })
  114. } else {
  115. config.loading = true
  116. this.changeChartLoading(config)
  117. // 否则说明是更新,这里的更新只指更新数据(改变样式时是直接调取changeStyle方法),因为更新数据会改变key,调用chart接口
  118. this.changeData(config).then((res) => {
  119. config.loading = false
  120. this.changeChartLoading(config)
  121. // 初始化图表
  122. this.newChart(res)
  123. })
  124. }
  125. },
  126. /**
  127. * 构造chart
  128. */
  129. newChart (config) {
  130. const chartDom = document.getElementById(this.chatId)
  131. this.chart = echarts.init(chartDom)
  132. config.option && this.chart.setOption(config.option)
  133. },
  134. /**
  135. * 控制底部阴影大小
  136. */
  137. observeChart (container, myChart, option) {
  138. const resizeObserver = new ResizeObserver(entries => {
  139. myChart.resize()
  140. // entries[0].contentRect.width:此时监测的盒子的宽度
  141. // entries[0].contentRect.height:此时监测的盒子的高度
  142. const width = entries[0].contentRect.width
  143. const height = entries[0].contentRect.height
  144. // 调整长方形的大小
  145. option.graphic.children[0].shape.width = width * 0.9
  146. // 调整多边形的大小
  147. option.graphic.children[1].shape.points = [
  148. [width / 10, -height / 6],
  149. [width - width / 6, -height / 6],
  150. [width * 0.9, 0],
  151. [0, 0]
  152. ]
  153. myChart.setOption(option)
  154. })
  155. resizeObserver.observe(container)
  156. },
  157. /**
  158. * 注册事件
  159. */
  160. registerEvent () {
  161. // 图表添加事件进行数据联动
  162. let formData = {}
  163. // eslint-disable-next-line no-unused-vars
  164. this.chart.on('tooltip:change', (...args) => {
  165. formData = {}
  166. formData = cloneDeep(args[0].data.items[0].data)
  167. })
  168. // eslint-disable-next-line no-unused-vars
  169. this.chart.on('plot:click', (...args) => {
  170. this.linkage(formData)
  171. })
  172. },
  173. // 将config.setting的配置转化为option里的配置,这里之所以将转化的方法提出来,是因为在改变维度指标和样式的时候都需要转化
  174. transformSettingToOption (config, type) {
  175. let option = null
  176. config.setting.forEach(set => {
  177. if (set.optionField) {
  178. const optionField = set.optionField.split('.')
  179. option = config.option
  180. // 判断是不是关于x轴的相关配置,x轴叠加了两层坐标轴,如果是x轴相关配置则作用于xAxis[0]
  181. if (optionField[0] === 'xAxis') {
  182. optionField.forEach((field, index) => {
  183. if (index === 0) {
  184. option = option.xAxis[0]
  185. } else if (index === optionField.length - 1) {
  186. // 数据配置时,必须有值才更新
  187. if ((set.tabName === type && type === 'data' && set.value) || (set.tabName === type && type === 'custom')) {
  188. option[field] = set.value
  189. }
  190. } else {
  191. option = option[field]
  192. }
  193. })
  194. } else {
  195. optionField.forEach((field, index) => {
  196. if (index === optionField.length - 1) {
  197. // 数据配置时,必须有值才更新
  198. if ((set.tabName === type && type === 'data' && set.value) || (set.tabName === type && type === 'custom')) {
  199. option[field] = set.value
  200. }
  201. } else {
  202. option = option[field]
  203. }
  204. })
  205. }
  206. }
  207. })
  208. config.option = { ...config.option, ...option }
  209. return config
  210. },
  211. dataFormatting (config, data) {
  212. // 数据返回成功则赋值
  213. if (data.success) {
  214. data = data.data
  215. config = this.transformSettingToOption(config, 'data')
  216. // 获取到后端返回的数据,有则赋值
  217. const option = config.option
  218. const setting = config.setting
  219. if (config.dataHandler) {
  220. try {
  221. // 此处函数处理data
  222. eval(config.dataHandler)
  223. } catch (e) {
  224. console.error(e)
  225. }
  226. }
  227. config.option = this.echartsOptionFormatting(config, data)
  228. } else {
  229. // 数据返回失败则赋前端的模拟数据
  230. // config.option.data = this.plotList?.find(plot => plot.name === config.name)?.option?.data || config?.option?.data
  231. }
  232. return config
  233. },
  234. getxDataAndYData (xField, yField, data, hasSeries) {
  235. let list = []
  236. let xData = []
  237. let yData = []
  238. const uniqueData = {}
  239. // 遍历原始数据数组
  240. data.forEach((item) => {
  241. // 使用城市名称作为键,覆盖旧数据,始终保留最后一条数据
  242. uniqueData[item[xField]] = item
  243. })
  244. // 将唯一数据对象的值(即去重后的数据)转换回数组
  245. list = Object.values(uniqueData)
  246. xData = list.map(item => item[xField])
  247. yData = list.map(item => item[yField])
  248. return { xData, yData }
  249. },
  250. // 格式化echarts的配置
  251. echartsOptionFormatting (config, data) {
  252. const option = config.option
  253. // 分组字段
  254. const xField = config.setting.find(item => item.optionField === 'xField')?.value
  255. const yField = config.setting.find(item => item.optionField === 'yField')?.value
  256. const hasSeries = config.setting.find(item => item.optionField === 'seriesField' && item.value !== '')
  257. const { xData, yData } = this.getxDataAndYData(xField, yField, data, hasSeries)
  258. // const xData = [...new Set(data.map(item => item[xField]))]
  259. // const yData = data.map(item => item[yField])
  260. const maxY = Math.max(...yData) + Math.max(...yData) * 0.2
  261. // 生成阴影柱子的值
  262. const shadowData = Array.from({ length: xData.length }, () => maxY)
  263. option.xAxis = option.xAxis.map(item => {
  264. return {
  265. ...item,
  266. data: xData
  267. }
  268. })
  269. // 判断是否存在分组字段
  270. if (hasSeries) {
  271. const seriesField = config.setting.find(item => item.optionField === 'seriesField')?.value
  272. const seriesFieldList = [...new Set(data.map(item => item[seriesField]))]
  273. option.series = []
  274. const offsetArr = []
  275. let index = 0
  276. let barWidth = 10
  277. if (seriesFieldList.length % 2 === 0) {
  278. const length = seriesFieldList.length / 2
  279. for (let i = 0; i < length; i++) {
  280. const offsetX = (parseInt('10%') + parseInt('50%')) * (2 * i + 1)
  281. offsetArr.push(offsetX)
  282. offsetArr.unshift(-offsetX)
  283. }
  284. } else {
  285. const length = Math.ceil(seriesFieldList.length / 2)
  286. for (let i = 0; i < length; i++) {
  287. if (i === 0) {
  288. offsetArr.push(0)
  289. } else {
  290. const offsetX = (parseInt('20%') + parseInt('100%')) * i
  291. offsetArr.push(offsetX)
  292. offsetArr.unshift(-offsetX)
  293. }
  294. }
  295. }
  296. for (const seriesFieldItem of seriesFieldList) {
  297. const seriesData = (data.filter(item => item[seriesField] === seriesFieldItem))?.map(item => item[yField])
  298. const seriesItem = [
  299. {
  300. name: seriesFieldItem + '柱子顶部',
  301. type: 'pictorialBar',
  302. tooltip: { show: false },
  303. symbol: 'diamond',
  304. symbolSize: [barWidth, barWidth / 2],
  305. symbolOffset: [offsetArr[index] + '%', -barWidth / 4],
  306. symbolPosition: 'end',
  307. z: 15,
  308. zlevel: 2,
  309. color: 'rgba(2, 175, 249,1)',
  310. data: seriesData
  311. },
  312. {
  313. name: seriesFieldItem,
  314. type: 'bar',
  315. barGap: '20%',
  316. barWidth: barWidth,
  317. itemStyle: {
  318. normal: {
  319. color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
  320. {
  321. offset: 0,
  322. color: '#115ba6'
  323. },
  324. {
  325. offset: 1,
  326. color: '#1db0dd'
  327. }
  328. ]),
  329. opacity: 0.8,
  330. shadowColor: 'rgba(0, 0, 0, 0.5)', // 阴影颜色
  331. shadowBlur: 0 // 阴影模糊值
  332. }
  333. },
  334. label: {
  335. show: false
  336. },
  337. zlevel: 2,
  338. z: 12,
  339. data: seriesData
  340. },
  341. {
  342. name: seriesFieldItem + '柱子底部',
  343. type: 'pictorialBar',
  344. tooltip: { show: false },
  345. symbol: 'diamond',
  346. symbolSize: [barWidth, barWidth / 2],
  347. symbolOffset: [offsetArr[index] + '%', barWidth / 4],
  348. zlevel: 2,
  349. z: 15,
  350. color: 'rgb(2, 192, 255)',
  351. data: seriesData
  352. },
  353. {
  354. name: seriesFieldItem + '背景柱子',
  355. type: 'bar',
  356. tooltip: { show: false },
  357. xAxisIndex: 1,
  358. barGap: '20%',
  359. data: shadowData,
  360. zlevel: 1,
  361. barWidth: barWidth,
  362. itemStyle: {
  363. normal: {
  364. color: 'rgba(9, 44, 76,.8)'
  365. }
  366. }
  367. },
  368. {
  369. name: seriesFieldItem + '背景柱子顶部',
  370. type: 'pictorialBar',
  371. tooltip: { show: false },
  372. symbol: 'diamond',
  373. symbolSize: [barWidth, barWidth / 2],
  374. symbolOffset: [offsetArr[index] + '%', -barWidth / 4],
  375. symbolPosition: 'end',
  376. z: 15,
  377. color: 'rgb(15, 69, 133)',
  378. zlevel: 1,
  379. data: shadowData
  380. }
  381. ]
  382. index++
  383. option.series.push(...seriesItem)
  384. }
  385. } else {
  386. option.series = [
  387. {
  388. id: 'barTopColor', // 用于区分是图表的什么部分
  389. type: 'pictorialBar', // 象形柱图
  390. symbol: 'diamond',
  391. symbolOffset: [0, '-50%'], // 上部菱形
  392. symbolSize: [30, 15],
  393. // symbolOffset: [0, -6], // 上部椭圆
  394. symbolPosition: 'end',
  395. z: 12,
  396. label: {
  397. normal: {
  398. show: true,
  399. position: 'top',
  400. fontSize: 15,
  401. fontWeight: 'bold',
  402. color: '#27a7ce'
  403. }
  404. },
  405. color: option.seriesCustom.barTopColor,
  406. data: yData
  407. },
  408. {
  409. id: 'barBottomColor', // 用于区分是图表的什么部分
  410. type: 'pictorialBar',
  411. symbol: 'diamond',
  412. symbolSize: [30, 15],
  413. symbolOffset: ['0%', '50%'], // 下部菱形
  414. // symbolOffset: [0, 7], // 下部椭圆
  415. z: 12,
  416. color: option.seriesCustom.barBottomColor,
  417. data: yData
  418. },
  419. {
  420. id: 'barColor', // 用于区分是图表的什么部分
  421. type: 'bar',
  422. barWidth: 30,
  423. z: 10,
  424. itemStyle: {
  425. normal: {
  426. color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
  427. {
  428. offset: 0,
  429. color: option.seriesCustom.barColor1
  430. },
  431. {
  432. offset: 1,
  433. color: option.seriesCustom.barColor2
  434. }
  435. ]),
  436. opacity: 0.8,
  437. shadowColor: 'rgba(0, 0, 0, 0.5)', // 阴影颜色
  438. shadowBlur: 0 // 阴影模糊值
  439. }
  440. },
  441. data: yData
  442. },
  443. {
  444. id: 'shadowColor', // 用于区分是图表的什么部分
  445. type: 'bar',
  446. barWidth: 30,
  447. xAxisIndex: 1,
  448. itemStyle: {
  449. normal: {
  450. color: option.seriesCustom.shadowColor,
  451. opacity: 0.8,
  452. shadowColor: 'rgba(0, 0, 0, 0.5)', // 阴影颜色
  453. shadowBlur: 0 // 阴影模糊值
  454. }
  455. },
  456. label: {
  457. show: false
  458. },
  459. tooltip: {
  460. show: false
  461. },
  462. data: shadowData
  463. },
  464. {
  465. id: 'shadowTopColor', // 用于区分是图表的什么部分
  466. type: 'pictorialBar', // 象形柱图
  467. xAxisIndex: 1,
  468. symbol: 'diamond',
  469. symbolOffset: [0, '-50%'], // 上部菱形
  470. symbolSize: [30, 15],
  471. // symbolOffset: [0, -6], // 上部椭圆
  472. symbolPosition: 'end',
  473. z: 12,
  474. label: {
  475. normal: {
  476. show: false,
  477. position: 'top',
  478. fontSize: 15,
  479. fontWeight: 'bold',
  480. color: '#27a7ce'
  481. }
  482. },
  483. color: option.seriesCustom.shadowTopColor,
  484. tooltip: {
  485. show: false
  486. },
  487. data: shadowData
  488. }
  489. ]
  490. }
  491. return option
  492. },
  493. // 对series里面的样式进行配置
  494. seriesStyle (config) {
  495. const _config = CloneDeep(config)
  496. const seriesCustom = _config.option.seriesCustom
  497. const ids = Object.keys(config.option.seriesCustom)
  498. // const ids = ['barTopColor', 'barBottomColor', 'shadowColor', 'shadowTopColor']
  499. const hasSeries = _config.setting.find(item => item.optionField === 'seriesField' && item.value !== '')
  500. // 如果是基础柱状图
  501. if (!hasSeries) {
  502. _config.option.series.forEach(item => {
  503. // 配置颜色
  504. if (ids.includes(item.id)) {
  505. item.color = seriesCustom[item.id]
  506. }
  507. // 配置宽度
  508. if (item.type === 'pictorialBar') {
  509. item.symbolSize = [seriesCustom.barWidth, seriesCustom.barWidth / 2]
  510. } else if (item.type === 'bar') {
  511. item.barWidth = seriesCustom.barWidth
  512. }
  513. })
  514. }
  515. _config.option.series.forEach((item) => {
  516. if (ids.includes(item.id)) {
  517. item.color = _config.option.seriesCustom[item.id]
  518. } else {
  519. // item.itemStyle.normal.color = new echarts.graphic.LinearGradient(0, 0, 0, 1, [
  520. // {
  521. // offset: 0,
  522. // color: _config.option.seriesCustom.barColor1
  523. // },
  524. // {
  525. // offset: 1,
  526. // color: _config.option.seriesCustom.barColor2
  527. // }
  528. // ])
  529. }
  530. })
  531. return _config
  532. },
  533. // 组件的样式改变,返回改变后的config
  534. changeStyle (config, isUpdateTheme) {
  535. config = { ...this.config, ...config }
  536. config = this.transformSettingToOption(config, 'custom')
  537. // 这里定义了option和setting是为了保证在执行eval时,optionHandler、dataHandler里面可能会用到,
  538. const option = config.option
  539. const setting = config.setting
  540. if (this.config.optionHandler) {
  541. try {
  542. // 此处函数处理config
  543. eval(this.config.optionHandler)
  544. } catch (e) {
  545. console.error(e)
  546. }
  547. }
  548. // 此时,setting中的部分变量映射到了option.seriesCustom中,但未映射到series的具体配置中
  549. config = this.seriesStyle(config)
  550. // 只有样式改变时更新主题配置,切换主题时不需要保存
  551. if (!isUpdateTheme) {
  552. config.theme = settingToTheme(_.cloneDeep(config), this.customTheme)
  553. }
  554. this.changeChartConfig(config)
  555. if (config.code === this.activeCode) {
  556. this.changeActiveItemConfig(config)
  557. }
  558. if (this.chart) {
  559. this.chart.setOption(config.option)
  560. }
  561. return config
  562. }
  563. }
  564. }
  565. </script>
  566. <style lang="scss" scoped>
  567. @import '../assets/style/echartStyle';
  568. .light-theme{
  569. background-color: #FFFFFF;
  570. color: #000000;
  571. }
  572. .auto-theme{
  573. background-color: transparent;
  574. }
  575. </style>