<!--  -->
<template>
  <div class="baselistbox">
    <div class="baselistbox_top">
      <div class="baselistbox_top_title">
        <p>虫情监测</p>
        <div class="warningInfo" v-if="warningList.length !== 0">
          <div class="title" @click="showWarningInfo">
            <div>
              <i class="iconfont el-icon-s-order" style="margin-right: 10px"></i
              >{{ onewarning.device_id | subDeviceId }}
              {{ warning_status(onewarning.warning_status) }}
            </div>
            <i class="el-icon-bell"></i>
          </div>
          <ul
            class="warningInfoList"
            v-if="isWarningList"
            v-infinite-scroll="load"
            infinite-scroll-delay="200"
            infinite-scroll-immediate="false"
          >
            <li @click="oneWarningList()">
              <div style="padding-left: 10px">
                <i class="iconfont el-icon-s-promotion"></i>一键已读
              </div>
            </li>
            <li v-for="(item, index) in warningList" :key="index">
              <el-popover placement="left" trigger="click" style="">
                <div style="padding: 5px 0px; width: 500px">
                  设备编号：{{ item.device_id }}
                </div>
                <div style="padding: 5px 0px; width: 500px; line-height: 30px">
                  详细信息：{{
                    item.detailsInfo ||
                    detail(item.warning_content, item.warning_status)
                  }}
                </div>
                <el-button
                  slot="reference"
                  @click="yidu(item.d_id)"
                  style="background-color: transparent"
                >
                  <i class="circle" v-if="item.status == 0"></i>
                  <div
                    style="width: 60%; text-align: left"
                    :class="item.status == 0 ? 'active' : ''"
                  >
                    {{ item.device_id | subDeviceId }}
                    {{ warning_status(item.warning_status) }}
                  </div>
                  <span :class="item.status == 0 ? 'active' : ''">{{
                    (item.upltime * 1000) | formatTime
                  }}</span>
                </el-button>
              </el-popover>
            </li>
          </ul>
        </div>
      </div>
      <p class="baselistbox_top_line"></p>
      <div class="baselistbox_top_search">
        <div class="left_search">
          <div class="firstsearch">
            <span class="biaoti">设备ID或名称</span>
            <el-input
              v-model="queryInfo.f_id"
              size="mini"
              placeholder="请输入设备ID或名称"
            ></el-input>
          </div>
          <div class="secsearch">
            <span class="biaoti">设备状态</span>
            <el-select
              v-model="queryInfo.is_online"
              size="mini"
              filterable
              placeholder="请选择"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </div>
        </div>
        <div class="right_search">
          <div class="btnbox" @click="searchChange">查询</div>
          <div class="btnbox2" @click="empty">重置</div>
        </div>
      </div>
    </div>
    <div class="baselistbox_table">
      <el-table
        v-loading="loading"
        :data="equipList"
        stripe
        style="width: 100%"
        height="560px"
        :default-sort="{ prop: 'device_name', order: 'addtime' }"
      >
        <el-table-column
          prop="device_name"
          sortable
          label="设备名称"
          width="180"
        >
          <template slot-scope="scope">{{
            scope.row.device_name == "" ? "无" : scope.row.device_name
          }}</template>
        </el-table-column>
        <el-table-column prop="imei" label="设备ID" width="180">
          <template slot-scope="scope">{{ scope.row.imei }}</template>
        </el-table-column>
        <el-table-column prop="device_status" label="在线状态" width="100">
          <template slot-scope="scope">
            <p style="color: #17bb89" v-if="scope.row.is_online == 1">在线</p>
            <p style="color: #eb6765" v-if="scope.row.is_online == 0">离线</p>
          </template>
        </el-table-column>
        <el-table-column
          prop="dtype"
          label="设备版本"
          width="300"
        ></el-table-column>
        <el-table-column prop="uptime" sortable label="最新上报时间">
          <template slot-scope="scope">{{
            (scope.row.uptime * 1000) | formatTime
          }}</template>
        </el-table-column>
        <el-table-column prop="address" label="地址" width="300">
          <template slot-scope="scope" :title="scope.row.address">{{
            scope.row.address || "无" | ellipsis
          }}</template>
        </el-table-column>
        <el-table-column label="操作" width="350">
          <template slot-scope="scope">
            <span
              style="color: #4f71ff; margin-right: 15px; cursor: pointer"
              @click="
                viewPhotoDialog(
                  scope.row.imei,
                  scope.row.d_id,
                  scope.row.device_name,
                  scope.row.address,
                  scope.row.disable
                )
              "
              >查看图片</span
            >
            <span
              style="color: #4f71ff; margin-right: 15px; cursor: pointer"
              @click="
                EquipControl(
                  scope.row.d_id,
                  scope.row.imei,
                  scope.row.device_name
                )
              "
              >设备控制</span
            >
            <span
              style="color: #4f71ff; margin-right: 15px; cursor: pointer"
              @click="
                showTimeControlDialog(
                  scope.row.d_id,
                  scope.row.imei,
                  scope.row.disable
                )
              "
              >虫情分析</span
            >
            <span
              style="color: #4f71ff; margin-right: 15px; cursor: pointer"
              @click="dataDetails(scope.row.imei, scope.row.d_id, scope.row)"
              >数据详情</span
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          background
          layout="prev, pager, next,sizes,jumper"
          :total="totalNum"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="queryInfo.page_size"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-size.sync="queryInfo.page"
          :key="queryInfo.pagekey"
        >
        </el-pagination>
      </div>
    </div>
    <el-dialog
      title="设备控制"
      :visible.sync="equipControlDialogVisible"
      @close="resetEquipControlDialogClosed"
      width="600px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="handAddForm">
        <el-form
          ref="equipContrlRef"
          :model="equipContrlForm"
          label-position="right"
          label-width="150px"
        >
          <el-form-item label="设备编号:">
            <el-input
              disabled
              size="mini"
              v-model="equipInfo.device_id"
            ></el-input>
          </el-form-item>
          <el-form-item label="设备名称:">
            <el-input
              size="mini"
              v-model="equipInfo.device_name"
              :maxlength="10"
              style="width: 200px"
            ></el-input>
          </el-form-item>
          <el-form-item label="设备开关:" prop="ds">
            <el-select v-model="equipContrlForm.ds" size="mini">
              <el-option label="开机" :value="1"></el-option>
              <el-option label="关机" :value="0"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="定时模式:" prop="ts">
            <el-select
              v-model="equipContrlForm.ts"
              placeholder="请选择定时模式"
              size="mini"
            >
              <el-option label="光控" :value="0"></el-option>
              <el-option label="时控" :value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-if="equipContrlForm.ts == 1" label="开始结束时间:">
            <el-col :span="11">
              <el-time-select
                placeholder="起始时间"
                v-model="equipContrlForm.st"
                :picker-options="{
                  start: '00:00',
                  step: '01:00',
                  end: '23:00',
                }"
                size="mini"
              ></el-time-select>
            </el-col>
            <el-col class="line" :span="2">-</el-col>
            <el-col :span="11">
              <el-time-select
                placeholder="结束时间"
                v-model="equipContrlForm.et"
                :picker-options="{
                  start: '00:00',
                  step: '01:00',
                  end: '23:00',
                }"
                size="mini"
              ></el-time-select>
            </el-col>
          </el-form-item>
          <el-form-item
            v-if="equipContrlForm.ts != 1"
            label="定时时长(h):"
            prop="tt"
          >
            <div class="sliderParent">
              <div class="block">
                <el-slider
                  v-model="equipContrlForm.tt"
                  show-input
                  :min="1"
                  :max="10"
                ></el-slider>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="落虫时间(min):" prop="collt">
            <div class="sliderParent">
              <div class="block">
                <el-slider
                  v-model="equipContrlForm.collt"
                  show-input
                  :min="1"
                  :max="20"
                ></el-slider>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="加热时间(min):" prop="htim">
            <div class="sliderParent">
              <div class="block">
                <el-slider
                  v-model="equipContrlForm.htim"
                  show-input
                  :min="1"
                  :max="20"
                ></el-slider>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="加热温度(℃):" prop="hst">
            <div class="sliderParent">
              <div class="block">
                <el-slider
                  v-model="equipContrlForm.hst"
                  show-input
                  :min="75"
                  :max="120"
                ></el-slider>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="高温保护阈值(℃):" prop="tph">
            <div class="sliderParent">
              <div class="block">
                <el-slider
                  v-model="equipContrlForm.tph"
                  show-input
                  :min="50"
                  :max="70"
                ></el-slider>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="低温保护阈值(℃):" prop="tpl">
            <div class="sliderParent">
              <div class="block">
                <el-slider
                  v-model="equipContrlForm.tpl"
                  show-input
                  :min="-30"
                  :max="10"
                ></el-slider>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="数据上传间隔(min):" prop="datt">
            <div class="sliderParent">
              <div class="block">
                <el-slider
                  v-model="equipContrlForm.datt"
                  :step="10"
                  show-input
                  :min="10"
                  :max="60"
                ></el-slider>
              </div>
            </div>
          </el-form-item>
          <!-- <el-form-item class="handAddFormBtn">
            <el-button type="primary" size="mini" @click="equipControlSubm()"
              >确定</el-button
            >
            <el-button size="mini" @click="equipControlDialogVisible = false"
              >取消</el-button
            >
          </el-form-item> -->
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="equipControlDialogVisible = false"
          >取 消</el-button
        >
        <el-button size="mini" type="primary" @click="equipControlSubm"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）

