<!--  -->
<template>
  <div class="home_box" :style="'height:' + fullHeight + 'px'">
    <!-- 头部 -->
    <div class="home_headrBox">
      <div class="home_divBox">
        <div class="home_headrBox-tlt">首页</div>
      </div>
    </div>

    <mescroll-vue
      ref="mescroll"
      class="home_box_mescroll"
      :down="mescrollDown"
      :up="mescrollUp"
      @init="mescrollInit"
    >
      <!-- 轮播图 -->
      <div id="htmlWrap" style="background: none">
        <!--header-->
        <div
          class="bg545C64"
          style="background: none; box-shadow: 0 0 3px #e5e5e5"
        ></div>

        <!-- 轮播图 -->
        <div class="bannerWrap" style="width: 100%; height: 5.5rem">
          <!-- Swiper -->
          <div class="swiper-container">
            <div class="swiper-wrapper">
              <div
                class="swiper-slide"
                v-for="(item, index) in lunboImgList"
                :key="index"
              >
                <!-- <img
                :src="item"
                @click.stop="imgClikc(index)"
                class="bannerWrap_img"
                alt
              /> -->
                <img :src="item" class="bannerWrap_img" alt />
              </div>
            </div>
            <div
              class="swiper-pagination swiper-pagination-white"
              id="swiper-spit"
            ></div>
          </div>
        </div>
        <div style="clear: both"></div>
      </div>
      <!-- 轮播图 -->

      <!-- 功能跳转列表 -->
      <div class="home_box_divUl">
        <ul class="home_box_ul">
          <li class="home_box_ul_list" @click="exchange()">
            <img
              src="../../assets/image/new/36.png"
              alt=""
              class="home_box_ul_list_img"
            />
            <div class="home_box_ul_list_txt">用户交流</div>
          </li>
          <li class="home_box_ul_list" @click="authenticate()">
            <img
              src="../../assets/image/new/37.png"
              alt=""
              class="home_box_ul_list_img"
            />
            <div class="home_box_ul_list_txt">病虫鉴定</div>
          </li>
          <li class="home_box_ul_list" @click="scheme()">
            <img
              src="../../assets/image/new/38.png"
              alt=""
              class="home_box_ul_list_img"
            />
            <div class="home_box_ul_list_txt">防治方案</div>
          </li>
          <li class="home_box_ul_list" @click="share()">
            <img
              src="../../assets/image/new/39.png"
              alt=""
              class="home_box_ul_list_img"
            />
            <div class="home_box_ul_list_txt">积分兑换</div>
          </li>
        </ul>
      </div>

      <!-- 最新几条防治方案 -->
      <div
        class="home_box_div1"
        v-loading="loading"
        element-loading-text="拼命加载中"
      >
        <ul class="home_box_div1_ul">
          <li
            class="home_box_div1_list"
            v-for="(item, index) in schemeArr"
            :key="index"
            @click="details(item.id, '0')"
          >
            <div class="home_box_div1_listBox">
              <div class="home_box_div1_listBox_article">
                {{ item.content | ellipsis }}
              </div>
              <div class="home_box_div1_listBox_article_div">
                <div class="home_box_div1_listBox_article_div1">
                  <img
                    src="../../assets/image/new/47.jpg"
                    alt=""
                    class="home_box_div1_listBox_article_div1_img"
                  />
                  <div class="home_box_div1_listBox_article_div1_username">
                    河南云飞科技
                  </div>
                </div>
                <div class="home_box_div1_listBox_article_div2">
                  <img
                    src="../../assets/image/new/8.png"
                    alt=""
                    class="home_box_div1_listBox_article_div2_img"
                  />
                  <div class="home_box_div1_listBox_article_div2_nums">
                    2000
                  </div>
                </div>
              </div>
            </div>

            <div class="home_box_div1_listBox_article2_div">
              <img
                v-lazy="'http://192.168.1.8:8002/' + item.imgArr[0]"
                alt=""
                class="home_box_div1_listBox_article2_div_img"
              />
            </div>
          </li>
        </ul>
      </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";
import "swiper/js/swiper.min.js";

