<!-- 预警图片 -->
<template>
  <div class="innerMargin">
      <el-card class="box-card">
        <div class="cbdPhoto">
            <div class="timeLIneLeft">
                <div class="title">项目名称</div>
                <div class="timeTree">
                  <div class="scroll">
                    <el-scrollbar>
                      <el-tree 
                        :data="menuData" 
                        accordion
                        :props="defaultProps"
                        node-key="name"
                        ref="tree"
                        :default-expanded-keys="[menuDataFirst]"
                        :highlight-current="true"
                        :check-on-click-node="true"
                        @node-click="treeClick">
                          <span class="custom-tree-node" slot-scope="{ node, data }">
                            <span>
                              <!-- <i :class="[node.data.leaf?'el-icon-document':'',node.expanded?'el-icon-folder-opened':'el-icon-folder']"></i>{{ data.label }} -->
                              <i :class="[renderIconContent(node,data),'treeicon']"></i>{{ data.name }}
                            </span>
                          </span>
                      </el-tree>
                    </el-scrollbar>
                  </div>
                </div>
            </div>
            <div class="photosRight">
              <div class="typeBtns">
                <div>
                  时间筛选：
                  <el-date-picker
                    v-model="queryInfo.searchTime"
                    type="daterange"
                    size="small" 
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    @change="DateChange">
                  </el-date-picker>
                </div>
                <div>
                  <el-button 
                    type="blueInfo" 
                    size="small" 
                    @click="equipStatusCheck('1')"
                    >刷新</el-button
                  >
                  <el-button
                    v-if="delBtnState"
                    type="blueInfo"
                    size="small"
                    @click="equipStatusCheck('2')"
                    >批量删除</el-button
                  >
                  <el-button
                    v-if="!delBtnState"
                    type="blueInfo"
                    size="small"
                    @click="equipStatusCheck('3')"
                    >删除</el-button
                  >
                  <el-button
                    v-if="!delBtnState"
                    type="grayInfo"
                    size="small"
                    @click="equipStatusCheck('4')"
                    >取消</el-button
                  >
                  <!-- <el-button type="blueInfo" size="small" @click="equipStatusCheck('5')"
                    >一键删除</el-button
                  >
                  <el-button
                    v-if="downBtnState"
                    type="blueInfo"
                    size="small"
                    @click="equipStatusCheck('7')"
                    >图片下载</el-button
                  >
                  <el-button
                    v-if="!downBtnState"
                    type="blueInfo"
                    size="small"
                    @click="equipStatusCheck('8')"
                    >下载</el-button
                  >
                  <el-button
                    v-if="!downBtnState"
                    type="grayInfo"
                    size="small"
                    @click="equipStatusCheck('9')"
                    >取消</el-button
                  > -->
                </div>
              </div>
              <div class="phohos">
                <el-row :gutter="20">
                  <el-col  :xs="12" :sm="12" :md="12" :lg="8" :xl="6" v-for="(item) in imgDataList" :key="item.id">
                    <div class="grid-content bg-gray">
                      <div class="delBoxs">
                        <i
                          class="iconfont icon-shanchu"
                          v-show="delBtnState && downBtnState"
                          @click="delectImg(item.id)"
                        ></i>
                        <el-checkbox
                          v-show="!delBtnState || !downBtnState"
                          v-model="item.checked"
                        ></el-checkbox>
                      </div>
                      <div class="imgBox" v-viewer>
                        <img
                          v-lazy="item.warning_pic"
                          @error="errImg"
                          alt
                        />
                      </div>
                      <div class="photoTime" >
                        <span>{{item.warning_time*1000 | formatTime}}</span>
                        <span  @click="searchResult(item)">
                          <i class="el-icon-search"></i>预警信息
                        </span>
                      </div>
                    </div>
                  </el-col>
                  <el-col  :xs="12"  v-if="!imgDataList.length">
                    <div class="empty">
                      <img src="../../../../static/images/emptyDataImg2.png" alt="">
                    </div>
                  </el-col>
                </el-row>

                <el-pagination
                  v-if="imgDataList.length"
                  background
                  layout="prev, pager, next"
                  :total="totalNum"
                  @current-change="changePage"
                  :current-page="queryInfo.page"
                  :page-size="8"
                ></el-pagination>
              </div>
                
            </div>
        </div>
      </el-card>
      <el-dialog
        title="预警详情"
        :visible.sync="detailsShow"
        width="500px"
        top="180px"
      >
        <div class="discernResult">
          <div :title="currDetails.device_id">关联设备：{{currDetails.device_name || '设备：'+currDetails.device_id}}</div>
          <div>拍照时间：{{currDetails.warning_time*1000 | formatTime}}</div>
          <div>拍照原因：{{currDetails.warning_info}}</div>
        </div>
      </el-dialog>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
