<template>
  <div class="photoStatisBox" ref="statisRef">
    <div class="searchBox" ref="searchref" v-if="drawerSearch">
      <el-form :inline="true" :model="formdata" class="demo-form-inline">
        <el-form-item label="电压等级" class="dyclass">
          <el-select v-model="formdata.dyid" @change="getSearchxl">
            <el-option
              v-for="item in dyOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
              {{ item.name }}
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="线路名称" class="xlclass">
          <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="gtclass">
          <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="tdclass">
          <el-select v-model="formdata.channelid">
            <el-option
              v-for="item in tdOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="活动"
          class="activitybox"
          v-if="roleName === 'superadmin' || roleName === 'Matthew'"
        >
          <el-select
            @keyup.enter.native="onSubmit()"
            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>
        <el-form-item label="开始日期" class="dateclass">
          <el-date-picker
            v-model="formdata.starttime"
            type="datetime"
            placeholder="开始日期"
            value-format="timestamp"
            :picker-options="pickerOptions"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束日期" class="dateclass">
          <el-date-picker
            v-model="formdata.endtime"
            type="datetime"
            placeholder="结束日期"
            value-format="timestamp"
            :picker-options="pickerOptions"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="装置查询" class="schclass">
          <el-input
            v-model="formdata.search"
            placeholder="请输入线路/杆塔/设备名称"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item class="onsubBtn">
          <el-button type="primary" @click="onSubmit">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="deviceTable">
      <el-table
        v-loading="photoLoading"
        ref="multipleTable"
        :data="photoList"
        tooltip-effect="dark"
        stripe
        style="width: 100%"
        :height="tableheight"
        fit
        :default-sort="{ order: 'descending' }"
      >
        <template slot="empty">
          <el-empty :image-size="160" description="暂无数据"></el-empty>
        </template>
        <el-table-column label="序号" width="50px">
          <template slot-scope="scope">
            {{ (page - 1) * pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <!-- <el-table-column prop="id" label="ID" width="80px"> </el-table-column> -->
        <el-table-column prop="dyName" label="电压等级" sortable>
        </el-table-column>
        <el-table-column
          prop="lineName"
          label="线路名称"
          show-overflow-tooltip
          sortable
        >
        </el-table-column>
        <el-table-column
          prop="towerName"
          label="杆塔名称"
          min-width="180"
          show-overflow-tooltip
          sortable
        >
        </el-table-column>
        <el-table-column
          prop="cmdid"
          label="装置id"
          min-width="140"
          show-overflow-tooltip
          sortable
        >
          <template slot-scope="scope">
            <el-link
              type="primary"
              @click.native.stop="handleShowPhoto(scope.row)"
            >
              {{ scope.row.cmdid }}</el-link
            ></template
          >
        </el-table-column>
        <el-table-column
          prop="protocolName"
          label="规约"
          show-overflow-tooltip
          sortable
        >
        </el-table-column>
        <el-table-column
          prop="lastHeartbeat"
          label="最后心跳时间"
          min-width="130"
          show-overflow-tooltip
          sortable
        >
          <template slot-scope="scope">
            <el-link
              type="primary"
              @click.native.stop="handleShowIp(scope.row)"
            >
              {{
                scope.row.lastHeartbeat == 0 || scope.row.lastHeartbeat == null
                  ? ""
                  : $moment(scope.row.lastHeartbeat * 1000).format(
                      "YYYY-MM-DD HH:mm:ss"
                    )
              }}</el-link
            ></template
          >
        </el-table-column>
        <el-table-column
          prop="firstPhotoTime"
          label="当天第一张照片时间"
          min-width="130"
          show-overflow-tooltip
          sortable
          :sort-method="sortfirstTime"
        >
          <template slot-scope="scope">
            {{ scope.row.photoInfo.firstPhotoTime }}
          </template>
        </el-table-column>
        <el-table-column
          prop="lastPhotoTime"
          label="照片最后拍摄时间"
          min-width="130"
          show-overflow-tooltip
          sortable
          :sort-method="sortlastPhotoTime"
        >
          <template slot-scope="scope">
            {{ scope.row.photoInfo.lastPhotoTime }}
          </template>
        </el-table-column>
        <el-table-column
          prop="lastRecvTime"
          label="照片最后接收时间"
          min-width="130"
          show-overflow-tooltip
          sortable
          :sort-method="sortRecvTime"
        >
          <template slot-scope="scope">
            {{ scope.row.photoInfo.lastRecvTime }}
          </template>
        </el-table-column>
        <el-table-column prop="rebootCount" label="重启次数" sortable>
        </el-table-column>
        <el-table-column
          prop="workingStatus.bootTime"
          label="最后重启时间"
          min-width="130"
          show-overflow-tooltip
          sortable
        >
          <template slot-scope="scope">
            {{ formatLastHeartbeat(scope.row.workingStatus.bootTime) }}
            <!-- {{
              scope.row.workingStatus.bootTime == null ||
              scope.row.workingStatus.bootTime == 0
                ? ""
                : $moment(scope.row.workingStatus.bootTime * 1000).format(
                    "YYYY-MM-DD HH:mm:ss"
                  )
            }} -->
          </template>
        </el-table-column>
        <el-table-column
          prop="photoCount"
          label="照片数量"
          sortable
          :sort-method="picSort"
        >
          <template slot-scope="scope">
            <el-link
              type="primary"
              @click.native.stop="handleShowtime(scope.row)"
            >
              {{ scope.row.photoInfo.photoCount }}</el-link
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="pageNation">
        <el-pagination
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
          :current-page="page"
          :page-size="pageSize"
          :page-sizes="[20, 50, 100, 500, 1000]"
          layout="sizes, prev, pager, next, jumper,total"
          :total="total"
          background
        >
        </el-pagination>
      </div>
    </div>

    <ipDialog ref="ipDialogref"></ipDialog>
    <photoDialog ref="photoDialogref"></photoDialog>
    <photoTimeList ref="phototimeDialogref"></photoTimeList>
  </div>
</template>
<script>
import {
  gettermAllList,
  getSearchInfo,
  getActivityApi,
} from "@/utils/api/reportApi";
import ipDialog from "./components/ipDialog";
import photoDialog from "./components/photoList";
import photoTimeList from "./components/photoTimeList";

export default {
  name: "photoStatisBox",
  components: {
    ipDialog,
    photoDialog,
    photoTimeList,
  },
  data() {
    return {
      pickerOptions: {
        disabledDate(date) {
          return date.getTime() > Date.now(); // 禁用大于今天的日期
        },
      },
      photoList: [],
      dyOptions: [{ id: -1, name: "全部" }], //电压数据
      xlOptions: [{ id: -1, name: "全部" }], //线路数据
      gtOptions: [{ id: -1, name: "全部" }], //杆塔数据
      activityOptions: [{ id: -1, name: "全部" }], //活动
      tdOptions: [
        { id: -1, name: "全部" },
        { id: 1, name: "通道1" },
        { id: 2, name: "通道2" },
        { id: 3, name: "通道3" },
        { id: 4, name: "通道4" },
        { id: 5, name: "通道5" },
        { id: 6, name: "通道6" },
        { id: 7, name: "通道7" },
        { id: 8, name: "通道8" },
      ], //通道数据
      formdata: {
        dyid: -1,
        lineid: -1,
        towerid: -1,
        channelid: -1,
        activityId: -1,
        starttime: new Date(new Date().setHours(0, 0, 0, 0)).getTime(), // 设置开始时间为当天凌晨00:00:00的时间戳
        endtime: new Date(new Date().setHours(23, 59, 59, 0)).getTime(), // 设置结束时间为当天夜晚23:59:59的时间戳
        search: "",
      },
      page: 1, // 当前页数
      pageSize: 20, // 每页数量
      total: 0, //总条数
      photoLoading: false,
      drawerSearch: false,
      tableheight: "100%",
      roleName: "",
      picflag: false,
    };
  },
  created() {
    this.roleName = localStorage.getItem("userName");
    let pageSizeFromStorage = localStorage.getItem("photoPageSize");
    // 使用三元运算符设置this.pageSize
    this.pageSize =
      pageSizeFromStorage !== null && pageSizeFromStorage !== ""
        ? parseInt(pageSizeFromStorage, 10)
        : 20;

    // this.picflag = localStorage.getItem("picflag");
    // const backButtonRouteGuard = this.$router.beforeEach((to, from, next) => {
    //   if (from.name == "reportData" && this.picflag == "true") {
    //     console.log(from.name == "reportData" && this.picflag);
    //     /* Blocking back button in menu route */
    //     console.log(from.name);
    //     next(false);
    //     // this.hide();
    //     this.$refs.photoDialogref.hide();
    //   } else {
    //     /* allowing all other routes*/
    //     next(true);
    //   }
    // });

    // this.$once("hook:destroyed", () => {
    //   backButtonRouteGuard();
    // });
  },
  mounted() {
    this.getSearchdy();
    this.getactiveList();
  },
  watch: {},
  methods: {
    //传图pic排序
    picSort(a, b) {
      // 确保 a 和 b 都有 mntnStatus.reportMap 对象
      const aPic = (a.photoInfo.photoCount && a.photoInfo.photoCount) || 0;
      const bPic = (b.photoInfo.photoCount && b.photoInfo.photoCount) || 0;
      // 将 pic 转换为数字进行比较
      const numA = Number(aPic);
      const numB = Number(bPic);
      // 根据需要进行升序或降序排序
      // 这里假设你想要升序排序（从小到大）
      return numA - numB;
      // 如果你想要降序排序（从大到小），则返回 numB - numA
    },
    formatLastHeartbeat(timestamp) {
      return this.$moment(timestamp * 1000).format("YYYY-MM-DD HH:mm:ss");
    },
    sortRecvTime(a, b) {
      // 将字符串转换为日期对象，处理 null 值
      const dateA = a.photoInfo.lastRecvTime
        ? new Date(a.photoInfo.lastRecvTime)
        : new Date(0);
      const dateB = b.photoInfo.lastRecvTime
        ? new Date(b.photoInfo.lastRecvTime)
        : new Date(0);

      // 比较日期
      if (dateA < dateB) return -1;
      if (dateA > dateB) return 1;
      return 0;
    },
    sortlastPhotoTime(a, b) {
      // 将字符串转换为日期对象，处理 null 值
      const dateA = a.photoInfo.lastPhotoTime
        ? new Date(a.photoInfo.lastPhotoTime)
        : new Date(0);
      const dateB = b.photoInfo.lastPhotoTime
        ? new Date(b.photoInfo.lastPhotoTime)
        : new Date(0);

      // 比较日期
      if (dateA < dateB) return -1;
      if (dateA > dateB) return 1;
      return 0;
    },
    sortfirstTime(a, b) {
      // 将字符串转换为日期对象，处理 null 值
      const dateA = a.photoInfo.firstPhotoTime
        ? new Date(a.photoInfo.firstPhotoTime)
        : new Date(0);
      const dateB = b.photoInfo.firstPhotoTime
        ? new Date(b.photoInfo.firstPhotoTime)
        : new Date(0);

      // 比较日期
      if (dateA < dateB) return -1;
      if (dateA > dateB) return 1;
      return 0;
    },
    //获取电压信息
    getSearchdy() {
      getSearchInfo({ type: 1 })
        .then((res) => {
          this.dyOptions = this.dyOptions.concat(res.data.list);
          console.log(this.dyOptions);
          this.getSearchxl();
        })
        .catch((err) => {});
    },
    //获取线路数据
    getSearchxl() {
      getSearchInfo({ type: 2, id: this.formdata.dyid })
        .then((res) => {
          this.xlOptions = this.xlOptions.concat(res.data.list);
          this.getSearchgt();
        })
        .catch((err) => {});
    },
    //获取杆塔数据
    getSearchgt() {
      getSearchInfo({ type: 3, id: this.formdata.lineid })
        .then((res) => {
          this.gtOptions = this.gtOptions.concat(res.data.list);
          this.onSubmit();
        })
        .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;
        })
        .catch((err) => {});
    },
    changeActive(val) {
      // localStorage.setItem("activeId", JSON.stringify(val));
    },
    onSubmit() {
      if (this.formdata.starttime > this.formdata.endtime) {
        return this.$message({
          duration: 1500,
          showClose: true,
          message: "开始日期不能大于结束日期",
          type: "warning",
        });
      }
      this.page = 1;
      this.getPhotoFun();
    },
    //获取带有图片信息的内容
    getPhotoFun() {
      console.log(this.formdata);
      this.photoLoading = true;
      let params = {
        dataFlag: "PSC", //只要photoInfo信息
        start: this.formdata.starttime / 1000,
        end: this.formdata.endtime / 1000,
        pageNum: this.page,
        pageSize: this.pageSize,
      };

      // 根据条件添加参数
      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.channelid !== -1) {
        params.channelId = this.formdata.channelid;
      }
      if (this.formdata.activityId !== -1) {
        params.activityId = this.formdata.activityId;
      }
      if (this.formdata.search !== "") {
        params.cmdid = this.formdata.search;
      }
      setTimeout(() => {
        gettermAllList(params)
          .then((res) => {
            console.log(res);
            this.photoList = res.data.list;
            this.total = res.data.total;
            this.photoLoading = false;
          })
          .catch((err) => {
            this.photoLoading = false;
          });
      }, 100);
    },

    //点击分页
    handleCurrentChange(val) {
      this.page = val;
      this.getPhotoFun();
    },

    //每页条数
    handleSizeChange(val) {
      this.pageSize = val;
      localStorage.setItem("photoPageSize", this.pageSize);
      //this.getPhotoFun();
    },
    //点击装置查看历史图片
    handleShowPhoto(row) {
      let params = this.formdata;
      this.$refs.photoDialogref.display(row, params);
    },
    handleShowtime(row) {
      let params = this.formdata;
      this.$refs.phototimeDialogref.display(row, params);
    },
    //点击最后心跳时间获取历史 ip和端口
    handleShowIp(row) {
      this.$refs.ipDialogref.display(row);
    },
    showSearch() {
      this.drawerSearch = !this.drawerSearch;
      console.log(this.drawerSearch);

      this.$nextTick(() => {
        if (this.drawerSearch) {
          // 如果抽屉现在是可见的，获取其高度
          console.log(this.$refs.statisRef.offsetHeight);
          const searchBoxHeight = this.$refs.searchref.offsetHeight;
          console.log("搜索框的高度:", searchBoxHeight);
          this.tableheight =
            this.$refs.statisRef.offsetHeight - searchBoxHeight - 36;
          console.log(this.tableheight);
        } else {
          this.tableheight = "100%";
        }
      });
    },
  },
};
</script>
<style lang="less">
.photoStatisBox {
  height: 100%;
  //background-color: #fcc;
  .searchBox {
    .el-form {
      .el-form-item--small.el-form-item {
        margin-bottom: 8px;
      }
    }

    .dyclass {
      .el-select {
        width: 120px;
      }
    }
    .xlclass {
      .el-select {
        width: 150px;
      }
    }
    .gtclass {
      .el-select {
        width: 180px;
      }
    }
    .tdclass {
      .el-select {
        width: 80px;
      }
    }
    .dateclass {
      .el-date-editor.el-input,
      .el-date-editor.el-input__inner {
        width: 190px;
      }
    }
  }
  .deviceTable {
    height: calc(100% - 32px);
    //background: #fcc;
    .el-table {
      .cell {
        text-align: center;
        vertical-align: middle; /* 如果需要垂直居中 */
      }
    }
    .el-table {
      color: #000;
      thead {
        color: #000;
        font-weight: bold;
      }
      th.el-table__cell {
        background: #dcdcdc !important;
      }
      td.el-table__cell,
      th.el-table__cell.is-leaf {
        border-bottom: 1px solid #dcdcdc;
      }
      .el-table__cell {
        border-right: 1px solid #dcdcdc;
      }
    }
  }
}
</style>
