<template>
  <div class="searchPage1">
    <div class="query mg-b-8">
      <div class="query-items">
        <div class="query-item">
          <div class="lable">日期：</div>
          <div class="search-input">
            <el-date-picker size="medium" v-model="form.dateArea" type="datetimerange" :picker-options="pickerOptions" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" align="right"> </el-date-picker>
          </div>
        </div>
        <div class="query-item">
          <div class="lable">间隔：</div>
          <div class="search-input">
            <el-input v-model="form.interval" type="number" ></el-input>
          </div>
        </div>
        <div class="query-item">
          <div class="lable">间隔：</div>
          <div class="search-input">
            <el-checkbox v-model="form.autoReq" label="刷新" :border="true"></el-checkbox>
          </div>
        </div>
        <div class="query-item">
          <div class="lable"></div>
          <div class="search-input">
            <transition name="el-zoom-in-center">
              <el-radio-group v-model="form.type" size="small" v-show="form.interval">
                <el-radio label="0" @click.prevent="getRadio('0')">最大</el-radio>
                <el-radio label="1" @click.prevent="getRadio('1')">最小</el-radio>
                <el-radio label="2" @click.prevent="getRadio('2')">平均</el-radio>
              </el-radio-group>
            </transition>
          </div>
        </div>
      </div>
      <div class="query-actions">
        <button class="btn green" @click="renderCharts">生成曲线</button>
      </div>
    </div>
    <div class="cardBox">
      <el-card class="box-card">
        <template v-slot:header class="clearfix">
          <span>类型</span>
          <!-- <el-button style="float: right; padding: 3px 0" type="text">操作按钮</el-button> -->
        </template>
        <div>
          <el-radio-group
            v-model="form.fjType"
            size="small"
            @change="
              (fjType) => {
                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">
        <template v-slot:header class="clearfix">
          <span>设备结构</span>
        </template>
        <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">
        <template v-slot:header class="clearfix">
          <span>关键参数</span>
        </template>
        <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 * 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: [
        {
          id: 1,
          label: "一级 2",
          children: [
            {
              id: 3,
              label: "二级 2-1",
              children: [
                {
                  id: 4,
                  label: "三级 3-1-1",
                },
                {
                  id: 5,
                  label: "三级 3-1-2",
                  disabled: true,
                },
              ],
            },
            {
              id: 2,
              label: "二级 2-2",
              disabled: true,
              children: [
                {
                  id: 6,
                  label: "三级 3-2-1",
                },
                {
                  id: 7,
                  label: "三级 3-2-2",
                  disabled: true,
                },
              ],
            },
          ],
        },
      ],
      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({
        baseURL: "http://10.155.32.4:8031/",
        subUrl: "paramComparison/equipmentStructure",
        timeout: 30000,
        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({
        baseURL: "http://10.155.32.4:8031/",
        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 ? new Date(that.form.dateArea[0]).formatDate("yyyy-MM-dd hh:mm:ss") : "";
        let end = that.form.dateArea.length ? new Date(that.form.dateArea[1]).formatDate("yyyy-MM-dd hh:mm:ss") : "";
        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({
            baseURL: "http://10.155.32.4:8031/",
            subUrl: "paramComparison/generatingCurve",
            timeout: 10000,
            data,
            success(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 {
                that.BASE.showMsg({
                  type: "warning",
                  msg: "所选参数暂无数据，请切换参数后再次尝试",
                });
              }
            },
          });
        } else {
          that.BASE.showMsg({
            msg: "无法生成，请检查 日期、设备结构与关键参数是否已选择",
          });
        }
      });
    },

    // 过滤树形节点
    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="less" scoped>
.searchBox1 {
  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;
  margin-top: 20px;

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

    .treeBox {
      width: 100%;

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

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

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

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