<template>
  <div class="searchPage">
    <div class="searchBox">
      <el-form ref="form" :model="form" inline label-width="80px">
        <el-form-item label="日期：">
          <el-date-picker size="medium" value-format="yyyy-MM-dd HH:mm:ss" v-model="form.dateArea" type="datetimerange"
            :picker-options="pickerOptions" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" align="right">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="间隔：">
          <el-input placeholder="请输入间隔" clearable v-model="form.interval" type="number"></el-input>
        </el-form-item>
        <transition name="el-zoom-in-center">
          <el-form-item v-show="form.interval" label=" ">
            <el-radio-group v-model="form.type" size="small">
              <el-radio label="0" @click.native.prevent="getRadio('0')">最大</el-radio>
              <el-radio label="1" @click.native.prevent="getRadio('1')">最小</el-radio>
              <el-radio label="2" @click.native.prevent="getRadio('2')">平均</el-radio>
            </el-radio-group>
          </el-form-item>
        </transition>
      </el-form>
      <div class="btnBox">
        <el-button type="primary" size="middle" @click="renderCharts">查询</el-button>
      </div>
    </div>
    <div class="cardBox">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>类型</span>
          <!-- <el-button style="float: right; padding: 3px 0" type="text">操作按钮</el-button> -->
        </div>
        <div>
          <el-radio-group v-model="form.fjType" size="small" @change="(fjType) => { this.resetForm(); }">
            <el-form ref="form" :model="form">
              <el-form-item style="margin-bottom:5px;">
                <el-radio border size="medium" label="1">单风机多参数对比</el-radio>
              </el-form-item>
              <el-form-item style="margin-bottom:5px;">
                <el-radio border size="medium" label="2">多风机单参数对比</el-radio>
              </el-form-item>
            </el-form>
          </el-radio-group>
        </div>
      </el-card>
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>设备结构</span>
        </div>
        <div>
          <div class="treeBox">
            <el-input size="small" placeholder="输入以检索" :disabled="!treeData.length" v-model="filterText"></el-input>
            <el-tree ref="treeRef" node-key="id" :data="treeData" :props="treeProps" :show-checkbox="true"
              :highlight-current="true" :filter-node-method="filterNode" @check-change="getTreeChecked"></el-tree>
          </div>
        </div>
      </el-card>
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>关键参数</span>
        </div>
        <div class="selectBox treeBox">
          <el-input size="small" placeholder="输入以检索" :disabled="!gjcsOptions.length" v-model="filterText1"></el-input>
          <el-tree ref="treeRef1" node-key="code" :data="gjcsOptions" :props="{children: null, label: 'description'}"
            :show-checkbox="true" :highlight-current="true" :filter-node-method="filterNode1" @check-change="getTreeChecked1"></el-tree>
          <!-- <el-select style="width:100%;" v-model="form.gjcs" filterable clearable :multiple="!treeIsMultiple"
            placeholder="输入以检索" @change="(res) => { this.$forceUpdate(); }">
            <el-option v-for="item in gjcsOptions" :key="item.id" :label="item.description" :value="item.code">
            </el-option>
          </el-select> -->
        </div>
      </el-card>
    </div>
    <div class="chartsBox">
      <div id="lineChart" style="width:100%;height:100%;"></div>
    </div>
  </div>
</template>

<script>
import { Message } from 'element-ui';
import * as echarts from "echarts";

