<template>
  <div>
    <el-card body-style="padding:0;" style="margin-bottom: 20px;" class="panel-header">
      <div slot="header" style="display: flex; justify-content:space-between;">
        <span>
          <span class="back-button" @click="$router.push({ name: 'BoardEchartManagement', params: { tab: 'second' } })">
            <i class="el-icon-back" />
            <span>返回</span>
          </span>
          <span v-if="this.$route.params.id == 'create'">新增图表</span>
          <span v-if="this.$route.params.isEdit == 'view'">查看图表</span>
          <span v-if="this.$route.params.isEdit == 'edit' &&  this.$route.params.id != 'create'">编辑图表</span>

        </span>
        <span>
          <el-button v-if="false" size="mini" type="primary" style="float: right;margin:0 10px 0 0;" icon="el-icon-download" @click="handleDownload" />
          <el-button v-if="this.$route.params.isEdit == 'edit'" size="mini" type="primary" style="float: right;margin:0 10px 0 0;" @click="handleLinkDB">添加到仪表盘</el-button>
          <el-button v-if="this.$route.params.isEdit == 'edit'" size="mini" type="primary" style="float: right;margin:0 10px 0 0;" icon="el-icon-save" @click="handleSave">保存</el-button>
          <el-button v-if="false" size="mini" type="primary" style="float: right;margin:0 10px 0 0;" @click="$router.replace(`/chartpanel/create`)">创建新的图表</el-button>
        </span>
      </div>
    </el-card>

    <div class="app-container" style="display: flex;">
      <el-card id="dataPanel" style="width:300px;margin-right: 20px;text-align:center;">
        <data-panel ref="dataPanel" :result-loading="loading" :data-src="dataSrc" :isEdit="this.$route.params.isEdit || this.$store.state.user.dashchartidisedit" @change="handleDataSrcChange" />
      </el-card>

      <!-- 图表部分 -->

      <el-card style="width: 100%;" body-style="padding: 10px 20px;">
        <div class="form-wrapper">
          <el-form id="formPanel" size="mini" class="analysis-form">
            <el-form-item id="dimensionInput" label="维度">
              <draggable v-model="sharedState.dimensions" :group="{name: 'col',pull: true, put: true}" class="draggable-wrapper" @change="handleDimensionChange">
                <el-tag v-for="col in sharedState.dimensions" :key="col.Column" class="draggable-item" size="small" closable @close="handleCloseDimensionTag(col)">
                  {{ col.Comment }}
                </el-tag>
              </draggable>
            </el-form-item>

            <!-- <el-form-item id="fieldInput" label="数值">
              <draggable v-model="sharedState.caculCols" :group="{name: 'col',pull: true, put: true}" class="draggable-wrapper" @change="handleColChange">
                <el-tag v-for="col in sharedState.caculCols" :key="col.Column" size="small" closable class="selected-field" @close="handleCloseColTag(col)">
                  <el-select v-model="col.calculFunc" class="draggable-item" size="mini" closable style="background: rgba(0,0,0,0);">
                    <el-option v-for="(item, optIndex) in col.availableFunc" :key="optIndex" :label="`${col.Comment}(${item.name})`" :value="item.func" />
                  </el-select>
                </el-tag>
              </draggable>
            </el-form-item> -->
            <el-form-item id="fieldInput" label="数值（主）">
              <draggable v-model="sharedState.caculCols" :group="{name: 'col',pull: true, put: true}" class="draggable-wrapper" @change="handleColChange">
                <el-tag v-for="col in sharedState.caculCols" :key="col.Column" size="small" closable class="selected-field" @close="handleCloseColTag(col)">
                  <el-select v-model="col.calculFunc" class="draggable-item" size="mini" closable style="background: rgba(0,0,0,0);">
                    <el-option v-for="(item, optIndex) in col.availableFunc" :key="optIndex" :label="`${col.Comment}(${item.name})`" :value="item.func" />
                  </el-select>
                </el-tag>
              </draggable>
            </el-form-item>
            <el-form-item id="fieldInput2" label="数值（次）">
              <draggable v-model="sharedState.caculCols2" :group="{name: 'col',pull: true, put: true}" class="draggable-wrapper" @change="handleColChange2">
                <el-tag v-for="col in sharedState.caculCols2" :key="col.Column" size="small" closable class="selected-field" @close="handleCloseColTag2(col)">
                  <el-select v-model="col.calculFunc" class="draggable-item" size="mini" closable style="background: rgba(0,0,0,0);">
                    <el-option v-for="(item, optIndex) in col.availableFunc" :key="optIndex" :label="`${col.Comment}(${item.name})`" :value="item.func" />
                  </el-select>
                </el-tag>
              </draggable>
            </el-form-item>

            <orderPanel v-model="orderByStrs" />

            <filterPanel :filters.sync="currentFilters" :disabled="!allSelected || allSelected.length===0" @change="handleAddFilter" />

            <el-form-item>
              <div class="limit-input">
                <span v-show="!editLimit">
                  {{ $t('chart.limit', [limit]) }}
                  <el-button type="text" @click="editLimit=true">{{ $t('common.edit') }}</el-button>
                </span>
                <span v-show="editLimit">
                  <el-input-number v-model="limit" :disabled="loading" size="mini" style="width:100px;" @blur="editLimit=false" :max="60000" />
                  <el-button size="mini" @click="editLimit=false">确认</el-button>
                </span>
              </div>
            </el-form-item>
          </el-form>
          <el-form class="chart-form" size="mini" label-position="top">
            <el-form-item label="图表名称:">
              <el-input v-model="chartName" size="mini" :placeholder="$t('chart.namePlaceholder')" />
            </el-form-item>
            <el-form-item label="图表描述:">
              <el-input v-model="chartDesc" size="mini" :placeholder="$t('chart.descPlaceholder')" />
            </el-form-item>
          </el-form>
        </div>
        <!-- 图表内容展现主体 -->
        <visualize-panel id="vizPanel" v-loading="loading" :data="result" :chart-type.sync="chartType" :schema="allSelected" v-if="sonRefresh" />

      </el-card>
    </div>
    <el-dialog :title="$t('chart.myChart')" :visible.sync="showMyCharts">
      <el-table :data="myChartList">
        <el-table-column :label="$t('chart.chartName')" width="200" prop="chart_name" />
        <el-table-column :label="$t('chart.chartDesc')" prop="desc" />
        <el-table-column :label="$t('common.operation')" width="200" align="center">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit" @click="switchChart(scope.row)">
              {{ $t('common.edit') }}
            </el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteChart(scope.row)">
              {{ $t('common.delete') }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="mini" @click="showMyCharts = false">{{ $t('common.close') }}</el-button>
      </span>
    </el-dialog>

    <el-dialog title="仪表盘列表" :visible.sync="showDashboards" width="390px" style="text-align:center">

      <p style="margin-right:110px;">请选择仪表盘</p>
      <div style="margin-bottom:20px;">
        <el-select v-model="selectedDb" size="small">
          <el-option v-for="(item,index) in dashboardList" :key="item.objectId" :label="item.name" :value="item.dashboard_id" />
        </el-select>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="showDashboards = false">取消</el-button>
        <el-button type="primary" size="small" @click="linkDb">添加到仪表盘</el-button>
      </span>
    </el-dialog>
    <!-- <el-tooltip content="帮助中心" placement="top"> -->
    <el-dropdown v-if="false" class="help-center-wrapper" placement="top" size="mini" @command="handleHelp">
      <div class="help-center">
        <i class="el-icon-question" />
      </div>
      <el-dropdown-menu slot="dropdown" size="mini">
        <el-dropdown-item command="guide">
          {{ this.$t('common.openGuide') }}
        </el-dropdown-item>
      </el-dropdown-menu>
    </el-dropdown>
    <!-- </el-tooltip 1> -->
  </div>
</template>
<script>
import draggable from 'vuedraggable'
import Driver from 'driver.js' // import driver.js
import 'driver.js/dist/driver.min.css' // import driver.js css
import { GetDataByName, ExeSqlJiade, PostDataByName, dashboardListJiade } from '@/api/common'
import filterPanel from './components/filterPanel'
import orderPanel from './components/orderPanel'
import visualizePanel from './components/visualizePanel'
import dataPanel from './components/dataPanel'
import Cookies from 'js-cookie'
import { createChart, updateChart, getChartById, chartList, deleteChart } from '@/api/chart'
import { dashboardList, addChartToDB, dbByChart } from '@/api/dashboard'
import exeSql from '@/api/exeSql'
import { parseTime } from '@/utils'
import { buildSqlSentence } from '@/utils/buildSentence'

import steps from './guideSteps'
import store from './store'

const driver = new Driver()

export default {
  inject: ['reload'],
  name: 'ChartPanel',
  components: { visualizePanel, dataPanel, draggable, filterPanel, orderPanel },
  data() {
    return {

      sonRefresh: true,
      loading: false,
      result: [],
      dataSrc: {},
      limit: 200,
      orderByStrs: [],
      filterStr: undefined,
      editLimit: false,
      currentFilters: [],
      sharedState: store.state,
      chartType: 'table',
      chartName: undefined,
      chartDesc: undefined,
      showMyCharts: false,
      myChartList: [],
      showDashboards: false,
      dashboardList: [],
      selectedDb: undefined,
      linkedDbIds: [],
      execInstance: null,
      LastInsertId: "",

      isSaving: false
    }
  },
  computed: {

    // allSelected() {
    //   return store.state.dimensions.concat(store.state.caculCols)
    // },
    allSelected() {
      return store.state.dimensions.concat(store.state.caculCols).concat(store.state.caculCols2)
    },
    sqlSentence() {
      return buildSqlSentence({
        dataSrc: this.dataSrc.table,
        selectedCalcul: this.sharedState.caculCols,
        selectedCalcul2: this.sharedState.caculCols2,
        selectedDimension: this.sharedState.dimensions,
        orderByStrs: this.orderByStrs,
        filterStr: this.filterStr,
        limit: this.limit
      })
    }
  },
  watch: {


    sqlSentence(value) {
      if (value) {
        this.fetchData(value)
      } else {
        this.result = []
      }
    },
    '$route.params.id': {
      immediate: true,
      handler() {
        console.log("this.$route.params.id=====================", this.$route.params.id)
        if (this.$route.params.id !== 'create') {
          console.log('我是编辑图表哦~~~')
          console.log('this.$route.params.id', this.$route.params.id)

          console.log('localStorage==========', localStorage.getItem('ChartPanelIsEditId'))


          console.log('this.$store.state.user.dashchartid==========', this.$store.state.user.dashchartid)

          if (this.$route.params.id) {
            console.log('我是编辑图表第一次跳转~~~')
            var send_data = {
              name: 'getChartDetail',
              parammaps: {
                pastureid: Cookies.get('pastureid'),
                id: this.$route.params.id
              }

            }
            GetDataByName(send_data).then(response => {
              console.log('图表数据', response.data.list)
              const chart = response.data.list[0]
              this.chartName = chart.chart_name
              this.chartDesc = chart.desc
              const content = JSON.parse(chart.content) || {}

              this.dataSrc.table = content.dataSrc
              this.dataSrc.source_id = chart.source_id
              this.chartType = content.chartType
              this.limit = content.limit || 200
              this.currentFilters = content.filters
              this.orderByStrs = content.orderByStrs
              store.setCaculColsAction(content.selectedCalcul)
              store.setCaculColsAction2(content.selectedCalcul2)
              store.setDimensionsAction(content.selectedDimension)
              this.$refs.dataPanel.initWithDataSrc(this.dataSrc)
            })
          } else {
            console.log('我是编辑图表切换跳转~~~')
            var send_data = {
              name: 'getChartDetail',
              parammaps: {
                pastureid: Cookies.get('pastureid'),
                // id: this.$route.params.id
                id: localStorage.getItem('ChartPanelIsEditId')
              }

            }
            GetDataByName(send_data).then(response => {
              console.log('图表数据', response.data.list)
              const chart = response.data.list[0]
              this.chartName = chart.chart_name
              this.chartDesc = chart.desc
              const content = JSON.parse(chart.content) || {}

              this.dataSrc.table = content.dataSrc
              this.dataSrc.source_id = chart.source_id
              this.chartType = content.chartType
              this.limit = content.limit || 200
              this.currentFilters = content.filters
              this.orderByStrs = content.orderByStrs
              store.setCaculColsAction(content.selectedCalcul)
              store.setCaculColsAction2(content.selectedCalcul2)
              store.setDimensionsAction(content.selectedDimension)
              this.$refs.dataPanel.initWithDataSrc(this.dataSrc)
            })
          }


        } else {
          console.log('我是新增图标哦~~~')
          this.chartName = undefined
          this.chartDesc = undefined
          store.setCaculColsAction([])
          store.setCaculColsAction2([])
          store.setDimensionsAction([])
          this.$nextTick(() => {
            this.$refs.dataPanel.initWithDataSrc()
          })
        }
      }
    }
  },
  created() {

  },
  methods: {
    // fetchData(sqlSentence) {
    //   if (this.loading) {
    //     this.execInstance && this.execInstance.cancel()
    //   }
    //   this.loading = true
    //   this.execInstance = exeSql()
    //   this.execInstance.fetch({ source_id: this.dataSrc.source_id, sql: sqlSentence }).then(resp => {
    //     this.loading = false
    //     this.result = resp.data
    //   })
    // },
    fetchData(sqlSentence) {
      if (this.loading) {
        this.execInstance && this.execInstance.cancel()
      }
      this.loading = true
      this.execInstance = exeSql()


      this.sharedState.caculCols2.map(function (i) {
        return (i.is_second = true)
      })


      const obj = {
        dataSrc: this.dataSrc.table,
        source_id: this.dataSrc.source_id,
        orderByStrs: this.orderByStrs,
        limit: this.limit,
        selectedCalcul: this.sharedState.caculCols,
        selectedCalcul2: this.sharedState.caculCols2,
        selectedDimension: this.sharedState.dimensions,
        chartType: this.chartType,
        filters: this.currentFilters
      }


      var send_data = { source_id: this.dataSrc.source_id, content: obj, pastureid: Cookies.get('pastureid') }
      ExeSqlJiade(send_data).then(response => {
        console.log('ExeSql发的数据======', send_data)
        console.log('图的数据', response.data.list)
        if (response.data !== null) {
          console.log('维度+数值获得的数据', Array.isArray(response.data))


          //判断是不是数组！result无论有没有值都必须是数组格式，不然会报错！
          if (Array.isArray(response.data)) {
            this.loading = false
            this.result = response.data


          } else {
            this.loading = false
            this.result = []
          }

        } else {
          this.loading = false
          this.result = []
        }
      })
    },
    handleDataSrcChange(value) {
      console.log('dataSrc======================', value)
      this.dataSrc = value
      store.setCaculColsAction([])
      store.setCaculColsAction2([])
      store.setDimensionsAction([])
      this.filterStr = undefined
      this.orderByStrs = []
    },
    handleColChange(evt) {
      if (evt.added) {
        store.addCaculColAction(evt.added.element)
      }
    },
    handleColChange2(evt) {
      if (evt.added) {
        store.addCaculColAction2(evt.added.element)
      }
    },
    // handleDimensionChange(evt) {
    //   console.log('handleDimensionChange的evt', evt)
    //   if (evt.added) {
    //     store.addDimensionAction(evt.added.element)
    //   }
    // },
    handleDimensionChange(evt) {
      console.log('this.sharedState.dimensions', this.sharedState.dimensions)
      if (evt.added) {
        store.addDimensionAction(evt.added.element)
      }
      if (evt.moved) {

        this.sonRefresh = false;
        this.$nextTick(() => {
          this.sonRefresh = true;
        });
      }
    },
    handleCloseColTag(col) {
      store.deleteCaculColAction(col)
    },
    handleCloseColTag2(col) {
      store.deleteCaculColAction2(col)
    },
    handleCloseDimensionTag(col) {
      store.deleteDimensionAction(col)
    },
    handleAddFilter(value) {
      this.filterStr = value
    },
    // 保存
    // handleSave() {
    //   if (!this.chartName) {
    //     this.$message({
    //       type: 'warning',
    //       message: this.$t('chart.chartNameWarning')
    //     })
    //     return
    //   }
    //   const chartId = this.$route.params.id === 'create' ? undefined : this.$route.params.id
    //   const obj = {
    //     dataSrc: this.dataSrc.table,
    //     source_id: this.dataSrc.source_id,
    //     orderByStrs: this.orderByStrs,
    //     limit: this.limit,
    //     selectedCalcul: this.sharedState.caculCols,
    //     selectedDimension: this.sharedState.dimensions,
    //     chartType: this.chartType,
    //     filters: this.currentFilters
    //   }
    //   const data = {
    //     id: chartId,
    //     chart_name: this.chartName,
    //     source_id: this.dataSrc.source_id,
    //     desc: this.chartDesc,
    //     content: obj
    //   }
    //   if (chartId) {
    //     updateChart(data).then(resp => {
    //       this.$message({
    //         type: 'success',
    //         message: this.$t('common.saveSuccess')
    //       })
    //     })
    //   } else {
    //     createChart(data).then(resp => {
    //       // console.log(resp)
    //       this.$router.replace(`/chartpanel/${resp.data.id}`)
    //       this.$message({
    //         type: 'success',
    //         message: this.$t('common.saveSuccess')
    //       })
    //     })
    //   }
    // },
    handleSave() {
      if (!this.chartName) {
        this.$message({
          type: 'warning',
          message: this.$t('chart.chartNameWarning')
        })
        return
      }

      // const chartId = this.$route.params.id === 'create' ? undefined : this.$route.params.id
      const chartId = localStorage.getItem('ChartPanelIsEditId') === 'create' ? undefined : localStorage.getItem('ChartPanelIsEditId')
      const obj = {
        dataSrc: this.dataSrc.table,
        source_id: this.dataSrc.source_id,
        orderByStrs: this.orderByStrs,
        limit: this.limit,
        selectedCalcul: this.sharedState.caculCols,
        selectedCalcul2: this.sharedState.caculCols2,
        selectedDimension: this.sharedState.dimensions,
        chartType: this.chartType,
        filters: this.currentFilters
      }
      const data = {
        name: 'insertChart',
        parammaps: {
          id: chartId,
          cname: this.chartName,
          source_id: this.dataSrc.source_id,
          desc: this.chartDesc,
          display: this.chartDesc,
          pastureid: Cookies.get('pastureid'),
          empid: Cookies.get('employeid'),
          emp: Cookies.get('employename'),
          content: obj
        }
      }

      var send_data2 = {
        name: 'updateChartV2',
        parammaps: {
          id: chartId,
          cname: this.chartName,
          source_id: this.dataSrc.source_id,
          desc: this.chartDesc,
          display: this.chartDesc,
          pastureid: Cookies.get('pastureid'),
          empid: Cookies.get('employeid'),
          emp: Cookies.get('employename'),
          content: obj
        }
      }


      this.isSaving = true
      if (chartId) {
        PostDataByName(send_data2).then(res => {
          console.log('编辑保存发送参数', data)


          if (res.msg == 'ok') {
            this.$message({
              type: 'success',
              message: this.$t('common.saveSuccess')
            })
          } else {
            this.$message({ type: 'error', message: '保存失败，请不要输入已有的图表名称！' })
          }
        })
      } else {
        PostDataByName(data).then(res => {
          console.log('新增保存发送参数', data)

          if (res.msg == 'ok') {
            this.$message({
              type: 'success',
              message: this.$t('common.saveSuccess')
            })
            this.LastInsertId = res.data.LastInsertId
          } else {
            this.$message({ type: 'error', message: '保存失败，请不要输入已有的图表名称！' })
          }


        })
        // createChart(data).then(resp => {
        //   // console.log(resp)
        //   this.$router.replace(`/chartpanel/${resp.data.id}`)
        //   this.$message({
        //     type: 'success',
        //     message: this.$t('common.saveSuccess')
        //   })
        // })
      }
    },
    handleLinkDB() {
      this.showDashboards = true

      var send_data = {
        name: 'getdashboards',
        parammaps: {
          pastureid: Cookies.get('pastureid'),
          empid: Cookies.get('employeid'),
          emp: Cookies.get('employename')
        }
      }
      dashboardListJiade(send_data).then(resp => {
        console.log('看板列表数据：', resp)
        this.dashboardList = resp.data.list
      })
    },
    getDbByChart(id) {
      dbByChart(id).then(resp => {
        this.linkedDbIds = resp.data || []
      })
    },
    isDbDisbaled(db) {
      return !!this.linkedDbIds.find(id => id === db.objectId)
    },

    linkDb() {
      this.showDashboards = false

      console.log(this.$route.params.id)
      console.log('仪表盘列表ID：', this.selectedDb)

      // var chartid1 = this.$route.params.id
      // if (chartid1 == "create") {
      //   chartid1 = this.LastInsertId
      // } else {
      //   chartid1 = this.$route.params.id
      // }


      var chartid1 = localStorage.getItem('ChartPanelIsEditId')
      if (chartid1 == "create") {
        chartid1 = this.LastInsertId
      } else {
        chartid1 = localStorage.getItem('ChartPanelIsEditId')
      }


      // var chartid1 = localStorage.getItem('ChartPanelIsEditId')
      // if (chartid1 == "create") {
      //   chartid1 = this.LastInsertId
      // } else {
      //   chartid1 = localStorage.getItem('ChartPanelIsEditId')
      // }


      const data = {
        name: 'insertdashboard_chart',
        parammaps: {
          did: this.selectedDb,
          cid: chartid1,
          pastureid: Cookies.get('pastureid')
        }
      }

      PostDataByName(data).then(response => {
        console.log('看板保存发送参数', data)
        this.$message({
          type: 'success',
          message: this.$t('common.saveSuccess')
        })
      })
    },
    viewAllChart() {
      this.showMyCharts = true
      // chartList().then(resp => {
      //   this.myChartList = resp.data
      // })

      this.myChartList = [{ 'name': 'kook', 'desc': '', 'content': '{"layout": [{"id": "035573f4-bf71-4472-814a-f1747b6bd8e0", "x": 0, "y": 7, "w": 5, "h": 6, "i": "035573f4-bf71-4472-814a-f1747b6bd8e0", "moved": false, "yOffSet": 13, "xOffSet": 5, "bottomLine": [[0, 13], [5, 13]], "topLine": [[0, 7], [5, 7]]}, {"id": "02c012be-db57-431b-b9aa-40d1640a2592", "x": 2, "y": 29, "w": 7, "h": 6, "i": "02c012be-db57-431b-b9aa-40d1640a2592", "yOffSet": 35, "xOffSet": 9, "bottomLine": [[2, 35], [9, 35]], "topLine": [[2, 29], [9, 29]], "moved": false}, {"id": "087df61d-b02e-49a5-a954-b2d9124df685", "x": 6, "y": 0, "w": 7, "h": 7, "i": "087df61d-b02e-49a5-a954-b2d9124df685", "moved": false, "yOffSet": 7, "xOffSet": 13, "bottomLine": [[6, 7], [13, 7]], "topLine": [[6, 0], [13, 0]]}, {"id": "045ad6b0-8f7e-47db-92a7-8c4a31b7683d", "x": 5, "y": 16, "w": 10, "h": 6, "i": "045ad6b0-8f7e-47db-92a7-8c4a31b7683d", "moved": false, "yOffSet": 22, "xOffSet": 15, "bottomLine": [[5, 22], [15, 22]], "topLine": [[5, 16], [15, 16]]}, {"id": "182d02ef-ced5-4ded-a648-630c94f4a790", "x": 9, "y": 22, "w": 9, "h": 9, "i": "182d02ef-ced5-4ded-a648-630c94f4a790", "moved": false, "yOffSet": 31, "xOffSet": 18, "bottomLine": [[9, 31], [18, 31]], "topLine": [[9, 22], [18, 22]]}, {"id": "0755ae6e-6869-4e09-8630-62dd3118a2fc", "x": 0, "y": 0, "w": 6, "h": 7, "i": "0755ae6e-6869-4e09-8630-62dd3118a2fc", "moved": false, "yOffSet": 7, "xOffSet": 6, "bottomLine": [[0, 7], [6, 7]], "topLine": [[0, 0], [6, 0]]}, {"id": "3e4408f1-67c2-45c7-8315-136a6eec6980", "x": 5, "y": 22, "w": 4, "h": 7, "i": "3e4408f1-67c2-45c7-8315-136a6eec6980", "moved": false, "yOffSet": 29, "xOffSet": 9, "bottomLine": [[5, 29], [9, 29]], "topLine": [[5, 22], [9, 22]]}, {"id": "00af7fdb-b486-4855-ac7c-85014d283f2c", "x": 5, "y": 7, "w": 5, "h": 9, "i": "00af7fdb-b486-4855-ac7c-85014d283f2c", "moved": false, "yOffSet": 16, "xOffSet": 10, "bottomLine": [[5, 16], [10, 16]], "topLine": [[5, 7], [10, 7]]}, {"id": "3e39e265-684b-4d62-be3c-4613fd8730cd", "x": 14, "y": 7, "w": 8, "h": 9, "i": "3e39e265-684b-4d62-be3c-4613fd8730cd", "moved": false}]}', 'is_private': true, 'status': 1, 'creator': 1, 'created_at': '2020-05-13T06:08:39.438Z', 'updated_at': '2020-09-14T07:48:58.477Z', 'dashboard_id': 'dd02cfe9-8ee9-48fa-83b3-98b604d87b57' }]
    },
    switchChart(chart) {
      this.$confirm(this.$t('chart.beforeLeaveConfirm'), this.$t('common.confirm')).then(() => {
        this.$router.replace(`/chartpanel/${chart.chart_id}`)
        this.showMyCharts = false
      })
    },
    deleteChart(chart) {
      this.$confirm(this.$t('chart.deleteConfirm', chart.chart_name), this.$t('common.confirm')).then(() => {
        deleteChart({ chart_id: chart.chart_id }).then(() => {
          // if (this.$route.params.id === chart.chart_id) {
          //   this.$router.push('/chartpanel/create')
          //   this.showMyCharts = false
          // } else {
          //   this.viewAllChart()
          // }
          if (localStorage.getItem('ChartPanelIsEditId') === chart.chart_id) {
            this.$router.push('/chartpanel/create')
            this.showMyCharts = false
          } else {
            this.viewAllChart()
          }
          this.$message({
            type: 'success',
            message: this.$t('common.deleteSuccess')
          })
        })
      })
    },
    handleHelp(command) {
      if (command === 'guide') {
        driver.defineSteps(steps)
        driver.start()
      }
    },
    handleDownload() {
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = this.allSelected.map(item => item.Column)
        const filterVal = tHeader
        const data = this.formatJson(filterVal, this.result)
        excel.export_json_to_excel({ header: tHeader, data, filename: 'DataExport' + parseTime(Date.now(), '{m}{d}{h}{i}{s}'), autoWidth: true })
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          const tempArr = j.split('.')
          if (tempArr.length <= 1) {
            return v[j]
          } else {
            return tempArr.reduce(
              (pre, cur) => (pre[cur] ? pre[cur] : '--'),
              v
            )
          }
        })
      )
    }
  }
}
</script>
<style lang="scss" scoped>
.back-button {
  display: inline-block;
  padding-right: 10px;
  margin-right: 10px;
  border-right: 1px solid #909090;
  cursor: pointer;
  span {
    padding: 5px;
    font-size: 14px;
  }
}
.analysis-form {
  width: 100%;
  padding-right: 20px;
  /deep/ .el-form-item--mini.el-form-item {
    margin-bottom: 10px;
  }
  /deep/ .el-form-item--mini .el-form-item__label,
  .limit-input {
    color: #909399;
    font-size: 14px;
  }
}
.form-wrapper {
  display: flex;
}
.chart-form {
  width: 250px;
  /deep/ .el-form-item--mini.el-form-item {
    margin-bottom: 10px;
  }
}