export default {
  filters: {
    ellipsis(value) {
      if (!value) return "";
      if (value.length > 15) {
        return value.slice(0, 15) + "...";
      }
      return value;
    },
    momentTime(data) {
      // return moment(Number(data * 1000)).format("YYYY-MM-DD HH:mm:ss");
      return data;
    },
    subDeviceId(data) {
      if (!data) return "";
      let id = data.substring(data.length - 6);
      return id;
    },
  },
  //import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    //这里存放数据
    return {
      queryInfo: {
        page_size: "10",
        page: "1",
        is_online: "",
        f_id: "",
        pagekey:1
      },
      options: [
        {
          value: "",
          label: "全部",
        },
        {
          value: "1",
          label: "在线",
        },
        {
          value: "0",
          label: "离线",
        },
      ],
      equipList: [],
      loading: false,
      equipControlDialogVisible: false,
      equipContrlForm: {},
      equipInfo: {},
      totalNum: 0,
      isWarningList: false,
      warningList: [],
      onewarning: {
        warning_status: "",
        device_id: "",
      },
      cbdWarningPage: 1,
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    //获取设备列表
    getEquipList() {
      this.$axios({
        method: "POST",
        url: "/api/api_gateway?method=forecast.worm_lamp.lamp_list",
        data: this.qs.stringify({
          device_type_id: 3,
          page_size: this.queryInfo.page_size,
          page: this.queryInfo.page,
          device_status: this.queryInfo.is_online,
          device_id: this.queryInfo.f_id,
        }),
      }).then((res) => {
        if (res.data.message == "") {
          this.equipList = res.data.data.data;
          // insectVal
          for (var i = 0; i < this.equipList.length; i++) {
            if (this.equipList[i].disable == 0) {
              // 禁用
              this.equipList[i].insectVal = "禁用";
            } else if (this.equipList[i].disable == 1) {
              // 识别
              this.equipList[i].insectVal = "识别";
            } else if (this.equipList[i].disable == 2) {
              // 计数
              this.equipList[i].insectVal = "计数";
            }
          }
          this.equipList.insectVal = this.totalNum = res.data.data.counts;
          this.loading = false;
        }
        console.log(res.data.data.data);
        var data = res.data.data.data;
        for (var i = 0; i < data.length; i++) {
          if (data[i].disable == "2") {
            console.log(data[i].imei + "这是计数");
          } else if (data[i].disable == "1") {
            console.log(data[i].imei + "这是带识别的");
          }
        }
        // this.$nextTick(() => {
        //   document.getElementsByClassName("number")[0].innerText = "首页";
        //   var length = document.getElementsByClassName("number").length;
        //   document.getElementsByClassName("number")[length - 1].innerText =
        //     "末页";
        // });
      });
    },
    handleSizeChange(e) {
      this.queryInfo.page_size = e;
      this.getEquipList();
    },
    handleCurrentChange(e) {
      this.queryInfo.page = e;
      this.getEquipList();
    },
    searchChange() {
      this.queryInfo.page = 1;
      this.pagekey = Math.random()*10+1
      this.getEquipList();
    },
    empty() {
      this.queryInfo.page = 1;
      this.pagekey = Math.random()*10+1
      this.queryInfo.is_online = "";
      this.queryInfo.f_id = "";
      this.getEquipList();
    },
    EquipControl(d_id, device_id, device_name) {
      this.d_id = d_id;
      this.equipInfo = { device_id, device_name };
      this.$axios({
        method: "POST",
        url: "/api/api_gateway?method=forecast.send_control.device_control_info",
        data: this.qs.stringify({ d_id, cmd: "paramconf" }),
      }).then((res) => {
        if (res.data.data && Object.keys(res.data.data).length > 0) {
          let data = res.data.data;
          data.ds = Number(data.ds);
          data.st =
            data.st && data.st < 10 ? "0" + data.st + ":00" : data.st + ":00";
          data.et =
            data.et && data.et < 10 ? "0" + data.et + ":00" : data.et + ":00";
          // this.equipContrlForm = data;
          // console.log(data)
          var obj = {};
          console.log(data);
          console.log(data.ds);
          for (let kay in data) {
            if (typeof data[kay] == "string" && kay !== "st" && kay !== "et") {
              var a = data[kay];
              if (Number(a) < 0) {
                obj[kay] = Number(data[kay]);
              } else if (Number(a) >= 0) {
                obj[kay] = parseInt(data[kay]);
              }
            } else {
              obj[kay] = data[kay];
            }
          }
          // this.equipContrlForm = data;
          console.log(obj);
          this.equipContrlForm = obj;
        }
        this.equipControlDialogVisible = true;
      });
    },
    resetEquipControlDialogClosed() {
      this.$refs.equipContrlRef.resetFields();
      this.ws = 0;
    },
    //设备控制提交
    equipControlSubm() {
      let newForm = Object.assign({}, this.equipContrlForm); //深拷贝
      newForm.st = newForm.st + "";
      newForm.et = newForm.et + "";
      newForm.st && newForm.st.slice(0, 2).charAt(0) != "0"
        ? newForm.st.slice(0, 2)
        : newForm.st.slice(1, 2);
      newForm.et =
        newForm.et && newForm.et.slice(0, 2).charAt(0) != "0"
          ? newForm.et.slice(0, 2)
          : newForm.et.slice(1, 2);
      console.log(newForm);

      for (let k in newForm) {
        if (typeof newForm[k] == "number") {
          newForm[k] = newForm[k] + "";
        }
      }
      newForm.st = newForm.st.replace(":00", "");
      this.$delete(newForm, "admin");

      this.$axios({
        method: "POST",
        url: "/api/api_gateway?method=forecast.send_control.device_control",
        data: this.qs.stringify({
          device_type_id: 3,
          d_id: this.d_id,
          config: JSON.stringify(newForm),
          device_name: this.equipInfo.device_name,
        }),
      }).then((res) => {
        if (res.data.message == "") {
          if (document.getElementsByClassName("el-message").length == 0) {
            this.$message.success("设备控制修改成功");
          }
          this.getEquipList();
        } else {
          if (document.getElementsByClassName("el-message").length == 0) {
            this.$message.error("设备控制修改失败");
          }
        }
        this.equipControlDialogVisible = false;
      });
    },
    showTimeControlDialog(d_id, id) {
      this.device_id = id;
      this.$router.push({
        path: `/index/pestsStats`,
        query: { d_id: d_id, identify_model: "A" },
      });
    },
    // 查看图片
    viewPhotoDialog(id, d_id, name, addr, disable) {
      this.device_id = id;
      // this.$store.commit("set_cacheData_postData", "");
      this.$router.push({
        path: `/index/cbdDataPhotos/${id}`,
        query: {
          d_id: d_id,
          name: name,
          addr: addr,
          disable: disable,
          identify_model: "A",
        },
      });
    },
    // 数据详情
    dataDetails(e_id, d_id, data) {
      this.device_id = e_id;
      this.$router.push({
        path: `/index/cbdDataDetails/${e_id}/${d_id}`,
        query: {
          addr: data.address,
          name: data.device_name,
        },
      });
    },
    // 点击预警信息
    showWarningInfo() {
      this.isWarningList = !this.isWarningList;
    },
    // 一键已读
    oneWarningList() {
      this.$axios({
        method: "POST",
        url: "/api/api_gateway?method=forecast.worm_lamp.cbd_pest_warning",
        data: this.qs.stringify({
          status: "yes",
        }),
      }).then((res) => {
        if (res.data.data == true) {
          // this.warningList = []
          // this.cbdWarningPage=1
          // this.cbdWarningList();
        }
      });
    },
    // 单条信息已读
    yidu(id) {
      this.$axios({
        method: "POST",
        url: "/api/api_gateway?method=forecast.worm_lamp.cbd_pest_warning",
        data: this.qs.stringify({
          d_id: id,
        }),
      }).then((res) => {
        console.log(res.data.data);
        if (res.data.data == true) {
          // this.warningList = []
          // this.cbdWarningPage=1
          // this.cbdWarningList();
        }
      });
    },
    // 测报灯信息预警
    cbdWarningList() {
      this.$axios({
        method: "POST",
        url: "/api/api_gateway?method=forecast.worm_lamp.cbd_pest_warning",
        data: this.qs.stringify({
          page: this.cbdWarningPage,
        }),
      }).then((res) => {
        var data = res.data.data.data;
        data = data.map((v) => {
          const details = v.warning_content;
          let target = Object.prototype.toString
            .call(details)
            .slice(8, -1)
            .toLowerCase();
          console.log(target);
          let detailsInfo = "";
          if (["object"].includes(target)) {
            for (const key in details) {
              detailsInfo += `${key}:${details[key]}`;
            }
          }
          return { ...v, detailsInfo };
        });
        for (var i = 0; i < data.length; i++) {
          this.warningList.push(data[i]);
        }
        // this.warningList = res.data.data.data;
        this.onewarning = this.warningList[0];
        console.log(this.warningList);
      });
    },
    warning_status(date) {
      if (date === "1") {
        return "目标种类预警";
      } else if (date == "2") {
        return "指定害虫数量预警";
      } else if (date == "3") {
        return "害虫数量总和预警 ";
      } else if (date === "4") {
        return "综合预警";
      }
    },
    detail(con, status) {
      if (status === "1") {
        return "目标种类预警" + con + "类";
      } else if (status == "3") {
        return "害虫数量总和预警" + con + "头";
      }
    },
    load() {
      this.cbdWarningPage++;
      this.cbdWarningList();
    },
  },
  beforeCreate() {}, //生命周期 - 创建之前
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.getEquipList();
    this.cbdWarningList(); //预警信息
  },
  beforeMount() {}, //生命周期 - 挂载之前
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    // console.log(document.getElementsByClassName("number")[0]).innerText = "888"
  },
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style lang="less" scoped>
.baselistbox {
  width: 100%;
  height: 100%;
  .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;
      justify-content: space-between;
      p:first-child {
        font-size: 18px;
        font-weight: 700;
      }
      .warningInfo {
        width: 30%;
        font-size: 15px;
        display: flex;
        flex-direction: column;
        align-items: flex-end;
        position: relative;
        border: 1px solid #c0c4cc;
        border-radius: 25px;
        padding: 0 15px;
        .title {
          width: 100%;
          // padding: 5px 10px;
          border-radius: 15px;
          margin-bottom: 10px;
          // background: #fff;
          display: flex;
          align-items: center;
          justify-content: space-between;
        }
        .title > i {
          color: #ccc !important;
        }
        .warningInfoList {
          position: absolute;
          right: 0px;
          top: 45px;
          z-index: 9;
          width: 100%;
          max-height: 310px;
          padding: 5px 0px;
          background: #fff;
          box-shadow: 0px 5px 18px 0px #999;
          overflow-y: scroll;
          overflow-x: hidden;
        }
        /deep/ .el-button:focus {
          border: none !important;
          font-weight: 600 !important;
          // font-size: 15px !important;
          color: black !important;
          background: #fff !important;
          padding: 0;
        }
        /deep/ .el-button {
          width: 100%;
          font-size: 15px !important;
          padding: 10px 10px !important;
          color: rgb(26, 25, 25) !important;
          border: none !important;
        }
        /deep/ .el-button > span {
          display: flex;
          align-items: center;
          justify-content: space-between;
        }
        /deep/ .el-button > span .circle {
          display: inline-block;
          width: 5px;
          height: 5px;
          border-radius: 50%;
          background: red;
        }
        .active {
          color: red;
        }
      }
    }
    .baselistbox_top_line {
      width: 100%;
      height: 1px;
      background-color: #f2f2f2;
    }
    .baselistbox_top_search {
      width: 100%;
      height: 68px;
      display: flex;
      padding: 20px;
      box-sizing: border-box;
      line-height: 28px;
      justify-content: space-between;
      .left_search {
        display: flex;
        .firstsearch,
        .secsearch {
          display: flex;
          margin-right: 40px;
          /deep/.el-input {
            width: 240px;
          }
          .biaoti {
            font-size: 14px;
            margin-right: 20px;
          }
        }
      }
      .right_search {
        display: flex;
        .btnbox,
        .btnbox2 {
          width: 68px;
          height: 28px;
          border: 1px solid #4f71ff;
          text-align: center;
          border-radius: 3px;
          font-size: 14px;
          margin-left: 20px;
          cursor: pointer;
        }
        .btnbox {
          background-color: #4f71ff;
          color: #fff;
        }
        .btnbox2 {
          color: #4f71ff;
        }
      }
    }
  }
  .baselistbox_table {
    width: 100%;
    // height: calc(100% - 140px);
    background-color: #fff;
    margin-top: 10px;
    padding: 20px;
    box-sizing: border-box;
    position: relative;
    border-radius: 10px;
    /deep/.el-table__header {
      th {
        background-color: #f1f1f3;
      }
    }
    .pagination {
      display: flex;
      justify-content: flex-end;
      margin-top: 20px;
      /deep/.el-pager {
        .active {
          background-color: #4f71ff !important;
        }
      }
      /deep/.el-input__inner:hover {
        border-color: #4f71ff;
      }
    }
  }
}
.handAddForm {
  /deep/.el-form-item {
    margin-bottom: 8px;
  }
  .handAddFormBtn {
    text-align: right;
  }
  /deep/.el-date-editor {
    width: 160px;
  }
}
/deep/.el-slider__bar {
  background-color: #4f71ff !important;
}
</style>