<template>
  <el-tabs type="card" @tab-click="initClick">
    <el-tab-pane label="查看图表">
      <el-switch
        v-model="isDark"
        active-text="深色模式"
        inactive-text="浅色模式"
        @change="modeChange"
        style="margin-bottom: 5px"
      />
      <div
        v-if="showTable"
        :id="id"
        :style="{width: '100%', height: customChart.height + 'px'}"
      ></div>
    </el-tab-pane>
    <el-tab-pane label="查看数据">
      <ht-table
        v-if="showTable"
        ref="table"
        :data="data"
        :page-result="pageResult"
        :default-querys="defaultQuery"
        :selectable="false"
        :show-export="true"
        :show-custom-column="false"
        :quick-search-props="quickSearchProp"
        :quick-search-width="quickSearchWidth"
        :nopagination="true"
        custom-table-height="500"
        @load="loadData"
        @export="exportData"
      >
        <ht-table-column
          v-for="xaxisField in customChart.xaxisField"
          :key="xaxisField.field"
          :prop="xaxisField.field.toUpperCase()"
          :label="xaxisField.comment"
        ></ht-table-column>
        <ht-table-column
          v-for="displayfield in customChart.displayfield"
          :key="displayfield.field"
          :prop="displayfield.field.toUpperCase()"
          :label="displayfield.comment"
        ></ht-table-column>
      </ht-table>
    </el-tab-pane>
  </el-tabs>
</template>