export default {
  //import引入的组件需要注入到对象中才能使用
  components: {
  },
  data() {
    //这里存放数据
    return {
      currProjectId:'',
      menuData: [],
      menuDataFirst:'',
      defaultProps: {
        children: 'children',
        label: 'name1',
      },
      totalNum:0,
      queryInfo:{
        searchTime:'',
        begin:'',
        end:'',
        page:1,
      },
      imgDataList:[],
      delBtnState:true,
      downBtnState: true,
      detailsShow:false,
      currDetails:{},
    };
  },
  //监听属性 类似于data概念
  computed: {

  },
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    getProject() {
      this.$axios({
        method: "post",
        url: "/api/api_gateway?method=weather.weather.classify_page",
        data: this.qs.stringify({
          device_type:'11',
        })
      }).then(res => {
        if (res.data.message == "") { 
          var dat  = res.data.data;
          this.menuData = dat.filter((item)=>{
            return item.children.length>0
          });
          if(this.menuData.length){
            if(this.$store.state.wran_project_name){
              this.menuDataFirst = this.$store.state.wran_project_name;
              this.currProjectId = this.$store.state.jk_wran_id;
            }else{
              this.menuDataFirst = this.menuData[0].name;
              this.currProjectId = this.menuData[0].children[0].device_id;
            }
            this.$nextTick(() => {
            if(this.$store.state.jk_wran_name){
              this.$refs.tree.setCurrentKey(this.$store.state.jk_wran_name);
            }else{
              this.$refs.tree.setCurrentKey(this.menuData[0].children[0].name);
            }
            })
            this.imgListData()
          }
        }
      });
    },
    treeClick(data) {
      console.log(data);
      if(data.children){
      }else{
        this.currProjectId = data.device_id;
        this.imgListData()
      }
    },
    // 列表图片加载失败
    errImg(e) {
      e.target.src = $imghost + "/images/expertDiagnosis/ku/noData.jpg";
    },
    DateChange(val){
      if(this.queryInfo.searchTime){
        this.queryInfo.begin = parseInt(
          new Date(this.queryInfo.searchTime[0]).getTime() / 1000
        )
        this.queryInfo.end = parseInt(
          new Date(this.queryInfo.searchTime[1]).getTime() / 1000
        )
      }else{
        this.queryInfo.begin = '';
        this.queryInfo.end = '';
      }
      this.imgListData();
    },
    renderIconContent(node,data){
      if(node.data.leaf){
        return 'el-icon-document document'
      }else{
        if(node.expanded){
          return 'el-icon-folder-opened'
        }else{
          return 'el-icon-folder'
        }
      }
      
    },
    //控制按钮
    equipStatusCheck(flag) {
      if (flag == 1) {
        this.imgListData(); //图片列表数据请求
      }
      if (flag == 2) {
        //批量删除
        this.delBtnState = false;
        this.downBtnState = true;
      }

      if (flag == 3) {
        //删除
        this.idList = this.imgDataList
          .filter((item) => {
            return item.checked == true;
          })
          .map((item) => {
            return item.id;
          });
        if (this.idList.length == 0) {
          this.$message.warning("请选择要删除的图片！");
        } else {
          this.delImgFun(this.idList);
        }
      }

      if (flag == 4) {
        //取消
        this.imgDataList.map((item) => {
          item.checked = false;
        });
        this.delBtnState = true;
      }

      if (flag == 5) {
        this.delImgFun("");
      }
      if (flag == 6) {
        this.$router.push(`/index/messageWarn/${this.id}`);
      }
      if (flag == 7) {
        this.downBtnState = !this.downBtnState;
        this.delBtnState = true;
      }
      if (flag == 8) {
        //批量下载图片
        this.idList = this.imgDataList
          .filter((item) => {
            return item.checked == true;
          })
          .map((item) => {
            return item.id;
          });
        if (this.idList.length == 0) {
          this.$message.warning("请选择要下载的图片！");
        } else {
          this.downPhoto(this.idList);
        }
      }
      if (flag == 9) {
        this.imgDataList.map((item) => {
          item.checked = false;
        });
        this.downBtnState = !this.downBtnState;
      }
    },
     //图片列表数据请求
    imgListData() {
      let postData = this.qs.stringify({
        device_id: this.currProjectId,
        page_size: 8,
        page: this.queryInfo.page,
        start_time:  this.queryInfo.begin, //开始时间（时间戳）
        end_time: this.queryInfo.end, //结束时间（时间戳）
      });
      this
        .$axios({
          method: "post",
          url: "/api/api_gateway?method=weather.weather.warning_info", //forecast.forecast_system.equip_photo
          data: postData,
        })
        .then((res) => {
          if(res.data.message == ""){
            this.imgDataList = res.data.data.data
            this.totalNum = res.data.data.nums;
          }

        })
        .catch((err) => {
          console.log(err);
        });
    },
    //改变page
    changePage(val) {
      this.queryInfo.page = val;
      this.imgListData();
    },
    delectImg(id){
      this.delImgFun([id])
    },
    // 批量删除
    delImgFun(idList) {
      this.$confirm("此操作将永久删除该设备图片, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$axios({
            method: "POST",
            url:
              "/api/api_gateway?method=weather.weather.warning_info",
            data: this.qs.stringify({
              id: JSON.stringify(idList),
            }),
          }).then((res) => {
            if (res.data.message == "") {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.imgListData(); //图片列表数据请求
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    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 = this.$store.state.user_id;
      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",
                        withCredentials: true,
                        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);
        }
      });
    },
    // 预警信息
    searchResult(data) {
      this.currDetails = data;
      this.detailsShow = true;
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.getProject()
    console.log(this.id);
    console.log(this.d_id);
    
  },
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {
    this.$store.commit('setData',{
        name:'wran_project_name',
        val:''
    })
    this.$store.commit('setData',{
        name:'jk_wran_name',
        val:''
    })
  }, //生命周期 - 销毁完成
  activated() {} //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style scoped lang="less">
