<template>
  <div class="common-page page-t1 page-panelnbwy">
    <div class="tabCard">
      <!-- <ul class="topTab">
        <li
          v-for="(item, i) in tabData"
          :key="i"
          @click="tabTop(i), (topTabNum = i)"
          :class="{ activeTop: topTabNum == i }"
        >
          {{ item.xd }}
        </li>
      </ul> -->
      <div class="tabCon">
        <ul class="leftTab">
          <li
            v-for="(item, i) in lefttabdata"
            :key="i"
            @click="tabLeftClick(item), (leftTabNum = i)"
            :class="{ activeLeft: leftTabNum == i }"
          >
            断面{{ item }}
          </li>
        </ul>

        <div class="rightCon">
          <div id="leftChartnbwy"></div>
          <div id="rightChartnbwy"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { listChqNopage } from "@/api/project/chq";
import { listDev } from "@/api/project/device";
// import { getDepts } from '@/api/data'
// import * as echarts from "echarts";
export default {
  name: "Dashboard",

  data() {
    return {
      // 内部位移数据表格数据
      dmList: [],
      //设备列表
      devList: [],
      // 显示搜索条件
      showSearch: true,
      // 查询参数
      queryParams: {
        equipno: null,
        time: ["2022-03-01", "2022-03-07"],
        alarm: null,
      },
      data2: "",
      activeDmDevName: [],
      tableData: [],
      tabData: [],
      topTabNum: 0,
      leftTabNum: 0,
      lefttabdata: ["设备1"],
      devName: "dev",
      dmData: [],
      chartsData: [],
      noAlarmData: [], //没有报警的数据
      alarmDataNow: [{ alarm: "否" }], //报警的数据
      xData: [], //x轴时间
      yValue: [], //
      nowDM: "断面",
      ylzVal: null,
      nowDmObj: {},
      nowEquipnoAll: [],
      nowAllyValue: {},
      nowAllxValue: {},
      nowDmDivName: [],
      seriesDataNow: ["2022-03-01", "2022-03-07"],
      alarmLine: [
        { lev: "onelevelalarm", color: "#e91e63", name: "一级预警" },
        { lev: "twolevelalarm", color: "#ff5722", name: "二级预警" },
        { lev: "threelevelalarm", color: "#ffeb3b", name: "三级预警" },
        { lev: "fourlevelalarm", color: "#03a9f4", name: "四级预警" },
      ],
      lineColor: [
        "#00bcd4",
        "#2196f3",
        "#3f51b5",
        "#673ab7",
        "#9c27b0",
        "#009688",
      ],
      levelList: [],
    };
  },
  beforeCreate() {},

  created() {},
  beforeMount() {
    this.leftName();
  },
  mounted() {
    this.$nextTick(() => {
      this.dayTime();

      this.tabData = [
        {
          id: 1,
          xd: 123,
          children: [
            { dm: "断面1", jcz: 20 },
            { dm: "断面11", jcz: 21 },
            { dm: "断面12", jcz: 22 },
          ],
          dev: "dev1",
        },
        {
          id: 2,
          xd: 1230,
          children: [
            { dm: "断面21", jcz: 24 },
            { dm: "断面21", jcz: 24 },
            { dm: "断面22", jcz: 25 },
          ],
          dev: "dev2",
        },
      ];
    });
  },
  methods: {
    //封装的日期排序方法
    ReverseRankingDate(data, p) {
      for (let i = 0; i < data.length - 1; i++) {
        for (let j = 0; j < data.length - 1 - i; j++) {
          if (Date.parse(data[j][p]) > Date.parse(data[j + 1][p])) {
            var temp = data[j];
            data[j] = data[j + 1];
            data[j + 1] = temp;
          }
        }
      }
      return data;
    },
    //默认时间
    dayTime() {
      var date = new Date();
      date.getFullYear(); //获取完整的年份(4位)
      date.getMonth(); //获取当前月份(0-11,0代表1月)
      date.getDate(); //获取当前日(1-31)
      date.getHours();

      date.getMinutes();

      date.getSeconds();
      let beginTime =
        new Date().getFullYear() +
        "-" +
        (new Date().getMonth() + 1).toString().padStart(2, "0") +
        "-" +
        new Date().getDate().toString().padStart(2, "0") +
        " 00:00:00";

      let end = new Date();
      end.setTime(end.getTime());
      var endTime =
        end.getFullYear() +
        "-" +
        (end.getMonth() + 1).toString().padStart(2, "0") +
        "-" +
        end.getDate().toString().padStart(2, "0") +
        " 23:59:59";

      this.queryParams.time[0] = beginTime;
      this.queryParams.time[1] = endTime;
    },
    getAllDevList() {
      let that = this;
    },

    getList() {
      let that = this;
      // for (let i = 0; i < that.nowEquipnoAll.length; i++) {
      //   that.queryParams.equipno = that.nowEquipnoAll[i];
      // }
      // this.timeoutFalg = setTimeout(reqData.bind(this), tempTimer);

      var tempTimer = 60 * 1000;
      (function reqData() {
        let chartsAllData = {};
        let chartsAllTime = {};
        let allObj = {};
        let allArray = [];
        clearTimeout(this.timeoutFalg);

        for (let i = 0; i < that.nowEquipnoAll.length; i++) {
          let objnow = {};
          objnow.name = that.nowDmDivName[i];
          allArray.push(objnow);

          let item = that.nowEquipnoAll;
          let devNo = item[i];
          let yAxisDataAllList = chartsAllData[devNo] || [];
          let xAxisDataAllList = chartsAllTime[devNo] || [];
          that.queryParams.equipno = devNo;

          listChqNopage(this.queryParams)
            .then((response) => {
              let aaa = that.ReverseRankingDate(response.rows, "time");

              // that.dmList = aaa;
              for (let j = 0; j < aaa.length; j++) {
                yAxisDataAllList.push(aaa[j].value);
                xAxisDataAllList.push(aaa[j].time);
                chartsAllData[devNo] = yAxisDataAllList;
                chartsAllTime[devNo] = xAxisDataAllList;
                delete objnow.time;
                delete objnow.data;

                objnow.time = xAxisDataAllList;
                objnow.data = yAxisDataAllList;
              }

              that.loading = false;
            })
            .then(() => {
							
              this.timeoutFalg = setTimeout(reqData.bind(this), tempTimer);
            });
        }

        setTimeout(() => {
          console.log(allArray);
        }, 200);
      }.bind(this)());
      // this.tabLeftClick();

      // (function reqData() {
      //   clearTimeout(this.timeoutFalg);
      //   listChqNopage(this.queryParams)
      //     .then((response) => {
      //       let aaa = that.ReverseRankingDate(response.rows, "time");
      //       this.dmList = aaa;

      //       this.loading = false;
      //       console.log(aaa, "aaa");
      //     })
      //     .then(() => {

      //     })
      //     .then(() => {
      //       // clearTimeout(this.timeoutFalg);
      //       // this.rightLine();
      //       // this.leftLine();
      //     });
      // }.bind(this)());
    },
    // 去重封装
    dedupe(array) {
      return Array.from(new Set(array));
    },
    //左侧tab
    leftName() {
      listDev({ devicetype: "衬砌内应力" })
        .then((response) => {
          console.log(response.rows);
          this.devList = response.rows;
          let leftNamedata = [];
          let nowDevName = [];
          let levData = this.alarmLine;

          var duanmiuanObj = {};

          for (let i = 0; i < response.rows.length; i++) {
            var item = response.rows[i];
            console.log(item.equipname, "item");
            var duanmianno = item.duanmianno;
            var equipno = item.equipno;
            var duanmiuanList = duanmiuanObj[duanmianno] || [];
            duanmiuanList.push(equipno);
            duanmiuanObj[duanmianno] = duanmiuanList;

            nowDevName.push(item.equipname);
          }

          for (let i in duanmiuanObj) {
            leftNamedata.push(i);
          }
          console.log(leftNamedata);

          // this.lefttabdata = leftNamedata;
          this.lefttabdata = this.dedupe(leftNamedata);
          this.nowDmObj = duanmiuanObj;
          this.nowDmDivName = nowDevName;
					 this.leftLine(response.rows);
        })
        .then(() => {
          this.nowDM = this.lefttabdata[0];
        })
        .then(() => {
          this.tabLeftClick();
        })
        .then(() => {
          this.getList();
        })
        .then(() => {
          setTimeout(() => {
            this.rightLine();
            this.leftLine();
          }, 400);
        });
    },
    //点击左侧右边显示数据
    tabLeftClick(e) {
      let that = this;

      // let allData = JSON.parse(JSON.stringify(that.dmList));
      // let allNowDev = JSON.parse(JSON.stringify(that.activeDmDevName));
      let rightChartnbwy = e || that.nowDM;
      this.activeDmDevName = rightChartnbwy;
      let nowEquipno = [];

      for (let j in that.nowDmObj) {
        if (j == rightChartnbwy) {
          nowEquipno = that.nowDmObj[j];
        }
      }
      that.nowEquipnoAll = nowEquipno; //当前断面对应的设备号
      console.log(that.nowDmObj, "that.nowDmObj");
      // for (let i = 0; i < allData.length; i++) {
      //   if (allData[i].equipno == that.lefttabdata) {
      //     console.log();
      //   }
      // }

      // for (let i = 0; i < allNowDev.length; i++) {
      //   for (let j = 0; j < allData.length; j++) {}
      // }

      // if (typeof e == String) {
      //   rightChartnbwy = e;
      // } else {
      //   rightChartnbwy = that.nowDevice;
      // }
      // console.log(rightChartnbwy, "ddddd");

      // let chartData = [];
      // let alarmData = [];
      // let xAxis = [];
      // let yAxis = [];
      // that.nowDevice = rightChartnbwy;
      // for (let i = 0; i < allData.length; i++) {
      //   if (allData[i].equipname == that.nowDevice) {
      //     chartData.push(allData[i]);
      //   }
      // }
      // this.chartsData = chartData;
      // //警戒线
      // for (let i = 0; i < allNow.length; i++) {
      //   if (that.nowDevice == allNow[i].equipname) {
      //     alarmData.push(allNow[i]);
      //   }
      // }
      // this.alarmDataNow = alarmData;
      // //x y轴数据
      // for (let i = 0; i < chartData.length; i++) {
      //   xAxis.push(chartData[i].time);
      //   yAxis.push(chartData[i].value);
      // }
      // console.log(xAxis);
      // this.xData = xAxis;
      // this.yValue = yAxis;
      // for (let i = 0; i < chartData.length; i++) {
      //   if (chartData[i].alarm == "否") {
      //     that.noAlarmData.push(chartData[i]);
      //   } else {
      //     that.alarmData.push(chartData[i]);
      //   }
      // }
      // console.log(yAxis);
      // let n = yAxis.length - 1;

      // that.ylzVal = yAxis[n];
      // console.log(that.ylzVal);
      // that.leftLine();
      // that.rightLine();
    },

    tabTop(e) {
      console.log(e);
      this.leftTabNum = 0;
      this.lefttabdata = this.tabData[e].children;
      this.devName = this.tabData[e].dev;
      // this.leftLine();
      // this.rightLine();
    },

    chartTab() {},

    leftLine(rows) {
		  if(!rows || !rows[0]) return;
      console.log("leftLine");
      let that = this;

      // 基于准备好的dom，初始化echarts实例
      let leftChartnbwy = this.$echarts.init(
        document.getElementById("leftChartnbwy")
      );

      // 绘制图表
      leftChartnbwy.setOption({
        xAxis: {
          show: false,
          max: 10,
          splitLine: {
            show: false,
          },
        },
        yAxis: {
          show: false,
          max: 10,
          splitLine: {
            show: false,
          },
        },
       tooltip: {
         trigger: "item",
         formatter: function (params) {
       	var item = rows[params.componentIndex];
       	console.log(item,"item")
           let text = "设备:" + item.equipname + "<br/>应力值:" + item.initial;
           return text;
         },
       },
        series: [
          {
            name: 111,
            symbolSize: 20,
            data: [[1.2, 4.2]],
            type: "scatter",
          },
		  {
		    name: 222,
		    symbolSize: 20,
		    data: [[8.7, 4.4]],
		    type: "scatter",
		    color:'green',
		  },
          /*{
            name: device2,
            symbolSize: 20,
            data: [
                [8.8, 4.2]
            ],
            type: 'scatter'
        }*/
        ],
      });
      window.onresize = function () {
        leftChartnbwy.resize();
      };
    },
    rightLine() {
      let that = this;
      let oneAlarm = 1;
      let twoAlarm = 2;
      let threeAlarm = 3;
      let fourAlarm = 4;
      let devall = that.nowDmDivName;
      let seriesData = that.seriesDataNow;
      console.log(seriesData, "seriesData");
      let allData = JSON.parse(JSON.stringify(that.devList));
      let yAxisValue = [];
      let arrLev = [];

      console.log(seriesData, "seriesData");
      for (let j = 0; j < devall.length; j++) {
        if (devall[j] == seriesData[j].name) {
          let objLev = {};
          objLev.onelevelalarm = allData[j].onelevelalarm;
          objLev.twolevelalarm = allData[j].twolevelalarm;
          objLev.threelevelalarm = allData[j].threelevelalarm;
          objLev.fourlevelalarm = allData[j].fourlevelalarm;

          arrLev.push(objLev);
        }
        let yObj = {
          name: "检测值",
          type: "line",
          smooth: true,
          data: [1, 2],
          itemStyle: {
            normal: {
              color: that.lineColor[j], //折线点的颜色
              lineStyle: {
                color: that.lineColor[j], //折线的颜色
              },
            },
          },
          markLine: {
            silent: true,
            lineStyle: {
              color: "#333",
            },
            data: [
              {
                silent: true, //鼠标悬停事件  true没有，false有
                lineStyle: {
                  //警戒线的样式  ，虚实  颜色
                  type: "solid",
                  color: "#e91e63",
                },
                label: {
                  position: "end",
                  formatter: "一级预警",
                },
                yAxis: arrLev[j].onelevelalarm,
              },
              {
                silent: true, //鼠标悬停事件  true没有，false有
                lineStyle: {
                  //警戒线的样式  ，虚实  颜色
                  type: "solid",
                  color: "#ff5722",
                },
                label: {
                  position: "end",
                  formatter: "二级预警",
                },
                yAxis: arrLev[j].twolevelalarm,
              },
              {
                silent: true, //鼠标悬停事件  true没有，false有
                lineStyle: {
                  //警戒线的样式  ，虚实  颜色
                  type: "solid",
                  color: "#ffeb3b",
                },
                label: {
                  position: "end",
                  formatter: "三级预警",
                },
                yAxis: arrLev[j].threelevelalarm,
              },
              {
                silent: true, //鼠标悬停事件  true没有，false有
                lineStyle: {
                  //警戒线的样式  ，虚实  颜色
                  type: "solid",
                  color: "#03a9f4",
                },
                label: {
                  position: "end",
                  formatter: "四级预警",
                },
                yAxis: arrLev[j].fourlevelalarm,
              },
            ],
          },
        };
        if (devall[j] == seriesData[j].name) {
          yObj.data = seriesData[j].data;
          yObj.name = seriesData[j].name;

          yAxisValue.push(yObj);
        }
      }

      let xAxisTime = seriesData[0]["time"];
      console.log(yAxisValue, "yAxisValue");
      console.log(arrLev, "arrLev");

      let rightChartnbwy = this.$echarts.init(
        document.getElementById("rightChartnbwy")
      );
      // 绘制图表
      rightChartnbwy.setOption(
        {
          title: "",

          tooltip: {
            trigger: "axis",
          },
          grid: {
            left: "3%",
            right: "10%",
            bottom: "3%",
            containLabel: true,
          },
          legend: {
            data: that.nowDmDivName,
          },
          xAxis: {
            data: xAxisTime,
            axisLine: {
              show: true,
              onZero: false,
            },
          },
          yAxis: {
            // min: -1, // 刻度最小值
            // max: 10, // 刻度最大值（需要动态获取最大值,并且能被3整除（向下取整再乘回来））
            // splitNumber: 0, // 横线数
            // interval: 2, // 刻度间隔
          },
          series: yAxisValue,
        },
        true
      );
      setTimeout(() => {
        window.onresize = function () {
          rightChartnbwy.resize();
        };
      }, 200);
    },
  },
  beforeRouteLeave(to, form, next) {
    clearTimeout(this.timeoutFalg);
    next();
  },
};
</script>

