<template>
  <div style="cursor: default">
    <div class="baselistbox_top">
      <div class="baselistbox_top_title">
        <p @click="goBackPage()" style="cursor: pointer">
          <i class="el-icon-back"></i>
          <span>返回</span>
        </p>
        <p>查看图片</p>
      </div>
      <p class="baselistbox_top_line"></p>
      <div class="baselistbox_top_search">
        <div class="capzuo_left">
          <span>设备ID：{{ device_id }}</span>
        </div>
        <div class="check-btns">
          <div class="type-check">
            <el-button type="primary" size="mini" @click="equipStatusCheck('0')"
              >拍照</el-button
            >
            <el-button type="primary" size="mini" @click="equipStatusCheck('1')"
              >刷新</el-button
            >
            <template>
              <el-button
                v-if="delBtnState"
                type="primary"
                size="mini"
                @click="equipStatusCheck('2')"
                >批量删除</el-button
              >
              <el-button
                v-if="!delBtnState"
                type="primary"
                size="mini"
                @click="equipStatusCheck('3')"
                >删除</el-button
              >
              <el-button
                v-if="!delBtnState"
                size="mini"
                @click="equipStatusCheck('4')"
                >取消</el-button
              >
              <el-button
                type="primary"
                v-if="downBtnState"
                size="mini"
                @click="equipStatusCheck('7')"
                >图片下载</el-button
              >
              <el-button
                v-if="!downBtnState"
                type="primary"
                size="mini"
                @click="equipStatusCheck('8')"
                >下载</el-button
              >
              <el-checkbox-button
                size="mini"
                v-if="!downBtnState"
                :indeterminate="isIndeterminate"
                v-model="checkAll"
                @change="handleCheckAllChange"
                >全选</el-checkbox-button
              >
              <el-button
                v-if="!downBtnState"
                size="mini"
                @click="equipStatusCheck('9')"
                class="quxiao"
                >取消</el-button
              >
            </template>
          </div>
          <div class="search-box">
            <el-date-picker
              style="cursor: pointer"
              size="mini"
              v-model="timeRange"
              type="daterange"
              range-separator="至"
              clearable
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="DateChange"
            ></el-date-picker>
          </div>
        </div>
      </div>
    </div>
    <div class="baselistbox_photo">
      <el-row :gutter="30" v-viewer v-if="photoList.length > 0">
        <div class="none" v-if="!photoList.length">
          <img src="../../../static/images/quexingye.png" alt="" />
        </div>
        <el-col
          :xs="24"
          :sm="24"
          :md="12"
          :lg="6"
          :xl="6"
          v-for="item in photoList"
          :key="item.addr"
        >
          <div class="photoItem">
            <div class="photoInfo">
              <template>
                <i
                  class="iconfont icon-shanchu"
                  v-show="delBtnState && downBtnState"
                  @click="delectImg(item.id)"
                ></i>
                <el-checkbox
                  v-show="!delBtnState || !downBtnState"
                  style="width: 100%; height: 237px"
                  :value="idList.indexOf(item.id) != -1"
                  @change="stopDefault($event, item)"
                ></el-checkbox>
              </template>
            </div>
            <div class="photoImg">
              <!-- 有的图片放到阿里云，有的放到了服务器 -->
              <template v-if="item.addr.indexOf('http') != -1">
                <!-- <img :src="item.addr" /> -->
                <img v-lazy="item.addr" alt="" />
              </template>
              <template v-else>
                <!-- <img :src="$host + item.addr" /> -->
                <img v-lazy="$host + item.addr" />
              </template>
            </div>
            <div class="date" style="background: #fff">
              <div>
                {{ (item.addtime * 1000) | formatTime }}
              </div>
              <div>
                <span
                  style="color: #4f71ff; margin-left: 15px; cursor: pointer"
                  @click="addearly(item.id)"
                  >手动预警</span
                >
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
      <!-- 暂无数据 -->
      <div style="text-align: center" v-else>
        <img src="../../../static/images/quexingye.png" alt />
      </div>
      <div class="pagination">
        <el-pagination
          v-if="photoList.length > 0"
          background
          layout="prev, pager, next,jumper"
          :total="totalNum"
          :page-size="8"
          @current-change="changePage"
        >
        </el-pagination>
      </div>
    </div>
    <el-dialog
      title="手动预警"
      :visible.sync="adddialogVisible"
      :close-on-click-modal="false"
      width="580px"
    >
      <div class="addwarnbox">
        <el-form
          :model="warninginfo"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="预警标题" prop="title">
            <el-input
              size="mini"
              maxlength="15"
              v-model="warninginfo.title"
            ></el-input>
          </el-form-item>
          <el-form-item label="预警内容" prop="describe">
            <el-input
              size="mini"
              maxlength="100"
              type="textarea"
              v-model="warninginfo.describe"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="adddialogVisible = false"
          >取 消</el-button
        >
        <el-button size="mini" type="primary" @click="amend">确 定</el-button>
      </span>
    </el-dialog>
    <!-- <el-dialog
      title="预警信息"
      :visible.sync="seedialogVisible"
      :close-on-click-modal="false"
      width="580px"
    >
      <div class="addwarnbox">
        <el-form
          :model="seewarninginfo"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="预警标题" prop="title">
            <p>{{ seewarninginfo.title }}</p>
          </el-form-item>
          <el-form-item label="预警内容" prop="describe">
            <p>{{ seewarninginfo.describe }}</p>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog> -->
  </div>
