<template>
  <div class="picRotation">
    <div class="rotationBox">
      <div class="picHead">
        <div class="pageNation">
          <el-pagination
            @current-change="handleCurrentChange"
            :current-page="page"
            :page-size="pageSize"
            layout=" prev, pager, next, jumper,total"
            :total="total"
          >
          </el-pagination>
        </div>
        <div class="buttonGroup">
          <span class="info">
            <b> {{ isRuning ? remainingTime : "已暂停" }} </b>
          </span>
          <el-button type="primary" @click="toggleCountdown">{{
            isRuning ? "暂停轮巡" : "开始轮巡"
          }}</el-button>
          <el-button type="primary" @click="setbtn">设置</el-button>
        </div>
      </div>
      <div class="imageCenter" v-loading="loading" v-cloak>
        <el-row
          v-for="i in rowNum"
          :key="'row-' + i"
          :style="{ height: 100 / rowNum + '%' }"
        >
          <el-col
            :span="24 / colNum"
            v-for="(item, index) in picList"
            v-if="index < colNum * i && index >= colNum * (i - 1)"
            :key="'col-' + index"
          >
            <div class="imgList" @click="handleShowHistory(item)">
              <div
                v-if="item.path !== null && item.path.indexOf('videos') == -1"
                class="bigpic"
                :style="
                  item.path
                    ? 'backgroundImage:url(' + item.path + '!128x72)'
                    : ''
                "
              >
                <!-- <img
                  :src="item.path"
                  :id="'img' + index"
                  :ref="'imgref' + index"
                /> -->
                <el-image
                  :src="item.path"
                  :id="'img' + index"
                  :ref="'imgref' + index"
                >
                  <div
                    slot="placeholder"
                    class="image-slot"
                    :style="{
                      backgroundImage: 'url(' + item.path + '!260x160' + ')',
                    }"
                  >
                    <i class="el-icon-loading"></i>
                  </div>
                  <template slot="error">
                    <img
                      :id="'img' + index"
                      src="../../assets/img/nodatapic2.jpg"
                    />
                  </template>
                </el-image>
                <canvas
                  :ref="'canvansref' + index"
                  :id="'canvas_' + index"
                  class="canvasAll"
                ></canvas>
                <canvas
                  :id="'markCanvas' + index"
                  class="markCanvas"
                  :ref="'markCanvas' + index"
                ></canvas>
              </div>
              <div
                class="bigpic"
                v-else-if="
                  item.path !== null && item.path.indexOf('videos') !== -1
                "
              >
                <video
                  width="100%"
                  height="100%"
                  :src="item.path"
                  controls="controls"
                ></video>
              </div>
              <div class="bigpic" v-else>
                <img src="../../assets/img/nodatapic2.jpg" />
              </div>
              <div class="picInfo">
                <p>
                  {{ item.linename }}-{{ item.towername }}-（{{
                    item.alias !== null && item.alias !== ""
                      ? item.alias
                      : item.channnelname
                  }}）
                </p>
                <p class="timeinfo" v-if="item.photoTime !== null">
                  {{ $moment(item.photoTime).format("YYYY-MM-DD HH:mm:ss") }}
                </p>
                <p class="timeinfo" v-else>无抓拍</p>
                <span class="isOffLine" v-if="item.isOnline == 0"
                  >(设备已离线)</span
                >
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>
    <el-dialog
      title="设置"
      :visible.sync="setdialog"
      width="480px"
      :close-on-click-modal="false"
      class="setPicShow"
    >
      <el-form label-position="left">
        <el-form-item label="轮巡速度">
          <el-select v-model="selSpeed" placeholder="请选择">
            <el-option
              v-for="item in speedOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择通道">
          <el-select v-model="channelVal" placeholder="请选择">
            <el-option
              v-for="item in channelOption"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="画面布局" class="layoutBox">
          <!-- <el-select v-model="selLayout" placeholder="s请选择">
            <el-option
              v-for="item in layoutOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select> -->
          <div class="selectGroup">
            <div class="rowbox">
              <el-radio-group v-model="rowradio" class="radio1">
                <el-radio-button label="1"></el-radio-button>
                <el-radio-button label="2"></el-radio-button>
                <el-radio-button label="3"></el-radio-button>
                <el-radio-button label="4"></el-radio-button>
                <!-- <el-radio-button label="5"></el-radio-button>
                <el-radio-button label="6"></el-radio-button> -->
              </el-radio-group>
              <span class="labelinfo">行</span>
            </div>
            <div class="colbox">
              <el-radio-group v-model="colradio" class="radio2">
                <el-radio-button label="1"></el-radio-button>
                <el-radio-button label="2"></el-radio-button>
                <el-radio-button label="3"></el-radio-button>
                <el-radio-button label="4"></el-radio-button>
                <!-- <el-radio-button label="5"></el-radio-button>
                <el-radio-button label="6"></el-radio-button> -->
              </el-radio-group>
              <span class="labelinfo">列</span>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="setdialog = false">取 消</el-button>
        <el-button type="primary" @click="submitForm()">确 定</el-button>
      </div>
    </el-dialog>

    <div class="morePicBox" v-if="historyPicdialog">
      <div class="headTitle">
        <div class="info">
          <p>
            {{ picInfoData.linename }} - {{ picInfoData.towername }} - （{{
              picInfoData.alias !== null && picInfoData.alias !== ""
                ? picInfoData.alias
                : picInfoData.channnelname
            }}）{{ $moment(picInfoData.photoTime).format("YYYY-MM-DD ") }}
          </p>

          <!-- <p class="timeinfo" v-if="item.mediatype !== null">
          {{ $moment(item.photoTime).format("YYYY-MM-DD HH:mm:ss") }}
        </p> -->
        </div>
        <div class="closeBox" @click="handleclose">
          <i class="el-icon-close"></i>
        </div>
      </div>
      <div class="picmain">
        <carouselChartmore
          ref="carouselpic"
          :key="carouselKey"
          :terminalPhoto="terminalPhoto"
          :photoNum="photoNum"
          v-loading="historyPicLoading"
        ></carouselChartmore>
      </div>
    </div>
  </div>
