<template>
  <div class="dashboard-wrapper">

    <el-card v-if="title !=='3'" 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: 'first' } })">
            <i class="el-icon-back" />
            <span>返回</span>

          </span>

          <span v-if="mode == 'view'">查看仪表盘</span>
          <span v-if="mode == 'edit'">编辑仪表盘</span>
          <span v-if="mode == 'create'">新增仪表盘</span>
        </span>
      </div>
    </el-card>
    <div class="tool-bar">
      <div>
        <span class="db-name">{{ dashboard.name }}</span>
        <span>{{ dashboard.desc }}</span>
      </div>
      <div v-show="mode === 'edit' || mode === 'create' ">
        <!-- <el-button type="primary" size="mini" @click="handleShare">
          {{ $t('common.share') }}
        </el-button> -->
        <el-button class="successBorder" style="margin-top: 9px;" @click="handleLinkChart">
          添加图表
        </el-button>
      </div>
    </div>
    <grid-layout
      v-if="charts.length!==0"
      v-loading="loading"
      :layout="layout || []"
      :col-num="24"
      :row-height="30"
      :is-draggable="mode === 'edit' || mode === 'create' "
      :is-resizable="mode === 'edit' || mode === 'create' "
      :is-mirrored="false"
      :vertical-compact="true"
      :pane-container="false"
      :margin="[10, 10]"
      :use-css-transforms="true"
      style="min-height: 500px;"
      @layout-updated="handleLayoutChange"
    >
      <grid-item v-for="item in layout || []" :key="item.index" :x="item.x" :y="item.y" :w="item.w" :h="item.h" :i="item.i" @resized="handleResize">
        <el-card v-loading="chartLoading[item.i]" class="visualize-card" body-style="padding: 10px;">
          <div slot="header" class="operation-bar">
            <div>
              <span>{{ getChartItem(item.i).chart_name }}</span>
            </div>
            <div>
              <i v-show="mode === 'edit' || mode === 'create' " class="el-icon-edit" @click="handleEdit(getChartItem(item.i))" />
              <i v-show="mode === 'edit' || mode === 'create' " class="el-icon-delete" @click="form_delete(getChartItem(item.i))" />
              <el-tooltip :content="getChartItem(item.i).desc" class="item" effect="dark" placement="top-end">
                <i class="el-icon-info" style="color:#009C69;cursor:pointer;" />
              </el-tooltip>
            </div>
          </div>
          <visualize-panel :key="item.index" :ref="`chartInstance${item.i}`" :data="results[item.i]" :schema="getChartItem(item.i).content.allSelected" :chart-type.sync="getChartItem(item.i).content.chartType" :is-edit-mode="false" :chart-style="{height: `${item.h*30 + 10 * (item.h-1) - 60}px`}" />
        </el-card>
      </grid-item>
    </grid-layout>
    <div v-if="charts.length === 0 && mode === 'edit' || mode === 'create' && charts.length === 0" v-loading="loading" class="welcome-container">
      <el-button type="primary" size="mini" @click="handleLinkChart">
        {{ $t('dashboard.addChart') }}
      </el-button>
      <div>
        <el-link type="info" :underline="false">
          <router-link to="/chartpanel/create">
            {{ $t('dashboard.emptyDashboardTip') }}
          </router-link>
        </el-link>
      </div>
    </div>
    <el-dialog :title="$t('chart.myChart')" :visible.sync="showChartList">
      <!-- <el-button type="primary" size="mini" @click="$router.push({ name: 'ChartPanel', params: { id: 'create' , isEdit: 'edit'}})">
        创建新的图表
      </el-button> -->

      <el-button class="save" style="margin-bottom: 10px;" @click="jumpCreate()"> 创建新的图表 </el-button>

      <el-table :data="myChartList" border>
        <el-table-column :label="$t('common.name')" width="200" prop="chart_name" />
        <el-table-column :label="$t('common.desc')" prop="desc" />
        <el-table-column :label="$t('common.operation')" align="center">
          <template slot-scope="scope">
            <el-button class="miniPrimary" :disabled="isExisted(scope.row)" @click="linkChart(scope.row)">添加</el-button>
            <el-button size="mini" type="warning" style="padding: 6px 10px !important;font-size:14px;" @click="jumpEdit2(scope.row)">  编辑 </el-button>

          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer" style="bottom: 10px;">
        <el-button class="cancelClose1" @click="showChartList = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { GridLayout } from 'vue-grid-layout'
