<template>
  <div class="homeBox">
    <div class="filterBox">
      <el-form
        v-show="showDiv"
        :inline="true"
        :model="formdata"
        class="demo-form-inline"
      >
        <div class="topSearch">
          <el-form-item label="线路" class="xlbox">
            <el-select
              v-model="formdata.lineId"
              @change="getSearchgt"
              filterable
            >
              <el-option
                v-for="item in xlOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
                {{ item.vname + item.name }}
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="杆塔" class="gtbox">
            <el-select v-model="formdata.towerId" filterable>
              <el-option
                v-for="item in gtOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="是否在线" class="isonLineClass">
            <el-select v-model="formdata.isonline">
              <el-option
                v-for="item in onlineOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="是否运维" class="ismntClass">
            <el-select v-model="formdata.ismntend">
              <el-option
                v-for="item in mntendOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="规约" class="gybox">
            <el-select v-model="formdata.protocolId" filterable>
              <el-option
                v-for="item in protocolOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="活动" class="activitybox">
            <el-select
              v-model="formdata.activityId"
              filterable
              @change="changeActive"
            >
              <el-option
                v-for="item in activityOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </div>
        <div class="bottomSearch">
          <el-form-item label="出厂ID" class="oidbox">
            <el-input
              v-model="formdata.oidInput"
              placeholder="请输入出厂ID"
              clearable
            ></el-input>

            <el-tooltip
              class="item"
              effect="dark"
              content="反选"
              placement="top"
            >
              <el-checkbox
                v-model="formdata.oidCheck"
                :checked="formdata.oidCheck == 1 ? true : false"
                true-label="1"
                false-label="0"
              ></el-checkbox>
            </el-tooltip>
          </el-form-item>

          <el-form-item label="装置编号" class="cmdibox">
            <el-input
              v-model="formdata.cmdidInput"
              placeholder="请输入装置编号"
              clearable
            ></el-input>
            <el-tooltip
              class="item"
              effect="dark"
              content="反选"
              placement="top"
            >
              <el-checkbox
                v-model="formdata.cmdidCheck"
                :checked="formdata.cmdidCheck == 1 ? true : false"
                true-label="1"
                false-label="0"
              ></el-checkbox>
            </el-tooltip>
          </el-form-item>

          <el-form-item label="CMA服务器" class="cmabox">
            <el-input
              v-model="formdata.cmaInput"
              placeholder="请输入CMA服务器"
              clearable
            ></el-input>
            <el-tooltip
              class="item"
              effect="dark"
              content="反选"
              placement="top"
            >
              <el-checkbox
                v-model="formdata.cmaCheck"
                :checked="formdata.cmaCheck == 1 ? true : false"
                true-label="1"
                false-label="0"
              ></el-checkbox>
            </el-tooltip>
          </el-form-item>

          <el-form-item label="版本" class="versionbox">
            <el-input
              v-model="formdata.versionInput"
              placeholder="请输入版本"
              clearable
            ></el-input>
            <el-tooltip
              class="item"
              effect="dark"
              content="反选"
              placement="top"
            >
              <el-checkbox
                v-model="formdata.versionCheck"
                :checked="formdata.versionCheck == 1 ? true : false"
                true-label="1"
                false-label="0"
              ></el-checkbox>
            </el-tooltip>
          </el-form-item>
          <el-form-item class="btngrop">
            <el-button type="primary" @click="onSubmit">查询</el-button>
            <el-button type="primary" @click="onReset">重置</el-button>
          </el-form-item>
        </div>
      </el-form>
      <el-tooltip
        class="item"
        effect="dark"
        :content="showDiv ? '收起' : '展开'"
        placement="top"
      >
        <el-button
          type="primary"
          :class="showDiv ? 'toggleClass' : 'toggleClass2'"
          :icon="showDiv ? 'el-icon-d-arrow-right' : 'el-icon-d-arrow-left'"
          circle
          @click="toggleDiv"
        ></el-button>
      </el-tooltip>
    </div>
    <div
      class="tableBox"
      :style="{ height: showDiv ? 'calc(100% - 82px)' : 'calc(100% - 2px)' }"
    >
      <tableMain
        ref="tableRef"
        :tableData="dataListNew"
        :onlineNum="onlineNum"
        :offlineNum="offlineNum"
        :noPicNum="noPicNum"
        :freeNum="freeNum"
        :tableLoaidng="tableLoaidng"
      ></tableMain>
    </div>
  </div>
