<template>
  <div class="cqcy-content">
    <el-button type="primary" icon="el-icon-circle-plus-outline"
               size="mini" @click="addIndexChartBtnEvent">添加图表
    </el-button>
    <el-divider></el-divider>
    <div>
      <el-table
          :data="chartDataList" border :stripe="true"
          :header-cell-style="{background: '#E8E8E8'}"
          style="width: 100%; height: calc(100% - 100px); overflow: auto;">
        <el-table-column
            align="center"
            label="图表名称"
            prop="chartName">
          <template slot-scope="scope">
                <span style="color: #409EFF; cursor: pointer;"
                      @click="handleChartNodeClick(scope.row)"
                      :title="scope.row.reportTableName">{{ scope.row.chartName }}</span>
          </template>
        </el-table-column>
        <el-table-column
            align="center"
            label="统计图类型"
            prop="chartType"
            width="200">
          <template slot-scope="scope">
            <span>{{ scope.row.chartType == 'bar' ? '柱状图'
                : (scope.row.chartType == 'line' ? '折线图' : '饼状图') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="300">
          <template slot-scope="scope">
            <el-button type="text"
                       size="small"
                       icon="el-icon-delete"
                       style="color: red;"
                       @click="removeChartItem(scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          style="margin-top: 20px;"
          background
          layout="sizes, prev, pager, next, total"
          :current-page="chartPage"
          :page-size="chartLimit"
          @size-change="sizeChartChangeEvent"
          @current-change="currentChartChangeEvent"
          :total="chartTotal">
      </el-pagination>
    </div>

    <!-- 新增首页图表 -->
    <el-dialog
        title="添加图表"
        width="600px"
        top="5vh"
        center
        v-dialog-drag
        v-if="dialogIndexChartVisible"
        :before-close="dialogClose"
        :visible.sync="dialogIndexChartVisible"
        :close-on-click-modal="false"
        :append-to-body="true">
      <el-form ref="chartForm" :model="chartForm" :rules="chartFormRules" label-width="110px">
        <el-form-item label='统计图名称：' prop="chartName">
          <el-input placeholder="请输入统计图名称" v-model="chartForm.chartName" maxlength="20" show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="取值类型：" prop="valueType">
          <el-radio v-for="item in valueTypeList"
                    v-model="chartForm.valueType"
                    :label="item.value">{{ item.label }}</el-radio>
        </el-form-item>
        <el-form-item label="统计图类型：" prop="chartType">
          <el-radio v-for="item in chartTypeList"
                    v-model="chartForm.chartType"
                    :label="item.value">{{ item.label }}</el-radio>
        </el-form-item>
        <el-form-item label="取值模式：" prop="valueTakingMode">
          <el-radio v-for="item in valueTakingModeList"
                    v-model="chartForm.valueTakingMode"
                    :label="item.value">{{ item.label }}</el-radio>
        </el-form-item>
        <el-form-item label="时间单位：" prop="bucketType">
          <el-radio v-for="item in bucketTypeList"
                    v-model="chartForm.bucketType"
                    :label="item.value">{{ item.label }}</el-radio>
        </el-form-item>
        <el-form-item label="时段间隔：" prop="bucketValue">
          <el-input-number label="请输入时段值"
                           v-model="chartForm.bucketValue"
                           :min="1"
                           :max="100"></el-input-number>
        </el-form-item>
        <el-form-item label="取值时间：" prop="dateRange">
          <el-date-picker
              v-model="chartForm.dateRange"
              type="datetimerange"
              :clearable="false"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              placeholder="选择取值时间范围"
              :picker-options="{
                      format: 'yyyy-MM-dd HH:mm:ss'
                    }"
              value-format="yyyy-MM-dd HH:mm:ss"
              :default-time="['09:00:00', '18:00:00']">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="数据项：" prop="chartItemList">
          <el-button size="mini" @click="chooseDataItemEvent">选择数据项</el-button>
          <el-tag size="mini" v-if="chartForm.chartItemList.length" style="margin-left: 10px;">
            已选择({{ chartForm.chartItemList.length }})项
          </el-tag>
        </el-form-item>
        <el-form-item label="用户组：" prop="userGroupList">
          <el-button size="mini" @click="chooseUserGroupEvent">选择用户组</el-button>
          <el-tag size="mini" v-if="chartForm.userGroupList.length" style="margin-left: 10px;">
            已选择({{ chartForm.userGroupList.length }})组
          </el-tag>
        </el-form-item>
      </el-form>
      <span slot='footer'>
        <el-button type="primary" @click="addIndexChartEvent">添加</el-button>
        <el-button @click="dialogClose">取消</el-button>
      </span>
    </el-dialog>

    <!-- 选择数据项 -->
    <data-item ref="dataItem" @update-message="updateDataItemEmit"></data-item>
    <!-- 选择用户组 -->
    <user-group ref="userGroup" @update-message="updateUserGroupEmit"></user-group>
  </div>
</template>

<script>
import DataItem from '@/components/CustomDialog/DataItem'
import UserGroup from '@/components/CustomDialog/UserGroup'
import {goPage, showAlertMsgWin, showAlertWin, showConfirmWin, showLoading} from "@/utils/cqcy";
import {delIndexChartById, getIndexChartById, getIndexChartList, saveIndexChart} from "@/api/chart";
import {delItemGroupById} from "@/api/datasource";

export default {
  name: "index",
  components: {
    DataItem, UserGroup
  },
  data() {
    return {
      dialogIndexChartVisible: false,
      chartDataList: [],
      chartTotal: 0,
      chartPage: 1,
      chartLimit: 10,
      chartTypeList: [
        { 'label': '柱状图', 'value': 'bar' },
        { 'label': '折线图', 'value': 'line' },
        { 'label': '饼状图', 'value': 'pie' }
      ],
      valueTypeList: [
        { 'label': '原始值', 'value': 0 },
        { 'label': '计算值', 'value': 1 }
      ],
      bucketTypeList: [
        { 'label': '天', 'value': 0 },
        { 'label': '时', 'value': 1 },
        { 'label': '分', 'value': 2 },
        { 'label': '秒', 'value': 3 }
      ],
      valueTakingModeList: [
        { 'label': '平均值', 'value': 0 },
        { 'label': '最大值', 'value': 1 },
        { 'label': '最小值', 'value': 2 },
        { 'label': '瞬时值', 'value': 3 }
      ],
      chartForm: {
        chartName: '',
        valueType: 0,
        chartType: 'bar',
        valueTakingMode: 0,
        bucketType: 1,
        bucketValue: 1,
        dateRange: [],
        startTime: null,
        endTime: null,
        chartItemList: [],
        userGroupList: []
      },
      chartFormRules: {
        chartName: [
          { required: true, message: '名称不能为空', trigger: 'blur' }
        ],chartItemList: [
          { required: true, message: '数据项不能为空', trigger: 'blur' }
        ],userGroupList: [
          { required: true, message: '用户组不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getIndexAllChart()
  },
  methods: {
    sizeChartChangeEvent(val) {
      this.chartPage = 1
      this.chartLimit = val
      this.getIndexAllChart()
    },
    currentChartChangeEvent(val) {
      this.chartPage = val
      this.getIndexAllChart()
    },
    /** 图表点击事件 */
    handleChartNodeClick(row) {
      getIndexChartById(row.id).then(res => {
        console.log(res)
      }).catch((e) => {
        showAlertWin(this, null, e)
      })
    },
    /** 图表删除事件 */
    removeChartItem(row) {
      let _this = this
      showConfirmWin(_this, null, '您确定要删除该图表吗？', () => {
        const loading = showLoading(_this, '删除中，请稍候···')
        delIndexChartById(row.id).then(res => {
          loading.close()
          this.getIndexAllChart()
          showAlertMsgWin(this, null, res.data)
        }).catch((e) => {
          loading.close()
          showAlertWin(this, null, e)
        })
      })
    },
    /** 保存首页图表添加事件 */
    addIndexChartBtnEvent() {
      this.dialogIndexChartVisible = true
    },
    /** 查询首页图表信息 */
    getIndexAllChart() {
      getIndexChartList(this.chartPage, this.chartLimit, {}).then(res => {
        this.chartTotal = res.data.count
        this.chartDataList = res.data.reportTableList
      }).catch((e) => {
        showAlertWin(this, null, e)
      })
    },
    /** 保存首页图表操作 */
    addIndexChartEvent() {
      if (!this.chartForm.chartName || !this.chartForm.chartName.trim()) {
        showAlertMsgWin(this, null, '图表名称不能为空！')
        return
      }
      if (this.chartForm.dateRange.length == 0) {
        showAlertMsgWin(this, null, '取值时间不能为空！')
        return
      }
      if (this.chartForm.chartItemList.length == 0) {
        showAlertMsgWin(this, null, '数据项不能为空！')
        return
      }
      if (this.chartForm.userGroupList.length == 0) {
        showAlertMsgWin(this, null, '用户组不能为空！')
        return
      }
      this.chartForm.startTime = this.chartForm.dateRange[0]
      this.chartForm.endTime = this.chartForm.dateRange[1]
      saveIndexChart(this.chartForm).then(res => {
        this.dialogIndexChartVisible = false
        this.getIndexAllChart()
        showAlertMsgWin(this, null, res.data)
      }).catch((e) => {
        showAlertWin(this, null, e)
      })
    },
    /** 更新已选择数据项 */
    updateDataItemEmit(items) {
      this.chartForm.chartItemList = []
      items.forEach((item) => {
        this.chartForm.chartItemList.push({
          'itemId': item.id,
          'itemGroupId': item.itemGroupId
        })
      })
    },
    /** 更新已选择用户组 */
    updateUserGroupEmit(groups) {
      this.chartForm.userGroupList = []
      groups.forEach((id) => {
        this.chartForm.userGroupList.push({
          'id': id
        })
      })
    },
    /** 选择数据项 */
    chooseDataItemEvent() {
      this.$refs.dataItem.show()
    },
    /** 选择用户组 */
    chooseUserGroupEvent() {
      this.$refs.userGroup.show()
    },
    /** 弹出层关闭事件 */
    dialogClose(done) {
      Object.assign(this.$data.chartForm, this.$options.data.call(this).chartForm)
      if (typeof (done) === 'function') {
        done()
      } else {
        this.dialogIndexChartVisible = false
      }
    }
  }
}
</script>

<style>

</style>