</template>
<script>
export default {
  data() {
    return {
      zanwu: "/images/expertDiagnosis/zanwu.png",
      totalNum: 0,
      timeRange: [],
      delBtnState: true,
      downBtnState: true,
      device_id: this.$route.params.id,
      d_id: this.$route.query.d_id,
      photoList: [],
      queryInfo: {
        begin: "",
        end: "",
        page: 1,
      },
      // idList: [], //删除图片的地址数组
      idList: [], //选中图片的ids数组
      photoDescDialogVisible: false,
      times: 50, //下载图片定时器次数,超过50停止下载

      // 图片全选
      isIndeterminate: false,
      checkAll: false,
      dataList: [], // 选中图片的完整数据数组
      equipStatusObj: {
        name: this.$route.query.name,
        addr: this.$route.query.addr,
      },
      img_id: "",
      adddialogVisible: false,
      warninginfo: {
        title: "",
        describe: "",
      },
      rules: {
        title: [{ required: true, message: "请输入预警标题", trigger: "blur" }],
        describe: [
          { required: true, message: "请输入预警内容", trigger: "blur" },
        ],
      },
      seedialogVisible: false,
      seewarninginfo: {},
    };
  },
  mounted() {
    this.getPhoteList();
  },
  watch: {
    downBtnState(val) {
      if (val == true) {
        this.dataList = [];
        this.idList = [];
      }
    },
  },
  computed: {
    userType: function () {
      //获取用户类型
      return window.sessionStorage.getItem("myuser_type");
    },
  },
  methods: {
    // 册数多选框
    stopDefault(e, item) {
      if (this.idList.indexOf(item.id) == -1) {
        this.idList.push(item.id);
        this.dataList.push(item);
      } else {
        this.idList.splice(this.idList.indexOf(item.id), 1);
        this.dataList.splice(this.dataList.indexOf(item.id), 1);
      }
    },

    // 图片全选
    handleCheckAllChange(val) {
      // photoList
      console.log(val);
      if (val == true) {
        var list = [];
        var data = [];
        for (var i = 0; i < this.photoList.length; i++) {
          list.push(this.photoList[i].id);
          data.push(this.photoList[i]);
        }
        this.idList = list;
        this.dataList = data;
      } else if (val == false) {
        this.idList = [];
        this.dataList = [];
      }
      this.isIndeterminate = !this.isIndeterminate;
    },

    equipStatusCheck(flag) {
      this.active = flag;
      if (flag == 0) {
        //拍照
        this.equipBtnControl("takephoto");
      }
      if (flag == 1) {
        //刷新
        this.getPhoteList();
        if (document.getElementsByClassName("el-message").length == 0) {
          this.$message.success("图片刷新成功");
        }
      }
      if (flag == 2) {
        this.delBtnState = false;
        this.idList = this.photoList
          .filter((item) => {
            return item.checked == true;
          })
          .map((item) => {
            return item.id;
          });
      }
      if (flag == 3) {
        if (this.idList.length == 0) {
          if (document.getElementsByClassName("el-message").length == 0) {
            this.$message.warning("请选择要删除的图片！");
          }
        } else {
          this.delImgFun(this.idList);
        }
      }
      if (flag == 4) {
        this.photoList.map((item) => {
          item.checked = false;
        });
        this.delBtnState = true;
      }
      if (flag == 5) {
        this.delImgFun("");
      }

      if (flag == 7) {
        this.downBtnState = !this.downBtnState;
      }
      if (flag == 8) {
        //批量下载图片
        // if (this.dataList.length == 0) {
        //   if (document.getElementsByClassName("el-message").length == 0) {
        //     this.$message.warning("请选择要下载的图片！");
        //   }
        // } else {
        //   var a = {};
        //   for (let i = 0; i < this.dataList.length; i++) {
        //     setTimeout(() => {
        //       a["link" + i] = document.createElement("a"); // 创建a标签
        //       a["link" + i].href = this.dataList[i].addr;
        //       a["link" + i].download = "下载图片"; // 重命名文件
        //       a["link" + i].click();
        //     }, i * 1000);
        //   }
        // }
        var arr = [];
        for (let i = 0; i < this.dataList.length; i++) {
          arr.push(this.dataList[i].id);
        }
        console.log(arr)
        if (arr.length) {
          this.$axios({
            method: "POST",
            url: "api/img_download",
            data: this.qs.stringify({
              img_id: arr.join(","),
              device_type: 7,
            }),
            headers: {
              // 这里需要使用form-data格式数据发送请求
              "Content-Type": "application/x-www-form-urlencoded",
            },
            responseType: "blob",
          })
            .then((res) => {
              console.log(res);
              const elink = document.createElement("a");
              elink.download = "img.zip";
              elink.style.display = "none";
              const blob = new Blob([res.data], { type: "application/zip" });
              const href = URL.createObjectURL(blob);
              elink.href = href;
              document.body.appendChild(elink);
              elink.click();
              document.body.removeChild(elink);
              window.URL.revokeObjectURL(href);
            })
            .catch(() => {
              if (document.getElementsByClassName("el-message").length == 0) {
                this.$message.error("请求图片资源超时，请稍后重试");
              }
            });
        } else {
          if (document.getElementsByClassName("el-message").length == 0) {
            this.$message.warning("请选择下载图片");
          }
        }
      }
      if (flag == 9) {
        this.photoList.map((item) => {
          item.checked = false;
        });
        this.downBtnState = true;
        this.isIndeterminate = true;
        this.checkAll = false;
      }
    },
    equipBtnControl(cmd) {
      this.$axios({
        method: "POST",
        url: "/api/api_gateway?method=forecast.send_control.admin_device_control",
        data: this.qs.stringify({
          cmd,
          device_type_id: 7,
          d_id: this.$route.query.d_id,
        }),
      }).then((res) => {
        if (res.data.message == "") {
          if (document.getElementsByClassName("el-message").length == 0) {
            this.$message.success("指令下发成功!");
          }
        }
      });
    },
    getPhoteList() {
      this.$axios({
        method: "POST",
        url: "/api/api_gateway?method=forecast.forecast_system.equip_photo",
        data: this.qs.stringify({
          device_id: this.device_id,
          ret: "list",
          page: this.queryInfo.page,
          page_number: 8,
          time_begin: this.queryInfo.begin,
          time_end: this.queryInfo.end,
        }),
      }).then((res) => {
        if (res.data.message == "") {
          let data = res.data.data.data;
          this.photoList = data.map((item) => {
            item.checked = false;
            return item;
          });
          this.totalNum = res.data.data.num;
          console.log(this.totalNum);
        }
      });
    },
    //改变page
    changePage(val) {
      this.queryInfo.page = val;
      this.getPhoteList();
    },
    DateChange() {
      this.queryInfo.page = 1;
      if (this.timeRange) {
        this.queryInfo.begin = parseInt(
          new Date(this.timeRange[0]).getTime() / 1000
        );
        this.queryInfo.end = parseInt(
          new Date(this.timeRange[1]).getTime() / 1000
        );
      } else {
        this.queryInfo.begin = "";
        this.queryInfo.end = "";
      }
      this.getPhoteList();
    },
    viewDes() {
      this.$prompt("图片描述", "添加详情", {
        confirmButtonText: "保存",
        cancelButtonText: "取消",
      })
        .then(({ value }) => {})
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消输入",
          });
        });
    },
    delImgFun(idList) {
      this.$confirm("此操作将永久删除该设备图片, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$axios({
            method: "POST",
            url: "/api/api_gateway?method=forecast.forecast_system.equip_photo_del",
            data: this.qs.stringify({
              device_id: this.device_id,
              addrlist: JSON.stringify(idList),
            }),
          }).then((res) => {
            if (res.data.message == "") {
              if (document.getElementsByClassName("el-message").length == 0) {
                this.$message({
                  type: "success",
                  message: "删除成功!",
                });
              }
              this.getPhoteList();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    delectImg(id) {
      this.delImgFun([id]);
    },
    //返回上一页
    goBackPage() {
      this.$router.go(-1);
    },
    downloadFile(data) {
      let blob = new Blob([data], { type: "application/zip" });
      let url = window.URL.createObjectURL(blob);
      const link = document.createElement("a"); // 创建a标签
      link.href = url;
      link.download = "下载图片"; // 重命名文件
      link.click();
      URL.revokeObjectURL(url); // 释放内存
    },
    downPhoto(arr) {
      let uid = sessionStorage.getItem("myuid");
      let image_id = arr.join(",");
      this.$axios({
        method: "post",
        url: "/api/api_gateway?method=forecast.worm_lamp.get_task_id",
        data: this.qs.stringify({
          image_id,
          myuid: uid,
        }),
      }).then((res) => {
        if (res.data.message == "") {
          this.$message.success("图片下载中！");
          let that = this;
          this.cy_id = res.data.data;
          function downPhotoState() {
            if (that.times >= 0) {
              that.times--;
              that
                .$axios({
                  method: "POST",
                  url: "/api/api_gateway?method=forecast.worm_lamp.check_down",
                  data: that.qs.stringify({
                    get_id: that.cy_id,
                  }),
                })
                .then((res) => {
                  if (res.data.data) {
                    // 判断后台从阿里云下载图片是否完成
                    clearInterval(interval);
                    that
                      .$axios({
                        method: "POST",
                        url: "/api/image_down",
                        responseType: "blob",
                        data: that.qs.stringify({
                          get_id: that.cy_id,
                        }),
                      })
                      .then((res) => {
                        that.downloadFile(res.data);
                      });
                  }
                })
                .catch((error) => this.$message.error(error));
            } else {
              clearInterval(interval);
              that.$message.warning("图片下载失败！");
            }
          }
          var interval = setInterval(downPhotoState, 1000);
        }
      });
    },
    addearly(id) {
      this.img_id = id;
      this.adddialogVisible = true;
    },
    // seeearly(id) {
    //   this.seedialogVisible = true
    //   this.$axios({
    //     method: "POST",
    //     url: "/api/api_gateway?method=device.device_picture.bzy_warning_list",
    //     data: this.qs.stringify({
    //       img_id: id,
    //     }),
    //   }).then((res) => {
    //     if (res.data.message == "") {
    //       console.log(res.data.data.data[0])
    //       this.seewarninginfo  = res.data.data.data[0]
    //     }
    //   });
    // },
    amend() {
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          this.$axios({
            method: "POST",
            url: "/api/api_gateway?method=device.device_picture.bzy_photo_warning_save",
            data: this.qs.stringify({
              img_id: this.img_id,
              title: this.warninginfo.title,
              describe: this.warninginfo.describe,
            }),
          }).then((res) => {
            if (res.data.message == "") {
              if (document.getElementsByClassName("el-message").length == 0) {
                this.$message.success("设置成功");
              }
              this.adddialogVisible = false;
              this.warninginfo = {
                title: "",
                describe: "",
              };
            } else {
              if (document.getElementsByClassName("el-message").length == 0) {
                this.$message.error("设置失败");
              }
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
};
</script>

<style lang='less' scoped>
.baselistbox_top {
  width: 100%;
  // height: 130px;
  background-color: #fff;
  border-radius: 10px;
  .baselistbox_top_title {
    width: 100%;
    height: 65px;
    display: flex;
    padding: 20px;
    box-sizing: border-box;
    line-height: 25px;
    p:first-child {
      font-size: 14px;
      margin-right: 20px;
    }
    p:last-child {
      font-size: 18px;
      font-weight: 700;
    }
  }
  .baselistbox_top_line {
    width: 100%;
    height: 1px;
    background-color: #f2f2f2;
  }
  .baselistbox_top_search {
    width: 100%;
    padding: 20px;
    box-sizing: border-box;
    line-height: 28px;
    .capzuo_left {
      font-size: 14px;
      margin-bottom: 20px;
    }
  }
}
.baselistbox_photo {
  width: 100%;
  height: calc(100% - 140px);
  background-color: #fff;
  margin-top: 10px;
  padding: 20px;
  box-sizing: border-box;
  border-radius: 10px;
  .none {
    width: 100%;
    display: flex;
    justify-content: space-around;
  }
  .pagination {
    display: flex;
    justify-content: flex-end;
    margin-top: 10px;
    /deep/.el-pager {
      .active {
        background-color: #4f71ff !important;
      }
    }
    /deep/.el-input__inner:hover {
      border-color: #4f71ff;
    }
  }
}
.check-btns {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
  margin-bottom: 20px;
  align-items: center;
  .el-select {
    width: 90px;
  }
  .type-check {
    // 全选按钮
    /deep/ .el-checkbox-button__inner {
      background: #e6a23c;
      color: #fff;
      padding: 7px 15px;
      font-size: 12px;
      border-radius: 3px;
      border: 0;
      outline: none;
      height: 26px;
    }
    /deep/ .el-checkbox-button__inner:hover {
      color: #fff;
    }
    /deep/ .el-checkbox-button__inner {
      border-color: #e6a23c;
    }
    .quxiao {
      color: black !important;
      background: white !important;
    }
  }
}
.backbox {
  display: flex;
}
.photoItem {
  position: relative;
  border-radius: 10px;
  overflow: hidden;
  .photoInfo {
    position: absolute;
    top: 10px;
    left: 10px;
    right: 10px;
    display: flex;
    justify-content: space-between;
    span {
      color: #fff;
    }
    i {
      cursor: pointer;
      color: red;
      display: none;
    }
  }
  .photoImg {
    height: 250px;
    cursor: pointer;
    img {
      width: 100%;
      height: 100%;
    }
  }
  .date {
    text-align: center;
    font-size: 14px;
    padding: 10px 0;
    display: flex;
    justify-content: space-between;
    line-height: 19px;
  }
  .photoCtrl {
    background-color: #fff;
    text-align: center;
    line-height: 30px;
    font-size: 14px;
    color: #666;
    display: flex;
    justify-content: center;
    position: relative;
    cursor: pointer;
    .el-checkbox {
      position: absolute;
      right: 10px;
    }
  }
}
.photoItem:hover {
  .photoInfo i {
    display: block;
  }
}
/deep/.el-button {
  background-color: #4f71ff;
  color: #fff;
}
/deep/.el-checkbox-button__inner {
  background-color: #4f71ff !important;
  color: #fff;
}
.addwarnbox {
  /deep/.el-textarea {
    .el-textarea__inner {
      font-family: "Avenir", Helvetica, Arial, sans-serif;
    }
  }
}
</style>