export default {
  data () {
    return {
      form: {
        pointId: "",
        pointName: "",
        autoReq: false,
        dateArea: [
          this.fmtDate(new Date(new Date().setTime(new Date().getTime() - 3600 * 1000 * 24))),
          this.fmtDate(new Date())
        ],
        interval: "",
        type: "",
        fjType: "1",
        gjcs: ''
      },

      treeIsMultiple: false,
      filterText: "",
      filterText1: "",

      treeData: [],
      gjcsOptions: [],

      treeProps: {
        children: 'children',
        label: 'label'
      },

      pickerOptions: {
        shortcuts: [{
          text: '最近一天',
          onClick (picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一周',
          onClick (picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick (picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick (picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      }
    }
  },

  mounted () {
    let that = this;
    that.$nextTick(() => {
      that.getEquipmentStructure();
      that.getEquipmentParams();
    });
  },

  methods: {
    // 获取设备结构
    getEquipmentStructure () {
      let that = this;
      that.API.requestData({
        subUrl: "paramComparison/equipmentStructure",
        success (res) {
          // 请求成功的回调
          let treeData = [];

          res.data.forEach(ele => {
            let findRes = treeData.find(findEle => {
              return ele.windpowerstationid === findEle.label;
            });
            if (!findRes) {
              let treeTemp = {
                label: ele.windpowerstationid,
                children: []
              };
              treeTemp.children.push({
                label: ele.name,
                id: ele.id
              });
              treeData.push(treeTemp);
            } else {
              findRes.children.push({
                label: ele.name,
                id: ele.id
              });
            }
          });
          that.treeData = treeData;
        }
      });
    },

    // 获取关键节点
    getEquipmentParams () {
      let that = this;
      that.API.requestData({
        subUrl: "paramComparison/equipmentParams",
        success (res) {
          that.gjcsOptions = res.data;
        }
      });
    },

    // 获取单选结果
    getRadio (type) {
      if (type === this.form.type && this.form.type !== '') {
        this.form.type = '';
      } else {
        this.form.type = type;
      }
    },

    // 渲染图表
    renderCharts () {
      let that = this;
      that.$nextTick(() => {

        let begin = that.form.dateArea.length ? that.form.dateArea[0] : '';
        let end = that.form.dateArea.length ? that.form.dateArea[1] : '';
        let interval = that.form.interval;
        let type = that.form.type;
        let paramtype = that.form.fjType;
        let wts = [];
        let wtsArray = that.$refs.treeRef.getCheckedNodes();
        let params = [];
        let paramsArray = that.$refs.treeRef1.getCheckedNodes();
        // let params = that.form.gjcs;

        wtsArray.forEach(pEle => {
          if (pEle.id) {
            wts.push(pEle.id);
          } else {
            pEle.children.forEach(cEle => {
              wts.push(cEle.id);
            });
          }
        });

        paramsArray.forEach(pEle => {
          params.push(pEle.code);
        });

        let data = {};
        data.begin = begin;
        data.end = end;
        interval && (data.interval = interval);
        type && (data.type = type);
        data.paramtype = paramtype;
        data.wts = wts.toString();
        data.params = params.toString();

        if (begin && end && paramtype && wts.length && params.length) {
          that.API.requestData({
            subUrl: "paramComparison/generatingCurve",
            timeout: 30000,
            data,
            success (res) {
              console.log('res', res);

              if (res.data.length) {

                let xAxisData = []; // x轴标题
                let seriesData = []; // 折线图数据

                let keyArray = [];

                if (that.form.fjType === '1') {
                  params.forEach(ele => {
                    let findRes = that.gjcsOptions.find(findEle => {
                      return ele === findEle.code;
                    });
                    keyArray.push(findRes.description);
                  });
                } else {
                  wtsArray.forEach(pEle => {
                    if (pEle.id) {
                      keyArray.push(pEle.label);
                    } else {
                      pEle.children.forEach(cEle => {
                        keyArray.push(cEle.label);
                      });
                    }
                  });
                }

                keyArray.forEach(ele => {
                  seriesData.push({
                    data: [],
                    type: 'line',
                    smooth: true,
                    name: ele
                  });
                });

                res.data.forEach(pEle => {
                  xAxisData.push(that.fmtDate(new Date(pEle.time)));
                  keyArray.forEach((cEle, cIndex) => {
                    seriesData[cIndex].data.push((pEle[cEle] || null));
                  });
                });

                document.getElementById("lineChart").removeAttribute("_echarts_instance_");
                let chartDom = document.getElementById('lineChart');
                let myChart = echarts.init(chartDom);
                let option = {
                  xAxis: {
                    type: 'category',
                    data: xAxisData
                  },
                  yAxis: {
                    type: 'value'
                  },
                  series: seriesData,
                  tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                      type: 'cross',
                      label: {
                        backgroundColor: '#6a7985'
                      }
                    }
                  }
                };
                option && myChart.setOption(option);

              } else {
                Message.warning("所选参数暂无数据，请切换参数后再次尝试");
              }
            }
          });
        } else {
          Message.error("无法查询，请检查 日期、设备结构与关键参数是否已选择");
        }

      });
    },

    // 过滤树形节点
    filterNode (value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },

    // 过滤树形节点
    filterNode1 (value, data) {
      if (!value) return true;
      return data.description.indexOf(value) !== -1;
    },

    // 获取树形选中
    getTreeChecked (data, checked, node) {
      if (!this.treeIsMultiple) {
        if (checked === true) {
          this.checkedId = data.id;
          this.$refs.treeRef.setCheckedKeys([data.id]);
        } else {
          if (this.checkedId == data.id) {
            this.$refs.treeRef.setCheckedKeys([]);
          }
        }
      }
    },

    // 获取树形选中
    getTreeChecked1 (data, checked, node) {
      if (this.treeIsMultiple) {
        if (checked === true) {
          this.checkedId = data.code;
          this.$refs.treeRef1.setCheckedKeys([data.code]);
        } else {
          if (this.checkedId == data.code) {
            this.$refs.treeRef1.setCheckedKeys([]);
          }
        }
      }
    },

    // 重置表单
    resetForm () {
      this.form.fjType === '1' ? this.treeIsMultiple = false : this.treeIsMultiple = true;
      this.$refs.treeRef.setCheckedKeys([]);
      this.$refs.treeRef1.setCheckedKeys([]);
      this.form.gjcs = '';
      this.$forceUpdate();
      document.getElementById("lineChart").removeAttribute("_echarts_instance_");
      echarts.init(document.getElementById('lineChart'));
    },

    // 格式化日期
    fmtDate (date) {
      let curDate = date || new Date();
      let year = curDate.getFullYear();
      let mouth = curDate.getUTCMonth() + 1;
      let day = curDate.getDate();
      let hour = curDate.getHours();
      let minutes = curDate.getMinutes();
      let seconds = curDate.getSeconds();
      return year + '-' + (mouth < 10 ? '0' + mouth : mouth) + '-' + (day < 10 ? '0' + day : day) + ' ' + (hour < 10 ? '0' + hour : hour) + ':' + (minutes < 10 ? '0' + minutes : minutes) + ':' + (seconds < 10 ? '0' + seconds : seconds);
    }
  },

  watch: {
    filterText (val) {
      this.$refs.treeRef.filter(val);
    },

    filterText1 (val) {
      this.$refs.treeRef1.filter(val);
    }
  },
}
</script>
<style lang="scss" scoped>
.searchBox {
  width: 80%;
  display: flex;
  justify-content: start;
  align-items: center;
  position: relative;

  .btnBox {
    position: absolute;
    left: calc(100% + 60px);
    top: 0;
    display: flex;
    justify-content: start;
    align-items: center;
  }

  .el-input {
    width: 150px;
  }
}

.cardBox {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .el-card {
    width: 32%;
    height: 255px;

    .treeBox {
      width: 100%;

      .el-tree {
        width: 100%;
        height: 160px;
        margin-top: 10px;
        overflow-y: scroll;

        &::-webkit-scrollbar {
          width: 6px;
          height: 6px;
          background: #fff;
        }

        &::-webkit-scrollbar-track {
          border-radius: 5px;
          background: #fff;
        }

        &::-webkit-scrollbar-thumb {
          border-radius: 10px;
          background: rgba(144, 147, 153, 0.3);
        }
      }
    }
  }
}

.selectBox {
  .el-select {
    max-height: 150px;
    overflow-y: scroll;

    &::-webkit-scrollbar {
      width: 6px;
      height: 6px;
      background: #fff;
    }

    &::-webkit-scrollbar-track {
      border-radius: 5px;
      background: #fff;
    }

    &::-webkit-scrollbar-thumb {
      border-radius: 10px;
      background: rgba(144, 147, 153, 0.3);
    }
  }
}

.chartsBox {
  width: 100%;
  height: 400px;
}
</style>
<style lang="scss">
.cardBox {
  .el-card__header {
    padding: 5px 20px;
  }

  .el-card__body {
    padding: 10px 20px;
  }
}
</style>
