<!--  -->
<template>
  <div class="record_box" :style="'height:' + fullHeight + 'px'">
    <!-- 页头 -->
    <div class="record_box_headr">
      <el-page-header title @back="goBack" content="识别记录"></el-page-header>
    </div>

    <!-- 主内容 -->
    <div class="record_box_main">
      <!-- tab切换 -->
      <ul class="record_box_main_tab">
        <li
          class="main_tab_plant"
          v-for="(item,index) in items"
          :key="index"
          :class="{active:istrue==index}"
          @click="istrue=index, qingqiu(index)"
        >{{ item.name }}</li>
      </ul>

      <!-- 列表 -->
      <mescroll-vue ref="mescroll" :down="mescrollDown" :up="mescrollUp" @init="mescrollInit">
        <ul class="record_box_main_ul" v-if="axiosShow">
          <li
            class="record_box_main_li"
            v-for="(item, index) in this.redata"
            :key="index"
            @click="listAdd($event, index, item.id, item.name)"
          >
            <!--  -->
            <div class="record_box_main_li_box">
              <!-- 图片 -->
               <!-- <img
                v-lazy="item.img_urls === null || item.img_urls === '' ? 'bigservers/' + item.img : item.img_urls"
                alt
                class="record_box_main_li_img"
              /> -->
              <img
                v-lazy="'bigservers/' + item.img"
                alt
                class="record_box_main_li_img"
              />
              <!-- 病虫害名称 -->
              <div class="record_box_main_li_name">
                <div
                  class="record_box_main_li_name_text"
                >{{ item.name === null || item.name === '' ? '识别失败！' : item.name }}</div>
                <div
                  class="record_box_main_li_name_xiqng"
                >{{ item.addr == 'undefined' || item.addr == "null" ? '定位失败' : item.addr | ellipsis }}</div>
              </div>

              <!-- 详情 -->
              <div class="record_box_main_li_btn">
                <span
                  class="record_box_main_li_btn_text"
                >{{ item.name === null || item.name === '' ? '编辑' : '详情' }}</span>
                <img src="../../assets/imageOne/right.png" alt class="record_box_main_li_btn_del" />
              </div>
            </div>
            <!-- 删除 -->
            <img
              @click="del($event, index, item.id, item.ret)"
              src="../../assets/imageOne/41.png"
              alt
              class="record_box_main_li_del"
            />
          </li>
        </ul>
        <!-- 暂空判断 -->
        <div class="record_judge" v-else>
          <img src="../../assets/imageOne/wu.png" alt class="record_judge_img" />
          <div class="record_judge_text">抱歉，暂无此数据</div>
        </div>
      </mescroll-vue>
    </div>
  </div>
</template>