<style rel="stylesheet/scss" lang="scss" scope>
.page-panelnbwy {
  .tabCard {
    width: 100%;
    height: calc(100vh - 90px);
    // height: calc(100vh - 130px);
    padding: 10px;
    background: #ccc;
    border: 1px solid #dcdfe6;
    box-shadow: 0 2px 4px 0 rgb(0 0 0 / 12%), 0 0 6px 0 rgb(0 0 0 / 4%);
    color: #fff;
    padding-top: 10px;
    border-sizing: border-box;
    overflow: hidden;

    ul {
      padding-left: 0;
      list-style: none;
    }
    li {
      opacity: 0.5;
      background-color: #008080;
      cursor: pointer;
      text-align: center;
    }
    li.activeTop {
      opacity: 1;
    }
    li.activeLeft {
      opacity: 1;
      border-right: 1px solid #008080;
    }

    .topTab {
      margin-left: 100px;
      border-bottom: 1px solid #008080;
      overflow: hidden;

      li {
        padding: 0px 10px;
        display: inline-block;
        margin-right: 3px;
        float: left;
        line-height: 30px;
        text-align: center;

        border-radius: 6px 6px 0 0;
      }
    }
    .leftTab {
      width: 90px;
      float: left;
      margin-right: 7px;
      li {
        width: 100%;
        // display: inline-block;
        line-height: 30px;
        margin-bottom: 2px;
      }
    }
    .rightCon {
      width: calc(100% - 100px);
      float: left;
      border: 1px solid #008080;
      min-height: 600px;
    }
    #leftChartnbwy {
      width: 534px;
      height: 600px;
      border: 1px solid #fff;
      background: url("~@/assets/images/kuangdao.png") no-repeat;
      background-size: contain;
      float: left;
    }
    #rightChartnbwy {
      width: calc(100% - 534px);
      height: 562px;
      float: left;
    }
  }
}
</style>