<script>
import ecStat from 'echarts-stat'
import form from '@/api/form.js'
import {export_json_to_excel} from '@/vendor/Export2Excel.js'
import {VisualMapComponent} from 'echarts/components'
export default {
  props: {
    id: {
      type: [String, Number],
      required: true
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initData()
    })
    window.addEventListener('resize', this.resizeChart)
  },
  watch: {
    id: function(newV) {
      if (newV) {
        this.customChart = []
        this.data = []
        this.quickSearchProp = ''
        this.quickSearchWidth = 400
        this.defaultQuery = []
        this.showTable = false
        this.initData()
      }
    }
  },
  data() {
    return {
      customChart: {},
      pageResult: {
        page: 1,
        pageSize: 20,
        total: 0
      },
      data: [],
      showTable: false,
      quickSearchProp: '',
      quickSearchWidth: 400,
      defaultQuery: [],
      queryOpTransObj: {
        EQ: 'EQUAL',
        BETWEEN: 'BETWEEN',
        GE: 'GREAT_EQUAL',
        LE: 'LESS_EQUAL',
        LK: 'LIKE',
        IN: 'IN'
      },
      querrySelectList: [],
      myChart: null,
      isDark: false,
      dynamicInterval: null
    }
  },
  created() {
    this.$echarts.use([VisualMapComponent]) // 在 created 钩子函数中注册组件
  },
  destroyed() {
    window.removeEventListener('resize', this.resizeChart)
  },
  methods: {
    resizeChart() {
      this.myChart ? this.myChart.resize() : ''
    },
    initClick(tabVue) {
      if (tabVue.index === '1') {
        this.$refs.table.load()
      } else {
        this.buildChart(this.customChart)
      }
    },
    loadData(param, cb) {
      if (this.customChart.alias) {
        param.pageBean.pageSize = parseInt(
          this.customChart.conf.maxLength &&
            this.customChart.conf.maxLength !== '0'
            ? this.customChart.conf.maxLength
            : -1
        )
        param.sorter = param.sorter || []
        if (this.customChart.sortfield) {
          this.customChart.sortfield.forEach(item => {
            param.sorter.push({
              property: item.field,
              direction: item.sortType.toUpperCase()
            })
          })
        }
        form
          .getListData(this.customChart.alias, param)
          .then(response => {
            let chartData = response
            //把返回的数据的键统一为大写
            if(Object.prototype.toString.call(response) === '[object Object]'){
              response.rows.forEach((item) => {
                this.keyUpper(item)
              })
              this.data = response.rows
            }else{
              response.forEach((item) => {
                this.keyUpper(item)
              })
              this.data = response
            }
            this.pageResult = {
              page: response.page,
              pageSize: response.pageSize,
              total: response.total
            }
            this.customChart.rows = this.data
            this.buildChart(this.customChart)
          })
          .finally(() => {
            cb()
          })
      } else {
        cb()
      }
    },
    async initData() {
      let data = await form.getCustomChartById(this.id)
      if (!data) {
        this.$message.error('未获取到图表数据')
        return
      }
      data.conditionfield = JSON.parse(data.conditionfield)
      data.displayfield = JSON.parse(data.displayfield)
      data.xaxisField = JSON.parse(data.xaxisField)
      data.sortfield = JSON.parse(data.sortfield)
      data.conf = JSON.parse(data.conf)
      this.customChart = data
      this.initCondition()
      this.showTable = true
    },
    initCondition() {
      let conditions = this.customChart.conditionfield
      for (let i = 0; i < conditions.length; i++) {
        if (conditions[i].defaultType === '1') {
          this.quickSearchProp += conditions[i].field.toUpperCase() + ','
        } else {
          this.defaultQuery.push({
            property: conditions[i].field,
            value: conditions[i].defaultValue,
            operation: this.queryOpTransObj[conditions[i].condition],
            group: 'main'
          })
        }
      }
      if (this.quickSearchProp.length > 74) {
        this.quickSearchWidth = (this.quickSearchProp.length - 74) * 30 + 400
      }
    },
    async buildChart(data) {
      let that = this
      await this.$nextTick()
      this.myChart && this.myChart.dispose()
      this.myChart = this.$echarts.init(
        document.getElementById(this.id),
        this.isDark ? 'dark' : 'default'
      )

      let grid = this.getGrid()
      data.conf.title.text = data.name
      data.conf.title.top = this.getTitlePosition()
      let option = {
        title: data.conf.title,
        tooltip: {},
        toolbox: {feature: {saveAsImage: {}}},
        legend: {},
        grid: grid,
        series: {}
      }
      switch (data.style) {
        case 1:
          option = this.buildLine(data, option)
          break
        case 3:
          option = this.buildPie(data, option)
          break
        case 4:
          option = this.buildRadar(data, option)
          break
        case 5:
          option = this.buildFunnel(data, option)
          break
        case 6:
          option = this.buildScatter(data, option)
          break
        case 7:
          option = this.buildHeatmap(data, option)
          break
        default:
          break
      }

      option.title.text = data.name
      option.title.top = this.getTitlePosition()
      option.grid = this.getGrid()

      this.adjustChatTitle(data, option)

      this.myChart.setOption(option)
      this.myChart.on('mouseover', () => {
        return that.stop()
      })
      this.myChart.on('mouseout', () => {
        return that.goMove(option)
      })
      this.addDynamic(option)
    },
    //停止滚动
    stop() {
      this.dynamicInterval && clearInterval(this.dynamicInterval)
    },
    //继续滚动
    goMove(option) {
      this.addDynamic(option)
    },
    addDynamic(option) {
      this.dynamicInterval && clearInterval(this.dynamicInterval)
      let current = -1
      let index = -1
      let dataLen1 = option.series[0].data.length
      let dataLen2 = option.series.length
      this.dynamicInterval = setInterval(() => {
        // 取消之前高亮的图形
        this.myChart.dispatchAction({
          type: 'downplay',
          seriesIndex: index,
          dataIndex: current
        })
        current = (current + 1) % dataLen1
        if (current === 0) {
          index = (index + 1) % dataLen2
        }
        // 高亮当前图形
        this.myChart.dispatchAction({
          type: 'highlight',
          seriesIndex: index,
          dataIndex: current
        })
        // 显示 tooltip
        this.myChart.dispatchAction({
          type: 'showTip',
          seriesIndex: index,
          dataIndex: current
        })
      }, 2000)
    },
    buildLine(data, option) {
      let displayField = this.customChart.displayfield
      let legendData = []
      let xAxisData = []
      let seriesData = []
      let xAxisField = {}
      let series = this.customChart.conf.series
      if (this.customChart.xaxisField)
        xAxisField = this.customChart.xaxisField[0]

      for (let i = 0, d; (d = displayField[i++]); ) {
        if (d) {
          let arr = []
          let type = d.type
          legendData.push(d.comment)
          for (let j = 0, res; (res = data.rows[j++]); ) {
            if (i === 1) {
              let value = res[xAxisField.field.toUpperCase()]
              if (
                xAxisField.dbType === 'date' &&
                value &&
                typeof value === 'number'
              ) {
                value = new Date(value).format(defaultFmt)
              }
              xAxisData.push(value)
            }
            if (res) {
              let value = res[d.field.toUpperCase()]
              if (value && value.length >= 8) option.grid.left = '25%'
              arr.push(value)
            }
          }
          let se = {
            name: d.comment,
            type: d.type,
            data: arr,
            stack: series.stack ? 'one' : null
          }

          if (series.doubleYAxis) {
            se.yAxisIndex = d.yAxis === 1 ? 0 : 1
          }
          if (type === 'line') {
            se.smooth = series.smooth
          }
          seriesData.push(se)
        }
      }

      option.series = seriesData
      if (series.showType || !series.doubleYAxis) {
        option.xAxis = [
          {
            type: 'category',
            splitLine: {
              lineStyle: {
                type: 'dashed'
              }
            },
            data: xAxisData
          }
        ]
        let leftY = {
          type: 'value',
          axisLine: {
            lineStyle: {
              color: '#575E71'
            }
          },
          splitLine: {
            lineStyle: {
              type: 'dashed'
            }
          }
        }
        let rightY = {
          type: 'value',
          axisLine: {
            lineStyle: {
              color: '#575E71'
            }
          },
          splitLine: {
            lineStyle: {
              type: 'dashed'
            }
          },
          position: 'right'
        }
        option.yAxis = series.doubleYAxis ? [leftY, rightY] : [leftY]
      } else {
        option.xAxis = [
          {
            type: 'value',
            splitLine: {
              lineStyle: {
                type: 'dashed'
              }
            }
          }
        ]
        option.yAxis = [
          {
            type: 'category',
            splitLine: {
              lineStyle: {
                type: 'dashed'
              }
            },
            data: xAxisData
          }
        ]
      }

      //柱状图的时候两端留空。避免柱状图挡住y轴。折线图则不留空，
      if (data.style === 2) option.xAxis[0]['boundaryGap'] = true
      if (data.conf) {
        let obj = data.conf
        if (obj.yMin === 2) option.yAxis[0]['min'] = 'dataMin'
        if (obj.xShowAll === 2)
          option.xAxis[0]['axisLabel'] = {
            interval: 0, //横轴信息全部显示
            rotate: 30
          }
      }
      if (data.rows.length > 20 && series.dataZoom) {
        option.dataZoom = [
          {
            type: 'slider',
            show: true,
            bottom: '20px',
            borderColor: '#07417a',
            backgroundColor: 'transparent',
            dataBackground: {
              lineStyle: {
                color: 'transparent',
                shadowOffsetY: 0
              },
              areaStyle: {
                color: 'transparent',
                shadowOffsetY: 0
              }
            },
            // 拖拽手柄样式 svg 路径
            handleIcon:
              'M512 512m-208 0a6.5 6.5 0 1 0 416 0 6.5 6.5 0 1 0-416 0Z M512 192C335.264 192 192 335.264 192 512c0 176.736 143.264 320 320 320s320-143.264 320-320C832 335.264 688.736 192 512 192zM512 800c-159.072 0-288-128.928-288-288 0-159.072 128.928-288 288-288s288 128.928 288 288C800 671.072 671.072 800 512 800z',
            handleColor: '#aab6c6',
            height: 6,
            handleSize: 12,
            showDataShadow: false,
            filterMode: 'filter',
            textStyle: {
              color: '#ccc'
            },
            start: 0,
            end: 100
          }
        ]
        option.grid.bottom = 50
      } else {
        delete option.dataZoom
      }
      option.legend = {
        top: 10,
        itemGap: 50,
        data: legendData,
        ...data.conf.legend
      }

      return option
    },
    buildPie(data, option) {
      let displayField = data.displayfield
      let legendData = []
      let seriesData = []
      let xAxisField = data.xaxisField
      let series = data.conf.series
      if (xAxisField) xAxisField = xAxisField[0]

      if (series.showType) {
        let duration = 100 / data.rows.length
        for (let j = 0; j < data.rows.length; j++) {
          let value = []
          for (let i = 0; i < displayField.length; i++) {
            value.push({
              name: displayField[i].comment,
              value: data.rows[j][displayField[i].field.toUpperCase()]
            })
            if (j === 0) {
              legendData.push(displayField[i].comment)
            }
          }
          seriesData.push({
            name: data.rows[j][xAxisField.field.toUpperCase()],
            type: 'pie',
            data: value,
            radius: [series.radius[0] + '%', series.radius[1] + '%'],
            center: [
              Number(series.center[0]) + j * duration + '%',
              series.center[1] + '%'
            ],
            roseType: series.roseType,
            selectedMode: series.selectedMode,
            label: {
              position: series.label.position
            },
            itemStyle: {
              emphasis: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          })
        }
      } else {
        let duration = 100 / displayField.length
        for (let i = 0; i < displayField.length; i++) {
          let value = []
          for (let j = 0; j < data.rows.length; j++) {
            value.push({
              name: data.rows[j][xAxisField.field.toUpperCase()],
              value: data.rows[j][displayField[i].field.toUpperCase()]
            })
            if (i === 0) {
              legendData.push(data.rows[j][xAxisField.field.toUpperCase()] + '')
            }
          }
          seriesData.push({
            name: displayField[i].comment,
            type: 'pie',
            data: value,
            radius: [series.radius[0] + '%', series.radius[1] + '%'],
            center: [
              Number(series.center[0]) + i * duration + '%',
              series.center[1] + '%'
            ],
            roseType: series.roseType,
            selectedMode: series.selectedMode,
            label: {
              position: series.label.position
            },
            itemStyle: {
              emphasis: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          })
        }
      }

      option.series = seriesData
      option.tooltip = {
        trigger: 'item',
        formatter: '{a} <br/>{b} : {c} ({d}%)'
      }

      option.legend = {
        orient: 'horizontal',
        bottom: 5,

        pageButtonGap: 50,

        textStyle: {
          fontSize: 16
        },

        data: legendData,
        ...data.conf.legend
      }

      return option
    },
    buildRadar(data, option) {
      let displayField = data.displayfield
      let legendData = []
      let xAxisField = data.xaxisField
      let arr = []
      let seriesData = []
      let indicator = []
      let series = data.conf.series
      if (xAxisField) xAxisField = xAxisField[0]

      if (series.showType) {
        for (let j = 0; j < data.rows.length; j++) {
          let value = []
          for (let i = 0; i < displayField.length; i++) {
            value.push(data.rows[j][displayField[i].field.toUpperCase()])
            if (j === 0) {
              indicator.push({
                name: displayField[i].comment
              })
            }
          }
          legendData.push(data.rows[j][xAxisField.field.toUpperCase()] + '')
          arr.push({
            name: data.rows[j][xAxisField.field.toUpperCase()],
            value: value,
            areaStyle: {
              opacity: '0'
            }
          })
        }
        seriesData = [
          {
            type: 'radar',
            data: arr,
            itemStyle: {
              emphasis: {
                areaStyle: {
                  opacity: series.areaStyle ? '0' : '0.5'
                }
              }
            },
            areaStyle: {
              color: {
                type: 'radial',
                colorStops: [
                  {
                    offset: 0,
                    color: 'rgba(137, 190, 252, 0.00)' // 0% 处的颜色
                  },
                  {
                    offset: 1,
                    color: 'rgba(137, 190, 252, 0.5)' // 100% 处的颜色
                  }
                ]
              }
            }
          }
        ]
      } else {
        for (let i = 0; i < displayField.length; i++) {
          let value = []
          for (let j = 0; j < data.rows.length; j++) {
            value.push(data.rows[j][displayField[i].field.toUpperCase()])
            if (i === 0) {
              indicator.push({
                name: data.rows[j][xAxisField.field.toUpperCase()]
              })
            }
          }
          legendData.push(displayField[i].comment)
          arr.push({
            name: displayField[i].comment,
            value: value,
            areaStyle: {
              color: {
                type: 'radial',
                colorStops: [
                  {
                    offset: 0,
                    color: 'rgba(137, 190, 252, 0.00)' // 0% 处的颜色
                  },
                  {
                    offset: 1,
                    color: 'rgba(137, 190, 252, 1)' // 100% 处的颜色
                  }
                ]
              }
            }
          })
        }
        seriesData = [
          {
            type: 'radar',
            data: arr,
            itemStyle: {
              emphasis: {
                areaStyle: {
                  opacity: series.areaStyle ? '0' : '0.5'
                }
              }
            },
            areaStyle: {
              color: {
                type: 'radial',
                colorStops: [
                  {
                    offset: 0,
                    color: 'rgba(137, 190, 252, 0.00)' // 0% 处的颜色
                  },
                  {
                    offset: 1,
                    color: 'rgba(81, 137, 248, 0.5)' // 100% 处的颜色
                  }
                ]
              }
            }
          }
        ]
      }
      /* 取展示的数据中最大值作为最大刻度 */
      let newArr = arr
        .map(item => {
          return item.value
        })
        .flat()
      let arrMax = Math.max(...newArr.map(Number))
      let indicatorArr = []
      indicator.forEach(item => {
        indicatorArr.push(Object.assign({}, item, {max: arrMax}))
      })
      option.series = seriesData
      option.radar = {
        axisName: {
          fontSize: 14,
          color: '#6D7278'
        },
        axisLine: {
          lineStyle: {
            color: '#ebeef3'
          }
        },
        shape: 'circle',
        triggerEvent: false,
        center: [series.center[0] + '%', series.center[1] + '%'],
        radius: series.radius,
        indicator: indicatorArr
      }
      option.legend = {
        ...data.conf.legend,
        data: legendData
      }
      return option
    },
    buildFunnel(data, option) {
      let displayField = data.displayfield
      let legendData = []
      let xAxisField = data.xaxisField
      let seriesData = []
      let series = data.conf.series
      if (xAxisField) xAxisField = xAxisField[0]

      //列数据展示
      if (series.showType) {
        let duration = 100 / data.rows.length
        for (let j = 0; j < data.rows.length; j++) {
          let value = []
          for (let i = 0; i < displayField.length; i++) {
            value.push({
              name: displayField[i].comment,
              value: data.rows[j][displayField[i].field.toUpperCase()]
            })
            if (j === 0) {
              legendData.push(displayField[i].comment)
            }
          }
          seriesData.push({
            name: data.rows[j][xAxisField.field.toUpperCase()],
            type: 'funnel',
            data: value,
            width: duration - 5 + '%',
            left: j * duration + '%',
            funnelAlign: series.funnelAlign,
            sort: series.sort,
            label: {
              position: series.label.position
            }
          })
        }
      } else {
        //行数据展示
        let duration = 100 / displayField.length
        for (let i = 0; i < displayField.length; i++) {
          let value = []
          for (let j = 0; j < data.rows.length; j++) {
            value.push({
              name: data.rows[j][xAxisField.field.toUpperCase()],
              value: data.rows[j][displayField[i].field.toUpperCase()]
            })
            if (i === 0) {
              legendData.push(data.rows[j][xAxisField.field.toUpperCase()] + '')
            }
          }
          seriesData.push({
            name: displayField[i].comment,
            type: 'funnel',
            data: value,
            width: duration - 5 + '%',
            left: i * duration + '%',
            funnelAlign: series.funnelAlign,
            sort: series.sort,
            label: {
              position: series.label.position
            }
          })
        }
      }

      option.series = seriesData
      option.legend = data.conf.legend
      option.legend.type = 'scroll'
      option.legend.orient = 'horizontal'
      option.legend.bottom = 'bottom'

      option.legend.data = legendData
      this.adjustChatTitle(data, option)
      option.title.left = '50%'
      return option
    },
    buildScatter(data, option) {
      let displayField = data.displayfield
      let legendData = []
      let xAxisData = []
      let xAxisField = data.xaxisField
      let seriesData = []
      let series = data.conf.series
      if (xAxisField) xAxisField = xAxisField[0]

      if (series.showType) {
        for (let j = 0; j < data.rows.length; j++) {
          let value = []
          for (let i = 0; i < displayField.length; i++) {
            if (j === 0) {
              xAxisData.push(displayField[i].comment)
            }
            value.push([
              displayField[i].comment,
              data.rows[j][displayField[i].field.toUpperCase()]
            ])
          }
          legendData.push(data.rows[j][xAxisField.field.toUpperCase()] + '')
          seriesData.push({
            name: data.rows[j][xAxisField.field.toUpperCase()],
            type: 'scatter',
            data: value,
            symbolSize() {
              return 30
            },
            itemStyle: {
              shadowBlur: 10,
              shadowColor: 'rgba(77,76,76,0.5)',
              shadowOffsetY: 5
            }
          })
        }
      } else {
        for (let i = 0; i < displayField.length; i++) {
          let value = []
          for (let j = 0; j < data.rows.length; j++) {
            if (i === 0) {
              xAxisData.push(data.rows[j][xAxisField.field.toLocaleUpperCase()])
            }
            value.push([
              data.rows[j][xAxisField.field.toLocaleUpperCase()],
              data.rows[j][displayField[i].field.toLocaleUpperCase()]
            ])
          }
          legendData.push(displayField[i].comment)
          seriesData.push({
            name: displayField[i].comment,
            type: 'scatter',
            data: value,
            symbolSize() {
              return 30
            },
            itemStyle: {
              shadowBlur: 10,
              shadowColor: 'rgba(77,76,76,0.5)',
              shadowOffsetY: 5
            }
          })
          if (
            displayField[i].regression &&
            displayField[i].regression !== 'none'
          ) {
            let myRegression = ecStat.regression(
              displayField[i].regression,
              value
            )
            myRegression.points.sort(function(a, b) {
              return a[0] - b[0]
            })
            seriesData.push({
              name: 'line',
              type: 'line',
              showSymbol: false,
              data: myRegression.points,
              markPoint: {
                itemStyle: {
                  color: 'transparent'
                },
                label: {
                  show: true,
                  position: 'left',
                  formatter: myRegression.expression,
                  color: '#333',
                  fontSize: 14
                },
                data: [
                  {
                    coord: myRegression.points[myRegression.points.length - 1]
                  }
                ]
              }
            })
          }
        }
      }

      option.series = seriesData
      option.xAxis = {
        type: data.conf.series.xAxisType,
        splitLine: {
          lineStyle: {
            type: 'dashed'
          }
        }
      }
      if (data.conf.series.xAxisType === 'category') {
        option.xAxis.data = xAxisData
      }
      option.yAxis = {
        splitLine: {
          lineStyle: {
            type: 'dashed'
          }
        },
        scale: true
      }
      option.legend = data.conf.legend
      option.legend.data = legendData
      option.title.left = '50%'
      return option
    },
    buildHeatmap(data, option) {
      let displayField = data.displayfield
      let legendData = []
      let rows = []
      let columns = []
      let arr = []
      let max = 0
      let xAxisField = data.xaxisField
      if (xAxisField) xAxisField = xAxisField[0]

      for (let i = 0; i < data.rows.length; i++) {
        for (let j = 0; j < displayField.length; j++) {
          if (i === 0) {
            columns.push(displayField[j].comment)
          }
          const field = data.rows[i][displayField[j].field.toUpperCase()] || 0
          //如果值为中文时设为0
          const num = /[\u4e00-\u9fa5]/gm.test(field) ? 0 : field
          arr.push([i, j, num])
          if (Number(num) > max) {
            max = num
          }
        }
        rows.push(data.rows[i][xAxisField.field.toUpperCase()])
      }
      option.series = [
        {
          type: 'heatmap',
          data: arr,
          label: {
            normal: {
              show: true
            }
          }
        }
      ]
      option.xAxis = {
        type: 'category',
        data: rows,
        splitArea: {
          show: true
        }
      }
      option.yAxis = {
        type: 'category',
        data: columns,
        splitArea: {
          show: true
        }
      }
      option.visualMap = {
        show: true,
        min: 0,
        calculable: true,
        orient: 'horizontal',
        left: 'center',
        // color: ['#0d59b7', '#bee8ff'],
        max: max,
        bottom: '0%'
      }
      option.tooltip = {
        position: 'top'
      }

      option.legend = data.conf.legend
      option.legend.data = legendData
      return option
    },
    getGrid() {
      let top = 0
      let bottom = 0
      let grid = {}
      if (this.customChart.conf.title.show) {
        if (this.customChart.conf.title.top === 'top') {
          top += 7
          if (this.customChart.conf.title.subtext) {
            top += 5
          }
        } else if (this.customChart.conf.title.top === 'bottom') {
          bottom += 16
        }
      }
      if (this.customChart.conf.legend.show) {
        if (this.customChart.conf.legend.top === 'top') {
          top += 7
        } else if (this.customChart.conf.legend.top === 'bottom') {
          bottom += 10
        }
      }
      if (top !== 0) {
        grid.top = top + '%'
      } else {
        grid.top = '5%'
      }
      if (bottom !== 0) {
        grid.bottom = bottom + '%'
      }
      return grid
    },
    getTitlePosition() {
      if (this.customChart.conf.title.top === 'top') {
        return this.customChart.conf.legend.show &&
          this.customChart.conf.legend.top === 'top'
          ? '20'
          : 'auto'
      } else if (this.customChart.conf.title.top === 'bottom') {
        return this.customChart.conf.legend.show &&
          this.customChart.conf.legend.top === 'bottom'
          ? '84%'
          : '88%'
      } else {
        return this.customChart.conf.title.top
      }
    },
    adjustChatTitle(data, option) {
      option.legend.top = 30
      option.grid.top = 80
      if (data.conf && data.conf.title && data.conf.title.subtext) {
        option.legend.top = 50
        option.grid.top = 100
      }
    },
    modeChange(value) {
      this.buildChart(this.customChart)
    },
    /**
     * 导出查询的数据，excel
     */
    exportData() {
      //头部标题列
      const header = []
      //导出的字段列
      const fields = []
      //处理标题列和要导出的列
      const xaxisFields = this.customChart.xaxisField
      xaxisFields &&
        xaxisFields.forEach(xaxis => {
          header.push(xaxis && xaxis.comment)
          fields.push(xaxis && xaxis.field && xaxis.field.toUpperCase())
        })
      const displayFields = this.customChart.displayfield
      displayFields &&
        displayFields.forEach(display => {
          header.push(display && display.comment)
          fields.push(display && display.field && display.field.toUpperCase())
        })

      //导出的数据结构
      const body = []
      this.data &&
        this.data.forEach(row => {
          const items = []
          let i = 0
          for (let datumKey in row) {
            //如果是要导出的列，则放入body中
            if (fields.includes(datumKey) && i < fields.length) {
              items.push(row[fields[i++]])
            }
          }
          //放入body中
          if (items.length) {
            body.push(items)
          }
        })
      //导出参数
      if (!body.length) {
        return this.$message.warning('未获取到数据图表数据！')
      }
      //构建导出参数
      const exportParam = {
        header: header,
        data: body,
        filename: this.customChart.name,
        sheetName: this.customChart.name
      }
      //执行导出
      export_json_to_excel(exportParam)
    },
    keyUpper(obj) {
        for (let key in obj) {
          let Allkey = key.toUpperCase()
          if (Allkey === key) {
            obj[Allkey] = obj[key]
          } else {
            obj[Allkey] = obj[key]
            delete obj[key]
          }
        }
        return obj
    },
  }
}
</script>

<style lang="scss" scoped>
/deep/.el-table {
  overflow: auto;
  height: 100% !important;
  max-height: unset !important;
}
</style>
