<template>
  <div class="vee-chart-template">
    <el-row>
      <el-col :span="12" v-for="(item, index) of tableDatas" :key="index">
        <div class="vee-chart-template-item">
          <el-card class="vee-chart-template-cart">
            <div slot="header" class="clearfix">
              <span>{{item.name}}</span>
              <el-button type="text" class="vee-chart-template-btn-usage" @click="handleUsageBtnClick(item)">使用</el-button>
            </div>
            <div class="vee-chart-template-chart">
              <v-chart class="vve-v-chart" :options="item.options" autoresize></v-chart>
            </div>
          </el-card>
        </div>
      </el-col>
    </el-row>
    <el-pagination
      v-show="total > initPageSize"
      class="vee-template-chart-pagination"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-size="pageSize"
      layout="total, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
  </div>
</template>
<script>
import { Row, Col, Card, Button, Pagination } from 'element-ui'
import ECharts from 'vue-echarts'
import 'echarts'
import { mapActions, mapState } from 'vuex'
import { veeStoreName } from './store/name'

const initPageSize = 4

export default {
  components: {
    ElRow: Row,
    ElCol: Col,
    ElCard: Card,
    ElButton: Button,
    ElPagination: Pagination,
    'v-chart': ECharts
  },
  data() {
    return {
      initPageSize,
      currentPage: 1,
      pageSize: initPageSize
    }
  },
  computed: {
    ...mapState(veeStoreName, ['chartTemplates']),
    total () {
      return this.chartTemplates.length
    },
    tableDatas () {
      const startIndex = (this.currentPage - 1) * this.pageSize
      const tableDatas = this.chartTemplates.slice(startIndex, startIndex + this.pageSize)
      return tableDatas
    },
  },
  methods: {
    ...mapActions(veeStoreName, ['restoreSoul']),
    handleCurrentChange (val) {
      this.currentPage = val
    },
    handleSizeChange (val) {
      this.pageSize = val
    },
    handleUsageBtnClick (item) {
      this.restoreSoul(item.options)
      document.body.click() // 强制点击body触发失焦事件触发
    }
  },
  watch: {
    chartTemplates () {
      this.currentPage = 1
    }
  }
}
</script>
<style lang="scss">
.vee-chart-template-item {
  box-sizing: border-box;
  padding: 5px;
}
.vee-chart-template-chart {
  height: 200px;
}
.vee-chart-template-btn-usage {
  float: right;
  padding: 3px 0;
}
.vee-chart-template {
  .el-card__header {
    padding: 10px 10px;
  }
  .el-card__body {
    padding: 10px;
  }
}
.vee-template-chart-pagination {
  margin-top: 5px;
  text-align: right;
}
</style>
