<template>
  <div class="cqcy-content" v-if="chooseGroupId">
    <div style="margin-bottom: 10px;">
      <span style="color: #474646; font-size: 14px;">数据组：</span>
      <el-select v-model="chooseGroupId" disabled size="mini">
        <el-option
            v-for="dict in groupDataList"
            :key="dict.id"
            :label="dict.groupName"
            :value="dict.id"
        ></el-option>
      </el-select>
      <span style="margin-left: 20px; color: #474646; font-size: 14px;">数据项名称：</span>
      <el-input placeholder="请输入数据项名称"
                size="mini"
                style="width: 200px;"
                @input="itemChangeEvent"
                v-model="filterItemText"
                prefix-icon="el-icon-search">
      </el-input>
      <el-checkbox v-model="groupRunStatus" size="mini" style="margin-left: 20px;"
                   @change="groupRunCheckboxEvent" title="固定每5秒刷新一次数据">实时数据</el-checkbox>
    </div>
    <el-table
        :data="itemDataList" border :stripe="true"
        :header-cell-style="{background: '#E8E8E8'}"
        style="width: 100%">
      <el-table-column label="序号" align="center" width="80">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="itemName" label="数据项名称" align="center">
      </el-table-column>
      <template v-if="groupRunStatus">
        <el-table-column prop="dataType" label="数据项类型" align="center" width="100">
        </el-table-column>
        <el-table-column prop="operationRule" label="表达式" align="center" width="200">
          <template slot-scope="scope">
            {{ scope.row.operationRule ? scope.row.operationRule : '默认值' }}
          </template>
        </el-table-column>
        <el-table-column prop="dataOrgValue" label="原始数据值" align="center" width="100">
          <template slot-scope="scope">
            {{ scope.row.dataOrgValue ? scope.row.dataOrgValue : '' }}
          </template>
        </el-table-column>
        <el-table-column prop="dataValue" label="计算值" align="center" width="100">
          <template slot-scope="scope">
            {{ (scope.row.dataValue && scope.row.dataValue != 'undefined') ? scope.row.dataValue : '' }}
          </template>
        </el-table-column>
        <el-table-column prop="dataSourceName" label="数据源名称" align="center" width="180">
        </el-table-column>
        <el-table-column prop="createTime" label="取值时间" align="center" width="180">
        </el-table-column>
      </template>
      <template v-else>
        <el-table-column prop="describe" label="描述" align="center" width="150">
          <template slot-scope="scope" v-if="scope.row.describe">
            <!--          <el-tag type="primary" disable-transitions>{{ scope.row.describe }}</el-tag>-->
            <span>{{ scope.row.describe }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="dataSourceName" label="数据源名称" align="center" width="180">
        </el-table-column>
        <el-table-column prop="operationRule" label="表达式" align="center" width="200">
          <template slot-scope="scope">
            {{ scope.row.operationRule ? scope.row.operationRule : '默认值' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="100">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handleClickByEdit(scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </template>
    </el-table>
  </div>
</template>

<script>
import {getItemGroupById, getItemValueById, updateItemDescribe} from "@/api/datasource";
import {showLoading} from "@/utils/cqcy";
import errorCode from "@/utils/errorCode";

export default {
  name: "index",
  components: {
  },
  data() {
    return {
      itemDataList: [],
      itemDataListF: [],
      groupDataList: [],
      chooseGroup: null,
      chooseGroupId: null,
      groupRunStatus: false,
      timeInterval: null,
      filterItemText: '',
    }
  },
  watch: {
    '$route'(to, from) {
      this.readParams()
    },
    '$route.query.t': {
      handler(o, n) {
      }
    },
    deep: true
  },
  created() {
    this.readParams()
  },
  beforeDestroy() {
    if (this.timeInterval) {
      clearInterval(this.timeInterval)
      this.timeInterval = null
    }
  },
  methods: {
    itemChangeEvent(value) {
      let arr = JSON.parse(JSON.stringify(this.itemDataListF))
      if (!value || !value.trim()) {
        this.itemDataList = arr
        return
      }
      let filterList = arr.filter(v => {
        return v.itemName.indexOf(value) !== -1
      })
      this.itemDataList = filterList
    },
    /** 读取参数 */
    readParams() {
      this.filterItemText = ''
      // let groupListStorage = sessionStorage.getItem('GROUP_LIST') ? sessionStorage.getItem('GROUP_LIST') : '[]'
      // this.groupDataList = JSON.parse(groupListStorage)
      let groupId = sessionStorage.getItem('GROUP_ID') ? sessionStorage.getItem('GROUP_ID') : '-1'
      this.chooseGroupId = parseInt(groupId)
      this.groupRunStatus = false
      this.getGroupById(this.chooseGroupId)
      // this.getItemValueById()
    },
    /** 运行状态值 */
    groupRunCheckboxEvent(val) {
      this.groupRunStatus = val
      this.getItemValueById()
    },
    /** 获取数据项值信息 */
    getItemValueById() {
      if (!this.groupRunStatus || !this.chooseGroup) {
        if (this.timeInterval) {
          clearInterval(this.timeInterval)
          this.timeInterval = null
        }
        this.getGroupById(this.chooseGroupId)
        return
      }
      getItemValueById(this.chooseGroup.id).then(res => {
        this.filterItemText = ''
        this.itemDataList = res.data
        // 避免布尔类型时页面无法显示数据
        for (let i = 0; i < this.itemDataList.length; i ++) {
          this.itemDataList[i].dataValue += ''
        }
        this.itemDataListF = JSON.parse(JSON.stringify(this.itemDataList))
      }).catch((e) => {
      })
      let temp = setInterval(() => {
        getItemValueById(this.chooseGroup.id).then(res => {
          this.filterItemText = ''
          this.itemDataList = res.data
          // 避免布尔类型时页面无法显示数据
          for (let i = 0; i < this.itemDataList.length; i ++) {
            this.itemDataList[i].dataValue += ''
          }
          this.itemDataListF = JSON.parse(JSON.stringify(this.itemDataList))
        }).catch((e) => {
        })
      }, 5 * 1000)
      this.timeInterval = temp
    },
    /** 获取组详细信息 */
    getGroupById(id) {
      if (this.timeInterval) {
        clearInterval(this.timeInterval)
        this.timeInterval = null
      }
      if (!id || id <= 0) {
        this.chooseGroupId = null
        return
      }
      const loading = showLoading(this, '加载中，请稍候···')
      getItemGroupById(id).then(res => {
        loading.close()
        this.chooseGroup = res.data
        this.groupDataList = [{
          'id': this.chooseGroup.id,
          'groupName': this.chooseGroup.groupName
        }]
        this.itemDataList = this.chooseGroup.itemList
        this.itemDataListF = JSON.parse(JSON.stringify(this.itemDataList))
      }).catch((e) => {
        loading.close()
        this.$alert(e, errorCode[100], {
          confirmButtonText: '确定',
          callback: action => {
          }
        })
      })
    },
    /** 编辑 */
    handleClickByEdit(row) {
      if (!row || !row.id) {
        this.$message({
          message: '编辑失败！',
          type: 'warning'
        })
        return
      }
      this.$prompt('请输入该数据项描述信息', '编辑', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        customClass: 'close_confirm',
        closeOnClickModal: false,
        inputValue: row.describe,
        inputValidator: (val) => {
          if (!val || !val.trim()) {
            return '描述信息不能为空'
          }
          if (val.length > 20) {
            return '描述信息必须在20字以内'
          }
        }
      }).then(({ value }) => {
        let data = {
          'id': row.id,
          'describe': value
        }
        updateItemDescribe(data).then(res => {
          let msg = res.data ? '编辑成功！' : '编辑失败！'
          let msgType = res.data ? 'success' : 'error'
          this.$message({
            message: msg,
            type: msgType
          })
          this.getGroupById(this.chooseGroupId)
        }).catch((e) => {
        })
      }).catch(() => {
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
.el-table--enable-row-hover .el-table__body tr:hover > td {
  background-color: transparent !important;
}
</style>