<!--  -->
<template>
  <div
    class="repository_box"
    :style="'height:' + fullHeight + 'px'"
    v-loading="loading"
    element-loading-text="拼命加载中"
  >
    <!-- 头部 -->
    <div class="repository_box-head">
      <div class="repository_divBox">
        <div class="repository_headrBox-tlt">百科</div>
      </div>
    </div>

    <!-- 主内容 -->
    <mescroll-vue
      ref="mescroll"
      class="home_box_mescroll"
      :down="mescrollDown"
      :up="mescrollUp"
      @init="mescrollInit"
    >
      <div class="repository_box-main">
        <!-- 搜索框 -->
        <el-input
          style="width: 90%; margin: 0.25rem auto"
          prefix-icon="el-icon-search"
          placeholder="搜索虫害或病害名称"
          v-model="input"
          @change="seekChange"
          clearable
        >
        </el-input>

        <!-- 虫害或病害切换 -->
        <div class="repository_box-mainB">
          <!-- 标题 -->
          <div class="navlist">
            <ul>
              <li
                class="navli"
                v-for="(item, index) in navList"
                :class="{ activeT: nowIndex === index }"
                @click="tabClick(index)"
                :key="index"
              >
                <div class="navliVal">{{ item.name }}</div>
              </li>
            </ul>
          </div>

          <!-- 相应内容 -->
          <div class="swiper-container swiper_con" style="background: #f7f8fc">
            <div class="swiper-wrapper">
              <!-- <mescroll-vue
              ref="mescroll"
              class="home_box_mescroll"
              :down="mescrollDown"
              :up="mescrollUp"
              @init="mescrollInit"
            > -->
              <!-- 虫害 -->
              <div class="swiper-slide">
                <ul class="home_box-main-authenticateUlA" v-if="insectShow">
                  <li
                    class="home_box-main-authenticateListA"
                    v-for="(item, index) in insectPlantDat"
                    :key="index"
                    @click="plantDetails(item.id)"
                  >
                    <div class="home_box-main-authenticateListA-box1">
                      <img
                        preview="1"
                        v-lazy="item.img_urls"
                        alt
                        class="home_box-main-authenticateListA-box1-img"
                      />
                      <div class="home_box-main-authenticateListA-box1-txt">
                        {{ item.name }}
                      </div>
                    </div>
                  </li>
                </ul>

                <!-- 暂空判断 -->
                <div class="seek_data_judge" v-else>
                  <img
                    src="../../assets/image/wu.png"
                    alt
                    class="seek_data_judge_img"
                  />
                  <div class="seek_data_judge_text">抱歉，暂无此数据</div>
                </div>
              </div>

              <!-- 病害 -->
              <div class="swiper-slide">
                <ul class="home_box-main-authenticateUlA" v-if="insectShow">
                  <li
                    class="home_box-main-authenticateListA"
                    v-for="(itemA, index) in this.insectPlantDat"
                    @click="plantDetails(itemA.id)"
                    :key="index"
                  >
                    <div class="home_box-main-authenticateListA-box1">
                      <img
                        preview="1"
                        v-lazy="itemA.img_urls"
                        alt
                        class="home_box-main-authenticateListA-box1-img"
                      />
                      <div class="home_box-main-authenticateListA-box1-txt">
                        {{ itemA.name }}
                        <!-- <span
                        class="home_box-main-authenticateListA-box1-num"
                        >1天前</span
                      > -->
                      </div>
                    </div>
                  </li>
                </ul>

                <!-- 暂空判断 -->
                <div class="seek_data_judge" v-else>
                  <img
                    src="../../assets/image/wu.png"
                    alt
                    class="seek_data_judge_img"
                  />
                  <div class="seek_data_judge_text">抱歉，暂无此数据</div>
                </div>
              </div>
              <!-- </mescroll-vue> -->
            </div>
          </div>
        </div>
      </div>
    </mescroll-vue>

    <!-- 底部导航 -->
    <bottomNav v-show="botNav"></bottomNav>
    <!-- 底部导航 -->
  </div>
</template>                          

