<template>
  <div>
    <div class="table-page-search-wrapper">
      <a-form layout="inline" :model="queryParams" ref="queryForm">
        <a-row :gutter="24">
          <a-col :xl="8" :lg="7" :md="8" :sm="24">
            <a-form-item label="设备名称">
              <a-select
              v-model="queryParams.equipmentid"
              placeholder="请输入设备名称或设备编号"
              show-search
              :filterOption="filterOptions"
              @change="clearOptions"
              @search="searchDevice"
              allowClear>
                <a-select-option v-for="(item, index) in deviceOptions" :key="index" :value="item.id" :label="item.equipmentname">
                  <span>{{item.equipmentname}}</span>
                  <span style="position: absolute;right: 2%;">{{ item.equipmentcode }}</span>
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xl="4" :lg="11" :md="12" :sm="24">
            <a-form-item label="查询日期">
              <a-date-picker v-model="queryParams.date" placeholder="选择日期" style="width:100%;" @change="handleSearch" />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-button type="primary" @click="handleSearch" icon="search">查询</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>    
    <div class="trend-charts" ref="trendCharts" :style="{ height: echartsHeight + 'px', }"></div>

  </div>
</template>

<script>
import * as echarts from 'echarts'
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { httpAction, getAction } from '@/api/manage'
import { emsdata } from '@/views/module_ems/energyAnalyse/emsdata'
import { pvdata } from '../../module_ems/photovoltaic/pvdata'
export default {
  name: 'realtime',
  mixins: [JeecgListMixin, mixinDevice],
  data() {
    return {
      loading: false,
      dataSource: [],
      times: [],
      myChart: null,
      echartsHeight: window.innerHeight - 330,
      // 查询参数
      queryParams: {
        equipmentid: '',
        date: '',
      },
      url: {
        list: '/equipmentOnoff/equipmentOnoff/getEquipmentHistoryDataDefault',
        listparams: '/tpmParams/tpmParams/queryByEquipId',
      },
      deviceOptions: [],
      deviceOptionsAll: [],
      // 时间
      timeList: [],
      // 表头
      columns: [],
      equipmentparams: [{"tagname": "电流", "symbol": "CURR"},{"tagname": "电压", "symbol": "VOLT"}],
      mongodbdata: [{"logtime":"2024-02-05 07:02:00","CURR":0.3,"VOLT":230},
        {"logtime":"2024-02-05 07:03:00","CURR":0.3,"VOLT":380},
        {"logtime":"2024-02-05 07:04:00","CURR":0.3,"VOLT":340},
        {"logtime":"2024-02-05 07:05:00","CURR":0.3,"VOLT":340},
        {"logtime":"2024-02-05 07:06:00","CURR":0.2,"VOLT":380},
        {"logtime":"2024-02-05 07:07:00","CURR":0.2,"VOLT":400},
        {"logtime":"2024-02-05 07:08:00","CURR":0.2,"VOLT":390},
        {"logtime":"2024-02-05 07:09:00","CURR":0.2,"VOLT":430},
        {"logtime":"2024-02-05 07:10:00","CURR":0.2,"VOLT":480},
        {"logtime":"2024-02-05 07:11:00","CURR":0.3,"VOLT":360},
        {"logtime":"2024-02-05 07:12:00","CURR":0.3,"VOLT":340},
        {"logtime":"2024-02-05 07:13:00","CURR":0.2,"VOLT":390},
        {"logtime":"2024-02-05 07:14:00","CURR":0.3,"VOLT":360},
        {"logtime":"2024-02-05 07:15:00","CURR":0.2,"VOLT":340},
        {"logtime":"2024-02-05 07:16:00","CURR":0.2,"VOLT":370},
        {"logtime":"2024-02-05 07:17:00","CURR":0.3,"VOLT":390},
        {"logtime":"2024-02-05 07:18:00","CURR":0.3,"VOLT":340},
        {"logtime":"2024-02-05 07:19:00","CURR":0.2,"VOLT":330},
        {"logtime":"2024-02-05 07:20:00","CURR":0.3,"VOLT":320},
        {"logtime":"2024-02-05 07:21:00","CURR":0.4,"VOLT":310},
        {"logtime":"2024-02-05 07:22:00","CURR":0.2,"VOLT":351},
        {"logtime":"2024-02-05 07:23:00","CURR":0.4,"VOLT":350},
        {"logtime":"2024-02-05 07:24:00","CURR":0.4,"VOLT":330},
        {"logtime":"2024-02-05 07:25:00","CURR":0.2,"VOLT":280},
        {"logtime":"2024-02-05 07:26:00","CURR":0.4,"VOLT":290},
        {"logtime":"2024-02-05 07:27:00","CURR":0.4,"VOLT":290},
        {"logtime":"2024-02-05 07:28:00","CURR":0.4,"VOLT":290},
        {"logtime":"2024-02-05 07:29:00","CURR":0.5,"VOLT":280},
        {"logtime":"2024-02-05 07:30:00","CURR":0.4,"VOLT":270},
        {"logtime":"2024-02-05 07:31:00","CURR":0.2,"VOLT":270},
        {"logtime":"2024-02-05 07:32:00","CURR":0.4,"VOLT":270},
        {"logtime":"2024-02-05 07:33:00","CURR":0.4,"VOLT":280},
        {"logtime":"2024-02-05 07:34:00","CURR":0.3,"VOLT":310},
        {"logtime":"2024-02-05 07:35:00","CURR":0.2,"VOLT":280},
        {"logtime":"2024-02-05 07:36:00","CURR":0.3,"VOLT":250},
        {"logtime":"2024-02-05 07:37:00","CURR":0.2,"VOLT":265},
        {"logtime":"2024-02-05 07:38:00","CURR":0.3,"VOLT":270},
        {"logtime":"2024-02-05 07:39:00","CURR":0.2,"VOLT":280},
        {"logtime":"2024-02-05 07:40:00","CURR":0.4,"VOLT":280},
        {"logtime":"2024-02-05 07:41:00","CURR":0.3,"VOLT":300},
        {"logtime":"2024-02-05 07:42:00","CURR":0.4,"VOLT":300},
        {"logtime":"2024-02-05 07:43:00","CURR":0.3,"VOLT":290},
        {"logtime":"2024-02-05 07:44:00","CURR":0.3,"VOLT":290},
        {"logtime":"2024-02-05 07:45:00","CURR":0.4,"VOLT":300},
        {"logtime":"2024-02-05 07:46:00","CURR":0.5,"VOLT":300},
        {"logtime":"2024-02-05 07:47:00","CURR":0.4,"VOLT":320},
        {"logtime":"2024-02-05 07:48:00","CURR":0.3,"VOLT":340},
        {"logtime":"2024-02-05 07:49:00","CURR":0.4,"VOLT":340},
        {"logtime":"2024-02-05 07:50:00","CURR":0.4,"VOLT":360},
        {"logtime":"2024-02-05 07:51:00","CURR":0.4,"VOLT":380},
        {"logtime":"2024-02-05 07:52:00","CURR":0.4,"VOLT":400},
        {"logtime":"2024-02-05 07:53:00","CURR":0.4,"VOLT":430},
        {"logtime":"2024-02-05 07:54:00","CURR":0.3,"VOLT":430},
        {"logtime":"2024-02-05 07:55:00","CURR":0.4,"VOLT":380},
        {"logtime":"2024-02-05 07:56:00","CURR":0.4,"VOLT":350},
        {"logtime":"2024-02-05 07:57:00","CURR":0.5,"VOLT":340},
        {"logtime":"2024-02-05 07:58:00","CURR":0.5,"VOLT":360},
        {"logtime":"2024-02-05 07:59:00","CURR":0.5,"VOLT":340},
        {"logtime":"2024-02-05 08:00:00","CURR":0.5,"VOLT":340}],
    }
  },
  created() {
    this.getDeviceOption();
  },
  mounted() {
    var now = this.dateformat(new Date()).substring(0, 10)
    this.queryParams.date = now
    this.$nextTick(() => {
    })
  },
  methods: {
    // 获取设备下拉列表
    getDeviceOption(){
      getAction(`/tpmEquipment/tpmEquipment/selectEquipmentList`).then(res=>{
        this.deviceOptions = res.result.map((res) => {
          return {
            id: res.id,
            equipmentname: res.equipmentname,
            equipmentcode: res.equipmentcode,
          }
        })
        // 存一个完整的设备表
        this.deviceOptionsAll = this.deviceOptions
      })
    },
    // 筛选设备
    searchDevice(value) {
      // 若输入的值删除，则重新赋完整的设备列表
      if (value.trim().length === 0) {
        this.deviceOptions = this.deviceOptionsAll
      }
      // 通过判断字符串中是数字还是文字进而判断是通过设备名筛选还是设备编号筛选
      let panDuan = isNaN(parseFloat(value))
      if (!panDuan) {
        let filteredArray = this.deviceOptionsAll.filter(item => item.equipmentcode.includes(value));
        this.deviceOptions = filteredArray
      } else {
        let filteredArray = this.deviceOptionsAll.filter(item => item.equipmentname.includes(value));
        this.deviceOptions = filteredArray
      }
    },
    // 解决筛选后option不回显问题
    filterOptions(input, option) {
      return this.deviceOptions
    },
    // 解决筛选后删除option不回显问题
    clearOptions() {
      this.deviceOptions = this.deviceOptionsAll
    },
    dateformat(date) {
      var year = date.getFullYear()
      var month = date.getMonth() + 1
      month = month < 10 ? '0' + month : month
      var strDate = date.getDate()
      strDate = strDate < 10 ? '0' + strDate : strDate
      var hour = date.getHours()
      hour = hour < 10 ? '0' + hour : hour
      var minute = date.getMinutes()
      minute = minute < 10 ? '0' + minute : minute
      var second = date.getSeconds()
      second = second < 10 ? '0' + second : second

      return year + '-' + month + '-' + strDate + ' ' + hour + ':' + minute + ':' + second
    },
    /** 查询设备运行状态时间段列表 */
    loadData(arg) {
    },
    getList(){
      console.log("this.queryParams", this.queryParams)
      var _this = this;
      if (!this.url.list) {
        this.$message.error('请设置url.list属性!')
        return
      }
      if (!this.queryParams.equipmentid) {
        this.$message.error('请选择设备!')
        return
      }
      if (!this.queryParams.date) {
        this.$message.error('请选择查询日期!')
        return
      }
      // 获取图表信息
      getAction(_this.url.listparams, _this.queryParams).then((res) => {
        if (res.success) {
          console.log("listparams")
          _this.equipmentparams = res.result.records || res.result;
          getAction(_this.url.list, _this.queryParams).then((res) => {
          console.log("list")
            if (res.success) {
            _this.mongodbdata = [];
              _this.mongodbdata = res.result.records || res.result;
              _this.initEcharts();
            } else {
              this.$message.warning(res.message)
            }
          });
        } else {
          this.$message.warning(res.message)
        }
      });
      // this.getTest();
    },
    // 后端好了需要删掉
    getTest() {
      var _this = this
      _this.times = []
      this.initEcharts()
    },
    initEcharts() {
      var _this = this
      var chartDom = this.$refs.trendCharts

      if (_this.myChart != null && _this.myChart.dispose) {
        _this.myChart.dispose(); // 销毁实例
      }
      _this.myChart = echarts.init(chartDom)
      // _this.echartsHeight = 4 * 300;
      _this.echartsHeight = _this.equipmentparams.length > 1 ? _this.equipmentparams.length * 180 : window.innerHeight - 330;
      // 获取time
      _this.times = [];
      _this.mongodbdata.forEach((i) => {
        _this.times.push(i.logtime.substring(11, 16))
      });      

      var leftValue = '5%';
      // Grid配置
      var grid = [];
      // xAxis配置
      var xAxis = [];
      // yAxis配置
      var yAxis = [];
      // series配置
      var series1 = [];
      var paramscount = 0;
      var paramslength = _this.equipmentparams.length;
      _this.equipmentparams.forEach((item) => {
        if(paramslength === 1){
          // 只有一个时，占满屏
          grid.push({left: leftValue, top: "15%", bottom: "8%"});
        }
        if(paramslength === 2){
          // 当两个时
          grid.push({left: leftValue,top: '15%', bottom: "56%"}, {left: leftValue, top: "58%", bottom: '8%'});
        }
        // 加判断是为了最上和最下有点间距好看，也可以不判断直接用注释那句
        var firstTop = 3 // 最上面一个距离顶部占比2%
        var lastBottom = 2 // 最上面一个距离顶部占比2%
        var itemPadding = 3 // 图形之间间隔占比1%
        var itemHP = (100 - firstTop - lastBottom - itemPadding * (paramslength - 1)) / paramslength // 每一个图形占比
        if(paramscount === 0){
          grid.push({left: leftValue, top: firstTop + "%", bottom: (lastBottom + ((itemHP + itemPadding) * (paramslength - (paramscount + 1)))) + "%"});
        } else if (paramscount === (paramslength - 1)){
          grid.push({left: leftValue, top: (firstTop + (itemHP + itemPadding) * paramscount) + "%", bottom: lastBottom + "%"});
        } else {
          grid.push({left: leftValue, top: (firstTop + (itemHP + itemPadding) * paramscount) + "%", bottom: (lastBottom + (itemHP + itemPadding) * (paramslength - (paramscount + 1))) + "%"});
        }
        // grid.push({left: leftValue, top: (0.02 + paramscount / paramslength) * 100 + "%", bottom: (1.01 - (paramscount + 1) / paramslength) * 100 + "%"});;
        console.log(grid)

        xAxis.push({
          type: 'category',
          gridIndex: paramscount,
          boundaryGap: false,
          name: item.symbol,
          data: _this.times,
        });

        yAxis.push({ type: 'value', gridIndex: paramscount });

        // 获取数据
        var realtimedata = [];
        _this.mongodbdata.forEach((i) => {
          realtimedata.push(i[item.symbol])
        });
        series1.push({
          name: item.symbol,
          type: 'line',
          symbol: 'none',
          sampling: 'lttb',
          xAxisIndex: paramscount,
          yAxisIndex: paramscount,
          itemStyle: {
            color: '#91CC75',
          },
          data: realtimedata
        });

        paramscount++;
      })

      var option = {
        title: {
          left: 'left',
          text: '设备运行数据趋势预测',
        },
        legend: {
          data: ['实际值'],
        },
        grid: grid,
        xAxis: xAxis,
        yAxis: yAxis,
        series: series1
      };
      
      option && _this.myChart.setOption(option)
      setTimeout(() => {
        _this.myChart.resize()
      }, 1000)

      window.addEventListener('resize', function () {
        _this.myChart.resize()
      })
    },
    /** 搜索按钮操作 */
    handleSearch(arg) {
      console.log(1)
      this.getList(arg)
    },
  },
}
</script>

<style lang="less" scoped>
@import '~@/assets/less/uStyle.less';
</style>
<style lang="less">
.trend-charts {
  padding: 12px;
  margin-top: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
</style>
