<template>
  <div>
    <el-container>
      <el-header>
        <el-card>
          <el-form
            :inline="true"
            ref="searchform"
            :model="config.filters"
            label-width="100px"
            size="mini"
          >
            <el-form-item
              v-for="(item, index) in config.Filters"
              :key="index"
              :label="item.DisplayName"
            >
              <el-input v-if="item.Type == 'input'" v-model="item.Value"></el-input>
              <el-select
                v-if="item.Type == 'select'"
                v-model="item.Value"
                size="mini"
                placeholder=""
                clearable
                v-on:change="loadData"
              >
                <el-option
                  v-for="item in item.Options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
              <el-select
                v-if="item.Type == 'select-multi'"
                multiple
                v-model="item.Value"
                size="mini"
                placeholder=""
                clearable
                v-on:change="loadData"
              >
                <el-option
                  v-for="item in item.Options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
              <el-date-picker
                v-if="item.Type == 'date'"
                v-model="item.Value"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                type="date"
                placeholder="选择日期"
              >
              </el-date-picker>
              <el-date-picker
                v-if="item.Type == 'datetime'"
                v-model="item.Value"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
                type="datetime"
                placeholder="选择日期"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" size="small" v-on:click="query">查询</el-button>
            </el-form-item>
            <el-form-item>
              <el-checkbox v-model="autoRefresh" size="mini">自动刷新</el-checkbox>
            </el-form-item>
          </el-form>
        </el-card>
      </el-header>
      <el-main>
        <el-card>
          <div style="padding-bottom: 5px">
            <el-button type="success" size="mini" v-on:click="openConfig">配置</el-button>
            <el-button type="info" size="mini" v-on:click="exportExcel" v-show="config.Export"
              >导出</el-button
            >
          </div>
          <el-table
            :data="tableData"
            border
            v-loading="loading"
            element-loading-text="数据加载中"
            element-loading-spinner="el-icon-loading"
            element-loading-background="rgba(192，192，192, 0.8)"
            :row-style="{ height: '35px' }"
            :cell-style="{ padding: '0px' }"
            height="650px"
            :cell-class-name="tableCellClassName"
            highlight-current-row
            v-on:current-change="handleCurrentChange"
          >
            <template v-for="(item, index) in config.Columns">
              <el-table-column
                v-if="item.Show"
                :key="index"
                :prop="item.Prop"
                :label="item.Label"
                :align="item.Align"
                :width="item.Width"
                :fixed="item.Fixed"
                :show-overflow-tooltip="true"
              >
              </el-table-column>
            </template>
          </el-table>
          <div style="text-align: right; padding-top: 3px" v-if="config.Pagination">
            <el-pagination
              background
              v-on:current-change="handlePageChanged"
              :current-page="pagination.currentPage"
              :page-size="20"
              v-on:size-change="handleSizeChange"
              layout="total, sizes, prev, pager, next"
              :total="pagination.totalRecord"
            >
            </el-pagination>
          </div>
        </el-card>
      </el-main>
    </el-container>
    <el-dialog
      append-to-body
      :close-on-click-modal="false"
      :visible.sync="dialogVisible"
      title="配置"
      width="1000px"
      destroy-on-close
    >
      <data-config ref="dataConfig" />
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getConfig,
  getDataValue,
  getSelectOptions,
  getData,
  exportData,
} from '@/api/dataQuery/query'
import DataConfig from './config.vue'
export default {
  name: 'dataQuery',
  components: { DataConfig },
  data() {
    return {
      loading: false,
      autoRefresh: false,
      autoRefreshValue: '', //自动刷新的值
      config: {}, //查询配置
      tableData: [], //具体查询出来的数据
      parameter: {
        pageSize: 20,
        pageIndex: 1,
      },
      pagination: {
        totalRecord: 0,
        currentPage: 1,
      },
      //闪烁颜色用的变量
      flashFlag: true, //闪烁标志变量
      flashFilter: {
        has: false,
        columnName: '',
        columnValue: '',
      },
      flashColors: {
        //装载颜色条件
        columnName: '',
        colors: [], //value,color1,color2
      },
      flashRuning: false,
      timerID: null,
      dateConst: ['now', 'today', 'yestoday', 'yestoday-now'],
      dialogVisible: false,
    }
  },
  methods: {
    loadConfig() {
      let _this = this
      getConfig({ configname: ys.request('configname') })
        .then(function (response) {
          console.log(response.data)
          let data = response.data
          _this.config = data
          _this.initDefaultValue()
          _this.loadData()
          _this.parsingFlashFilter()
          _this.parsingFlashColor()
          if (_this.config.Pagination) {
            _this.pagination.pagesizes = _this.config.PageSizeList
            _this.parameter.pageSize = _this.config.PageSize
          }
          if (_this.config.Flash) {
            clearTimeout(_this.timerID)
            _this.doFlash()
            //_this.$nextTick().then(() => {
            //    _this.doFlash();
            //})
          }
          _this.autoRefreshData()
        })
        .catch(function (error) {
          console.log(error)
        })
    },
    //初始化变量，主要针对日期关键字的解析
    initDefaultValue() {
      let l = this.config.Filters.length
      for (let i = 0; i < l; i++) {
        if (this.config.Filters[i].Type == 'date') {
          if (
            this.config.Filters[i].DefaultValue == 'now' ||
            this.config.Filters[i].DefaultValue == 'today'
          ) {
            this.config.Filters[i].Value = moment().format('YYYY-MM-DD')
          } else if (
            this.config.Filters[i].DefaultValue == 'yestoday' ||
            this.config.Filters[i].DefaultValue == 'yestoday-now'
          ) {
            this.config.Filters[i].Value = moment().subtract(1, 'days').format('YYYY-MM-DD')
          }
        } else if (this.config.Filters[i].Type == 'datetime') {
          if (this.config.Filters[i].DefaultValue == 'now') {
            this.config.Filters[i].Value = moment().format('YYYY-MM-DD HH:mm:ss')
          } else if (this.config.Filters[i].DefaultValue == 'today') {
            this.config.Filters[i].Value = moment().format('YYYY-MM-DD 00:00:00')
          } else if (this.config.Filters[i].DefaultValue == 'yestoday-now') {
            this.config.Filters[i].Value = moment()
              .subtract(1, 'days')
              .format('YYYY-MM-DD HH:mm:ss')
          } else if (this.config.Filters[i].DefaultValue == 'yestoday') {
            this.config.Filters[i].Value = moment()
              .subtract(1, 'days')
              .format('YYYY-MM-DD 00:00:00')
          }
        } else if (this.config.Filters[i].Type == 'select') {
          if (this.config.Filters[i].DataSource == 'dp') {
          } else if (this.config.Filters[i].DataSource == 'string') {
            this.loadStringOptions(i)
          } else {
            this.loadSqlOptions(i)
          }
        } else if (this.config.Filters[i].Type == 'select-multi') {
          if (this.config.Filters[i].DataSource == 'dp') {
          } else if (this.config.Filters[i].DataSource == 'string') {
            this.loadStringOptions(i)
          } else {
            this.loadSqlOptions(i)
          }
        }
      }
    },
    loadStringOptions(filterIndex) {
      this.config.Filters[filterIndex].Options = JSON.parse(
        this.config.Filters[filterIndex].DataSourceExpression
      )
    },
    //为选择器载入dp中的维度数据
    loadDPOptions(filterIndex, dataid) {
      let _this = this
      getDataValue({ dataid })
        .then((res) => {
          console.log(res) //在控制台输出获取的数据形式
          let o = res[dataid].split(',')
          _this.config.Filters[filterIndex].Options = new Array()
          $.each(o, function (index, element) {
            _this.config.Filters[filterIndex].Options.push({ value: element, label: element })
          })
        })
        .catch((err) => {
          alert('获取数据失败！')
        })
      // $.ajax({
      //   type: 'post',
      //   url: 'http://localhost:53489/Service/IO/RTDataJson.asmx/GetDataValue', //接口地址，后面加上 /方法名即可
      //   data: { dataid: dataid },
      //   dataType: 'json',
      //   success: function (data) {
      //     console.log(data) //在控制台输出获取的数据形式
      //     let o = data[dataid].split(',')
      //     _this.config.Filters[filterIndex].Options = new Array()
      //     $.each(o, function (index, element) {
      //       _this.config.Filters[filterIndex].Options.push({ value: element, label: element })
      //     })
      //   },
      //   error: function (XMLHttpRequest, textStatus, errorThrown) {
      //     alert('获取数据失败！')
      //   },
      // })
    },
    //为选择器载入sql或字典数据
    loadSqlOptions(filterIndex) {
      let _this = this
      getSelectOptions({
        configname: ys.request('configname'),
        filterIndex,
      })
        .then(function (response) {
          console.log(response.data)
          let data = response.data
          if (data.Tag == 1) {
            _this.config.Filters[filterIndex].Options = data.Data
          }
        })
        .catch(function (error) {
          console.log(error)
        })
    },
    loadData() {
      let _this = this
      _this.tableData = []
      this.loading = true
      getData({
        configname: ys.request('configname'),
        filters: this.config.Filters,
        autoRefreshValue: this.autoRefreshValue,
        pagesize: this.parameter.pageSize,
        pageindex: this.parameter.pageIndex,
      })
        .then(function (response) {
          console.log(response.data)
          let data = response.data
          if (data.Tag == 1) {
            _this.tableData = data.Data
            //_this.autoRefreshValue = data.Message;//把刷新变量的值放到message中
            _this.pagination.totalRecord = data.Total
            _this.loading = false
          }
        })
        .catch(function (error) {
          _this.loading = false
          console.log(error)
        })
    },
    tableCellClassName(obj) {
      return obj.column.property
    },
    parsingFlashFilter() {
      if (this.config.FlashFilter) {
        this.flashFilter.has = true
        let o = this.config.FlashFilter.split('=')
        this.flashFilter.columnName = o[0]
        this.flashFilter.columnValue = o[1]
      }
    },
    parsingFlashColor() {
      let temparr = this.config.FlashColorFilter.split(':')
      this.flashColors.columnName = temparr[0]
      let colors = temparr[1].split(';')
      for (let i = 0; i < colors.length; i++) {
        if (colors[i]) {
          let c = colors[i].split(',')
          let c1 = tinycolor(c[1]).setAlpha(1).toRgbString()
          let c2 = tinycolor(c[1]).setAlpha(0).toRgbString()
          this.flashColors.colors.push({ value: c[0], color1: c1, color2: c2 })
        }
      }
      console.log(this.flashColors)
    },
    //执行闪烁
    doFlash() {
      //console.log(new Date());
      let _this = this
      this.timerID = setTimeout(_this.doFlash, 500)
      for (let i = 0; i < this.flashColors.colors.length; i++) {
        let color = this.flashColors.colors[i]
        if (this.flashFlag) {
          this.setFlashColor(
            this.config.FlashColumn,
            this.flashColors.columnName,
            color.value,
            color.color1,
            100
          )
        } else {
          this.setFlashColor(
            this.config.FlashColumn,
            this.flashColors.columnName,
            color.value,
            color.color2,
            400
          )
        }
      }
      this.flashFlag = !this.flashFlag
    },
    setFlashColor(flashColumn, flashColorFilter, flashColorValue, flashColor, speed) {
      //如有设置了闪烁列，则按照列闪烁
      let _this = this
      if (flashColumn) {
        if (this.config.FlashFilter) {
          //console.log('YY')
          $(
            '.' +
              _this.flashFilter.columnName +
              " div:contains('" +
              _this.flashFilter.columnValue +
              "')"
          )
            .parent()
            .parent()
            .children('.' + flashColorFilter)
            .children("div:contains('" + flashColorValue + "')")
            .parent()
            .parent()
            .children('.' + flashColumn)
            .animate({ 'background-color': flashColor }, speed)
        } else {
          //有列的
          //console.log('YN')
          $('.' + flashColorFilter + " div:contains('" + flashColorValue + "')")
            .parent()
            .parent()
            .children('.' + flashColumn)
            .animate({ 'background-color': flashColor }, speed)
        }
      } else {
        if (this.config.FlashFilter) {
          //console.log('NY')
          $(
            '.' +
              _this.flashFilter.columnName +
              " div:contains('" +
              _this.flashFilter.columnValue +
              "')"
          )
            .parent()
            .parent()
            .children('.' + flashColorFilter)
            .children("div:contains('" + flashColorValue + "')")
            .parent()
            .parent()
            .children()
            .animate({ 'background-color': flashColor }, speed)
        } else {
          //无列的
          //console.log('NN')
          $('.' + flashColorFilter + " div:contains('" + flashColorValue + "')")
            .parent()
            .parent()
            .children()
            .animate({ 'background-color': flashColor }, speed)
        }
      }
    },
    //打开配置窗口
    openConfig() {
      this.dialogVisible = true
      // ys.openDialog({
      //   title: '配置',
      //   height: '750px',
      //   width: '1000px',
      //   content:
      //     '@Url.Content("~/DataQueryManage/DataQuery/Config")' +
      //     '?configname=' +
      //     ys.request('configname'),
      //   callback: function (index, layero) {
      //     var iframeWin = window[layero.find('iframe')[0]['name']]
      //     iframeWin.vue.saveForm(index)
      //   },
      // })
    },
    //查询数据，页码从1开始
    query() {
      this.parameter.pageIndex = 1
      this.loadData()
    },
    autoRefreshData() {
      let _this = this
      setTimeout(_this.autoRefreshData, 1000)
      if (this.autoRefresh) {
        //console.log("执行刷新")
        if (this.config.RefreshKey) {
          //console.log("按变量刷新")
          this.loadData()
        } else {
          //console.log("全部刷新")
          this.loadData()
        }
      } else {
        //console.log("不执行刷新")
      }
    },
    //根据监控变量进行刷新
    autoRefreshByKey() {},
    //表格相关固定方法，行号、分页等
    indexMethod(index) {
      return index + 1 + (this.parameter.pageIndex - 1) * this.parameter.pageSize
    },
    handlePageChanged(pageIndex) {
      console.log(pageIndex)
      this.parameter.pageIndex = pageIndex
      this.loadTableData()
    },
    handleNext(pageIndex) {
      console.log(pageIndex)
      this.parameter.pageIndex = pageIndex
      this.loadTableData()
    },
    handlePrev(pageIndex) {
      console.log(pageIndex)
      this.parameter.pageIndex = pageIndex
      this.loadTableData()
    },
    handleCurrentChange(row) {
      if (row != null) {
        this.currentRow = row
        this.editEnabled = false
        this.deleteEnabled = false
      }
    },
    handleSizeChange(pageSize) {
      console.log(pageSize)
      this.parameter.pageSize = pageSize
      this.loadTableData()
    },
    exportExcel() {
      exportData({
        params: {
          configname: ys.request('configname'),
          filters: this.config.Filters,
          autoRefreshValue: this.autoRefreshValue,
          pagesize: this.parameter.pageSize,
          pageindex: this.parameter.pageIndex,
        },
        responseType: 'blob',
      })
        .then(function (res) {
          console.log(res)
          let filename = '报警记录导出.xls'
          let blob = new Blob([res.data], { type: res.data.type })
          //兼容ie
          if (window.navigator && window.navigator.msSaveBlob) {
            window.navigator.msSaveBlob(blob, filename)
          } else {
            var downloadElement = document.createElement('a') //模拟一个a标签与asp.net试图操作类似
            var href = window.URL.createObjectURL(blob) //转成链接让其能供人下载
            downloadElement.href = href //a标签的href
            downloadElement.download = filename //a标签的下载名字
            document.body.appendChild(downloadElement) //注册这个控件将这个组件加到body尾部
            downloadElement.click() //注销掉
            window.URL.revokeObjectURL(href) //清除生成的链接，会占用一些东西，不知道啥，反正运行慢点
          }
        })
        .catch(function (error) {
          console.log(error)
        })
    },
    handleSave() {
      this.dialogVisible = false
      this.$refs.dataConfig.saveForm()
    },
  },
  mounted() {
    // this.loadConfig()
  },
}
</script>

<style lang="scss" scoped>
.el-main {
  padding: 10px 0;
}

.el-card {
  min-height: 100%;
  height: 100%;
}

.el-header {
  padding: 0;
  box-sizing: border-box;
  flex-shrink: 0;
}

.el-card__body {
  height: 100%;
  padding: 10px;
}
</style>