</template>
<script>
import {
  getqueryLineApi,
  getqueryTermsApi,
  getqueryProtocolApi,
  getqueryActivityApi,
  getqueryCmdsApi,
} from "@/utils/api/index";
import tableMain from "./components/tableMain";
export default {
  name: "home",
  components: {
    tableMain,
  },
  data() {
    return {
      showDiv: true, // 控制div的显示与隐藏
      nowTime: new Date().getTime() / 1000,
      xlOptions: [{ id: 0, name: "全部" }], //线路数据
      gtOptions: [{ id: 0, name: "全部" }], //杆塔数据
      onlineOptions: [
        { id: -1, name: "全部" },
        { id: 1, name: "在线" },
        { id: 0, name: "离线" },
      ],
      formdata: {
        lineId: 0,
        towerId: 0,
        isonline: -1,
        protocolId: 0,
        activityId: 0,
        ismntend: 1,
        oidInput: "",
        oidCheck: 0,
        cmdidInput: "",
        cmdidCheck: 0,
        cmaInput: "",
        cmaCheck: 0,
        versionInput: "",
        versionCheck: 0,
      },
      protocolOptions: [{ id: 0, name: "全部" }], //规约
      activityOptions: [{ id: 0, name: "全部" }], //活动
      mntendOptions: [
        { id: 0, name: "全部" },
        { id: 1, name: "运维" },
        { id: 2, name: "未运维" },
      ], //是否运维
      dataList: [],
      dataListNew: [],
      tableLoaidng: true,
      onlineNum: 0, //在线数量
      offlineNum: 0, //离线数量
      noPicNum: 0, //未上传图片数量
      freeNum: 0,
      intervalId: null, // 用于存储定时器的ID
      activityIdLoc: "",
      runCommand: [], //获取命令列表
    };
  },
  created() {
    var that = this;
    document.onkeydown = function (e) {
      var key = window.event.keyCode;
      if (key === 13) {
        that.onSubmit(); // 触发事件
      }
    };
    this.activityIdLoc =
      JSON.parse(localStorage.getItem("activeId")) !== null
        ? JSON.parse(localStorage.getItem("activeId"))
        : -1;
    //this.fetchData(); // 初始化时获取数据
    //setInterval(this.fetchData, 60000); // 每10秒刷新数据
    this.formdata =
      JSON.parse(localStorage.getItem("searchParams")) !== null
        ? JSON.parse(localStorage.getItem("searchParams"))
        : {
            lineId: 0,
            towerId: 0,
            isonline: -1,
            protocolId: 0,
            activityId: 0,
            ismntend: 1,
            oidInput: "",
            oidCheck: 0,
            cmdidInput: "",
            cmdidCheck: 0,
            cmaInput: "",
            cmaCheck: 0,
            versionInput: "",
            versionCheck: 0,
          };
  },
  mounted() {
    this.getActivityList();
    this.getLineList();
    this.getprotocolList();
  },
  watch: {},
  methods: {
    //获取linelist 线路内容
    getLineList() {
      getqueryLineApi()
        .then((res) => {
          console.log(res);
          this.xlOptions = [{ id: 0, name: "全部", vname: "" }];
          this.xlOptions = this.xlOptions.concat(res.data);
          this.formdata.lineId = this.xlOptions[0].id;
        })
        .catch((err) => {});
    },
    //通过线路获取杆塔
    getSearchgt() {
      getqueryLineApi({ lineId: this.formdata.lineId })
        .then((res) => {
          this.gtOptions = [{ id: 0, name: "全部" }];
          this.gtOptions = this.gtOptions.concat(res.data);
          this.formdata.towerId = this.gtOptions[0].id;
        })
        .catch((err) => {});
    },
    //获取linelist 线路内容
    getprotocolList() {
      getqueryProtocolApi()
        .then((res) => {
          console.log(res);
          this.protocolOptions = [{ id: 0, name: "全部" }];
          this.protocolOptions = this.protocolOptions.concat(res.data);
          this.formdata.protocolId = this.protocolOptions[0].id;
        })
        .catch((err) => {});
    },
    //获取活动列表
    getActivityList() {
      getqueryActivityApi({
        act: "list",
      })
        .then((res) => {
          console.log(res);
          console.log("222222222222222");
          this.activityOptions = [{ id: 0, name: "全部" }];
          let activeArr = res.data.map((item) => ({
            id: item.id,
            name: item.title,
          }));
          this.activityOptions = this.activityOptions.concat(activeArr);
          //this.formdata.activityId = this.activityOptions[0].id;
          this.formdata.activityId =
            JSON.parse(localStorage.getItem("activeId")) !== null
              ? JSON.parse(localStorage.getItem("activeId"))
              : this.activityOptions[0].id;
          this.onSubmit();
        })
        .catch((err) => {});
    },
    changeActive(val) {
      console.log(val);
      localStorage.setItem("activeId", JSON.stringify(val));
    },
    onSubmit() {
      this.tableLoaidng = true;
      this.dataList = [];
      console.log("我是查询", this.formdata);
      localStorage.setItem("searchParams", JSON.stringify(this.formdata));
      let params = {
        lineId: this.formdata.lineId,
        towerId: this.formdata.towerId,
        isonLine: this.formdata.isonline,
      };
      var nonmntnedObj = {
        name: "mntned",
        value: this.formdata.ismntend,
        invertVal: "",
      };
      var protocolObj = {
        name: "protocol",
        value: this.formdata.protocolId,
        invertVal: 0,
      };
      var activityObj = {
        name: "activity",
        value: this.formdata.activityId,
        invertVal: 0,
      };
      var oidObj = {
        name: "oid",
        value: this.formdata.oidInput.trim(),
        invertVal: this.formdata.oidCheck,
      };
      var cmdidObj = {
        name: "cmdid",
        value: this.formdata.cmdidInput.trim(),
        invertVal: this.formdata.cmdidCheck,
      };
      var cmaObj = {
        name: "cma",
        value: this.formdata.cmaInput.trim(),
        invertVal: this.formdata.cmaCheck,
      };
      var versionObj = {
        name: "version",
        value: this.formdata.versionInput.trim(),
        invertVal: this.formdata.versionCheck,
      };
      let arrayOfObjects = [nonmntnedObj, protocolObj, activityObj];
      if (oidObj.value !== "") {
        arrayOfObjects.push(oidObj);
      }
      if (cmaObj.value !== "") {
        arrayOfObjects.push(cmaObj);
      }
      if (cmdidObj.value !== "") {
        arrayOfObjects.push(cmdidObj);
      }
      if (versionObj.value !== "") {
        arrayOfObjects.push(versionObj);
      }
      console.log(arrayOfObjects);
      for (var k = 0; k < arrayOfObjects.length; k++) {
        params["fc"] = arrayOfObjects.length;
        params["fn" + (k + 1)] = arrayOfObjects[k].name;
        params["fv" + (k + 1)] = arrayOfObjects[k].value;
        params["frev" + (k + 1)] = arrayOfObjects[k].invertVal;
      }
      console.log(params);

      // 停止之前的定时器
      if (this.intervalId) {
        clearInterval(this.intervalId);
        this.intervalId = null;
      }
      const interval = 60000; // 60000毫秒等于一分钟
      this.intervalId = setInterval(() => {
        // 在这里执行接口请求的代码
        this.fetchData();
      }, interval);
      getqueryTermsApi(params)
        .then((res) => {
          res.data = res.data.map((item) => {
            if (!item.raw_report.pic) {
              item.raw_report.pic = 0;
            }
            return item;
          });

          if (this.formdata.isonline == "-1") {
            //全部
            this.dataList = res.data;
            // console.log(this.dataList)
          } else if (this.formdata.isonline == "1") {
            //在线
            this.dataList = res.data.filter(
              (item) => this.nowTime - item.last_heartbeat_ts <= 720
            );
          } else if (this.formdata.isonline == "0") {
            //离线
            this.dataList = res.data.filter(
              (item) => this.nowTime - item.last_heartbeat_ts > 720
            );
          }
          this.onlineNum = this.dataList.filter(
            (item) => this.nowTime - item.last_heartbeat_ts <= 720
          ).length;
          this.offlineNum = this.dataList.length - this.onlineNum;
          this.noPicNum = this.dataList.filter(
            (item) =>
              item.raw_report.pic == undefined ||
              item.raw_report.pic == 0 ||
              item.raw_report.pic == -1
          ).length;
          this.freeNum = this.dataList.filter(
            (item) => parseInt(item.raw_report.msgs.freeROM) < 50
          ).length;
          console.log("我是磁盘", this.freeNum);
          this.getCmdList();
          this.tableLoaidng = false;
        })
        .catch((err) => {});
    },
    fetchData() {
      let params = {
        lineId: this.formdata.lineId,
        towerId: this.formdata.towerId,
        isonLine: this.formdata.isonline,
      };
      var nonmntnedObj = {
        name: "mntned",
        value: this.formdata.ismntend,
        invertVal: "",
      };
      var protocolObj = {
        name: "protocol",
        value: this.formdata.protocolId,
        invertVal: 0,
      };
      var activityObj = {
        name: "activity",
        value: this.formdata.activityId,
        invertVal: 0,
      };
      var oidObj = {
        name: "oid",
        value: this.formdata.oidInput,
        invertVal: this.formdata.oidCheck,
      };
      var cmdidObj = {
        name: "cmdid",
        value: this.formdata.cmdidInput,
        invertVal: this.formdata.cmdidCheck,
      };
      var cmaObj = {
        name: "cma",
        value: this.formdata.cmaInput,
        invertVal: this.formdata.cmaCheck,
      };
      var versionObj = {
        name: "version",
        value: this.formdata.versionInput,
        invertVal: this.formdata.versionCheck,
      };
      let arrayOfObjects = [nonmntnedObj, protocolObj, activityObj];
      if (oidObj.value !== "") {
        arrayOfObjects.push(oidObj);
      }
      if (cmaObj.value !== "") {
        arrayOfObjects.push(cmaObj);
      }
      if (cmdidObj.value !== "") {
        arrayOfObjects.push(cmdidObj);
      }
      if (versionObj.value !== "") {
        arrayOfObjects.push(versionObj);
      }
      console.log(arrayOfObjects);
      for (var k = 0; k < arrayOfObjects.length; k++) {
        params["fc"] = arrayOfObjects.length;
        params["fn" + (k + 1)] = arrayOfObjects[k].name;
        params["fv" + (k + 1)] = arrayOfObjects[k].value;
        params["frev" + (k + 1)] = arrayOfObjects[k].invertVal;
      }
      console.log(params);
      getqueryTermsApi(params)
        .then((res) => {
          console.log(res);
          res.data = res.data.map((item) => {
            if (!item.raw_report.pic) {
              item.raw_report.pic = 0;
            }
            return item;
          });
          if (this.formdata.isonline == "-1") {
            //全部
            this.dataList = res.data;
          } else if (this.formdata.isonline == "1") {
            //在线

            this.dataList = res.data.filter(
              (item) => this.nowTime - item.last_heartbeat_ts <= 720
            );
          } else if (this.formdata.isonline == "0") {
            //离线
            this.dataList = res.data.filter(
              (item) => this.nowTime - item.last_heartbeat_ts > 720
            );
          }
          this.onlineNum = this.dataList.filter(
            (item) => this.nowTime - item.last_heartbeat_ts <= 720
          ).length;
          this.offlineNum = this.dataList.length - this.onlineNum;
          this.noPicNum = this.dataList.filter(
            (item) =>
              item.raw_report.pic == undefined ||
              item.raw_report.pic == 0 ||
              item.raw_report.pic == -1
          ).length;
          this.freeNum = this.dataList.filter(
            (item) => parseInt(item.raw_report.msgs.freeROM) < 50
          ).length;
          console.log("我是磁盘", this.freeNum);
          this.getCmdList();
        })
        .catch((err) => {});
    },
    //获取命令列表
    getCmdList() {
      getqueryCmdsApi({ p: 1, ps: 10000 })
        .then((res) => {
          console.log(res);
          console.log("我是命令列表");
          console.log(this.dataList);
          this.runCommand = res.data;
          // let array1 = [{ id: 0, name: "sss" },{ id: 1, name: "111" }];
          // let array2 = [{ termid: 0, time: "aaaa" },{ termid: 1, time: "s1111ss" }];

          // 过滤出array1中每个对象的id
          let ids = this.dataList.map((item) => item.id);

          // 过滤出array2中termId与array1中的id相等的项
          let filteredArray2 = this.runCommand.filter((item) =>
            ids.includes(item.termId)
          );

          // 遍历array1，找到匹配的项并添加到list属性中
          this.dataList.forEach((item) => {
            let match = filteredArray2.find((i) => i.termId === item.id);
            if (match) {
              item.list = item.list || []; // 如果list属性不存在，则初始化一个空数组
              item.list.push(match);
            }
          });
          this.dataListNew = this.dataList;
          console.log(this.dataList);
        })
        .catch((err) => {});
    },
    //重置
    onReset() {
      this.formdata = {
        lineId: 0,
        towerId: 0,
        isonline: -1,
        protocolId: 0,
        activityId:
          JSON.parse(localStorage.getItem("activeId")) !== null
            ? JSON.parse(localStorage.getItem("activeId"))
            : 0,
        ismntend: 1,
        oidInput: "",
        oidCheck: 0,
        cmdidInput: "",
        cmdidCheck: 0,
        cmaInput: "",
        cmaCheck: 0,
        versionInput: "",
        versionCheck: 0,
      };

      this.onSubmit();
    },
    //展开收起
    toggleDiv() {
      this.showDiv = !this.showDiv; // 切换showDiv的值
      this.$refs.tableRef.calculateHeight(this.showDiv);
    },
  },
};
</script>
<style lang="less">
.homeBox {
  height: calc(100% - 16px);
  width: calc(100% - 24px);
  padding: 12px 12px 4px 12px;
  .filterBox {
    position: relative;
    font-size: 12px;
    .el-form-item__label {
      font-size: 12px;
    }
    .el-input__inner {
      font-size: 12px;
      padding: 0px 24px 0px 4px !important;
    }
    .el-form {
      display: flex;
      // align-items: center;
      // flex-wrap: wrap;
      flex-direction: column;
      .el-form-item {
        margin-bottom: 8px;
      }
      .topSearch {
        display: flex;
      }
      .bottomSearch {
        display: flex;
        align-items: center;

        .el-form-item--small .el-form-item__label {
          white-space: nowrap;
        }
        .btngrop {
          .el-form-item__content {
            display: flex;
            flex-wrap: nowrap;
          }
        }
      }
      .ismntClass {
        .el-select {
          width: 100px;
        }
      }
      .isonLineClass {
        .el-select {
          width: 80px;
        }
      }
      .gybox {
        .el-select {
          width: 160px;
        }
      }
      .oidbox,
      .cmdibox,
      .cmabox,
      .versionbox {
        display: flex;
        align-items: center;
        background: #e9e9e9;
        padding: 0px 12px;
        border-radius: 3px;
        .el-form-item__content {
          display: flex;
          align-items: center;
          .el-input {
            margin-right: 8px;
            width: 162px;
          }
        }
      }
      .el-form-item__label,
      .el-checkbox {
        color: #333;
      }
    }
    .toggleClass {
      position: absolute;
      right: 2px;
      top: 82px;
      .el-icon-d-arrow-left {
        transform: rotate(-90deg);
      }
      .el-icon-d-arrow-right {
        transform: rotate(-90deg);
      }
    }
    .toggleClass2 {
      position: absolute;
      right: 2px;
      top: 0px;
      .el-icon-d-arrow-left {
        transform: rotate(-90deg);
      }
      .el-icon-d-arrow-right {
        transform: rotate(-90deg);
      }
    }
  }
  .tableBox {
    //height: calc(100% - 102px);
  }
}
.el-pagination {
  color: #606262;
  font-weight: normal;
  .el-pager li.active {
    font-weight: 800;
  }
}
.el-dialog__headerbtn {
  top: 18px;
  .el-dialog__close {
    font-size: 26px;
    &:hover {
      background: #e2e2e2;
    }
  }
}
</style>