.cbdPhoto,.photoTime{
  display: flex;
  justify-content: space-between;
}
.typeBtns{
  /deep/.el-input-group__append{
    background-color: #34abff;
    color: #ffffff;
    border: 1px solid #34abff;
  }
  .el-input{
    width: 230px;
    // display: inline-block;
  }
}
.photoTime{
  align-items: center;
}
.timeLIneLeft{
  width: 300px;
  max-height: 700px;
  overflow: auto;
  .title{
    font-size: 14px;
    color: #0195ff;
  }
}
.photosRight{
  flex: 1;
}
/deep/.el-radio-button__orig-radio:checked + .el-radio-button__inner {
    color: #FFFFFF;
    background-color: #0195ff;
    border-color: #0195ff;
    -webkit-box-shadow: -1px 0 0 0 #14a478;
    box-shadow: -1px 0 0 0 #14a478;
}
/deep/.el-radio-button__inner:hover{
  color: #0195ff;
}
.phohos{
  margin-top: 20px;
  .bg-gray{
    position: relative;
    background: #eee;
    padding: 15px;
    border-radius: 5px;
    margin-bottom: 11px;
    .imgBox{
      height: 315px;
      background: #000;
      text-align: center;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      img{
        height: 100%;
        position: absolute;
        left: 50%;
        transition: 1s;
        transform: translateX(-50%);
      }
      .uptime{
        position: absolute;
        left: 0;
        top: 0;
        color: #fff;
        font-size: 14px;
        line-height: 28px;
        padding-left: 5px;
      }
    }
    .delBoxs{
      position: absolute;
      right: 20px;
      color: red;
      z-index: 9;
      cursor: pointer;
      top: 25px;
      i{
        font-size: 18px;
        display: none;
      }
    }
    
    .photoTime{
      margin-top: 5px;
      font-size: 14px;
      line-height: 22px;
      span:nth-child(2){
        background: #f0c700;
        color: #fff;
        padding: 2px 7px;
        border-radius: 3px;
        cursor: pointer;
      }
    }
  }
  .bg-gray:hover .delBoxs i{
    display: block;
  }
}
.el-pagination .el-pager li.active{
  background-color: #0195ff!important;
}
.el-tree{
  font-size: 14px;
  .treeicon{
    margin-right: 5px;
    color: #f0bb25;
  }
  .document.treeicon{
    color: #d5eeff;
  }
  .is-current{
    .treeicon:nth-child(1){
      color: #ffa02a;
    }
  }
}
/deep/.el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
    background-color: #d5eeff;
}
/deep/.el-checkbox__input.is-checked .el-checkbox__inner{
    background-color: #0295ff;
    border-color: #006fbe;
}
// 滚动条
.timeTree{
  margin-right: 20px;
  height: 650px;
}
.scroll {
    height: 100%;
    overflow-y: hidden;
    }
    .el-scrollbar{
    height: 100%;
    }
    .el-scrollbar__bar{
    &.is-vertical{
        width:100px;//滚动条宽度
    }
    }
    /deep/.el-scrollbar__wrap{
    overflow-y: auto;
    overflow-x:hidden;
    }
    /deep/.el-scrollbar__thumb{
      background-color: rgb(2 149 255);
    }
    .el-scrollbar__thumb {
    // 可设置滚动条颜色
    background: red;
}
// 分页为蓝色调
/deep/.el-pagination .el-pager li.active{
  background-color: #0295ff!important;  
}
/deep/.el-pagination.is-background .el-pager li:not(.disabled):hover{
	color: #0295ff;
}
/deep/.el-input__inner:focus{
  outline: none;
  border-color: #0295ff;
}
// 预警信息弹框
.discernResult{
  div{
    line-height: 30px;
    cursor: pointer;
  }
}
.typeBtns {
  display: flex;
  justify-content: space-between;
}

.empty{
  line-height: 600px;
  text-align: center;
}
</style>