export default {
  name: "home",
  filters: {
    ellipsis(value) {
      if (!value) return "";
      if (value.length > 30) {
        return value.slice(0, 30) + "...";
      }
      return value;
    },
  },
  components: {
    bottomNav, //底部导航
    MescrollVue,
  },
  data() {
    //这里存放数据
    return {
      userAxios: {}, //获取用户个人信息
      fullHeight: document.documentElement.clientHeight, //自适应高度
      activeName: "second", //tab切换交流、鉴定、方案
      botNav: true, //底部导航
      lunboImgList: [
        "http://192.168.1.8:8002/discern_photos/rotation/1.png",
        "http://192.168.1.8:8002/discern_photos/rotation/2.png",
        "http://192.168.1.8:8002/discern_photos/rotation/3.png",
      ], //轮播图
      schemeArr: [], //方案数据数组
      loading: 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: "", //后端传来数据的总条数
      // 上拉加载下拉刷新
    };
  },
  beforeRouteEnter(to, from, next) {
    if (from.name === "schemeDetails") {
      to.meta.isBack = true;
    }
    // 如果没有配置顶部按钮或isBounce,则beforeRouteEnter不用写
    next((vm) => {
      if (from.name === "schemeDetails") {
        // 滚动到原来的列表位置,恢复顶部按钮和isBounce的配置
        vm.$refs.mescroll && vm.$refs.mescroll.beforeRouteEnter();
      }
    });
  },
  beforeRouteLeave(to, from, next) {
    if (to.name !== "schemeDetails") {
      to.meta.isBack = false;
    } else {
      to.meta.isBack = true;
      // 如果没有配置顶部按钮或isBounce,则beforeRouteLeave不用写
      // 记录列表滚动的位置,隐藏顶部按钮和isBounce的配置
      this.$refs.mescroll && this.$refs.mescroll.beforeRouteLeave();
    }
    // 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);
      }
    },

    // 监听切换
    nowIndex(val) {
      if (val == 0) {
        //交流
        this.interflowData();
      } else if (val == 1) {
        //鉴定
        this.interflowData();
      } else if (val == 2) {
        //方案
      }
    },
  },
  //方法集合
  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) {
      let that = this;
      that
        .$axios({
          method: "get",
          url: "http://192.168.1.8:8002/save_news",
          params: {
            page: that.mescrollUp.page.num,
          },
        })
        .then((res) => {
          var nums = res.data.nums;
          if (this.aggregate === "") {
            //存变量
            this.aggregate = nums;
            var b = "9";
            this.aggregate = this.aggregate / b;
            this.aggregate = Math.ceil(this.aggregate); //将小数点转换为整数
          }
          if (res.data.length !== 0) {
            // that.schemeArr = [];
            //重组数据数组
            var arr = res.data.data;
            for (var i = 0; i < arr.length; i++) {
              var d = new Date(arr[i].time);
              var r = d.getTime(d);

              //将图片对象进行处理
              var yourString = arr[i].img_urls;
              var result = yourString.split(",");
              arr[i]["newTime"] = r;
              arr[i]["imgArr"] = result;
            }
            // that.schemeArr = arr;

            // 如果是第一页需手动置空列表
            if (page.num === 1) this.schemeArr = [];
            // 把请求到的数据添加到列表
            this.schemeArr = this.schemeArr.concat(arr);

            // 数据渲染成功后,隐藏下拉刷新的状态
            this.$nextTick(() => {
              mescroll.endSuccess(arr.length);
            });
          } else {
            var arr = [];
            this.$nextTick(() => {
              mescroll.endSuccess(arr.length);
            });
          }
          that.loading = false;
        })
        .catch((err) => {
          mescroll.endErr();
        });
    },

    // 点击进入交流详情
    exchange() {
      var that = this;
      that.$router.push("/exchange");
    },

    // 点击进入病虫鉴定
    authenticate() {
      var that = this;
      that.$router.push("/authenticate");
    },

    // 点击进入防治方案
    scheme() {
      var that = this;
      that.$router.push("/scheme");
    },

    // 点击进入积分详情
    share() {
      var that = this;
      that.$router.push({
        name: "share",
        query: {
          ret: "integral",
          name: that.userAxios.username,
          num: that.userAxios.integral,
        },
      });
    },

    // 方案列表
    // schemeListData() {
    //   var that = this;
    //   that
    //     .$axios({
    //       method: "get",
    //       url: "http://192.168.1.8:8002/save_news",
    //       params: {
    //         page: 1,
    //       },
    //     })
    //     .then((res) => {
    //       if (res.data.length !== 0) {
    //         // that.schemeArr = res.data

    //         that.schemeArr = [];
    //         //重组数据数组
    //         var arr = res.data;
    //         for (var i = 0; i < arr.length; i++) {
    //           var d = new Date(arr[i].time);
    //           var r = d.getTime(d);

    //           //将图片对象进行处理
    //           var yourString = arr[i].img_urls;
    //           var result = yourString.split(",");
    //           arr[i]["newTime"] = r;
    //           arr[i]["imgArr"] = result;
    //         }
    //         that.schemeArr = arr;
    //       } else {
    //         console.log("暂无数据");
    //       }
    //       that.loading = false;
    //     })
    //     .catch((err) => {
    //       console.log(err);
    //     });
    // },

    // 点击进入方案详情、
    details(id, req) {
      var that = this;
      that.$router.push({
        name: "schemeDetails",
        query: {
          id: id,
          req: req,
        },
      });
    },

    // 用户个人信息数据请求
    userData() {
      var that = this;
      that
        .$axios({
          method: "get",
          url: "http://192.168.1.8:8002/see_user",
        })
        .then((res) => {
          that.userAxios = res.data;
        })
        .catch((err) => {
          console.log(err);
        });
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.get_boderHeight(); //动态获取浏览器高度
    // this.schemeListData(); //方案列表接口
    this.userData(); //获取用户个人信息

    // 【注意2:】
    // 轮播图 · 初始化设定
    var swiper = new Swiper(".swiper-container", {
      spaceBetween: 30,
      effect: "fade",
      autoplay: {
        delay: 3000,
        disableOnInteraction: false, // 取消鼠标操作后的轮播暂停【无操作轮播继续】【参考链接1】
        stopOnLastSlide: false, // 在最后一页停止
      },
      pagination: {
        el: ".swiper-pagination",
        clickable: true,
      },
      navigation: {
        nextEl: ".swiper-button-next",
        prevEl: ".swiper-button-prev",
      },
    });
  },
};
</script>
<style lang='scss'>
.home_box_mescroll {
  width: 100%;
  height: 100%;
  overflow-x: hidden;
}
.el-popup-parent--hidden {
  overflow: auto;
}

/* @import "./css/lovecircle.css"; */
/* 轮播图 */
.bannerWrap {
  /* margin: 1.5rem 0 0.5rem 0; */
  // margin: -1.8rem 0 0.5rem 0;
}
.swiper-container {
  width: 100%;
  height: 100%;
}
.swiper-slide {
  background-position: center;
  background-size: cover;
}
.bannerWrap_img {
  width: 100%;
  height: 100%;
}

@import "../../assets/scss/bus.scss";
@import "../../assets/scss/home.scss";
</style>