<template>
  <div class="alarmHandBox">
    <div class="searchMain">
      <div class="searchBox">
        <el-form :inline="true" :model="formdata" class="demo-form-inline">
          <el-form-item label="电压等级" class="dybox">
            <el-select v-model="formdata.dyId" @change="getSearchxl">
              <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="杆塔名称">
            <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="开始日期">
            <!-- <el-date-picker
              v-model="formdata.timeVal"
              type="datetimerange"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="timestamp"
            ></el-date-picker> -->
            <el-date-picker
              v-model="formdata.starttime"
              type="datetime"
              placeholder="开始日期"
              value-format="timestamp"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="结束日期">
            <el-date-picker
              v-model="formdata.endtime"
              type="datetime"
              default-time="23:59:59"
              placeholder="结束日期"
              value-format="timestamp"
              class="ml10"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="告警原因" class="gjbox">
            <el-select v-model="formdata.label">
              <el-option
                v-for="item in gjOptions"
                :key="item.label"
                :label="item.name"
                :value="item.label"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">查询</el-button>
          </el-form-item>
        </el-form>
      </div>

      <div class="alarmContain" v-loading="loading">
        <div class="alarmTable">
          <el-table
            ref="multipleTable"
            :data="tableData"
            stripe
            border
            tooltip-effect="dark"
            style="width: 100%"
            @selection-change="handleSelectionChange"
            height="calc(100% - 40px)"
            @row-click="handleRowClick"
            highlight-current-row
          >
            <el-table-column min-width="45" label="序号">
              <template slot-scope="scope">
                <span>{{ (page - 1) * pageSize + scope.$index + 1 }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="alarmTime"
              label="告警时间"
              min-width="135"
              :show-overflow-tooltip="true"
              :formatter="dateFormat"
            >
            </el-table-column>

            <!-- <el-table-column
              prop="dyLevel"
              label="电压等级"
              min-width="75"
              :show-overflow-tooltip="true"
            >
            </el-table-column> -->
            <el-table-column
              prop="lineName"
              label="线路名称"
              min-width="105"
              :show-overflow-tooltip="true"
            >
            </el-table-column>
            <el-table-column
              prop="towerName"
              label="杆塔名称"
              min-width="145"
              :show-overflow-tooltip="true"
            >
            </el-table-column>
            <el-table-column
              prop="displayName"
              label="设备名称"
              min-width="145"
              :show-overflow-tooltip="true"
            >
            </el-table-column>
            <el-table-column
              label="通道"
              min-width="75"
              :show-overflow-tooltip="true"
            >
              <template slot-scope="scope">{{
                scope.row.alias !== null && scope.row.alias !== ""
                  ? scope.row.alias
                  : scope.row.channnelName
              }}</template>
            </el-table-column>
            <!-- <el-table-column
              prop="termId"
              label="设备编号"
              min-width="75"
              :show-overflow-tooltip="true"
            >
            </el-table-column> -->

            <el-table-column
              prop="enname"
              label="告警原因"
              min-width="155"
              :show-overflow-tooltip="true"
            >
            </el-table-column>
            <el-table-column label="是否已读" min-width="95" fixed="right">
              <template slot-scope="scope">
                <span v-if="scope.row.isread == 1" class="readbox">[已读]</span>
                <span v-if="scope.row.isread == 0">[未读]</span>
              </template>
            </el-table-column>
          </el-table>
          <div class="pageNation">
            <el-pagination
              @current-change="handleCurrentChange"
              @size-change="handleSizeChange"
              :current-page="page"
              :page-size="pageSize"
              layout="sizes, prev, pager, next, jumper,total"
              :total="total"
            >
            </el-pagination>
          </div>
        </div>
        <div class="alarmPic">
          <div class="imgshow" @click="handleBigPicbox(selectRow)">
            <div
              class="picshow"
              v-if="selectRow.path !== '' && tableData.length !== 0"
            >
              <img ref="picJpg" :src="photoPic" />
              <canvas id="myCanvas" class="myCanvas" ref="myCanvas"></canvas>
            </div>
            <img
              ref="picJpg"
              src="../../assets/img/nopic.jpg"
              v-if="selectRow.path == '' || tableData.length == 0"
            />
          </div>
          <div class="editorBtn">
            <el-button
              type="primary"
              :loading="btnpicloading"
              @click="handleCommandpic"
              :disabled="tableData.length == 0"
              >主动拍照</el-button
            >
            <el-button
              type="primary"
              @click="handleHistory"
              :disabled="tableData.length == 0"
              >历史图片</el-button
            >
          </div>
        </div>
      </div>
    </div>
    <!-- 点击出现大图 -->
    <div v-if="showBigpic" class="showPic" @click="closePic">
      <div class="picboxI">
        <img class="maskPic" :src="bigPhotoPic" />
        <!-- <canvas id="myCanvas" class="myCanvas" ref="myCanvas"></canvas> -->
        <i @click="closePic" class="el-icon-circle-close"></i>
      </div>
    </div>
    <historyimg ref="historyimg_ref"></historyimg>
  </div>
</template>

<script>
import {
  getSearchInfo,
  getAlarmList,
  getAlarmTypeList,
  getLatestPhotoJoggle,
  getReturnedPhotoJoggle,
  readAlarm,
} from "@/utils/api/index";
import historyimg from "./components/historyimg.vue";
import moment from "moment";
export default {
  components: {
    historyimg,
  },
  data() {
    return {
      dyOptions: [{ id: 0, name: "全部" }], //电压数据
      xlOptions: [{ id: 0, name: "全部" }], //线路数据
      gtOptions: [{ id: 0, name: "全部" }], //杆塔数据
      gjOptions: [{ id: 0, label: -1, name: "全部" }], //告警数据
      formdata: {
        dyId: 0,
        lineId: 0,
        towerId: 0,
        label: -1,
        // timeVal: "",
      },
      photoPic: "",
      tableData: [],
      multipleSelection: [],
      page: 1, // 当前页数
      pageSize: 20, // 每页数量
      total: 0, //总条数
      loading: false,
      btnpicloading: false,
      timer: null,
      i: 0,
      isreadshow: false,
      showBigpic: false,
      textInfo: "",
      bigPhotoPic: "", //大图路径
      selectRow: {},
    };
  },
  mounted() {
    // this.$set(this.formdata, "timeVal", [
    //   new Date(new Date().toLocaleDateString()).getTime(),
    //   new Date().getTime(),
    // ]);
    this.$set(
      this.formdata,
      "starttime",
      new Date(new Date().toLocaleDateString()).getTime()
    );
    this.$set(this.formdata, "endtime", new Date().getTime());
    this.getSearchdy();
    this.getTableList();
  },
  methods: {
    handleBigPicbox(val) {
      if (val.path !== "" && tableData.length !== 0) {
        console.log(val);
        this.bigPhotoPic = val.path;
        this.showBigpic = true;
        this.$nextTick(() => {
          this.drawline(val);
        });
      }
    },
    closePic() {
      this.showBigpic = false;
    },
    //获取电压信息
    getSearchdy() {
      getSearchInfo({ type: 1 })
        .then((res) => {
          this.dyOptions = this.dyOptions.concat(res.data.list);
          this.formdata.dyId = this.dyOptions[0].id;
          this.getSearchxl();
        })
        .catch((err) => {});
    },
    //获取线路数据
    getSearchxl() {
      getSearchInfo({ type: 2, id: this.formdata.dyId })
        .then((res) => {
          this.xlOptions = [{ id: 0, 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: 0, name: "全部" }];
          this.gtOptions = this.gtOptions.concat(res.data.list);
          this.formdata.towerId = this.gtOptions[0].id;
          this.getSearchgj();
        })
        .catch((err) => {});
    },
    //获取告警原因
    getSearchgj() {
      getAlarmTypeList()
        .then((res) => {
          this.gjOptions = [{ id: 0, label: -1, name: "全部" }];
          this.gjOptions = this.gjOptions.concat(res.data.list);
          console.log(this.gjOptions);
          this.formdata.label = this.gjOptions[0].label;
          console.log(this.formdata.label);
        })
        .catch((err) => {});
    },
    //获取数据
    getTableList() {
      this.loading = true;
      this.$set(this.formdata, "pageindex", this.page);
      this.$set(this.formdata, "pagesize", this.pageSize);
      // this.$set(this.formdata, "starttime", this.formdata.timeVal[0]);
      // this.$set(this.formdata, "endtime", this.formdata.timeVal[1]);
      getAlarmList(this.formdata)
        .then((res) => {
          this.loading = false;
          this.tableData = res.data.list;
          this.total = res.data.total;
          this.photoPic = res.data.list[0].path;
          this.selectRow = res.data.list[0];
          console.log(this.selectRow);

          // 别忘了标签上定义ref  这里的 myTable就说获取的标签上的ref命的名
          this.$refs.multipleTable.setCurrentRow(this.selectRow);
          this.handleRowClick(this.selectRow);
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //查询
    onSubmit() {
      if (this.formdata.starttime > this.formdata.endtime) {
        return this.$message({
          showClose: true,
          message: "开始日期不能大于结束日期",
          type: "warning",
        });
      }
      this.getTableList();
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    //点击分页
    handleCurrentChange(val) {
      this.page = val;
      this.getTableList();
    },
    //每页条数
    handleSizeChange(val) {
      this.pageSize = val;
      this.getTableList();
    },
    //绘制告警区域
    drawline(data) {
      this.canvas = this.$refs.myCanvas;
      this.imgpic = this.$refs.picJpg;
      this.textInfo = data.enname;
      this.canvas.width = this.imgpic.offsetWidth; //设置画布大小
      this.canvas.height = this.imgpic.offsetHeight; //设置画布大小
      this.ctx = this.canvas.getContext("2d");
      this.ctx.beginPath();
      //设置线条颜色，必须放在绘制之前
      this.ctx.strokeStyle = "#ff0000";
      // 线宽设置，必须放在绘制之前
      this.ctx.lineWidth = 1;

      // 绘制矩形
      var scaleX = this.canvas.width / data.photoWidth, //this.iw图片的宽
        scaleY = this.canvas.height / data.photoHeight; //this.ih图片的高
      console.log(scaleX, scaleY);
      var top = data.x * scaleX,
        left = data.y * scaleY,
        width = data.width * scaleX,
        height = data.height * scaleY;
      console.log(top, left, width, height);
      // this.ctx.strokeStyle = "red"; //线的颜色
      this.ctx.strokeRect(top, left, width, height); //绘制路径矩形
      //this.ctx.strokeRect(data.x, data.y, data.width, data.height);
      this.ctx.font = "24px normal";
      this.ctx.fillStyle = "#ff0000";
      this.ctx.fillText(this.textInfo, top, left + 24);
      this.ctx.closePath();
      this.ctx.stroke();
    },
    //点击当前行
    handleRowClick(row) {
      //this.$refs.multipleTable.toggleRowSelection(row);
      console.log(row);
      this.photoPic = row.path;
      this.selectRow = row;
      //未读变已读
      if (row.isread == 0) {
        setTimeout(function () {
          readAlarm({
            id: row.id,
          })
            .then((res) => {
              console.log(res);
              row.isread = 1;
              console.log(row.isread);
            })
            .catch((err) => {
              console.log(err);
            });
        }, 300);
      }
      this.$nextTick(() => {
        this.drawline(row);
      });
    },
    //手动拍照
    handleCommandpic() {
      this.btnpicloading = true;
      getLatestPhotoJoggle({
        captureType: 0,
        channel: this.selectRow.channelId,
        termId: this.selectRow.termId,
        preset: 255,
      }).then((res) => {
        this.$message({
          showClose: true,
          message: "手动拍照请求成功！",
          type: "success",
        });
        this.timer = window.setInterval(() => {
          this.newPicApi(res.data);
          this.i++;
        }, 5000);
      });
    },
    //获取最新图片
    newPicApi(val) {
      getReturnedPhotoJoggle({
        photoTime: val,
        termId: this.selectRow.termId,
      }).then((res) => {
        if (res.data == true && this.i < 10) {
          clearInterval(this.timer);
          this.timer = null;
          this.i = 0;
          this.btnpicloading = false;
          this.$notify({
            title: "通知信息",
            message: "已返回最新图片",
            type: "success",
            position: "bottom-right",
          });
        } else if (res.data == false && this.i > 10) {
          clearInterval(this.timer);
          this.timer = null;
          this.i = 0;
          this.btnpicloading = false;
          this.$notify({
            title: "通知信息",
            message: "装置暂无响应，请稍后再试！",
            type: "warning",
            position: "bottom-right",
          });
        }
      });
    },
    //历史图片
    handleHistory() {
      this.$refs.historyimg_ref.display();
      this.$refs.historyimg_ref.getdataform(this.selectRow);
    },
    dateFormat(row, column) {
      var date = row[column.property];
      if (date == undefined) {
        return "";
      }
      return moment(date).format("YYYY-MM-DD HH:mm:ss");
    },
  },
};
</script>
<style lang="less">
.alarmHandBox {
  width: calc(100% - 32px);
  height: calc(100% - 32px);
  padding: 16px 16px;
  background: #ffffff;
  .showPic {
    position: fixed;
    background-color: rgba(0, 0, 0, 50%);
    bottom: 0;
    left: 0;
    overflow: hidden;
    right: 0;
    top: 0;
    z-index: 9999;
    display: flex;
    cursor: pointer;
    .picboxI {
      position: relative;
      max-width: 1280px;
      max-height: 720px;
      margin: auto;
      animation-name: scaleDraw;
      /*关键帧名称*/
      animation-timing-function: ease;
      /*动画的速度曲线*/
      animation-iteration-count: 1;
      /*动画播放的次数*/
      animation-duration: 0.65s;

      img {
        max-width: 1280px;
        max-height: 720px;
        margin: auto;
      }
      .myCanvas {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        cursor: pointer;
      }
      .el-icon-circle-close {
        position: absolute;
        right: -24px;
        font-size: 48px;
        color: #fff;
        cursor: pointer;
        top: -24px;
      }
    }
  }
  .searchMain {
    border: 1px solid #dddddd;
    height: calc(100% - 34px);
    max-height: calc(100% - 34px);
    padding: 16px;
    border-radius: 4px;
    .searchBox {
      .ml10 {
        margin-left: 10px;
      }
      .el-form {
        .dybox {
          .el-form-item__content {
            width: 120px;
          }
        }
        .xlbox {
          .el-form-item__content {
            width: 160px;
          }
        }
        .gjbox {
          .el-form-item__content {
            width: 140px;
          }
        }
      }
    }
  }
  .alarmTop {
    padding: 0px 8px 16px 8px;
  }
  .alarmContain {
    display: flex;
    height: calc(100% - 90px);
    padding: 0px 8px;
    .alarmTable {
      width: 50%;
      height: 100%;
      .el-table__body tr {
        cursor: pointer;
      }
      .el-table__body tr.current-row > td {
        background-color: rgba(18, 128, 113, 0.2);
      }
      .readbox {
        color: #e49e61;
      }
    }
    .pageNation {
      margin-top: 8px;
      justify-content: flex-start;
    }
    .alarmPic {
      width: 50%;
      height: 100%;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      .imgshow {
        width: 100%;
        height: 100%;
        position: relative;

        .picshow {
          width: 100%;
          height: 100%;
          position: relative;
        }
        img {
          width: 100%;
          height: 100%;
        }
        .myCanvas {
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          cursor: pointer;
        }
      }
      .editorBtn {
        margin-top: 8px;
        // border: 1px solid @border-color-base;
        padding-top: 5px;
        // border-radius: 4px;
      }
      .editorBtn {
        display: flex;
        justify-content: flex-start;
      }
    }
  }
}
</style>
