index.vue 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  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. },
  73. mounted () {
  74. },
  75. beforeDestroy () {
  76. if (this.chart) {
  77. this.chart.dispose()
  78. }
  79. },
  80. methods: {
  81. ...mapMutations('bigScreen', ['changeChartConfig', 'changeActiveItemConfig', 'changeChartLoading']),
  82. chartInit () {
  83. let config = this.config
  84. // key和code相等,说明是一进来刷新,调用list接口
  85. if (this.config.code === this.config.key || this.isPreview) {
  86. // 改变样式
  87. config = this.changeStyle(config)
  88. // 改变数据
  89. config.loading = true
  90. this.changeChartLoading(config)
  91. this.changeDataByCode(config).then((res) => {
  92. // 初始化图表
  93. config.loading = false
  94. this.changeChartLoading(config)
  95. this.newChart(res)
  96. }).catch(() => {
  97. })
  98. } else {
  99. config.loading = true
  100. this.changeChartLoading(config)
  101. // 否则说明是更新,这里的更新只指更新数据(改变样式时是直接调取changeStyle方法),因为更新数据会改变key,调用chart接口
  102. this.changeData(config).then((res) => {
  103. config.loading = false
  104. this.changeChartLoading(config)
  105. // 初始化图表
  106. this.newChart(res)
  107. })
  108. }
  109. },
  110. /**
  111. * 构造chart
  112. */
  113. newChart (config) {
  114. const chartDom = document.getElementById(this.chatId)
  115. this.chart = echarts.init(chartDom)
  116. config.option && this.chart.setOption(config.option)
  117. this.observeChart(chartDom, this.chart)
  118. },
  119. /**
  120. * 控制底部阴影大小
  121. */
  122. observeChart (container, myChart) {
  123. const resizeObserver = new ResizeObserver(entries => {
  124. myChart.resize()
  125. // entries[0].contentRect.width:此时监测的盒子的宽度
  126. // entries[0].contentRect.height:此时监测的盒子的高度
  127. const width = entries[0].contentRect.width
  128. const height = entries[0].contentRect.height
  129. const option = this.config.option
  130. // 调整长方形的大小
  131. option.graphic.children[0].shape.width = width * 0.9
  132. // 调整多边形的大小
  133. option.graphic.children[1].shape.points = [
  134. [width / 10, -height / 6],
  135. [width - width / 6, -height / 6],
  136. [width * 0.9, 0],
  137. [0, 0]
  138. ]
  139. myChart.setOption(option)
  140. })
  141. resizeObserver.observe(container)
  142. },
  143. /**
  144. * 注册事件
  145. */
  146. registerEvent () {
  147. // 图表添加事件进行数据联动
  148. let formData = {}
  149. // eslint-disable-next-line no-unused-vars
  150. this.chart.on('tooltip:change', (...args) => {
  151. formData = {}
  152. formData = cloneDeep(args[0].data.items[0].data)
  153. })
  154. // eslint-disable-next-line no-unused-vars
  155. this.chart.on('plot:click', (...args) => {
  156. this.linkage(formData)
  157. })
  158. },
  159. // 将config.setting的配置转化为option里的配置,这里之所以将转化的方法提出来,是因为在改变维度指标和样式的时候都需要转化
  160. transformSettingToOption (config, type) {
  161. let option = null
  162. config.setting.forEach(set => {
  163. if (set.optionField) {
  164. const optionField = set.optionField.split('.')
  165. option = config.option
  166. // 判断是不是关于x轴的相关配置,x轴叠加了两层坐标轴,如果是x轴相关配置则作用于xAxis[0]
  167. if (optionField[0] === 'xAxis') {
  168. optionField.forEach((field, index) => {
  169. if (index === 0) {
  170. option = option.xAxis[0]
  171. } else if (index === optionField.length - 1) {
  172. // 数据配置时,必须有值才更新
  173. if ((set.tabName === type && type === 'data' && set.value) || (set.tabName === type && type === 'custom')) {
  174. option[field] = set.value
  175. }
  176. } else {
  177. option = option[field]
  178. }
  179. })
  180. } else if (optionField[0] === 'series') {
  181. let changeObject = []
  182. let beforeChange = []
  183. // 如果要配置数据标签相关信息
  184. optionField.forEach((field, index) => {
  185. if (index === 0) {
  186. option = option[field]
  187. } else if (index === 1) {
  188. // 筛选出需要修改的series对象
  189. changeObject = option.filter(item => item.id.includes(field))
  190. beforeChange = [...changeObject]
  191. option = option.filter(item => !(item.id.includes(field)))
  192. } else if (index === optionField.length - 1) {
  193. if ((set.tabName === type && type === 'data' && set.value) || (set.tabName === type && type === 'custom')) {
  194. changeObject.map(item => {
  195. item[field] = set.value
  196. })
  197. }
  198. } else {
  199. const changeResult = []
  200. changeObject.forEach(item => {
  201. const result = { ...item[field] }
  202. changeResult.push(result)
  203. })
  204. changeObject = [...changeResult]
  205. }
  206. })
  207. // 合并修改后的series对象
  208. changeObject.forEach(
  209. (item, index) => {
  210. beforeChange[index].label = _.cloneDeep(item)
  211. option.push(beforeChange[index])
  212. }
  213. )
  214. } else if (optionField[0] === 'graphic') {
  215. option.graphic.children.forEach(item => {
  216. item.style.fill = set.value
  217. })
  218. } else {
  219. optionField.forEach((field, index) => {
  220. if (index === optionField.length - 1) {
  221. // 数据配置时,必须有值才更新
  222. if ((set.tabName === type && type === 'data' && set.value) || (set.tabName === type && type === 'custom')) {
  223. option[field] = set.value
  224. }
  225. } else {
  226. option = option[field]
  227. }
  228. })
  229. }
  230. }
  231. })
  232. config.option = { ...config.option, ...option }
  233. return config
  234. },
  235. dataFormatting (config, data) {
  236. console.log('config', config);
  237. // config = this.config
  238. // 数据返回成功则赋值
  239. if (data.success) {
  240. data = data.data
  241. // 获取到后端返回的数据,有则赋值
  242. const option = config.option
  243. const setting = config.setting
  244. if (config.dataHandler) {
  245. try {
  246. // 此处函数处理data
  247. eval(config.dataHandler)
  248. } catch (e) {
  249. console.error(e)
  250. }
  251. }
  252. config.option = this.echartsOptionFormatting(config, data)
  253. config = this.transformSettingToOption(config, 'data')
  254. } else {
  255. // 数据返回失败则赋前端的模拟数据
  256. // config.option.data = this.plotList?.find(plot => plot.name === config.name)?.option?.data || config?.option?.data
  257. }
  258. config = this.seriesStyle(config)
  259. return config
  260. },
  261. getxDataAndYData (xField, yField, data) {
  262. let list = []
  263. let xData = []
  264. let yData = []
  265. const uniqueData = {}
  266. // 遍历原始数据数组
  267. data.forEach((item) => {
  268. // 使用城市名称作为键,覆盖旧数据,始终保留最后一条数据
  269. uniqueData[item[xField]] = item
  270. })
  271. // 将唯一数据对象的值(即去重后的数据)转换回数组
  272. list = Object.values(uniqueData)
  273. xData = list.map(item => item[xField])
  274. yData = list.map(item => item[yField])
  275. return { xData, yData }
  276. },
  277. // 格式化echarts的配置
  278. echartsOptionFormatting (config, data) {
  279. const option = config.option
  280. // 分组字段
  281. const xField = config.setting.find(item => item.optionField === 'xField')?.value
  282. const yField = config.setting.find(item => item.optionField === 'yField')?.value
  283. // 判断是否存在分组
  284. const hasSeries = config.setting.find(item => item.optionField === 'seriesField' && item.value !== '')
  285. const { xData, yData } = this.getxDataAndYData(xField, yField, data)
  286. const maxY = Math.max(...yData) + Math.max(...yData) * 0.2
  287. // 生成阴影柱子的值
  288. const shadowData = Array.from({ length: xData.length }, () => maxY)
  289. option.xAxis = option.xAxis.map(item => {
  290. return {
  291. ...item,
  292. data: xData
  293. }
  294. })
  295. // 存在分组字段
  296. if (hasSeries) {
  297. const seriesField = config.setting.find(item => item.optionField === 'seriesField')?.value
  298. const seriesFieldList = [...new Set(data.map(item => item[seriesField]))]
  299. option.series = []
  300. const barWidth = option.seriesCustom.barWidth
  301. // 偏移量数组
  302. const offsetArr = []
  303. let index = 0
  304. if (seriesFieldList.length % 2 === 0) {
  305. const length = seriesFieldList.length / 2
  306. for (let i = 0; i < length; i++) {
  307. const offsetX = (parseInt('10%') + parseInt('50%')) * (2 * i + 1)
  308. offsetArr.push(offsetX)
  309. offsetArr.unshift(-offsetX)
  310. }
  311. } else {
  312. const length = Math.ceil(seriesFieldList.length / 2)
  313. for (let i = 0; i < length; i++) {
  314. if (i === 0) {
  315. offsetArr.push(0)
  316. } else {
  317. const offsetX = (parseInt('20%') + parseInt('100%')) * i
  318. offsetArr.push(offsetX)
  319. offsetArr.unshift(-offsetX)
  320. }
  321. }
  322. }
  323. for (const seriesFieldItem of seriesFieldList) {
  324. const seriesData = (data.filter(item => item[seriesField] === seriesFieldItem))?.map(item => item[yField])
  325. const seriesItem = [
  326. {
  327. id: 'barTopColor' + seriesFieldItem,
  328. type: 'pictorialBar',
  329. tooltip: { show: false },
  330. symbol: 'diamond',
  331. symbolSize: [barWidth, barWidth / 2],
  332. symbolOffset: [offsetArr[index] + '%', -barWidth / 4],
  333. symbolPosition: 'end',
  334. z: 15,
  335. zlevel: 2,
  336. color: '#ffff33',
  337. data: seriesData
  338. },
  339. {
  340. id: 'barColor' + seriesFieldItem,
  341. type: 'bar',
  342. barGap: '20%',
  343. barWidth: barWidth,
  344. color: '#115ba6',
  345. label: {
  346. show: false
  347. },
  348. zlevel: 2,
  349. z: 12,
  350. data: seriesData
  351. },
  352. {
  353. id: 'barBottomColor' + seriesFieldItem,
  354. type: 'pictorialBar',
  355. tooltip: { show: false },
  356. symbol: 'diamond',
  357. symbolSize: [barWidth, barWidth / 2],
  358. symbolOffset: [offsetArr[index] + '%', barWidth / 4],
  359. zlevel: 2,
  360. z: 15,
  361. color: 'rgb(2, 192, 255)',
  362. data: seriesData
  363. },
  364. {
  365. id: 'shadowColor' + seriesFieldItem,
  366. type: 'bar',
  367. tooltip: { show: false },
  368. xAxisIndex: 1,
  369. barGap: '20%',
  370. data: shadowData,
  371. zlevel: 1,
  372. barWidth: barWidth,
  373. color: 'rgba(9, 44, 76,.8)'
  374. },
  375. {
  376. id: 'shadowTopColor' + seriesFieldItem,
  377. type: 'pictorialBar',
  378. tooltip: { show: false },
  379. symbol: 'diamond',
  380. symbolSize: [barWidth, barWidth / 2],
  381. symbolOffset: [offsetArr[index] + '%', -barWidth / 4],
  382. symbolPosition: 'end',
  383. z: 15,
  384. color: 'rgb(15, 69, 133)',
  385. zlevel: 1,
  386. data: shadowData
  387. }
  388. ]
  389. index++
  390. option.series.push(...seriesItem)
  391. }
  392. } else {
  393. // 没有分组,不需要修改配置,直接修改series中每个对象的series
  394. option.series.forEach(item => {
  395. if (item.id.includes('shadow')) {
  396. item.data = shadowData
  397. } else {
  398. item.data = yData
  399. }
  400. })
  401. }
  402. return option
  403. },
  404. // 对series里面的样式进行配置
  405. seriesStyle (config) {
  406. const _config = CloneDeep(config)
  407. const seriesCustom = _config.option.seriesCustom
  408. // const ids = ['barTopColor', 'barColor', 'barBottomColor', 'shadowColor', 'shadowTopColor']
  409. const ids = Object.keys(config.option.seriesCustom)
  410. const isGroup = _config.option.series.length !== 5
  411. // 宽度配置
  412. _config.option.series.forEach(item => {
  413. if (item.type === 'pictorialBar') {
  414. item.symbolSize = [seriesCustom.barWidth, seriesCustom.barWidth / 2]
  415. } else if (item.type === 'bar') {
  416. item.barWidth = seriesCustom.barWidth
  417. }
  418. })
  419. // 如果是基础柱状图
  420. if (!isGroup) {
  421. _config.option.series.forEach(item => {
  422. // 配置颜色
  423. if (ids.includes(item.id)) {
  424. item.color = seriesCustom[item.id]
  425. }
  426. })
  427. } else {
  428. // 如果是分组柱状图
  429. ids.forEach(id => {
  430. if (id !== 'barWidth') {
  431. let index = 0
  432. _config.option.series.forEach(item => {
  433. if (item.id.includes(id)) {
  434. item.color = _config.option.seriesCustom[id][index]
  435. index++
  436. }
  437. })
  438. }
  439. })
  440. }
  441. return _config
  442. },
  443. // 组件的样式改变,返回改变后的config
  444. changeStyle (config, isUpdateTheme) {
  445. config = { ...this.config, ...config }
  446. config = this.transformSettingToOption(config, 'custom')
  447. // 这里定义了option和setting是为了保证在执行eval时,optionHandler、dataHandler里面可能会用到,
  448. const option = config.option
  449. const setting = config.setting
  450. if (this.config.optionHandler) {
  451. try {
  452. // 此处函数处理config
  453. eval(this.config.optionHandler)
  454. } catch (e) {
  455. console.error(e)
  456. }
  457. }
  458. // 此时,setting中的部分变量映射到了option.seriesCustom中,但未映射到series的具体配置中
  459. config = this.seriesStyle(config)
  460. // 只有样式改变时更新主题配置,切换主题时不需要保存
  461. if (!isUpdateTheme) {
  462. config.theme = settingToTheme(_.cloneDeep(config), this.customTheme)
  463. }
  464. this.changeChartConfig(config)
  465. if (config.code === this.activeCode) {
  466. this.changeActiveItemConfig(config)
  467. }
  468. if (this.chart) {
  469. this.chart.setOption(config.option)
  470. }
  471. return config
  472. }
  473. }
  474. }
  475. </script>
  476. <style lang="scss" scoped>
  477. @import '../assets/style/echartStyle';
  478. .light-theme{
  479. background-color: #FFFFFF;
  480. color: #000000;
  481. }
  482. .auto-theme{
  483. background-color: transparent;
  484. }
  485. </style>