<script>
// 引入mescroll的vue组件
import MescrollVue from "mescroll.js/mescroll.vue";
export default {
  inject: ["reload"], //刷新页面
  //import引入的组件需要注入到对象中才能使用
  //限时数据文本的字数限时
  filters: {
    ellipsis(value) {
      if (!value) return "";
      if (value.length > 4) {
        return value.slice(0, 4) + "...";
      }
      return value;
    }
  },
  components: {
    MescrollVue // 注册mescroll组件
  },
  data() {
    //这里存放数据
    return {
      fullHeight: document.documentElement.clientHeight,
      istrue: localStorage.getItem("biaoshi"),
      items: [{ name: "虫害" }, { name: "病害" }],
      redata: [], //列表get数据
      axiosShow: true, //暂空判断
      //测试
      mescroll: null, // mescroll实例对象
      mescrollDown: {}, //下拉刷新的配置. (如果下拉刷新和上拉加载处理的逻辑是一样的,则mescrollDown可不用写了)
      mescrollUp: {
        // 上拉加载的配置.
        callback: this.upCallback, // 上拉回调,此处简写; 相当于 callback: function(page, mescroll) { }
        //以下是一些常用的配置,当然不写也可以的.
        page: {
          num: 0, //当前页 默认0,回调之前会加1; 即callback(page)会从1开始
          size: 6 //每页数据条数,默认10
        },
        isBounce: true, //根据记录的滚动条高度回弹
        htmlNodata: '<p class="upwarp-nodata">-- 已经到底了! --</p>',
        noMoreSize: 6, //如果列表已无数据,可设置列表的总数量要大于5才显示无更多数据;
        // 避免列表数据过少(比如只有一条数据),显示无更多数据会不好看
        // 这就是为什么无更多数据有时候不显示的原因
        toTop: {
          //回到顶部按钮
          // src: "../../../static/gotop.png", //图片路径,默认null,支持网络图
          src:
            "http://pic.51yuansu.com/pic3/cover/00/65/23/5896fa4bc81fc_610.jpg", //图片路径,默认null,支持网络图
          offset: 800 //列表滚动1000px才显示回到顶部按钮
        },
        empty: {
          //列表第一页无任何数据时,显示的空提示布局; 需配置warpId才显示
          warpId: "", //父布局的id (1.3.5版本支持传入dom元素)
          icon: "./static/mescroll/mescroll-empty.png", //图标,默认null,支持网络图
          tip: "暂无相关数据~" //提示
        },
        onScroll: function(mescroll, y, isUp) {
          //监听滚动条
          // console.log(y);
        },
        lazyLoad: {
          use: true // 是否开启懒加载,默认false
        }
      },
      aggregate: "" //后端传来数据的总条数
    };
  },
  beforeRouteEnter(to, from, next) {
    // 如果没有配置顶部按钮或isBounce,则beforeRouteEnter不用写
    next(vm => {
      // 滚动到原来的列表位置,恢复顶部按钮和isBounce的配置
      vm.$refs.mescroll && vm.$refs.mescroll.beforeRouteEnter();
    });
  },
  beforeRouteLeave(to, from, next) {
    // 如果没有配置顶部按钮或isBounce,则beforeRouteLeave不用写
    // 记录列表滚动的位置,隐藏顶部按钮和isBounce的配置
    this.$refs.mescroll && this.$refs.mescroll.beforeRouteLeave();
    next();
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {
    fullHeight(val) {
      //监控浏览器高度变化
      if (!this.timer) {
        this.fullHeight = val;
        this.timer = true;
        let that = this;
        setTimeout(function() {
          //防止过度调用监测事件，导致卡顿
          that.timer = false;
        }, 400);
      }
    },
    items(val) {
      console.log(val);
    }
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //方法集合
  methods: {
    mescrollInit(mescroll) {
      this.mescroll = mescroll; // 如果this.mescroll对象没有使用到,则mescrollInit可以不用配置
    },
    // 上拉回调 page = {num:1, size:10}; num:当前页 ,默认从1开始; size:每页数据条数,默认10
    upCallback(page, mescroll) {
      let _this = this;
      if (localStorage.getItem("biaoshi") == "0") {
        _this
          .$axios({
            method: "get",
            url: "bigservers/insect_details",
            params: {
              page: this.mescrollUp.page.num
            }
          })
          .then(res => {
            //判断data中的变量是否为空 ，为空的话存后端发来的总条数
            if (this.aggregate === "") {
              //存变量
              this.aggregate = res.data.num;
              var b = "6";
              this.aggregate = this.aggregate / b;
              this.aggregate = Math.ceil(this.aggregate); //将小数点转换为整数
            }

            //删除了默认的每页条数后判断数是否大于页码
            if (this.mescrollUp.page.num <= this.aggregate) {
              if (this.aggregate <= "1") {
                var hasNext = false;
              } else if (this.aggregate > "1") {
                var hasNext = true;
              }
              this.$axios({
                method: "get",
                url: "bigservers/insect_details",
                params: {
                  page: this.mescrollUp.page.num
                }
              })
                .then(res => {
                  let arr = res.data.dat;
                  // 如果是第一页需手动置空列表
                  if (page.num === 1) this.redata = [];
                  // 把请求到的数据添加到列表
                  this.redata = this.redata.concat(arr);
                  // 数据渲染成功后,隐藏下拉刷新的状态
                  this.$nextTick(() => {
                    mescroll.endSuccess(arr.length, hasNext);
                  });
                  if (res.data.num === 0) {
                    _this.axiosShow = false;
                    _this.FenShow = false;
                  } else if (res.data.num !== 0) {
                    _this.axiosShow = true;
                    _this.FenShow = true;
                  }
                })
                .catch(error => {
                  mescroll.endErr();
                });
            } else if (this.mescrollUp.page.num > this.aggregate) {
              // 数据渲染成功后,隐藏下拉刷新的状态
              this.$nextTick(() => {
                mescroll.endSuccess(this.aggregate, hasNext);
              });
            }

            if (this.aggregate === 0) {
              this.axiosShow = false;
              this.FenShow = false;
            }
          })
          .catch(error => {
            mescroll.endErr();
          });
      } else if (localStorage.getItem("biaoshi") == "1") {
        _this
          .$axios({
            method: "get",
            url: "bigservers/plant_details",
            params: {
              page: this.mescrollUp.page.num
            }
          })
          .then(res => {
            //判断data中的变量是否为空 ，为空的话存后端发来的总条数
            if (this.aggregate === "") {
              //存变量
              this.aggregate = res.data.num;
              var b = "6";
              this.aggregate = this.aggregate / b;
              this.aggregate = Math.ceil(this.aggregate); //将小数点转换为整数
            }

            //删除了默认的每页条数后判断数是否大于页码
            if (this.mescrollUp.page.num <= this.aggregate) {
              if (this.aggregate <= "1") {
                var hasNext = false;
              } else if (this.aggregate > "1") {
                var hasNext = true;
              }
              this.$axios({
                method: "get",
                url: "bigservers/plant_details",
                params: {
                  page: this.mescrollUp.page.num
                }
              })
                .then(res => {
                  let arr = res.data.dat;
                  // 如果是第一页需手动置空列表
                  if (page.num === 1) this.redata = [];
                  // 把请求到的数据添加到列表
                  this.redata = this.redata.concat(arr);
                  // 数据渲染成功后,隐藏下拉刷新的状态
                  this.$nextTick(() => {
                    mescroll.endSuccess(arr.length, hasNext);
                  });
                  if (res.data.num === 0) {
                    _this.axiosShow = false;
                    _this.FenShow = false;
                  } else if (res.data.num !== 0) {
                    _this.axiosShow = true;
                    _this.FenShow = true;
                  }
                })
                .catch(error => {
                  mescroll.endErr();
                });
            } else if (this.mescrollUp.page.num > this.aggregate) {
              // 数据渲染成功后,隐藏下拉刷新的状态
              this.$nextTick(() => {
                mescroll.endSuccess(this.aggregate, hasNext);
              });
            }

            if (this.aggregate === 0) {
              this.axiosShow = false;
              this.FenShow = false;
            }
          })
          .catch(error => {
            mescroll.endErr();
          });
      }
    },
    //动态获取浏览器高度
    get_boderHeight() { 
      const that = this;
      window.onresize = () => {
        return (() => {
          window.fullHeight = document.documentElement.clientHeight;
          that.fullHeight = window.fullHeight;
        })();
      };
    },

    //点击返回系统设置
    goBack() {
      let _this = this;
      localStorage.removeItem("recordRet");
      localStorage.removeItem("recordID");
      localStorage.removeItem("recordPage");
      // _this.$router.push("/discern");
      _this.$router.replace("/discern");
    },

    //点击进入详情并获取到数据id
    listAdd(e, index, id, name) {
      let _this = this;
      if (
        e.target.className === "record_box_main_li_btn_text" ||
        e.target.className === "record_box_main_li_name" ||
        e.target.className === "record_box_main_li_img" ||
        e.target.className === "record_box_main_li_box"
      ) {
        _this.current = index;
        //获取点击对象
        let el = e.currentTarget;
        let listId = id;
        localStorage.setItem("recordID", listId);
        // //判断是否识别失败
        if (name === null) {
          _this.$router.push("/addData");
          // location.reload();
        } else if (name !== null) {
          _this.$router.push("/details");
        }
      }
    },

    //点击tab切换并请求后端数据
    qingqiu(index) {
      let _this = this;
      //判断是点击虫害还是病害
      // location.reload();
      if (index === 0) {
        localStorage.setItem("biaoshi", "0"); //0是虫害
        _this
          .$axios({
            method: "get",
            url: "bigservers/insect_details?page=1"
          })
          .then(res => {
            // this.reload();
            if (res.data.num === 0) {
              _this.axiosShow = false;
            } else if (res.data.num !== 0) {
              _this.axiosShow = true;
              _this.redata = res.data.dat;
              _this.FenShow = false;
              let a = res.data.page;
              let b = "6";
              let d = a / b;
              if (d % 1 === 0) {
              } else {
                let g = Math.ceil(d) * 10;
                // console.log(g);
                _this.page = g;
              }
              _this.FenShow = true;
            }
          })
          .catch(error => {
            console.log(error);
          });
        localStorage.removeItem("recordPage"); //删除记录当前页数
      } else if (index === 1) {
        localStorage.setItem("biaoshi", "1"); //1是病害
        _this
          .$axios({
            method: "get",
            url: "bigservers/plant_details?page=1"
          })
          .then(res => {
            if (res.data.num === 0) {
              _this.axiosShow = false;
              _this.FenShow = false;
            } else if (res.data.num !== 0) {
              _this.axiosShow = true;
              _this.redata = res.data.dat;
              let a = res.data.page;
              let b = "6";
              let d = a / b;
              if (d % 1 === 0) {
              } else {
                let g = Math.ceil(d) * 10;
                _this.page = g;
              }
              _this.FenShow = true;
            }
          })
          .catch(error => {
            console.log(error);
          });
        localStorage.removeItem("recordPage"); //删除记录当前页数
      }
    },

    //删除
    del(e, index, id, ret) {
      let _this = this;
      if (e.target.className === "record_box_main_li_del") {
        _this.current = index;
        //获取点击对象
        let el = e.currentTarget;
        let listId = id;
        let listRet = ret;
        localStorage.setItem("recordID", listId);
        localStorage.setItem("recordRet", listRet);
      }
      let postData = _this.$qs.parse({
        id: localStorage.getItem("recordID"),
        ret: localStorage.getItem("recordRet")
      });
      _this
        .$axios({
          method: "post",
          url: "bigservers/del_record",
          data: postData,
          headers: {
            "Content-Type": "application/json"
          }
        })
        .then(res => {
          if (res.data === 1) {
            this.$notify({
              title: "成功",
              message: "删除成功",
              type: "success",
              duration: 1000
            });
            _this.refreshData();
          } else if (res.data === 0) {
            this.$notify.error({
              title: "错误",
              message: "删除失败",
              duration: 1000
            });
          }
        })
        .catch(error => {
          this.$notify.error({
            title: "错误",
            message: "删除失败",
            duration: 1000
          });
        });
    },

    //删除等事件触发后请求数据
    refreshData() {
      var _this = this;
      //判断当前是病害还是虫害
      if (localStorage.getItem("biaoshi") == "0") {
        //虫害
        _this
          .$axios({
            method: "get",
            url: "bigservers/insect_details?page=1"
          })
          .then(res => {
            // this.reload();
            if (res.data === 0) {
              _this.axiosShow = false;
            } else if (res.data !== 0) {
              _this.redata = res.data.dat;
              _this.FenShow = false;
              let a = res.data.page;
              let b = "6";
              let d = a / b;
              if (d % 1 === 0) {
              } else {
                let g = Math.ceil(d) * 10;
                // console.log(g);
                _this.page = g;
              }
              _this.FenShow = true;
            }
            _this.axiosShow = true;
          })
          .catch(error => {
            console.log(error);
          });
      } else if (localStorage.getItem("biaoshi") == "1") {
        //病害
        _this
          .$axios({
            method: "get",
            url: "bigservers/plant_details?page=1"
          })
          .then(res => {
            if (res.data === 0) {
              _this.axiosShow = false;
              _this.FenShow = false;
            } else if (res.data !== 0) {
              _this.redata = res.data.dat;
              let a = res.data.page;
              let b = "6";
              let d = a / b;
              if (d % 1 === 0) {
              } else {
                let g = Math.ceil(d) * 10;
                _this.page = g;
              }
              _this.FenShow = true;
            }
            _this.axiosShow = true;
          })
          .catch(error => {
            console.log(error);
          });
      }
    }
  },

  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    let _this = this;
    _this.get_boderHeight();
    //判断如果biaoshi为空的话就存否则不存
    if (localStorage.getItem("biaoshi") == null) {
      localStorage.setItem("biaoshi", 0);
    }
  }
};
</script>
<style lang='scss'>
@import "../../assets/style/bus.scss";
@import "../../assets/style/scss/record.scss";
</style>