<!--  -->
<template>
  <div class="laboratory_box">
    <!-- 筛选 -->
    <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="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            align="right"
            :editable="false"
          >
          </el-date-picker>

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

    <el-card style="margin-top: 15px">
      <!-- 列表 -->
      <el-table
        :data="tableData"
        stripe
        v-loading="loading"
        :height="48 * 13"
        style="width: 100%; overflow-y: auto"
      >
        <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="20"
        @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="800px"
      :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]"
              disabled
              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
              disabled
              placeholder="请输入内容"
              size="mini"
              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"
              :disabled="item1.disabled"
            >
            </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>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button :disabled="submitBtn" type="primary" @click="confirmAxios">{{
          submitBtn == true ? "发布中..." : "发布"
        }}</el-button>
      </span>
    </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, // 加载
      submitBtn: 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.models = [];
        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.page = 1
      this.tableData = [];
      this.tableList();
    },

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

    // 下页
    newPage(page) {
      this.loading = true;
      this.page = page;
      this.tableData = [];
      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: 20,
          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) {
                if (document.getElementsByClassName("el-message").length == 0) {
                  this.$message({
                    type: "success",
                    message: "接收成功!",
                    duration: 1500,
                  });
                }
                this.loading = true;
                this.tableList();
              }
            })
            .catch((err) => {
              console.log(err);
            });
        })
        .catch(() => {
          if (document.getElementsByClassName("el-message").length == 0) {
            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;
            obj["disabled"] = false;
            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;
              obj["disabled"] = false;
              list.push(obj);
            }
            this.options2 = list;
            this.indexRedact(); // 有害生物删除添加
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },

    // 添加有害生物
    addInsect() {
      if (this.insectVal !== "" && this.numVal !== "") {
        var array = [];
        var arr = [];
        for (var i = 0; i < this.options2.length; i++) {
          if (this.options2[i].label == this.insectVal) {
            var obj = {};
            obj["value"] = this.options2[i].id;
            obj["label"] = this.options2[i].label;
            obj["num"] = Number(this.numVal);
            arr = [obj, ...this.fillList];
            this.models = [obj.value, ...this.models];
          }
        }
        // 修改原数据
        this.fillList = [];
        this.insectVal = "";
        this.numVal = "";
        arr.forEach((item, index) => {
          item.ind = index;
          this.fillList.push(item);
        });
        // for (var i = 0; i < this.fillList.length; i++) {
        //   for (var j = 0; j < this.options2.length; j++) {
        //     if (this.fillList[i].label == this.options2[j].label) {
        //       this.options2[j].disabled = true;
        //     } else {
        //       this.options2[j].disabled = false;
        //     }
        //   }
        // }
        this.indexRedact(); // 有害生物添加
      } else {
        if (document.getElementsByClassName("el-message").length == 0) {
          this.$message({
            type: "info",
            message: "请将信息填写完整！",
            duration: 1500,
          });
        }
      }
    },

    // 删除有害生物
    delInsect(data) {
      this.$delete(this.fillList, data.ind); // 删除渲染列表对应数据
      this.$delete(this.models, data.ind); // 删除对应双向绑定数据
      var list = [];
      this.fillList.forEach((item, index) => {
        item.ind = index;
        list.push(item);
      });
      this.fillList = [];
      this.fillList = list;

      this.options2.forEach((item) => {
        item.disabled = false
      })
      this.indexRedactA(); // 有害生物删除
    },

    // 添加、删除确定事件
    confirmAxios() {
      this.submitBtn = true;
      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);
      }

      if (this.insectVal !== "" && this.numVal !== "") {
        array = [
          {
            pest_name: this.insectVal,
            pest_number: this.numVal,
          },
          ...array,
        ];
      }

      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 == "") {
            if (document.getElementsByClassName("el-message").length == 0) {
              this.$message({
                type: "success",
                message: "成功!",
                duration: 1500,
              });
            }
            this.fillList = [];
            this.models = [];
            this.dialogVisible = false;
          }
          this.insectVal = "";
          this.numVal = "";
          this.submitBtn = false;
        })
        .catch((err) => {
          this.submitBtn = false;
        });
    },

    // 编辑有害生物
    compileInsect(e, data, index) {
      var list = this.spareData;
      var newList = [];
      // 下拉框数据改变处理
      var name = "";
      for (var i = 0; i < list.length; i++) {
        var obj = {};
        if (e == list[i].value) {
          name = list[i].label;
        }
      }
      this.$set(this.models, index, e);
      this.fillList[index].label = name;
      this.fillList[index].value = e;
    },

    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) {
        //禁止输入负数
        if (document.getElementsByClassName("el-message").length == 0) {
          this.$message.warning("禁止输入负数");
        }
        e.target.value = 0;
      }

      if (String(e.target.value).indexOf("-") == -1) {
      } else {
        //禁止输入负数
        if (document.getElementsByClassName("el-message").length == 0) {
          this.$message.warning("禁止输入负数");
        }
        e.target.value = 0;
      }
    },

    // 有害生物添加
    indexRedact() {
      this.fillList.forEach((item) => {
        this.options2.forEach((e) => {
          if (item.label == e.label) {
            e.disabled = true;
            // console.log(e.label, e.disabled);
          }
        });
      });
    },
    // 有害生物删除
    indexRedactA() {
      this.fillList.forEach((item) => {
        this.options2.forEach((e) => {
          if (item.label == e.label) {
            // console.log(e.label, e.disabled)
            e.disabled = true;
          }
        });
      });
    }
  },
  //生命周期 - 创建完成（可以访问当前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;
}
/deep/.el-date-editor {
  cursor: pointer;
  .el-range-input {
    cursor: pointer;
  }
}

/deep/.el-button--info {
  background-color: #409eff;
  border-color: #409eff;
}
</style>