</template>
<script>
import { getPictureList, getTerminalPhotoListJoggle } from "@/utils/api/index";
import carouselChartmore from "../components/carouselChartmore.vue";

export default {
  components: {
    carouselChartmore,
  },
  data() {
    return {
      carouselKey: 0,
      OptionssalseImg: {
        inline: false,
        button: true,
        navbar: false,
        title: false,
        toolbar: false,
        tooltip: false,
        zoomable: true,
        url: "src",
      },
      value: "选项1",
      page: 1, // 当前页数
      pageSize: 4, // 每页数量
      totalPage: 0, //总页数
      total: 0, //总条数
      picList: [], //图片列表数据
      remainingTime: 0, //剩余时间
      photoNum: 8,
      isRuning: false,
      timer: null,
      loading: false,
      setdialog: false, //设置弹框
      channelVal: 1, //默认全部
      channelOption: [
        { name: "全部", value: -1 },
        { name: "通道一", value: 1 },
        { name: "通道二", value: 2 },
      ],
      speedOptions: [
        {
          value: 5,
          label: "5秒",
        },
        {
          value: 11,
          label: "11秒",
        },
        {
          value: 12,
          label: "12秒",
        },
        {
          value: 13,
          label: "13秒",
        },
        {
          value: 14,
          label: "14秒",
        },
        {
          value: 15,
          label: "15秒",
        },
      ], //轮巡速度
      selSpeed: 5,
      //画面布局
      rowNum: "",
      colNum: "",
      rowradio: "4",
      colradio: "4",
      selLayout: 1,
      options: [
        {
          value: "选项1",
          label: "顺序",
        },
        {
          value: "选项2",
          label: "倒序",
        },
      ],

      //点击查看历史图片
      picInfoData: {}, //获取当前图片的信息
      historyPicdialog: false,
      historyPicLoading: false,
      terminalPhoto: [], //获取装置当前图片数据
      nopicPath: require("@/assets/img/nopic.jpg"),
    };
  },
  methods: {
    //点击图片弹出历史图
    handleShowHistory(item) {
      console.log(item);
      this.picInfoData = item;
      console.log(this.picInfoData);
      this.historyPicdialog = true;
      if (item.photoTime == null) {
        item.photoTime = new Date().getTime();
      }
      //this.getTerminalPhotoList(item.cmdid);
      this.getTerminalPhotoList(item.channelid, item.photoTime, item.termid);
    },
    handleclose() {
      this.historyPicdialog = false;
    },

    //获取图片
    getTerminalPhotoList(channelId, date, termId) {
      console.log(channelId, date, termId);
      this.historyPicLoading = true;
      console.log("zhanshi asdadadadadadsddadadadadad", this.terminalPhoto);
      //this.terminalPhoto = [];
      getTerminalPhotoListJoggle({
        channelid: channelId,
        time: date,
        terminalid: termId,
      })
        .then((res) => {
          console.log(res);
          if (res.data.list.length == 0) {
            this.terminalPhoto = [
              {
                path: this.nopicPath,
                termId: termId,
                mediaType: 0,
              },
            ];
          } else {
            this.terminalPhoto = res.data.list;
          }
          this.carouselKey++; // 更新key以强制重新渲染

          this.$nextTick(() => {
            this.$refs.carouselpic.changeBigPic(this.terminalPhoto[0], 0);
          });
          this.historyPicLoading = false;
        })
        .catch((err) => {
          console.log(err); //代码错误、请求失败捕获
        });
    },
    setbtn() {
      this.isRuning = false;
      this.pauseCountdown();
      this.setdialog = true;
      this.selSpeed = parseInt(localStorage.getItem("totalTime"))
        ? parseInt(localStorage.getItem("totalTime"))
        : 15;
      this.rowNum = parseInt(localStorage.getItem("row"))
        ? parseInt(localStorage.getItem("row"))
        : 4;
      this.colNum = parseInt(localStorage.getItem("col"))
        ? parseInt(localStorage.getItem("col"))
        : 4;
      this.rowradio = parseInt(localStorage.getItem("row"))
        ? parseInt(localStorage.getItem("row"))
        : 4;
      this.colradio = parseInt(localStorage.getItem("col"))
        ? parseInt(localStorage.getItem("col"))
        : 4;
      this.channelVal = parseInt(localStorage.getItem("channelNum"))
        ? parseInt(localStorage.getItem("channelNum"))
        : 1;
    },
    submitForm() {
      localStorage.setItem("totalTime", this.selSpeed);
      localStorage.setItem("row", this.rowradio);
      localStorage.setItem("col", this.colradio);
      localStorage.setItem("channelNum", this.channelVal);
      this.rowNum = parseInt(localStorage.getItem("row"))
        ? parseInt(localStorage.getItem("row"))
        : 4;
      this.colNum = parseInt(localStorage.getItem("col"))
        ? parseInt(localStorage.getItem("col"))
        : 4;
      this.channelVal = parseInt(localStorage.getItem("channelNum"))
        ? parseInt(localStorage.getItem("channelNum"))
        : 1;
      this.page = 1;
      this.pageSize = this.rowradio * this.colradio;
      this.setdialog = false;
      this.$message.success("设置成功");
      this.getPicData();
    },
    //点击分页
    handleCurrentChange(val) {
      this.isRuning = false;
      this.pauseCountdown();
      this.page = val;
      this.getPicData();
    },
    //请求数据接口方法
    getPicData() {
      this.loading = true;
      console.log(this.picList);
      this.picList = [];
      const params = {
        pageindex: this.page,
        pagesize: this.rowNum * this.colNum,
      };
      if (this.channelVal !== -1) {
        params.channelId = this.channelVal;
      }
      getPictureList(params)
        .then((res) => {
          this.picList = res.data.list;
          this.totalPage = res.data.totalpage;
          this.total = res.data.total;
          this.loading = false;
          console.log("我是来获取图片的", document.getElementById("img" + 0));
          setTimeout(() => {
            this.drawlineListAll(this.picList);
            this.$nextTick(() => {
              this.drawmarkAll(this.picList);
            });
          }, 200); // 200 毫秒
          // this.$nextTick(() => {

          // });
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //开始轮询
    startCountdown() {
      this.timer = setInterval(() => {
        if (this.remainingTime <= 0) {
          this.clearTimer();

          this.page++;

          if (this.page > this.totalPage) {
            this.page = 0;
            this.startCountdown();
          } else {
            this.remainingTime = parseInt(localStorage.getItem("totalTime"))
              ? parseInt(localStorage.getItem("totalTime"))
              : 15;
            this.getPicData();
            this.startCountdown();
          }
        } else {
          this.remainingTime--;
        }
      }, 1000);
    },
    clearTimer() {
      //清除定时器
      clearInterval(this.timer);
      this.timer = null;
    },
    pauseCountdown() {
      //清除定时器
      clearInterval(this.timer);
      this.timer = null;
    },
    //根据isRuning执行开始暂停操作
    toggleCountdown() {
      if (this.isRuning) {
        this.pauseCountdown();
      } else {
        this.startCountdown();
        this.getPicData();
      }
      this.isRuning = !this.isRuning;
    },
    //绘制所有的图片告警区域
    drawlineListAll(val) {
      console.log(val);
      for (let i = 0; i < val.length; i++) {
        if (val[i].isAlarm == 1) {
          console.log(i);
          console.log(document.getElementById("canvas_" + i));
          this.canvas = document.getElementById("canvas_" + i);
          this.imgpic = document.getElementById("img" + i);
          this.textInfo = val[i].alarmlist[0].enname;
          console.log(this.textInfo);
          console.log(this.imgpic.offsetWidth);
          console.log(this.canvas);
          this.canvas.width = this.imgpic.offsetWidth; //设置画布大小
          this.canvas.height = this.imgpic.offsetHeight; //设置画布大小
          console.log(this.canvas.width, this.canvas.height);
          this.ctx = this.canvas.getContext("2d");
          this.ctx.beginPath();
          //设置线条颜色，必须放在绘制之前
          this.ctx.strokeStyle = "#ff0000";
          // 线宽设置，必须放在绘制之前
          this.ctx.lineWidth = 1;

          // 绘制矩形
          var scaleX = this.canvas.width / val[i].alarmlist[0].photoWidth, //this.iw图片的宽
            scaleY = this.canvas.height / val[i].alarmlist[0].photoHeight; //this.ih图片的高
          console.log(scaleX, scaleY);
          var top = val[i].alarmlist[0].x * scaleX,
            left = val[i].alarmlist[0].y * scaleY,
            width = val[i].alarmlist[0].width * scaleX,
            height = val[i].alarmlist[0].height * scaleY;
          console.log(top, left, width, height);
          // this.ctx.strokeStyle = "red"; //线的颜色
          this.ctx.strokeRect(top, left, width, height); //绘制路径矩形
          //this.ctx.strokeRect(val[i].x, val[i].y, val[i].width, val[i].height);
          this.ctx.font = "16px normal";
          this.ctx.fillStyle = "#ff0000";
          //this.ctx.fillText(this.textInfo, top, left + 24);
          //距离上面有空间
          if (left > 32) {
            this.ctx.fillText(this.textInfo, top, left - 4);
          } else if (this.canvas.height - left + height > 32) {
            this.ctx.fillText(this.textInfo, top, height - 4);
          }
          this.ctx.closePath();
          this.ctx.stroke();
        } else {
          console.log("没有告警");
        }
      }
    },
    drawmarkAll(val) {
      console.log(val);
      for (let i = 0; i < val.length; i++) {
        this.canvas = document.getElementById("markCanvas" + i);
        this.imgpic = document.getElementById("img" + i);
        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 = 2;
        console.log(val);
        for (var j = 0; j < val[i].list.length; j++) {
          console.log(val[j].list);
          this.ctx.moveTo(
            val[i].list[j].x1 * this.imgpic.width,
            val[i].list[j].y1 * this.imgpic.height
          );
          this.ctx.lineTo(
            val[i].list[j].x2 * this.imgpic.width,
            val[i].list[j].y2 * this.imgpic.height
          );
        }
        this.ctx.closePath();
        this.ctx.stroke();
        // if (val[i].markEnable == 1) {

        // } else {
        //   console.log("没有绘制");
        // }
      }
    },
  },
  computed: {},
  mounted() {
    this.remainingTime = parseInt(localStorage.getItem("totalTime"))
      ? parseInt(localStorage.getItem("totalTime"))
      : 15;
    this.rowradio = this.rowNum = parseInt(localStorage.getItem("row"))
      ? parseInt(localStorage.getItem("row"))
      : 4;
    this.colradio = this.colNum = parseInt(localStorage.getItem("col"))
      ? parseInt(localStorage.getItem("col"))
      : 4;
    this.channelVal = parseInt(localStorage.getItem("channelNum"))
      ? parseInt(localStorage.getItem("channelNum"))
      : 1;
    this.pageSize = this.rowradio * this.colradio;
    //this.toggleCountdown();

    this.getPicData();
  },
  created() {},

  beforeDestroy() {
    // console.log("销毁定时器");
    clearInterval(this.timer);
    this.timer = null;
  },
};
</script>
<style lang="less">
.picRotation {
  width: calc(100% - 24px);
  height: calc(100% - 24px);
  padding: 12px 12px;
  background: #ffffff;
  .rotationBox {
    border: 1px solid #dddddd;
    height: calc(100% - 22px);
    max-height: calc(100% - 22px);
    padding: 12px;
    border-radius: 4px;
  }
  .picHead {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0px 0px 8px 0px;
    .buttonGroup {
      display: flex;
      .el-select {
        margin-left: 10px;
        width: 100px;
      }
      .info {
        width: 80px;
        text-align: center;
        margin-right: 16px;
        line-height: 32px;
        b {
          font-size: 24px;
          font-weight: normal;
          color: @color-success;
          vertical-align: middle;
        }
      }
    }
  }

  .imageCenter {
    // display: flex;
    // flex-wrap: wrap;
    height: calc(100% - 52px);
    .el-col {
      height: 100%;
      padding-right: 0.1%;
      padding-left: 0.1%;
      padding-top: 0.1%;
      padding-bottom: 0.1%;
    }
    // justify-content: space-between;
    .imgList {
      border: 1px solid #eee;
      width: 100%;
      position: relative;
      //background-color: #00eaff;
      height: 100%;
      .el-image {
        width: 100%;
        height: 100%;

        .image-slot {
          display: flex;
          justify-content: center;
          align-items: center;
          height: 100%;
          background-size: 100% 100%;
          i {
            font-size: 20px;
            color: #169e8c;
          }
        }
      }
      .bigpic {
        width: 100%;
        height: 100%;
        background-size: 100% 100%;
        position: relative;
      }
      img {
        width: 100%;
        height: 100%;
        cursor: pointer;
      }
      .canvasAll {
        position: absolute;
        width: 100%;
        height: 100%;
        z-index: 2;
        left: 0;
        top: 0;
        pointer-events: none;
      }
      .picInfo {
        position: absolute;
        background: #169e8ca1;
        color: #fff;
        height: auto;
        font-size: 12px;
        left: 0;
        bottom: 0;
        width: 100%;
        text-align: center;
        z-index: 4;
        p {
          margin-top: 4px;
        }
        .timeinfo {
          margin-bottom: 4px;
        }
        .isOffLine {
          color: #999;
          margin-bottom: 6px;
          display: flex;
          align-items: center;
          text-align: center;
          justify-content: center;
        }
      }
      .markCanvas {
        position: absolute;
        width: 100%;
        height: 100%;
        z-index: 2;
        left: 0;
        top: 0;
        pointer-events: none;
      }
    }
  }
  .setPicShow {
    .el-select {
      width: 222px;
    }
    .layoutBox {
      display: flex;
      align-items: center;
    }
    .selectGroup {
      display: flex;
      flex-direction: column;
      .el-radio-button--small .el-radio-button__inner {
        padding: 9px 24px;
      }
      .rowbox {
        margin-bottom: 8px;
        .labelinfo {
          margin-left: 8px;
        }
      }
      .colbox {
        .labelinfo {
          margin-left: 8px;
        }
      }
    }
  }

  .morePicBox {
    position: fixed;
    width: 100%;
    height: 100%;
    background: #fff;
    top: 0px;
    left: 0px;
    z-index: 99999;
    .headTitle {
      height: 40px;
      padding-left: 18px;
      padding-right: 18px;
      line-height: 40px;
      color: #fff;
      font-size: 14px;
      background: linear-gradient(180deg, #4cdbc8 10%, #128071);
      display: flex;
      justify-content: space-between;
      align-items: center;
      .closeBox {
        width: 24px;
        height: 24px;
        align-items: center;
        display: flex;
        justify-content: center;
        cursor: pointer;
      }
    }
    .picmain {
      width: 100%;
      height: calc(100% - 10px);
    }
    .el-loading-mask {
      background-color: rgba(0, 0, 0, 0.3);
    }
  }
}
[v-cloak] {
  display: none;
}
</style>