<script>
import bottomNav from "../bottomNav/bottomNav"; //底部导航栏
// 引入mescroll的vue组件
import MescrollVue from "mescroll.js/mescroll.vue";
import Swiper from "swiper";
import "../../../swiper/css/swiper.min.css";

export default {
  name: "repository",
  //import引入的组件需要注入到对象中才能使用
  components: {
    bottomNav, //底部导航
    MescrollVue,
    Swiper,
  },
  data() {
    return {
      fullHeight: document.documentElement.clientHeight, //自定义高度
      botNav: true, //底部导航
      input: "", //搜索
      navList: [{ name: "虫害" }, { name: "病害" }],
      nowIndex: 0,
      mySwiper: "",
      insectPlantDat: [], //病虫害数据列表
      insectShow: 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:
            "http://pic.51yuansu.com/pic3/cover/00/65/23/5896fa4bc81fc_610.jpg", //图片路径,默认null,支持网络图
          offset: 500, //列表滚动1000px才显示回到顶部按钮
        },
        onScroll: function (mescroll, y, isUp) {
          //吸顶
          // if (y > 500) {
          //   self.navBarFixed = true;
          // } else {
          //   self.navBarFixed = false;
          // }
        },
        lazyLoad: {
          use: true, // 是否开启懒加载,默认false
        },
      },
      aggregate: "", //后端传来数据的总条数
      loading: true,
      // 上拉加载下拉刷新
    };
  },
  beforeRouteEnter(to, from, next) {
    if (from.name === "record") {
      to.meta.isBack = true;
    }
    // 如果没有配置顶部按钮或isBounce,则beforeRouteEnter不用写
    next((vm) => {
      if (from.name === "record") {
        // 滚动到原来的列表位置,恢复顶部按钮和isBounce的配置
        vm.$refs.mescroll && vm.$refs.mescroll.beforeRouteEnter();
      }
    });
  },
  beforeRouteLeave(to, from, next) {
    if (to.name !== "record") {
      to.meta.isBack = false;
    } else {
      to.meta.isBack = true;
      // 如果没有配置顶部按钮或isBounce,则beforeRouteLeave不用写
      // 记录列表滚动的位置,隐藏顶部按钮和isBounce的配置
      this.$refs.mescroll && this.$refs.mescroll.beforeRouteLeave();
    }
    next();
  },
  activated() {
    if (!this.$route.meta.isBack) {
      // 如果isBack是false，表明需要获取新数据，否则就不再请求，直接使用缓存的数据
      this.mescroll.resetUpScroll(); // 刷新列表数据
    }
    // 恢复成默认的false，避免isBack一直是true，导致下次无法获取数据
    this.$route.meta.isBack = 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);
      }
    },

    // 输入框双向绑定
    input(val) {
      if (val == "") {
        this.insectPlantData(); //当值为空时直接请求虫害病害接口
      }
    },

    // tab切换
    nowIndex(val) {
      this.insectPlantData();
      this.input = "";
    },
  },
  //方法集合
  methods: {
    //动态获取浏览器高度
    get_boderHeight() {
      const that = this;
      window.onresize = () => {
        return (() => {
          window.fullHeight = document.documentElement.clientHeight;
          that.fullHeight = window.fullHeight;
        })();
      };
    },

    // mescroll组件初始化的回调,可获取到mescroll对象
    mescrollInit(mescroll) {
      this.mescroll = mescroll; // 如果this.mescroll对象没有使用到,则mescrollInit可以不用配置
    },

    upCallback(page, mescroll) {
      var that = this;
      if (that.nowIndex == 0) {
        var ret = "insect";
      } else if (that.nowIndex == 1) {
        var ret = "plant";
      }
      let postData = that.$qs.parse({
        ret: ret,
        page: that.mescrollUp.page.num,
      });
      that
        .$axios({
          method: "post",
          url: "http://192.168.1.8:8002/see_dase",
          data: postData,
          headers: {
            "Content-Type": "multipart/form-data",
          },
        })
        .then((res) => {
          var nums = res.data.num;
          that.aggregate = nums;
          if (this.aggregate === "") {
            //存变量
            this.aggregate = nums;
            var b = "6";
            this.aggregate = this.aggregate / b;
            this.aggregate = Math.ceil(this.aggregate); //将小数点转换为整数
            console.log(this.aggregate);
          }

          if (res.data.num !== "") {
            // that.insectPlantDat = res.data.dat;
            // 如果是第一页需手动置空列表
            if (page.num === 1) this.insectPlantDat = [];
            // 把请求到的数据添加到列表
            this.insectPlantDat = this.insectPlantDat.concat(res.data.dat);

            // 数据渲染成功后,隐藏下拉刷新的状态
            this.$nextTick(() => {
              mescroll.endSuccess(res.data.dat.length);
            });
            that.insectShow = true;
          } else {
            that.insectShow = false;
          }
          // console.log(res.data);
          that.loading = false;
          this.$nextTick(() => {
            mescroll.endSuccess(res.data.dat.length);
          });
        })
        .catch((err) => {
          mescroll.endErr();
          console.log(err);
        });
    },

    // tab切换交流、鉴定、方案
    initSwiper() {
      var that = this;
      that.mySwiper = new Swiper(".swiper-container", {
        initialSlide: 0,
        autoplay: false,
        keyboardControl: true,
        autoHeight: true,
        observer: true, //修改swiper自己或子元素时，自动初始化swiper
        observeParents: true,
        autoplayDisableOnInteraction: false, //解决拖动之后不能自动轮播
        preventLinksPropagation: false, // 阻止点击事件冒泡
        onSlideChangeStart: function (swiper) {
          //这个是当swiper被改变是的回调函数，可以拿到当前索引
          console.log(swiper.activeIndex);
          that.nowIndex = swiper.activeIndex;
        },
        onSlideChangeTransitionStart: function (swiper, event) {},
      });
    },
    tabClick(index) {
      this.nowIndex = index;
      if (!this.mySwiper.slideTo) {
        this.initSwiper();
      }
      this.mySwiper.slideTo(index, 300, false);
    },

    //虫害病害数据列表请求
    insectPlantData() {
      var that = this;
      if (that.nowIndex == 0) {
        var ret = "insect";
      } else if (that.nowIndex == 1) {
        var ret = "plant";
      }
      let postData = that.$qs.parse({
        ret: ret,
        page: "1",
      });
      that
        .$axios({
          method: "post",
          url: "http://192.168.1.8:8002/see_dase",
          data: postData,
          headers: {
            "Content-Type": "multipart/form-data",
          },
        })
        .then((res) => {
          if (res.data.num !== "") {
            that.insectPlantDat = res.data.dat;
            that.insectShow = true;
          } else {
            that.insectShow = false;
          }
          // console.log(res.data);
        })
        .catch((err) => {
          console.log(err);
        });
    },

    // 点击进入虫害病害详情
    plantDetails(id) {
      var that = this;
      that.$router.push({
        name: "record",
        query: {
          id: id,
          req: "0",
        },
      });
    },

    //搜索
    seekChange() {
      var that = this;
      // if (that.nowIndex == 0) {
      //   var ret = 'insect'
      // } else if (that.nowIndex == 1) {
      //   var ret = 'plant'
      // }

      var form = new FormData();
      form.append("page", 1);
      form.append("name", that.input);
      form.append("ret", that.nowIndex == 0 ? "insect" : "plant");
      if (that.input == "") {
        that.insectPlantData(); //请求虫害病害数据列表
      } else {
        that
          .$axios({
            method: "post",
            url: "http://192.168.1.8:8002/search",
            data: form,
            headers: {
              "Content-Type": "multipart/form-data",
            },
          })
          .then((res) => {
            if (res.data.num !== "") {
              that.insectPlantDat = res.data.dat;
              that.insectShow = true;
            } else {
              that.insectShow = false;
            }
          })
          .catch((err) => {
            console.log(err);
          });
      }
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.initSwiper();
    this.get_boderHeight();
    // this.insectPlantData(); //虫害病害数据列表请求
  },
};
</script>
<style lang='scss'>
//@import url(); 引入公共css类
@import "../../assets/scss/repository.scss";
.el-popup-parent--hidden {
  overflow: auto;
}
</style>