<!--  -->
<template>
  <div class="laboratory_box">
    <el-card :style="'height:' + fullHeight + 'px'">
      <!-- 筛选 -->
      <el-row>
        <el-col>
          <div class="search_box">
            <!-- 任务处理人 -->
            <el-select
              filterable
              v-model="input"
              clearable
              @change="searchData"
              placeholder="请选择任务处理人/实际处理人"
              size="mini"
            >
              <el-option
                v-for="item in conductorList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>

            <!-- 任务状态 -->
            <el-select
              filterable
              v-model="value"
              @change="searchData"
              clearable
              placeholder="请选择任务状态"
              size="mini"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>

            <!-- 时间筛选 -->
            <el-date-picker
              size="mini"
              v-model="value1"
              @change="searchData"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              align="right"
            >
            </el-date-picker>

            <div class="btn_box">
              <el-button type="primary" size="mini" @click="searchData"
                >搜索</el-button
              >
              <el-button type="primary" size="mini" @click="reset"
                >重置</el-button
              >
            </div>
          </div>
        </el-col>
      </el-row>

      <!-- 列表 -->
      <el-table
        :data="tableData"
        stripe
        v-loading="loading"
        style="width: 100%"
      >
        <el-table-column prop="serial" label="序号" width="100">
        </el-table-column>
        <el-table-column prop="trap_number" label="设备编号" width="120">
        </el-table-column>
        <el-table-column prop="lng" label="经度" width="150">
          <template slot-scope="scope">
            <span>{{ scope.row.lng || "无" }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="lat" label="纬度" width="150">
          <template slot-scope="scope">
            <span>{{ scope.row.lat || "无" }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="id" label="任务编号" width="180">
        </el-table-column>
        <el-table-column
          prop="operator_user_name"
          label="任务处理人"
          width="180"
        >
        </el-table-column>
        <el-table-column
          prop="actual_operator_name"
          label="实际处理人"
          width="180"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.actual_operator_name || "暂无" }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="report_time" label="带回时间">
          <template slot-scope="scope">
            <span>{{ scope.row.report_time || "暂无" }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="discern_status" label="任务状态" width="280">
          <template slot-scope="scope">
            <span v-if="scope.row.discern_status == '待接收'">
              <span
                style="
                  width: 6px;
                  height: 6px;
                  background: #f93f3d;
                  border-radius: 50%;
                  display: inline-block;
                  margin: 0 0 2px 0;
                "
              ></span>
              <span>待接收样本</span>
            </span>

            <span v-if="scope.row.discern_status == '已接收'">
              <span
                style="
                  width: 6px;
                  height: 6px;
                  background: #f93f3d;
                  border-radius: 50%;
                  display: inline-block;
                  margin: 0 0 2px 0;
                "
              ></span>
              <span>已接收样本</span>
            </span>

            <span v-if="scope.row.discern_status == '已填报'">
              <span
                style="
                  width: 6px;
                  height: 6px;
                  background: #e6a23c;
                  border-radius: 50%;
                  display: inline-block;
                  margin: 0 0 2px 0;
                "
              ></span>
              <span>已填报样本</span>
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right">
          <template slot-scope="scope">
            <a
              v-if="scope.row.discern_status == '待接收'"
              class="reset"
              href="javascript:;"
              @click="receive(scope.row)"
              >确认接收</a
            >

            <a
              v-if="scope.row.discern_status == '已接收'"
              class="reset"
              @click="examine(scope.row)"
              href="javascript:;"
              >填报</a
            >

            <a
              v-if="scope.row.discern_status == '已填报'"
              class="reset"
              href="javascript:;"
              @click="examine(scope.row)"
              >编辑</a
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        style="margin: 60px 0 0 0"
        :page-size="10"
        @current-change="newPage"
        :current-page="page"
        v-if="tableData.length > 0"
        background
        layout="prev, pager, next, jumper"
        :total="tableSum"
      >
      </el-pagination>
    </el-card>

    <!-- 填报弹框 -->
    <el-dialog
      title="填报"
      v-loading="loading1"
      :visible.sync="dialogVisible"
      width="50%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <ul class="fill_ul">
        <li class="fill_listTlt">
          <div class="fill_div">
            <div class="fill_tltie">有害生物</div>
            <div class="fill_tltie">
              数量
            </div>
          </div>
        </li>

        <li class="fill_list1" v-if="fillList.length !== 0">
          <div v-for="(item, index) in fillList" :key="item.ind">
            <el-select
              v-model="models[index]"
              size="mini"
              clearable
              @change="compileInsect($event, item, index)"
              placeholder="请选择"
            >
              <el-option
                v-for="item1 in fillList"
                :key="item1.value"
                :label="item1.label"
                :value="item1.value"
              >
              </el-option>
            </el-select>

            <el-input
              placeholder="请输入内容"
              size="mini"
              @change="compileInsect($event, item, index)"
              v-model="item.num"
              clearable
              type="number"
              style="width: 30%"
            >
            </el-input>

            <span @click="delInsect(item)">删除</span>
          </div>
        </li>

        <!-- 添加 -->
        <li class="fill_list">
          <el-select
            style="margin: 0 0 0 -8px;"
            v-model="insectVal"
            size="mini"
            clearable
            placeholder="请选择"
            filterable
          >
            <el-option
              v-for="item1 in options2"
              :key="item1.value"
              :label="item1.label"
              :value="item1.value"
            >
            </el-option>
          </el-select>

          <el-input
            placeholder="请输入数量"
            size="mini"
            v-model="numVal"
            clearable
            onkeypress="return (/[\d]/.test(String.fromCharCode(event.keyCode)));"
            @keyup.native="proving2($event)"
            type="number"
            style="width: 30%"
          >
          </el-input>

          <span
            style="color: #000; font-size: 30px; cursor: pointer"
            @click="addInsect()"
            >+</span
          >
        </li>
      </ul>
    </el-dialog>
  </div>
</template>

<script>
export default {
  components: {},
  data() {
    //这里存放数据
    return {
      fullHeight: document.documentElement.clientHeight - 116, //

      // 筛选
      input: "", // 任务处理人
      conductorList: [], // 任务处理人列表
      options: [
        {
          value: "待接收",
          label: "待接收"
        },
        {
          value: "已接收",
          label: "已接收"
        },
        {
          value: "已填报",
          lanbel: "已填报"
        }
      ],
      value: "", // 任务状态
      value1: "", // 时间筛选
      startTime: "",
      endTime: "",

      // 表格
      tableData: [],
      page: 1,
      tableSum: 0, // 总页数

      // 填报弹框
      dialogVisible: false,
      options1: [],
      options2: [], //新增有害生物
      value2: "",
      input2: "",
      loading: false, // 加载

      // 已识别
      examineObj: {}, // 选中的对象值
      fillList: [], // 填报详情数据
      spareData: [], // 填报详情备用数据
      // models: Array(fillList.length).fill(''), // 填报select数据
      models: null, // 填报select数据
      insectVal: "", // 添加 - 有害生物
      numVal: "", // 添加 - 数量
      loading1: false // 加载
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {
    fullHeight(val) {
      //监控浏览器高度变化
      if (!this.timer) {
        this.fullHeight = val;
        this.timer = true;
        let that = this;
        setTimeout(function() {
          //防止过度调用监测事件，导致卡顿
          that.timer = false;
        }, 400);
      }
    },

    // 填报弹框
    dialogVisible(val) {
      if (val == false) {
        this.fillList = [];
        this.spareData = []; // 备用数据
      }
    },

    // 填报 - 新添加数据
    numValZ(val) {
      console.log(val);
    }
  },
  //方法集合
  methods: {
    //动态获取浏览器高度
    get_boderHeight() {
      const that = this;
      window.onresize = () => {
        return (() => {
          window.fullHeight = document.documentElement.clientHeight;
          that.fullHeight = window.fullHeight;
        })();
      };
    },

    // 筛选
    searchData() {
      // 对时间筛选中获取到的时间进行处理
      if (this.value1) {
        this.startTime = this.formatTime(this.value1[0], "yyyy-MM-dd");
        this.endTime = this.formatTime(this.value1[1], "yyyy-MM-dd");
      } else {
        this.startTime = "";
        this.endTime = "";
      }
      this.loading = true;
      this.tableData = [];
      this.tableList();
    },

    // 重置
    reset() {
      this.input = "";
      this.value = "";
      this.value1 = "";
      this.startTime = "";
      this.endTime = "";
      this.loading = true;
      this.tableList();
    },

    // 下页
    newPage(page) {
      this.loading = true;
      this.page = page;
      this.tableList();
    },

    // 表格数据
    tableList() {
      this.$axios({
        method: "POST",
        url: "/api/api_gateway?method=control_center.task.discern_list",
        data: this.qs.stringify({
          page: this.page,
          page_item: 10,
          operator_user_id: this.input, // 任务处理人id
          start_time: this.startTime, // 开始时间
          end_time: this.endTime, // 结束时间
          task_status: this.value // 任务状态
        })
      })
        .then(res => {
          if (res.data.data.total_item !== 0) {
            this.tableSum = res.data.data.total_item;
            var data = res.data.data.page_list;
            var list = [];
            data.forEach((item, index) => {
              item.serial = index + 1;
              list.push(item);
            });
            this.tableData = list;
          }
          this.loading = false;
        })
        .catch(err => {
          this.loading = false;
        });
    },

    // 筛选列表 - 任务处理人
    conductorAxios() {
      this.$axios({
        method: "POST",
        url: "/api/api_gateway?method=control_center.task.task_user_list",
        data: this.qs.stringify({
          user_type: "operator", // 用户类型，operator（任务处理人）, supervisor（任务监督人）, owner（任务发布人）
          operator_id: "", // 已经选择的任务处理人id
          supervisor_id: "", // 已经选择的任务监督人id
          owner_id: "" // 已经选择的任务发布人id
        })
      })
        .then(res => {
          if (res.data.data.length !== 0) {
            var data = res.data.data;
            var list = [];
            data.forEach(item => {
              var obj = {};
              obj["value"] = item.user_id;
              obj["label"] = item.real_name;
              list.push(obj);
            });
            this.conductorList = list;
          }
        })
        .catch(err => {});
    },

    // 确认接收
    receive(data) {
      this.$confirm("此操作将确认接收, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$axios({
            method: "POST",
            url: "/api/api_gateway?method=control_center.task.discern_modify",
            data: this.qs.stringify({
              record_id: data.id // 任务id
            })
          })
            .then(res => {
              if (res.data.data == true) {
                this.$message({
                  type: "success",
                  message: "接收成功!",
                  duration: 1500
                });
                this.loading = true;
                this.tableList();
              }
            })
            .catch(err => {
              console.log(err);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消接收",
            duration: 1500
          });
        });
    },

    // 填报、编辑事件  （表格中的操作）
    examine(data) {
      // console.log(data);
      this.examineObj = data;
      // 填报记录详情接口
      this.$axios({
        method: "POST",
        url:
          "/api/api_gateway?method=control_center.task.trap_pest_record_info",
        data: this.qs.stringify({
          trap_record_id: data.id // 任务id
        })
      })
        .then(res => {
          var data = res.data.data;
          var list = [];
          var arr = [];
          data.forEach((item, index) => {
            var obj = {};
            obj["value"] = item.id;
            obj["label"] = item.pest_name;
            obj["num"] = item.pest_number;
            obj["ind"] = index;
            list.push(obj);
            arr.push(item.id);
          });
          this.fillList = list;
          this.spareData = list; // 备用数据
          this.models = arr;
          this.dialogVisible = true;
          this.addEditor(); // 新添加 - 编辑接口
        })
        .catch(err => {
          console.log(err);
        });
    },

    // 新添加 -编辑
    addEditor() {
      this.$axios({
        method: "POST",
        url: "/api/api_gateway?method=sysmenage.maintain.pest_list",
        data: this.qs.stringify({
          page: 1, // 页码
          page_item: "1000000000000000000000000000", // 每页条目数，默认10
          pest_name: "" // 有害生物
        })
      })
        .then(res => {
          if (res.data.data.total_item !== 0) {
            var data = res.data.data;
            var list = [];
            for (var i = 0; i < data.page_list.length; i++) {
              var obj = {};
              obj["id"] = data.page_list[i].pest_id;
              obj["value"] = data.page_list[i].pest_name;
              obj["label"] = data.page_list[i].pest_name;
              list.push(obj);
            }
            this.options2 = list;
          }
        })
        .catch(err => {
          console.log(err);
        });
    },

    // 添加有害生物
    addInsect() {
      if (this.insectVal !== "" && this.numVal !== "") {
        var array = [];
        for (var i = 0; i < this.fillList.length; i++) {
          var obj = {};
          obj["pest_name"] = this.fillList[i].label;
          obj["pest_number"] = this.fillList[i].num;
          array.push(obj);
        }
        var obj1 = {};
        obj1["pest_name"] = this.insectVal;
        obj1["pest_number"] = Number(this.numVal);
        array = [...array, obj1];

        this.$confirm("此操作将新增有害生物, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            this.$axios({
              method: "POST",
              url: "/api/api_gateway?method=control_center.task.discern_add",
              data: this.qs.stringify({
                record_id: this.examineObj.id, // 任务id
                pest_list: JSON.stringify(array) // 害虫数组
              })
            })
              .then(res => {
                if (res.data.message == "") {
                  this.$message({
                    type: "success",
                    message: "添加成功!",
                    duration: 1500
                  });
                  this.examine(this.examineObj);
                }
                this.insectVal = "";
                this.numVal = "";
              })
              .catch(err => {
                console.log(err);
              });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消添加",
              duration: 1500
            });
          });
      } else {
        this.$message({
          type: "info",
          message: "请将信息填写完整！",
          duration: 1500
        });
      }
    },

    // 删除有害生物
    delInsect(data) {
      this.$confirm("此操作将永久删除该有害生物, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.loading1 = true;
          var list = this.fillList;
          list.splice(data.ind, 1);
          var arr = [];
          list.forEach(item => {
            var obj = {};
            obj["pest_name"] = item.label;
            obj["pest_number"] = item.num;
            arr.push(obj);
          });
          this.$axios({
            method: "POST",
            url: "/api/api_gateway?method=control_center.task.discern_add",
            data: this.qs.stringify({
              record_id: this.examineObj.id, // 任务id
              pest_list: JSON.stringify(arr) // 害虫数组
            })
          })
            .then(res => {
              if (res.data.message == "") {
                this.$message({
                  type: "success",
                  message: "删除成功!",
                  duration: 1500
                });
                this.examine(this.examineObj);
              }
              this.loading1 = false;
            })
            .catch(err => {
              this.loading1 = false;
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
            duration: 1500
          });
        });
    },

    // 编辑有害生物
    compileInsect(e, data, index) {
      this.$confirm("此操作将编辑该有害生物, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$set(this.models, index, e);
          var list = this.spareData;
          var newList = [];
          // 下拉框数据改变处理
          for (var i = 0; i < list.length; i++) {
            var obj = {};
            if (e == list[i].value) {
              obj["pest_name"] = list[i].label;
              obj["pest_number"] = data.num;
              newList.push(obj);
            }
          }
          // 修改数据为可发送到后端接口数据
          var arr = [];
          var list = this.fillList;
          list.forEach(item => {
            var obj = {};
            obj["pest_name"] = item.label;
            obj["pest_number"] = item.num;
            arr.push(obj);
          });
          arr.splice(index, 1, ...newList);
          this.$axios({
            method: "POST",
            url: "/api/api_gateway?method=control_center.task.discern_add",
            data: this.qs.stringify({
              record_id: this.examineObj.id, // 任务id
              pest_list: JSON.stringify(arr) // 害虫数组
            })
          })
            .then(res => {
              if (res.data.message == "") {
                this.$message({
                  type: "success",
                  message: "编辑成功!",
                  duration: 1500
                });
                this.examine(this.examineObj);
              }
              this.insectVal = "";
              this.numVal = "";
            })
            .catch(err => {
              console.log(err);
            });
        })
        .catch(() => {
          this.loading1 = false;
          this.$set(this.models, index, this.fillList[index].value);
          this.$message({
            type: "info",
            message: "已取消编辑"
          });
        });
    },

    getBit(value, bit) {
      let str = Number(value);
      str = str.toFixed(bit);
      return str;
    },
    proving2(e) {
      var keynum = window.event ? e.keyCode : e.which; //获取键盘码
      var keychar = String.fromCharCode(keynum); //获取键盘码对应的字符
      if (keynum == 189 || keynum == 109) {
        //禁止输入负数
        this.$message.warning("禁止输入负数");
        e.target.value = 0;
      }

      if (String(e.target.value).indexOf("-") == -1) {
      } else {
        //禁止输入负数
        this.$message.warning("禁止输入负数");
        e.target.value = 0;
      }
    }
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.loading = true;
    this.get_boderHeight(); // 动态获取浏览器高度
    this.tableList(); // 表格列表数据
    this.conductorAxios(); // 筛选列表 - 任务处理人列表
  },
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {} //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style lang="less" scoped>
.laboratory_box {
  // 搜索
  .search_box {
    display: flex;
    /deep/.el-select {
      margin: 0 15px 0 0;
    }
    /deep/.el-input {
      // width: 15%;
      margin: 0 15px 0 0;
    }
    .btn_box {
      margin: 0 0 0 15px;
      // width: 50%;
      display: flex;
      justify-content: start;
    }

    /deep/.el-range-editor--mini.el-input__inner {
      width: 20%;
    }
  }

  a {
    text-decoration: none;
  }
  .reset {
    color: #1890ff;
  }

  // 填报弹框
  .fill_ul {
    .fill_listTlt {
      width: 95%;
      .fill_div {
        width: 60%;
        margin: 0 0 0 60px;
        display: flex;
        justify-content: space-between;

        .fill_tltie {
          margin: 0 0 10px 0;
          width: 35%;
          display: inline-block;
        }
      }
    }
    .fill_list {
      display: flex;
      justify-content: space-around;
      margin: 0 20px 10px 0;
      span {
        line-height: 30px;
        color: #1890ff;
      }
    }

    .fill_list1 {
      div {
        display: flex;
        justify-content: space-around;
        margin: 0 20px 10px 0;
        span {
          line-height: 30px;
          color: #1890ff;
          cursor: pointer;
        }
      }
    }
  }

  /deep/.el-card {
    overflow: hidden;
    overflow-y: auto;
  }
}

// 去除elementui input数字框里上下箭头
/deep/ input::-webkit-outer-spin-button,
/deep/ input::-webkit-inner-spin-button {
  -webkit-appearance: none !important;
}
/deep/ input[type="number"] {
  -moz-appearance: textfield !important;
}
</style>