.draggable-wrapper {
  font-size: 14px;
  min-height: 30px;
  border-bottom: 1px solid #e4e7ed;
  .draggable-item {
    margin-right: 10px;
  }
  /deep/ .el-select--mini {
    margin: 0;
  }
}
.selected-field {
  /deep/ .el-input__inner {
    height: 20px;
    line-height: 20px;
    border: none;
    background-color: rgba($color: #fff, $alpha: 0);
    padding: 0;
  }
  /deep/ .el-input__suffix {
    right: 0px;
    .el-input__suffix-inner {
      display: inline-block;
      height: 20px;
      line-height: 20px;
      .el-input__icon {
        font-size: 12px;
        line-height: 20px;
      }
    }
  }
}
.help-center-wrapper {
  cursor: pointer;
  position: fixed;
  bottom: 25px;
  right: 25px;
  .help-center {
    width: 45px;
    height: 45px;
    background: #fff;
    border-radius: 50%;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    line-height: 45px;
    font-size: 20px;
    color: #205cd8;
    text-align: center;
    /deep/ .el-dropdown {
      font-size: 20px;
      color: #205cd8;
    }
  }
}

.el-dialog__body {
  padding: 20px 20px 50px 20px;
  color: #606266;
  font-size: 14px;
  word-break: break-all;
}
</style>
