<!--  -->
<template>
  <div
    class="repository_box"
    :style="'height:' + fullHeight + 'px'"
    v-loading="loading"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)"
    :modal-append-to-body="false"
  >
    <!-- 头部 -->
    <div class="repository_head">
      <div class="repository_head_returnA" @click="FanHui()">
        <img src="../../assets/image/left.png" alt class="repository_head_returnA_img" />
      </div>

      <!-- 标题 -->
      <div class="head_title">
        <span class="head_title_text">知识库</span>
      </div>

      <!-- 搜索框 -->
      <div class="head_souSuo_box" @click="seek()">
        <img src="../../assets/image/seek.png" alt class="head_souSuo_img" />
      </div>
    </div>

    <!-- 测试 -->
    <mescroll-vue ref="mescroll" :down="mescrollDown" :up="mescrollUp" @init="mescrollInit">
      <!-- 列表 -->
      <div class="repository_list">
        <ul class="repository_ul" v-if="axiosShow">
          <li
            class="repository_li"
            @click="xiangqi($event, index)"
            v-for="(item, index) in this.reData"
            :key="index"
          >
            <!-- 图片 -->
            <div class="repository_li_div">
              <img
                v-lazy="item.img_urls === null || item.img_urls === '' ? './static/picture.png' :  item.img_urls"
                alt
                class="repository_li_img"
              />
            </div>
            <!-- 昆虫或病害名称 -->
            <div class="repository_li_name">{{ item.name | ellipsis }}</div>

            <!-- 详情按钮 -->
            <div class="repository_li_btn_div">
              <span class="repository_li_btn_text">详情</span>
              <img src="../../assets/image/right.png" alt class="repository_li_btn_img" />
            </div>

            <!-- 科目 -->
            <div class="repository_li_subject">
              <span class="repository_li_subject_text">{{ item.course | ellipsis }}</span>
            </div>
          </li>
        </ul>

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

        <!-- 病虫害筛选按钮 -->
        <div class="repository_screen">
          <el-button class="repository_screen_btn" @click="show2 = !show2">
            <img src="../../assets/image/jia.png" alt class="repository_screen_btn_img" />
          </el-button>

          <transition name="el-zoom-in-bottom">
            <ul v-show="show2" class="transition-box">
              <!-- 全部 -->
              <li class="repository_all" :class="{activeA:shows == 1}" @click="all(),allA()">
                <div class="repository_all_text_box">
                  <span class="repository_all_text">全部病虫害</span>
                </div>

                <div class="repository_all_img_box">
                  <img src="../../assets/image/all.png" alt class="repository_all_img" />
                </div>
              </li>

              <!-- 病害 -->
              <li class="repository_plant" :class="{activeA:shows == 2}" @click="plant(),plantA()">
                <div class="repository_plant_text_box">
                  <span class="repository_plant_text">病害</span>
                </div>

                <div class="repository_plant_img_box">
                  <img src="../../assets/image/leaf.png" alt class="repository_plant_img" />
                </div>
              </li>

              <!-- 虫害 -->
              <li
                class="repository_insect"
                :class="{activeA:shows == 3}"
                @click="insect(),insectA()"
              >
                <div class="repository_insect_text_box">
                  <span class="repository_insect_text">虫害</span>
                </div>

                <div class="repository_insect_img_box">
                  <img src="../../assets/image/insect.png" alt class="repository_insect_img" />
                </div>
              </li>
            </ul>
          </transition>
        </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";
