<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-item>
            <el-button type="primary" @click="handleListRow">{{
              tableShow ? "图片列表" : "表格列表"
            }}</el-button>
          </el-form-item> -->
        </el-form>
      </div>

      <div class="alarmContain" v-loading="loading" v-if="tableShow">
        <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" v-loading="alarmLoading">
            <!-- @click="handleBigPicbox(selectRow)" -->
            <div
              class="picshow"
              v-if="selectRow.path !== '' && tableData.length !== 0"
              v-viewer="OptionssalseImg"
            >
              <!-- <div
                class="nosee"
                :style="'backgroundImage:url(' + photoPic + '!1366x768)'"
              ></div>
              <viewer :options="OptionssalseImg" class="bigimgView">
                <img
                  @load="imgOnload"
                  ref="picJpg"
                  class="animImg"
                  :src="photoPic + '!1366x768'"
                />
              </viewer> -->
              <img
                ref="picJpg"
                class="animImg"
                @load="imgOnload"
                :src="photoPic + '!1366x768'"
              />
              <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 class="pictureBox" v-else>
        <div class="piclist" v-if="tableData.length !== 0">
          <el-card
            class="box-card imgList"
            v-for="(item, index) in tableData"
            :key="index"
          >
            <div class="bigpic">
              <div class="picshow">
                <img :src="item.path + '!1366x768'" :ref="'picJpg' + index" />
                <canvas
                  id="myCanvas"
                  class="myCanvas"
                  :ref="'myCanvas' + index"
                ></canvas>
              </div>

              <div class="caption">
                <p class="infoTop">
                  {{ item.lineName }} /
                  {{
                    item.displayName !== null && item.displayName !== ""
                      ? item.displayName
                      : item.cmdid
                  }}
                  /
                  {{
                    item.alias !== null && item.alias !== ""
                      ? item.alias
                      : item.channnelName
                  }}
                  / 告警原因：<span class="alarmInfo">({{ item.enname }})</span>
                </p>
                <p class="infoBottom">
                  告警时间：{{
                    $moment(item.alarmTime).format("YYYY-MM-DD HH:mm:ss")
                  }}
                  <el-button
                    type="primary"
                    :loading="btnpicloading"
                    @click="handlePicList(item)"
                    >主动拍照</el-button
                  >
                  <el-button type="primary" @click="handlePicHistory(item)"
                    >历史图片</el-button
                  >
                </p>
              </div>
            </div>
          </el-card>
        </div>
        <div class="piclist" v-else>
          <el-empty description="暂无数据"></el-empty>
        </div>
        <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>
    <!-- 点击出现大图 -->
    <div
      v-if="showBigpic"
      class="showPic"
      @click="closePic"
      v-loading="canvasloading"
    >
      <div class="picboxI">
        <img @load="imgOnload" class="maskPic" :src="bigPhotoPic" />
        <canvas id="myCanvas" class="myCanvas" ref="myCanvas2"></canvas>
      </div>
      <div class="viewClose">
        <i @click="closePic" class="el-icon-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 {
      OptionssalseImg: {
        inline: false,
        button: true,
        navbar: false,
        title: false,
        toolbar: false,
        tooltip: false,
        zoomable: true,
        url: "src",
      },
      dyOptions: [{ id: -1, name: "全部" }], //电压数据
      xlOptions: [{ id: -1, name: "全部" }], //线路数据
      gtOptions: [{ id: -1, name: "全部" }], //杆塔数据
      gjOptions: [{ id: -1, label: -1, name: "全部" }], //告警数据
      formdata: {
        dyId: -1,
        lineId: -1,
        towerId: -1,
        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: {},
      alarmLoading: false,
      canvasloading: false,
      tableShow: true, //表格展示
    };
  },
  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) {
      this.canvasloading = true;
      if (val.path !== "" && this.tableData.length !== 0) {
        console.log(val);
        this.bigPhotoPic = val.path;
        this.showBigpic = true;
        this.$nextTick(() => {
          this.drawline2(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: -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;
          this.getSearchgj();
        })
        .catch((err) => {});
    },
    //获取告警原因
    getSearchgj() {
      getAlarmTypeList()
        .then((res) => {
          this.gjOptions = [{ id: -1, 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);

          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({
          duration: 1500,
          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;

      // 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";
      console.log(top, left, width, height);
      console.log(this.canvas.width, this.canvas.height);
      //距离上面有空间
      if (left > 32) {
        this.ctx.fillText(this.textInfo, top, left - 14);
      } else if (this.canvas.height - left + height > 32) {
        this.ctx.fillText(this.textInfo, top, height - 14);
      }

      this.ctx.closePath();
      this.ctx.stroke();
    },
    //绘制告警区域
    drawline2(data) {
      this.canvas = this.$refs.myCanvas2;
      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(this.$refs.picJpg.complete);
      this.alarmLoading = true;
      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);
        this.imgOnload();
      });
    },
    //手动拍照
    handleCommandpic() {
      this.btnpicloading = true;
      getLatestPhotoJoggle({
        captureType: 0,
        channel: this.selectRow.channelId,
        termId: this.selectRow.termId,
        preset: 255,
      }).then((res) => {
        this.$message({
          duration: 1500,
          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);
    },
    //切换图片
    handleListRow() {
      this.tableShow = !this.tableShow;
    },

    //在图片列表也执行  自动拍照和 查看历史图片
    handlePicList(val) {
      console.log(val);
      this.selectRow = val;
      this.handleCommandpic();
    },
    handlePicHistory(val) {
      console.log(val);
      this.selectRow = val;
      this.handleHistory();
    },
    dateFormat(row, column) {
      var date = row[column.property];
      if (date == undefined) {
        return "";
      }
      return moment(date).format("YYYY-MM-DD HH:mm:ss");
    },
    imgOnload() {
      console.log("加载完成");
      this.alarmLoading = false;
      this.canvasloading = false;
    },
  },
};
</script>
<style lang="less">
.alarmHandBox {
  width: calc(100% - 24px);
  height: calc(100% - 24px);
  padding: 12px 12px;
  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: 1366px;
      max-height: 768px;
      margin: auto;
      animation-name: scaleDraw;
      /*关键帧名称*/
      animation-timing-function: ease;
      /*动画的速度曲线*/
      animation-iteration-count: 1;
      /*动画播放的次数*/
      animation-duration: 0.65s;

      img {
        max-width: 1366px;
        max-height: 768px;
        margin: auto;
      }
      .myCanvas {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        cursor: pointer;
        pointer-events: none;
      }
    }
    .viewClose {
      -webkit-app-region: no-drag;
      background-color: rgba(0, 0, 0, 0.5);
      border-radius: 50%;
      cursor: pointer;
      height: 80px;
      overflow: hidden;
      position: absolute;
      right: -40px;
      top: -40px;
      transition: background-color 0.15s;
      width: 80px;
      .el-icon-close {
        bottom: 16px;
        left: 16px;
        position: absolute;
        color: #fff;
        font-size: 18px;
      }
    }
  }
  .searchMain {
    border: 1px solid #dddddd;
    height: calc(100% - 22px);
    max-height: calc(100% - 22px);
    padding: 12px;
    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;
        }
        .nosee {
          position: absolute;
          width: 100%;
          height: 100%;
          background-size: 100% 100%;
          z-index: 2;
        }
        .bigimgView {
          position: absolute;
          width: 100%;
          height: 100%;
          z-index: 3;
          opacity: 0;
        }
        img {
          width: 100%;
          height: 100%;
        }
        .myCanvas {
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          cursor: pointer;
          z-index: 2;
          pointer-events: none;
        }
      }
      .editorBtn {
        margin-top: 8px;
        // border: 1px solid @border-color-base;
        padding-top: 5px;
        // border-radius: 4px;
      }
      .editorBtn {
        display: flex;
        justify-content: flex-start;
      }
    }
  }
  .pictureBox {
    height: calc(100% - 90px);
    max-height: calc(100% - 90px);
    .el-empty {
      margin: auto;
    }
    .piclist {
      display: flex;
      // justify-content: space-around;
      flex-wrap: wrap;
      overflow: auto;
      border: 1px solid #eee;
      height: calc(100% - 2px);
    }
    .imgList {
      width: calc((100% - 104px) / 3);
      position: relative;
      display: inline-block;
      margin: 8px;
      position: relative;
      padding: 4px;
      border-radius: 3px;
      background: #fff;
      height: fit-content;
      height: 320px;
      .el-card__body {
        padding: 0px;
      }
      .bigpic {
        width: 100%;
        height: 100%;
        background-size: 100% 100%;
        .picshow {
          position: relative;
          .myCanvas {
            position: absolute;
            width: 100%;
            height: 100%;
            z-index: 2;
            left: 0;
            top: 0;
          }
        }
      }
      img {
        cursor: pointer;
        width: 100%;
        height: 250px;
        object-fit: fill;
      }

      .caption {
        padding: 9px;
        color: #333;
        .alarmInfo {
          color: #e49e61;
        }
        .infoTop {
          font-size: 16px;
          color: #000;
          font-weight: normal;
          margin-top: 2px;
          padding-left: 5px;
          padding-right: 5px;
        }
        .infoBottom {
          color: #000;
          font-size: 12px;
          font-weight: normal;
          margin-top: 6px;
          padding-left: 5px;
          padding-right: 5px;
          .el-button--small {
            margin-left: 24px;
            padding: 4px;
            width: 78px;
          }
          .el-button + .el-button {
            margin-left: 10px;
          }
        }
      }
    }
  }
}
</style>
