<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="dybox">
            <el-select v-model="formdata.dyId" @change="getSearchxl" filterable>
              <el-option
                v-for="item in dyOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <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"
              >
              </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.mntn">
              <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.protocol" filterable>
              <el-option
                v-for="item in protocolOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
                {{ item.name }}-{{ 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.oid"
              placeholder="请输入出厂ID"
              clearable
            ></el-input>

            <el-tooltip
              class="item"
              effect="dark"
              content="反选"
              placement="top"
            >
              <el-checkbox
                v-model="formdata.oidExclude"
                :checked="formdata.oidExclude == 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.cmdid"
              placeholder="请输入装置编号"
              clearable
            ></el-input>
            <el-tooltip
              class="item"
              effect="dark"
              content="反选"
              placement="top"
            >
              <el-checkbox
                v-model="formdata.cmdidExclude"
                :checked="formdata.cmdidExclude == 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.cma"
              placeholder="请输入CMA服务器"
              clearable
            ></el-input>
            <el-tooltip
              class="item"
              effect="dark"
              content="反选"
              placement="top"
            >
              <el-checkbox
                v-model="formdata.cmaExclude"
                :checked="formdata.cmaExclude == 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.version"
              placeholder="请输入版本"
              clearable
            ></el-input>
            <el-tooltip
              class="item"
              effect="dark"
              content="反选"
              placement="top"
            >
              <el-checkbox
                v-model="formdata.versionExclude"
                :checked="formdata.versionExclude == 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 {
  cmdActlistApi,
  getTerminalJoggle,
  getActivityApi,
  getProtocolList,
  getSearchInfo,
  exportTerminalApi,
} from "@/utils/api/index";
import tableMain from "./components/tableMain";
export default {
  name: "home",
  components: {
    tableMain,
  },
  data() {
    return {
      showDiv: true, // 控制div的显示与隐藏

      dyOptions: [{ id: -1, name: "全部" }], //电压数据
      xlOptions: [{ id: -1, name: "全部" }], //线路数据
      gtOptions: [{ id: -1, name: "全部" }], //杆塔数据
      onlineOptions: [
        { id: -1, name: "全部" },
        { id: 1, name: "在线" },
        { id: 0, name: "离线" },
      ],
      protocolOptions: [{ id: -1, name: "全部" }], //规约数据
      activityOptions: [{ id: -1, name: "全部" }], //活动
      mntendOptions: [
        { id: -1, name: "全部" },
        { id: 1, name: "运维" },
        { id: 2, name: "未运维" },
      ], //是否运维
      formdata: {
        dyId: -1,
        lineId: -1,
        towerId: -1,
        isonline: -1,
        protocol: -1,
        mntn: 1,
        activityId: -1,
        oid: "",
        oidExclude: 0,
        cmdid: "",
        cmdidExclude: 0,
        cma: "",
        cmaExclude: 0,
        version: "",
        versionExclude: 0,
      },

      dataList: [],
      dataListNew: [],
      tableLoaidng: true,
      onlineNum: 0, //在线数量
      offlineNum: 0, //离线数量
      noPicNum: 0, //未上传图片数量
      freeNum: 0,
      intervalId: null, // 用于存储定时器的ID
      activityIdLoc: "",
      runCommand: [], //获取命令列表
    };
  },
  created() {
    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"))
        : {
            dyId: -1,
            lineId: -1,
            towerId: -1,
            isonline: -1,
            protocol: -1,
            mntn: 1,
            activityId: -1,
            oid: "",
            oidExclude: 0,
            cmdid: "",
            cmdidExclude: 0,
            cma: "",
            cmaExclude: 0,
            version: "",
            versionExclude: 0,
          };
  },
  mounted() {
    this.getSearchdy();
    this.getProtocol();
    this.getactiveList();
  },
  watch: {},
  methods: {
    //导出数据
    exportTable() {
      let params = {
        pageindex: 1,
        pagesize: 10000,
      };
      // 根据条件添加参数
      if (this.formdata.dyId !== -1) {
        params.dyId = this.formdata.dyId;
      }
      if (this.formdata.lineId !== -1) {
        params.lineId = this.formdata.lineId;
      }
      if (this.formdata.towerId !== -1) {
        params.towerId = this.formdata.towerId;
      }
      if (this.formdata.isonline !== -1) {
        params.isonline = this.formdata.isonline;
      }
      if (this.formdata.protocol !== -1) {
        params.protocol = this.formdata.protocol;
      }
      if (this.formdata.mntn !== -1) {
        params.mntn = this.formdata.mntn;
      }
      if (this.formdata.activityId !== -1) {
        params.activityId = this.formdata.activityId;
      }

      if (this.formdata.oid !== "") {
        params.oid = this.formdata.oid;
      }
      console.log(this.formdata.oidExclude);
      if (this.formdata.oidExclude !== 0) {
        params.oidExclude = this.formdata.oidExclude;
      }
      if (this.formdata.cma !== "") {
        params.cma = this.formdata.cma;
      }
      if (this.formdata.cmaExclude !== 0) {
        params.cmaExclude = this.formdata.cmaExclude;
      }
      if (this.formdata.cmdid !== "") {
        params.cmdid = this.formdata.cmdid;
      }
      if (this.formdata.cmdidExclude !== 0) {
        params.cmdidExclude = this.formdata.cmdidExclude;
      }
      if (this.formdata.version !== "") {
        params.version = this.formdata.version;
      }
      if (this.formdata.versionExclude !== 0) {
        params.versionExclude = this.formdata.versionExclude;
      }
      console.log(params);
      exportTerminalApi(params)
        .then((res) => {
          console.log(res);
          const now = this.$moment(new Date());
          const formattedTime = now.format("YYYY年MM月DD日HH时mm分"); // 格式化时间字符串，例如 "2023-04-01_15_30_00"
          const blob = new Blob([res]);
          const link = document.createElement("a");
          link.href = window.URL.createObjectURL(blob);
          link.download = `运维数据报表_${formattedTime}.xls`;
          link.click();
        })
        .catch((err) => {});
    },
    //获取电压信息
    getSearchdy() {
      getSearchInfo({ type: 1 })
        .then((res) => {
          this.dyOptions = this.dyOptions.concat(res.data.list);
          console.log(this.dyOptions);
          this.formdata.dyId = this.dyOptions[0].id;
          this.getSearchxl();
        })
        .catch((err) => {});
    },
    //获取线路数据
    getSearchxl() {
      getSearchInfo({ type: 2, id: this.formdata.dyId })
        .then((res) => {
          this.xlOptions = [{ id: -1, name: "全部" }];
          this.xlOptions = this.xlOptions.concat(res.data.list);
          this.formdata.lineId = this.xlOptions[0].id;
          this.getSearchgt();
        })
        .catch((err) => {});
    },
    //获取杆塔数据
    getSearchgt() {
      getSearchInfo({ type: 3, id: this.formdata.lineId })
        .then((res) => {
          this.gtOptions = [{ id: -1, name: "全部" }];
          this.gtOptions = this.gtOptions.concat(res.data.list);
          this.formdata.towerId = this.gtOptions[0].id;
        })
        .catch((err) => {});
    },
    getProtocol() {
      //获取规约版本
      getProtocolList()
        .then((res) => {
          console.log(res);
          this.protocolOptions = this.protocolOptions.concat(res.data.list);
          this.formdata.protocol = this.protocolOptions[0].id;
        })
        .catch((err) => {});
    },
    //获取活动列表
    getactiveList() {
      getActivityApi()
        .then((res) => {
          console.log(res);
          // this.activityOptions = this.activityOptions.concat(res.data.list);
          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 = [];
      // 停止之前的定时器
      if (this.intervalId) {
        clearInterval(this.intervalId);
        this.intervalId = null;
      }
      this.fetchData();
      const interval = 60000; // 60000毫秒等于一分钟
      this.intervalId = setInterval(() => {
        // 在这里执行接口请求的代码
        this.fetchData();
      }, interval);
    },
    fetchData() {
      let params = {
        pageindex: 1,
        pagesize: 10000,
      };
      // 根据条件添加参数
      if (this.formdata.dyId !== -1) {
        params.dyId = this.formdata.dyId;
      }
      if (this.formdata.lineId !== -1) {
        params.lineId = this.formdata.lineId;
      }
      if (this.formdata.towerId !== -1) {
        params.towerId = this.formdata.towerId;
      }
      if (this.formdata.isonline !== -1) {
        params.isonline = this.formdata.isonline;
      }
      if (this.formdata.protocol !== -1) {
        params.protocol = this.formdata.protocol;
      }

      if (this.formdata.mntn !== -1) {
        params.mntn = this.formdata.mntn;
      }
      if (this.formdata.activityId !== -1) {
        params.activityId = this.formdata.activityId;
      }

      if (this.formdata.oid !== "") {
        params.oid = this.formdata.oid;
      }
      console.log(this.formdata.oidExclude);
      if (Number(this.formdata.oidExclude) !== 0) {
        params.oidExclude = this.formdata.oidExclude;
      }
      if (this.formdata.cma !== "") {
        params.cma = this.formdata.cma;
      }
      if (Number(this.formdata.cmaExclude) !== 0) {
        params.cmaExclude = this.formdata.cmaExclude;
      }
      if (this.formdata.cmdid !== "") {
        params.cmdid = this.formdata.cmdid;
      }
      if (Number(this.formdata.cmdidExclude) !== 0) {
        params.cmdidExclude = this.formdata.cmdidExclude;
      }
      if (this.formdata.version !== "") {
        params.version = this.formdata.version;
      }
      if (Number(this.formdata.versionExclude) !== 0) {
        params.versionExclude = this.formdata.versionExclude;
      }
      console.log(params);
      localStorage.setItem("searchParams", JSON.stringify(params));
      getTerminalJoggle(params)
        .then((res) => {
          console.log(res);
          this.dataList = res.data;
          this.getCmdList();
          this.onlineNum = this.dataList.filter(
            (item) => item.onlinestatus == 1
          ).length;
          this.offlineNum = this.dataList.length - this.onlineNum;
          this.tableLoaidng = false;
          this.noPicNum = this.dataList.filter(
            (item) =>
              item.mntnStatus.reportMap == null ||
              item.mntnStatus.reportMap.pic == undefined ||
              item.mntnStatus.reportMap.pic == 0 ||
              item.mntnStatus.reportMap.pic == -1
          ).length;

          this.freeNum = this.dataList.filter((item) => {
            // 确保mntnStatus和reportMap存在，并且freeROM不是null或undefined
            const freeROM = item.mntnStatus?.reportMap?.freeROM;
            // 如果freeROM存在并且可以被转换为数字
            if (
              freeROM !== null &&
              freeROM !== undefined &&
              !isNaN(parseInt(freeROM, 10))
            ) {
              // 转换为整数并检查是否小于50
              return parseInt(freeROM, 10) < 50;
            }
            // 如果freeROM不存在或不是数字，则忽略此项
            return false;
          }).length;

          console.log("我已经加载完数据");
        })
        .catch((err) => {});
    },
    //获取命令列表
    getCmdList() {
      cmdActlistApi({ p: 1, ps: 10000 })
        .then((res) => {
          console.log(res);
          console.log("我是命令列表");
          console.log(this.dataList);
          this.runCommand = res.data.list;
          // 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.dataListNew);
        })
        .catch((err) => {});
    },
    //重置
    onReset() {
      this.formdata = {
        dyId: -1,
        lineId: -1,
        towerId: -1,
        isonline: -1,
        protocol: -1,
        mntn: 1,
        activityId: -1,
        oid: "",
        oidExclude: 0,
        cmdid: "",
        cmdidExclude: 0,
        cma: "",
        cmaExclude: 0,
        version: "",
        versionExclude: 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;
          }
        }
      }
      .dybox {
        .el-select {
          width: 120px;
        }
      }
      .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;
          }
        }
      }
      .cmdibox {
        background: #d0ece8;
      }
      .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>