export default {
  name: "repository",
  //限时数据文本的字数限时
  filters: {
    ellipsis(value) {
      if (!value) return "";
      if (value.length > 5) {
        return value.slice(0, 5) + "...";
      }
      return value;
    }
  },

  components: {
    MescrollVue, // 注册mescroll组件
    bottomNav
  },
  data() {
    //这里存放数据
    const self = this;
    return {
      loading: true, //加载
      botNav: true, //底部导航
      fullHeight: document.documentElement.clientHeight,
      repositoryA: localStorage.getItem("seek_name"),
      show2: false, //筛选按钮
      reData: [], //后端传来的列表数据
      image: "", //后端传来的图片
      axiosShow: true, //暂空判断
      shows: localStorage.getItem("shows"), //active
      //测试
      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: 800 //列表滚动1000px才显示回到顶部按钮
        },
        empty: {
          //列表第一页无任何数据时,显示的空提示布局; 需配置warpId才显示
          warpId: "xxid", //父布局的id (1.3.5版本支持传入dom元素)
          icon: "./static/mescroll/mescroll-empty.png", //图标,默认null,支持网络图
          tip: "暂无相关数据~" //提示
        },
        onScroll: function(mescroll, y, isUp) {
          //监听滚动条
          // console.log(y)
          //y为列表当前滚动条的位置

          //隐藏底部导航
          if (y > 50) {
            self.botNav = false;
          } else {
            self.botNav = true;
          }
        },
        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);
      }
    }
  },
  //方法集合
  methods: {
    // mescroll组件初始化的回调,可获取到mescroll对象
    mescrollInit(mescroll) {
      this.mescroll = mescroll; // 如果this.mescroll对象没有使用到,则mescrollInit可以不用配置
    },
    // 上拉回调 page = {num:1, size:10}; num:当前页 ,默认从1开始; size:每页数据条数,默认10
    upCallback(page, mescroll) {
      let _this = this;
      let postData = this.$qs.parse({
        page: this.mescrollUp.page.num,
        ret: localStorage.getItem("memoryBiaoshi")
      });
      this.$axios({
        method: "post",
        url: "bigservers/see_dase",
        data: postData
      })
        .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) {
            let postData = this.$qs.parse({
              page: this.mescrollUp.page.num,
              ret: localStorage.getItem("memoryBiaoshi")
            });
            this.$axios({
              method: "post",
              url: "bigservers/see_dase",
              data: postData
            })
              .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);
                });
                if (res.data.dat.length === 0) {
                  _this.axiosShow = false;
                  _this.FenShow = false;
                } else if (res.data.dat.length !== 0) {
                  _this.axiosShow = true;
                  _this.FenShow = true;
                }
                _this.loading = false;
              })
              .catch(error => {
                mescroll.endErr();
              });
          } else if (this.mescrollUp.page.num > this.aggregate) {
            _this.loading = false;
            // 数据渲染成功后,隐藏下拉刷新的状态
            this.$nextTick(() => {
              mescroll.endSuccess(this.aggregate);
            });
          }

          if (this.aggregate === 0) {
            this.axiosShow = false;
            this.FenShow = false;
            _this.loading = false;
          }
        })
        .catch(error => {
          mescroll.endErr();
        });
    },

    //动态获取浏览器高度
    get_boderHeight() {
      const that = this;
      window.onresize = () => {
        return (() => {
          window.fullHeight = document.documentElement.clientHeight;
          that.fullHeight = window.fullHeight;
        })();
      };
    },

    // 返回home页面
    FanHui() {
      let _this = this;
      localStorage.removeItem("memoryBiaoshi");
      localStorage.removeItem("repositoryPage");
      localStorage.removeItem("shows");
      localStorage.removeItem("quebie");
      // _this.$router.push("/home");
      _this.$router.replace("/home");
    },

    //点击进入详情页面,并获取到当前列表的id
    xiangqi(e, index) {
      let _this = this;
      if (
        e.target.className === "repository_li_btn_text" ||
        e.target.className === "repository_li_name" ||
        e.target.className === "repository_li_subject" ||
        e.target.className === "repository_li_img" ||
        e.target.className === "repository_li_div"
      ) {
        _this.current = index;
        //获取点击对象
        let el = e.currentTarget;
        let listId = _this.reData[index].id;
        let listrank = _this.reData[index].ret;
        localStorage.setItem("repositoryID", listId); //保存获取的ID
        localStorage.setItem("repositoryRank", listrank); //保存获取的类型区别
        _this.$router.push("/details");
      }
    },

    // 点击全部筛选
    all() {
      location.reload();
      localStorage.removeItem("repositoryPage");
      localStorage.setItem("memoryBiaoshi", "edit"); //添加一个标识，好判断当前要请求什么数据
      let _this = this;
      let postData = _this.$qs.parse({
        ret: localStorage.getItem("memoryBiaoshi"),
        page: "1"
      });
      _this
        .$axios({
          method: "post",
          url: "bigservers/see_dase",
          data: postData,
          headers: {
            "Content-Type": "multipart/form-data"
          }
        })
        .then(res => {
          if (res.data.dat.length === 0) {
            _this.axiosShow = false;
            _this.FenShow = false;
          } else if (res.data.dat.length !== 0) {
            _this.axiosShow = true;
            _this.FenShow = true;
            _this.reData = res.data.dat; //全部数据
            let a = res.data.page;
            let b = "4";
            let d = a / b;
            if (d % 1 === 0) {
              _this.page = d * 10;
            } else {
              let g = Math.ceil(d) * 10;
              _this.page = g;
            }
          }
        })
        .catch(error => {
          alert("失败");
        });
    },

    // 点击病害筛选
    plant() {
      location.reload();
      localStorage.removeItem("repositoryPage");
      localStorage.setItem("memoryBiaoshi", "plant"); //添加一个标识，好判断当前要请求什么数据
      let _this = this;
      let postData = _this.$qs.parse({
        ret: localStorage.getItem("memoryBiaoshi"),
        page: "1"
      });
      _this
        .$axios({
          method: "post",
          url: "bigservers/see_dase",
          data: postData,
          headers: {
            "Content-Type": "multipart/form-data"
          }
        })
        .then(res => {
          if (res.data.dat.length === 0) {
            _this.axiosShow = false;
            _this.FenShow = false;
          } else if (res.data.dat.length !== 0) {
            _this.axiosShow = true;
            _this.FenShow = true;
            _this.reData = res.data.dat; //全部数据
            let a = res.data.page;
            let b = "4";
            let d = a / b;
            if (d % 1 === 0) {
              _this.page = d * 10;
            } else {
              let g = Math.ceil(d) * 10;
              _this.page = g;
            }
          }
        })
        .catch(error => {
          alert("失败");
        });
    },

    // 点击虫害筛选
    insect() {
      location.reload();
      localStorage.removeItem("repositoryPage");
      localStorage.setItem("memoryBiaoshi", "insect"); //添加一个标识，好判断当前要请求什么数据
      let _this = this;
      let postData = _this.$qs.parse({
        ret: localStorage.getItem("memoryBiaoshi"),
        page: "1"
      });
      _this
        .$axios({
          method: "post",
          url: "bigservers/see_dase",
          data: postData,
          headers: {
            "Content-Type": "multipart/form-data"
          }
        })
        .then(res => {
          if (res.data.dat.length === 0) {
            _this.axiosShow = false;
            _this.FenShow = false;
          } else if (res.data.dat.length !== 0) {
            _this.axiosShow = true;
            _this.FenShow = true;
            _this.reData = res.data.dat; //全部数据
            let a = res.data.page;
            let b = "4";
            let d = a / b;
            if (d % 1 === 0) {
              _this.page = d * 10;
            } else {
              let g = Math.ceil(d) * 10;
              _this.page = g;
            }
            _this.location = false;
          }
        })
        .catch(error => {
          alert("失败");
        });
    },

    //点击图标进行搜索
    seek() {
      let _this = this;
      localStorage.setItem("seekBiaishi", "1");
      _this.$router.push("/seek");
      localStorage.removeItem("memoryID");
      localStorage.removeItem("memoryDistinction");
      localStorage.removeItem("collectID");
      localStorage.removeItem("collectDistinction");
      localStorage.removeItem("showID");
      localStorage.removeItem("Point");
      localStorage.removeItem("axiosData");
      localStorage.removeItem("homeSeek");
    },

    //测试
    allA() {
      localStorage.setItem("shows", 1);
    },

    plantA() {
      localStorage.setItem("shows", 2);
    },

    insectA() {
      localStorage.setItem("shows", 3);
    }
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.get_boderHeight();

    //判断当前collectBiaoshi是否为空
    if (localStorage.getItem("memoryBiaoshi") === null) {
      localStorage.setItem("memoryBiaoshi", "edit"); //添加一个标识，好判断当前要请求什么数据
    }
  }
};
</script>
<style lang='scss'>
@import "../../assets/scss/bus.scss";
@import "../../assets/scss/repository.scss";
/*通过fixed固定mescroll的高度*/
.repository_box .mescroll {
  position: fixed;
  top: 44px;
  bottom: 0;
  height: auto;
}
</style>