import { GridItem } from 'vue-grid-layout'
import visualizePanel from '../ChartPanel/components/visualizePanel'
import exeSql from '@/api/exeSql'
import { chartByDashboard, updateDashboard, addChartToDB, unMapChartDb } from '@/api/dashboard'
import { GetDataByName, ExeSqlJiade, PostDataByName, dashboardListJiade, updateDashboardJiade } from '@/api/common'
import { chartList } from '@/api/chart'
import Cookies from 'js-cookie'
import { buildSqlSentence, buildFilterSentence } from '@/utils/buildSentence'

function isLineOverLap(line1, line2) {
  const start1 = {
    x: line1[0][0],
    y: line1[0][1]
  }
  const end1 = {
    x: line1[1][0],
    y: line1[1][1]
  }
  const start2 = {
    x: line2[0][0],
    y: line2[0][1]
  }
  const end2 = {
    x: line2[1][0],
    y: line2[1][1]
  }
  if (start1.y === start2.y && end1.y === end2.y) {
    if (start1.x >= start2.x && start1.x <= end2.x) {
      return true
    } else {
      return false
    }
  } else {
    return false
  }
}
export default {
  inject: ['reload'],
  components: { GridLayout, GridItem, visualizePanel },
  props: {
    dashboard: {
      required: false,
      type: Object,
      default: () => {
        return {}
      }
    },
    mode: {
      required: false,
      type: String,
      default: 'edit'
    },
    title: {
      required: false,
      type: String,
      default: '2'
    }
  },
  data() {
    return {
      charts: [],
      results: {},
      loading: false,
      layout: [],
      myChartList: [],
      showChartList: false,
      chartLoading: {}
    }
  },
  watch: {
    'dashboard.dashboard_id': {
      immediate: true,
      handler(value) {
        console.log('watch的:', value)
        if (!value) return
        this.getList(value)
      }
    }
  },
  methods: {
    // getList() {
    //   this.charts = []
    //   this.layout = []
    //   this.loading = true
    //   chartByDashboard(this.dashboard.dashboard_id).then(resp => {
    //     this.loading = false
    //     this.charts = resp.data || []
    //     let filterStrs = []
    //     console.log(this.dashboard.content)
    //     const layout = (this.dashboard.content && this.dashboard.content.layout) || []
    //     this.charts.forEach((chart, index) => {
    //       this.$set(this.results, chart.chart_id, [])
    //       this.$set(this.chartLoading, chart.chart_id, false)
    //       chart.content = JSON.parse(chart.content)
    //       chart.content.allSelected = []
    //       chart.content.allSelected = chart.content.allSelected.concat(chart.content.selectedCalcul).concat(chart.content.selectedDimension)
    //       if (chart.content.filters) {
    //         filterStrs = chart.content.filters.map(buildFilterSentence)
    //       }
    //       const sqlSentence = buildSqlSentence({
    //         dataSrc: chart.content.dataSrc,
    //         selectedCalcul: chart.content.selectedCalcul,
    //         selectedDimension: chart.content.selectedDimension,
    //         orderByStrs: chart.content.orderByStrs,
    //         filterStr: filterStrs.join(' and '),
    //         limit: chart.content.limit
    //       })
    //       this.exeSql(sqlSentence, chart, index)
    //       console.log(layout.find(layoutItem => layoutItem.id === chart.chart_id))
    //       if (!layout.find(layoutItem => layoutItem.id === chart.chart_id)) {
    //         this.generatePosition(chart, layout, index)
    //       }
    //     })
    //     this.layout = layout.filter(item => {
    //       return this.charts.find(chart => chart.chart_id === item.id)
    //     })
    //     this.handleLayoutChange()
    //   })
    // },
    getList() {
      console.log('进入页面组件=================')
      this.charts = []
      this.layout = []
      this.loading = true

      var send_data = {
        name: 'getdashboard_chart',
        parammaps: {
          pastureid: Cookies.get('pastureid'),
          did: this.dashboard.dashboard_id,
          empid: Cookies.get('employeid')
        }
      }
      GetDataByName(send_data).then(resp => {
        console.log('图表数据', resp)
        this.loading = false
        this.charts = resp.data.list || []
        let filterStrs = []
        console.log('this.dashboard', this.dashboard)
        const layout = (this.dashboard.content && this.dashboard.content.layout) || []
        console.log('layout', layout)
        console.log('this.charts', this.charts)
        this.charts.forEach((chart, index) => {
          this.$set(this.results, chart.chart_id, [])
          this.$set(this.chartLoading, chart.chart_id, false)
          chart.content = JSON.parse(chart.content)

          chart.content.allSelected = []
          chart.content.allSelected = chart.content.allSelected.concat(chart.content.selectedDimension).concat(chart.content.selectedCalcul).concat(chart.content.selectedCalcul2)

          console.log('chart.content.filters', chart.content.filters)
          if (chart.content.filters) {
            filterStrs = chart.content.filters.map(buildFilterSentence)
          }
          // const sqlSentence = buildSqlSentence({
          //   dataSrc: chart.content.dataSrc,
          //   selectedCalcul: chart.content.selectedCalcul,
          //   selectedDimension: chart.content.selectedDimension,
          //   orderByStrs: chart.content.orderByStrs,
          //   filterStr: filterStrs.join(' and '),
          //   limit: chart.content.limit
          // })
          this.exeSqlJia2(chart.content, chart, index)
          console.log(layout.find(layoutItem => layoutItem.id === chart.chart_id))
        })
        this.layout = layout.filter(item => {
          return this.charts.find(chart => chart.chart_id === item.id)
        })

        console.log('layout:', this.layout)
        this.handleLayoutChange()
      })
    },

    jumpCreate() {
      this.$router.push({ name: 'ChartPanel', params: { id: 'create', isEdit: 'edit' }})

      localStorage.setItem('ChartPanelIsEditId', 'create')
    },
    jumpEdit2(row) {
      // $router.push({ name: 'ChartPanel', params: { id: scope.row.id , isEdit: 'edit'}})
      console.log('点击了编辑', row)
      this.$router.push({ name: 'ChartPanel', params: { id: row.id, isEdit: 'edit' }})
      Cookies.set('ChartPanelIsEdit', 'edit')
      Cookies.set('ChartPanelIsEditId', row.id)

      localStorage.setItem('ChartPanelIsEditId', row.id)
    },

    exeSqlJia2(content, item, index) {
      this.$set(this.chartLoading, item.chart_id, true)
      if (!content) {
        this.$message.warning(this.$t('dashboard.chartQueryException', item.chart_name))
        this.$set(this.chartLoading, item.chart_id, false)
        return
      }
      // exeSql().fetch({ source_id: item.source_id, sql: sqlSentence }).then(resp => {
      //   this.$set(this.chartLoading, item.chart_id, false)
      //   this.$set(this.results, item.chart_id, resp.data)
      // }).catch(() => {
      //   this.$set(this.chartLoading, item.chart_id, false)
      // })
      var send_data = { source_id: item.source_id, content: content, pastureid: Cookies.get('pastureid') }
      ExeSqlJiade(send_data).then(resp => {
        console.log('图的数据', resp.data.list)
        this.$set(this.chartLoading, item.chart_id, false)
        this.$set(this.results, item.chart_id, resp.data)
      }).catch(() => {
        this.$set(this.chartLoading, item.chart_id, false)
      })
    },

    getChartItem(id) {
      return this.charts.find(chart => chart.chart_id === id)
    },
    handleCaculPos(layout) {
      // const layout = JSON.parse(JSON.stringify(layout))
      const bottomItems = []
      layout.forEach(i => {
        i.yOffSet = i.y + i.h
        i.xOffSet = i.x + i.w
        i.bottomLine = [[i.x, i.yOffSet], [i.xOffSet, i.yOffSet]]
        i.topLine = [[i.x, i.y], [i.xOffSet, i.y]]
      })
      layout.forEach(i => {
        const flag = layout.every(j => {
          return !isLineOverLap(i.bottomLine, j.topLine)
        })
        if (flag) {
          bottomItems.push(i)
        }
      })
      return bottomItems
    },
    generatePosition(chart, layout, index) {
      let posObj
      if (layout.length === 0) {
        posObj = {
          id: chart.chart_id,
          x: 0,
          y: 0,
          w: 12,
          h: 9,
          i: chart.chart_id
        }
      } else {
        const bottomItems = this.handleCaculPos(layout)
        const highestItem = bottomItems.reduce((result, item) => {
          if (result.bottomLine[0][1] > item.bottomLine[0][1]) {
            result = item
          }
          return result
        }, bottomItems[0])
        posObj = {
          id: chart.chart_id,
          x: highestItem.x,
          y: highestItem.yOffSet,
          w: highestItem.w,
          h: 9,
          i: chart.chart_id
        }
      }

      layout.push(posObj)
    },
    handleShare() {
      const h = this.$createElement
      const link = `http://${location.host}/#/fullscreendb/${this.dashboard.dashboard_id}`
      this.$msgbox({
        title: this.$t('dashboard.shareLink'),
        message: h('p', null, [
          h('a', { style: 'color: #205cd8', attrs: { href: link, target: '_blank' }}, link)
        ])
      })
    },
    // handleLinkChart() {
    //   chartList().then(resp => {
    //     this.myChartList = resp.data
    //     this.showChartList = true
    //   })
    // },

    handleLinkChart() {
      var send_data = {
        name: 'getChartListV2',
        page: 1,
        offset: 1,
        pagecount: 10,
        returntype: 'Map',
        parammaps: {
          pastureid: Cookies.get('pastureid'),
          empid: Cookies.get('employeid')
        }
      }
      GetDataByName(send_data).then(response => {
        console.log('table数据', response.data.list)
        if (response.data.list !== null) {
          this.myChartList = response.data.list
          this.showChartList = true
        } else {
          this.myChartList = []
          this.showChartList = true
        }
      })
    },

    // linkChart(chart) {
    //   const data = {
    //     chart_id: chart.chart_id,
    //     dashboard_id: this.dashboard.dashboard_id
    //   }
    //   addChartToDB(data).then(resp => {
    //     this.showChartList = false
    //     this.getList()
    //     this.$message({
    //       type: 'success',
    //       message: this.$t('common.saveSuccess')
    //     })
    //   })
    // },
    linkChart(chart) {
      const data = {
        name: 'insertdashboard_chart',
        parammaps: {
          cid: chart.chart_id,
          did: this.dashboard.dashboard_id,
          pastureid: Cookies.get('pastureid')
        }
      }

      PostDataByName(data).then(response => {
        console.log('新增保存发送参数', data)
        this.showChartList = false

        if (data.msg == 'fail') {
          this.$message({
            type: 'fail',
            message: '添加失败！'
          })
        } else {
          this.$message({
            type: 'success',
            message: this.$t('common.saveSuccess')
          })
        }
        this.$router.push({ name: 'Addboard', params: { id: '~' + this.dashboard.dashboard_id }})

        console.log('Addboard~' + this.dashboard.dashboard_id)

        this.getList()
        this.$emit('fatherMethod')

        // 重新刷新页面
        this.reload()
      })
    },
    isExisted(chart) {
      return this.charts.findIndex(item => item.chart_id === chart.chart_id) >= 0
    },
    // handleEdit(chart) {
    //   this.$router.push(`/chartpanel/${chart.chart_id}`)
    // },
    handleEdit(chart) {
      this.$router.push({ name: 'ChartPanel', params: { id: chart.chart_id, isEdit: 'edit' }})
      localStorage.setItem('ChartPanelIsEditId', chart.chart_id)
    },

    // form_delete(chart) {
    //   this.$confirm(this.$t('dashboard.removeChartConfirm'), this.$t('common.confirm'), {
    //     type: 'warning'
    //   }).then(() => {
    //     // deleteChart(index)
    //     const deleteChartIndex = this.layout.findIndex(item => item.id === chart.chart_id)
    //     const layout = JSON.parse(JSON.stringify(this.layout))
    //     layout.splice(deleteChartIndex, 1)
    //     this.dashboard.content.layout = layout
    //     const data = {
    //       chart_id: chart.chart_id,
    //       dashboard_id: this.dashboard.dashboard_id
    //     }
    //     Promise.all([updateDashboard(this.dashboard), unMapChartDb(data)]).then(resp => {
    //       this.getList()
    //       this.$message({
    //         type: 'success',
    //         message: this.$t('common.deleteSuccess')
    //       })
    //     })
    //   })
    // },
    form_delete(chart) {
      this.$confirm(this.$t('dashboard.removeChartConfirm'), this.$t('common.confirm'), {
        type: 'warning'
      }).then(() => {
        // deleteChart(index)
        const deleteChartIndex = this.layout.findIndex(item => item.id === chart.chart_id)
        const layout = JSON.parse(JSON.stringify(this.layout))

        layout.splice(deleteChartIndex, 1)
        this.dashboard.content.layout = layout

        const data = {
          name: 'deletedashboard_chart',
          parammaps: {
            cid: chart.chart_id,
            did: this.dashboard.dashboard_id,
            pastureid: Cookies.get('pastureid')
          }
        }

        PostDataByName(data).then(response => {
          console.log('删除发送参数', data)

          this.$message({
            type: 'success',
            message: this.$t('common.deleteSuccess')
          })
          this.getList()
        })
      })
    },
    // 拖拽
    // handleLayoutChange() {
    //   if (this.mode === 'view') return
    //   this.dashboard.content = this.dashboard.content || {}
    //   this.dashboard.content.layout = this.layout
    //   // updateDashboard(this.dashboard)
    // },
    handleLayoutChange() {
      console.log('this.mode:', this.mode)
      if (this.mode === 'view') return
      console.log('this.dashboard1', this.dashboard)
      this.dashboard.content = this.dashboard.content || {}
      this.dashboard.content.layout = this.layout
      console.log('this.dashboard2', this.dashboard)

      var send_data = { dashboard_id: this.dashboard.dashboard_id, content: this.dashboard.content, pastureid: Cookies.get('pastureid') }
      updateDashboardJiade(send_data).then(response => {
        console.log('拖拽位置的数据', response.data.list)
        // if (response.data !== null) {
        //   this.loading = false
        //   this.result = response.data
        // } else {
        //   this.loading = false
        //   this.result = []
        // }
      })
    },

    handleResize(i, newH, newW, newHPx, newWPx) {
      this.$refs[`chartInstance${i}`][0].$children[0].$emit('resized')
    },

    exeSql(sqlSentence, item, index) {
      this.$set(this.chartLoading, item.chart_id, true)
      if (!sqlSentence) {
        this.$message.warning(this.$t('dashboard.chartQueryException', item.chart_name))
        this.$set(this.chartLoading, item.chart_id, false)
        return
      }
      exeSql().fetch({ source_id: item.source_id, sql: sqlSentence }).then(resp => {
        this.$set(this.chartLoading, item.chart_id, false)
        this.$set(this.results, item.chart_id, resp.data)
      }).catch(() => {
        this.$set(this.chartLoading, item.chart_id, false)
      })
    }
  }
}
</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;
  }
}
.tool-bar {
  display: flex;
  justify-content: space-between;
  border-top: none;
  height: 45px;
  line-height: 45px;
  color: #303133;
  padding: 0 10px;
  position: relative;
  .db-name {
    font-size: 1.2em;
    font-weight: 600;
    color: #909399;
    margin-left: 0;
  }
  span {
    color: #c0c4cc;
    font-size: 0.8em;
    margin-left: 10px;
  }
}
.visualize-card {
  /deep/ .el-card__header {
    padding: 0;
    .operation-bar {
      font-size: 14px;
      display: flex;
      justify-content: space-between;
      height: 35px;
      padding: 0 10px;
      line-height: 35px;
      z-index: 9;
      i {
        margin-right: 10px;
        color: #409eff;
        cursor: pointer;
      }
    }
  }
}
.welcome-container {
  text-align: center;
  height: 500px;
  color: #c0c4cc;
  /deep/ .el-button {
    margin-top: 200px;
    margin-bottom: 25px;
  }
}
</style>
