index.vue 18 KB

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