<template>
  <view>
    <!-- 导航栏 -->
    <u-navbar :border-bottom="false" :is-back="false" :background="{ background: '#ffffff' }">
      <view class="pl-base w-full" @tap="$u.route('/pages/search/search')">
        <u-search class="w-full" :disabled="true" placeholder="搜索商品名称" v-model="searchText" :show-action="false"></u-search>
      </view>
      <template #right>
        <view class="mx-base relative" @tap="$u.routeAuth('/pageA/news/index')">
          <u-icon name="chat" size="48"></u-icon>
          <block v-if="news_num > 0">
            <u-badge :is-dot="true" size="16" :offset="[0, 2]" class="badge"></u-badge>
          </block>
        </view>
      </template>
    </u-navbar>
    <mescroll-body :bottombar="false" ref="mescrollRef" @init="mescrollInit" @down="downCallback" @up="upCallback" :down="downOption" :up="upOption">
      <view class="px-base">
        <!-- 轮播图 -->
        <view>
          <swiper
            class="swipers h-400rpx text-center mt-base m-auto rounded15rpx overflow"
            circular="true"
            autoplay="true"
            indicator-dots="true"
            indicator-color="#ffffff"
            indicator-active-color="#378264"
          >
            <swiper-item class="flex justify-center w-full h-full" v-for="(item, index) in bannerList['wechat_mini_top_banner']" :key="index">
              <image
                :src="`${item.image}?x-oss-process=image/resize,w_750/quality,q_90`"
                mode="aspectFill"
                class="w-full h-full"
                @tap="jumpByOption(item)"
              />
            </swiper-item>
          </swiper>
        </view>
        <!-- tabs -->
        <block v-if="!isVerify">
          <view class="grid grid-cols-5">
            <view
              @tap="jumpByOption(item)"
              class="py-25rpx flex flex-col justify-center items-center"
              v-for="(item, index) in bannerList['wechat_mini_top_navigation_banner']"
              :key="index"
            >
              <view class="flex items-end">
                <u-image width="70rpx" height="70rpx" :src="`${item.image}?x-oss-process=image/resize,w_70/quality,q_90`" :lazy-load="true"></u-image>
              </view>
              <view class="text-md mt-14rpx text-hex-txBase">{{ item.name }}</view>
            </view>
          </view>
        </block>
        <!--  -->
        <view class="bg-white m-auto shdow">
          <view class="px-base">
            <indexTitle></indexTitle>
            <!-- 第一张广告图 -->
            <view class="grid grid-cols-2 gap-x-20rpx mt-10rpx">
              <view
                v-for="(item, index) in bannerList['wechat_mini_recommend_banner']"
                :key="index"
                :class="index == 0 ? 'col-start-1 col-span-2' : ''"
                class="mt-20rpx"
              >
                <u-image
                  border-radius="15rpx"
                  width="100%"
                  height="260rpx"
                  :src="`${item.image}?x-oss-process=image/resize,w_750/quality,q_90`"
                  :lazy-load="true"
                  @tap="jumpByOption(item)"
                ></u-image>
              </view>
            </view>
          </view>
          <!--  -->
          <view class="mt-base">
            <u-line border-style="dashed" color="#E5E5E5" />
          </view>
          <!-- 左右滑动 -->
          <view class="px-base">
            <scroll-view scroll-x="true" class="mt-base scroll pb-10rpx">
              <view
                class="scroll-item mt-10rpx mr-20rpx"
                v-for="(item, index) in recommendList"
                @tap="$u.route('/pages/product_details/index', { skuId: item.id })"
                :key="index"
              >
                <u-image
                  border-radius="15rpx"
                  width="260rpx"
                  height="260rpx"
                  :src="`${item.cover}?x-oss-process=image/resize,w_260/quality,q_90`"
                  :lazy-load="true"
                ></u-image>
                <view class="text-md w-240rpx line-1 text-hex-bgBase h-40rpx">{{ item.name }}</view>
                <view class="text-md text-txBase">￥{{ item.sell_price }}</view>
                <view class="flex items-center" v-if="item.vip_price">
                  <view class="text-lg -mt-5rpx text-txSvip">￥{{ item.vip_price }}</view>
                  <image class="w-58rpx h-58rpx ml-10rpx" src="/static/svg/svip.svg" mode=""></image>
                </view>
              </view>
            </scroll-view>
          </view>
        </view>
        <!-- 第四张广告图 -->
        <view class="mt-base" v-for="(item, index) in bannerList['wechat_mini_floor_banner']" :key="index">
          <u-image
            @tap="jumpByOption(item)"
            border-radius="15rpx"
            width="100%"
            height="220rpx"
            :src="`${item.image}?x-oss-process=image/resize,w_750/quality,q_90`"
            :lazy-load="true"
          ></u-image>
        </view>
        <!--  -->
        <view class="bg-white m-auto shdow mt-base px-base">
          <indexTitle name="热销商品"></indexTitle>
          <scroll-view scroll-x="true" class="mt-base scroll">
            <view
              class="scroll-item mt-10rpx mr-20rpx"
              v-for="(item, index) in hotList"
              @tap="$u.route('/pages/product_details/index', { skuId: item.id })"
              :key="index"
            >
              <u-image
                border-radius="15rpx"
                width="260rpx"
                height="260rpx"
                :src="`${item.cover}?x-oss-process=image/resize,w_260/quality,q_90`"
                :lazy-load="true"
              ></u-image>
              <view class="text-md w-240rpx line-1 text-hex-bgBase h-40rpx">{{ item.name }}</view>
              <view class="text-md text-txBase">￥{{ item.sell_price }}</view>
              <view class="flex items-center" v-if="item.vip_price">
                <view class="text-lg -mt-5rpx text-txSvip">￥{{ item.vip_price }}</view>
                <image class="w-58rpx h-58rpx ml-10rpx" src="/static/svg/svip.svg" mode=""></image>
              </view>
            </view>
          </scroll-view>
        </view>
        <!-- 精品书籍 -->
        <view class="bg-white m-auto shdow mt-base px-base" v-if="boutique_books.length">
          <indexTitle name="精品书籍"></indexTitle>
          <scroll-view scroll-x="true" class="mt-base scroll">
            <view
              class="scroll-item mt-10rpx mr-20rpx"
              v-for="(item, index) in boutique_books"
              @tap="$u.route('/pages/product_details/index', { skuId: item.id })"
              :key="index"
            >
              <u-image
                border-radius="15rpx"
                width="260rpx"
                height="260rpx"
                :src="`${item.cover}?x-oss-process=image/resize,w_260/quality,q_90`"
                :lazy-load="true"
              ></u-image>
              <view class="text-md w-240rpx line-1 text-hex-bgBase h-40rpx">{{ item.name }}</view>
              <view class="text-md text-txBase">￥{{ item.sell_price }}</view>
              <view class="flex items-center" v-if="item.vip_price">
                <view class="text-lg -mt-5rpx text-txSvip">￥{{ item.vip_price }}</view>
                <image class="w-58rpx h-58rpx ml-10rpx" src="/static/svg/svip.svg" mode=""></image>
              </view>
            </view>
          </scroll-view>
        </view>
        <!-- 自然水景 -->
        <view class="bg-white m-auto shdow mt-base px-base" v-if="natural_water_feature.length">
          <indexTitle name="自然水景"></indexTitle>
          <scroll-view scroll-x="true" class="mt-base scroll">
            <view
              class="scroll-item mt-10rpx mr-20rpx"
              v-for="(item, index) in natural_water_feature"
              @tap="$u.route('/pages/product_details/index', { skuId: item.id })"
              :key="index"
            >
              <u-image
                border-radius="15rpx"
                width="260rpx"
                height="260rpx"
                :src="`${item.cover}?x-oss-process=image/resize,w_260/quality,q_90`"
                :lazy-load="true"
              ></u-image>
              <view class="text-md w-240rpx line-1 text-hex-bgBase h-40rpx">{{ item.name }}</view>
              <view class="text-md text-txBase">￥{{ item.sell_price }}</view>
              <view class="flex items-center" v-if="item.vip_price">
                <view class="text-lg -mt-5rpx text-txSvip">￥{{ item.vip_price }}</view>
                <image class="w-58rpx h-58rpx ml-10rpx" src="/static/svg/svip.svg" mode=""></image>
              </view>
            </view>
          </scroll-view>
        </view>
        <!-- 观赏生物  -->
        <view class="bg-white m-auto shdow mt-base px-base" v-if="ornamental_creatures.length">
          <indexTitle name="观赏生物"></indexTitle>
          <scroll-view scroll-x="true" class="mt-base scroll">
            <view
              class="scroll-item mt-10rpx mr-20rpx"
              v-for="(item, index) in ornamental_creatures"
              @tap="$u.route('/pages/product_details/index', { skuId: item.id })"
              :key="index"
            >
              <u-image
                border-radius="15rpx"
                width="260rpx"
                height="260rpx"
                :src="`${item.cover}?x-oss-process=image/resize,w_260/quality,q_90`"
                :lazy-load="true"
              ></u-image>
              <view class="text-md w-240rpx line-1 text-hex-bgBase h-40rpx">{{ item.name }}</view>
              <view class="text-md text-txBase">￥{{ item.sell_price }}</view>
              <view class="flex items-center" v-if="item.vip_price">
                <view class="text-lg -mt-5rpx text-txSvip">￥{{ item.vip_price }}</view>
                <image class="w-58rpx h-58rpx ml-10rpx" src="/static/svg/svip.svg" mode=""></image>
              </view>
            </view>
          </scroll-view>
        </view>
        <!-- 珊瑚水草  -->
        <view class="bg-white m-auto shdow mt-base px-base" v-if="coral_aquatic_plants.length">
          <indexTitle name="珊瑚水草"></indexTitle>
          <scroll-view scroll-x="true" class="mt-base scroll">
            <view
              class="scroll-item mt-10rpx mr-20rpx"
              v-for="(item, index) in coral_aquatic_plants"
              @tap="$u.route('/pages/product_details/index', { skuId: item.id })"
              :key="index"
            >
              <u-image
                border-radius="15rpx"
                width="260rpx"
                height="260rpx"
                :src="`${item.cover}?x-oss-process=image/resize,w_260/quality,q_90`"
                :lazy-load="true"
              ></u-image>
              <view class="text-md w-240rpx line-1 text-hex-bgBase h-40rpx">{{ item.name }}</view>
              <view class="text-md text-txBase">￥{{ item.sell_price }}</view>
              <view class="flex items-center" v-if="item.vip_price">
                <view class="text-lg -mt-5rpx text-txSvip">￥{{ item.vip_price }}</view>
                <image class="w-58rpx h-58rpx ml-10rpx" src="/static/svg/svip.svg" mode=""></image>
              </view>
            </view>
          </scroll-view>
        </view>
        <!-- 设备耗材 -->
        <view class="bg-white m-auto shdow mt-base px-base" v-if="equipment_consumables.length">
          <indexTitle name="设备耗材"></indexTitle>
          <scroll-view scroll-x="true" class="mt-base scroll">
            <view
              class="scroll-item mt-10rpx mr-20rpx"
              v-for="(item, index) in equipment_consumables"
              @tap="$u.route('/pages/product_details/index', { skuId: item.id })"
              :key="index"
            >
              <u-image
                border-radius="15rpx"
                width="260rpx"
                height="260rpx"
                :src="`${item.cover}?x-oss-process=image/resize,w_260/quality,q_90`"
                :lazy-load="true"
              ></u-image>
              <view class="text-md w-240rpx line-1 text-hex-bgBase h-40rpx">{{ item.name }}</view>
              <view class="text-md text-txBase">￥{{ item.sell_price }}</view>
              <view class="flex items-center" v-if="item.vip_price">
                <view class="text-lg -mt-5rpx text-txSvip">￥{{ item.vip_price }}</view>
                <image class="w-58rpx h-58rpx ml-10rpx" src="/static/svg/svip.svg" mode=""></image>
              </view>
            </view>
          </scroll-view>
        </view>
        <view class="flex items-center justify-center mt-base">
          <view class="w-25rpx h-1rpx bg-txBase"></view>
          <view class="text-xl font-extrabold text-txBase mx-10rpx">猜你喜欢</view>
          <view class="w-25rpx h-1rpx bg-txBase"></view>
        </view>

        <view class="mt-20rpx -mx-10rpx">
          <goods-list ref="uWaterfall" :list="interestList"></goods-list>
        </view>
      </view>
    </mescroll-body>
    <!-- <popupView v-model="popupShow"></popupView> -->
    <!-- <u-no-network></u-no-network> -->
    <!-- 广告位弹窗 -->
    <popupView v-model="popupShow" :item="popAdvertising"></popupView>
  </view>
</template>

<script>
import { strToParams } from '@/utils/tools';
import indexTitle from './components/title.vue';
import popupView from './components/popup-view.vue';
import MescrollMixin from '@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js';
import { checkUpdate } from '@/utils/check-update';
import CartMixin from '@/pages/shop_cart/mixin';
const defaultBanner = {
  wechat_mini_top_banner: [],
  wechat_mini_recommend_banner: [],
  wechat_mini_floor_banner: [],
  wechat_mini_top_navigation_banner: [],
};
const CONST_BANNERLIST = 'bannerList';
const CONST_HOTLIST = 'hotList';
const CONST_RECOMMEND = 'recommend';

export default {
  mixins: [MescrollMixin, CartMixin],
  components: {
    indexTitle,
    popupView,
  },
  data() {
    return {
      popupShow: false, //广告弹窗开关
      popAdvertising: {},
      searchText: '',
      bannerList: Object.assign({}, defaultBanner),
      interestList: [],
      hotList: [],
      recommendList: [],
      downOption: {
        // use: false,
      },
      upOption: {
        page: {
          size: 20,
        },
        noMoreSize: 1,
      },
      boutique_books:[],//精品书籍
      natural_water_feature:[],//自然水景
      ornamental_creatures:[],//观赏生物
      coral_aquatic_plants:[],//珊瑚水草
      equipment_consumables:[]//设备耗材
    };
  },
  computed: {
    isVerify() {
      return this.$store.getters.hiddenConfig?.is_verify ?? false;
    },
    user() {
      return this.$store.getters.user ?? {};
    },
  },
  //微信分享
  onShareAppMessage() {
    let code = this.user.code ? this.user.code : '';
    let shareObj = {
      title: '我正在使用积趣自然图书馆，赶紧跟我一起来体验吧！',
      path: `/pages/index/index?invite_code=${code}`,
    };
    return shareObj;
  },
  onLoad(e) {
    this.init();
    this.getpopAdver();
    this.$store.dispatch('user/getUserInfo');
    this.$store.dispatch('user/getNewsNum');
  },
  methods: {
    //新增开始-精品书籍
    async getrecGoods(){
      return new Promise((resolve, reject) => {
        this.$api
          .get('/v1/product/part', {
            params: {
              part:'boutique_books',
            },
          })
          .then((res) => {
          this.boutique_books=res.data
            resolve(res);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    //自然水景
    async getnatural_water_feature(){
      return new Promise((resolve, reject) => {
        this.$api
          .get('/v1/product/part', {
            params: {
              part:'natural_water_feature',
            },
          })
          .then((res) => {
          this.natural_water_feature=res.data
            resolve(res);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    //观赏生物
    async getornamental_creatures(){
      return new Promise((resolve, reject) => {
        this.$api
          .get('/v1/product/part', {
            params: {
              part:'ornamental_creatures',
            },
          })
          .then((res) => {
          this.ornamental_creatures=res.data
            resolve(res);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    //珊瑚水草
    async getcoral_aquatic_plants(){
      return new Promise((resolve, reject) => {
        this.$api
          .get('/v1/product/part', {
            params: {
              part:'coral_aquatic_plants',
            },
          })
          .then((res) => {
          this.coral_aquatic_plants=res.data
            resolve(res);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    //设备耗材
    async getequipment_consumables(){
      return new Promise((resolve, reject) => {
        this.$api
          .get('/v1/product/part', {
            params: {
              part:'equipment_consumables',
            },
          })
          .then((res) => {
          this.equipment_consumables=res.data
            resolve(res);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    //新增结束
    init() {
      return Promise.all([this.getHot(), this.getBanner(), this.getRecommend(),this.getrecGoods(),this.getnatural_water_feature(),this.getornamental_creatures(),this.getcoral_aquatic_plants(),this.getequipment_consumables()]);
    },
    async downCallback() {
      await this.init();
      this.interestList = [];
      this.$refs.uWaterfall.clear();
      this.mescroll.resetUpScroll();
    },
    async upCallback(page) {
      this.getInterest(page);
    },
    //获取首页弹窗广告
    async getpopAdver() {
      let resDate = await this.$api.get('/v1/ads', {
        params: {
          keys: 'wechat_mini_homepage_popup',
        },
      });
      if (resDate.wechat_mini_homepage_popup.length > 0) {
        this.popAdvertising = resDate.wechat_mini_homepage_popup[0];
        this.popupShow = true;
      }
    },
    //获取热销商品
    async getHot() {
      return new Promise((resolve, reject) => {
        this.$api
          .get('/v1/product/hot')
          .then((resData) => {
            this.hotList = resData;
            uni.setStorageSync(CONST_HOTLIST, resData);
            resolve(resData);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    //精品推荐
    async getRecommend() {
      return new Promise((resolve, reject) => {
        this.$api
          .get('/v1/product/part', {
            params: {
              part: 'recommend',
            },
          })
          .then((resData) => {
            this.recommendList = resData.data;
            uni.setStorageSync(CONST_RECOMMEND, resData.data);
            resolve(resData);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    //猜你喜欢
    async getInterest({ num, size }) {
      this.$api
        .get(`/v1/product/part`, {
          params: {
            per_page: size,
            page: num,
            part: 'guess',
          },
        })
        .then((res) => {
          this.mescroll.endSuccess(res.data.length);
          if (num == 1) this.interestList = [];
          this.interestList = this.interestList.concat(res.data);
        })
        .catch((err) => {
          this.mescroll.endErr();
        });
    },
    //banner
    async getBanner() {
      return new Promise((resolve, reject) => {
        this.$api
          .get('/v1/ads', {
            params: {
              keys: Object.keys(this.bannerList),
            },
          })
          .then((resData) => {
            this.bannerList = resData;
            uni.setStorageSync(CONST_BANNERLIST, resData);
            resolve(resData);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    getBannerByKey(key) {
      return this.bannerList[key] ?? [];
    },
    jumpByOption(e) {
      const whiteRouter = ['/pages/user_sign/index', '/pageA/user_sign/index','/pages/points/swap','/pageB/lucky/index'];
      const tabRouter = ['/pages/sort/index', '/pages/shop_cart/index', '/pages/healthy/index', '/pages/me/me'];
      if (!!e.jump_link) {
        if (e.jump_type == 1) {
          if (tabRouter.findIndex((el) => e.jump_link?.includes(el)) >= 0) {
            const params = this.getParams(e.jump_link);
            // console.log(params); 
            if(Object.keys(params.params).length>0) {
            uni.$emit('jumpTab',params.params)
            this.$u.route({
              url: params.path,
              type: 'switchTab',
            });
            }
          } else if (whiteRouter.findIndex((el) => e.jump_link?.includes(el)) >= 0) {
            this.$u.routeAuth(e.jump_link);
          } else {
            this.$u.route(e.jump_link);
          }
        } else if (e.jump_type == 2) {
          this.$u.route(`/pages/web_view/index?url=${e.jump_link}`);
        }
      }
    },

    getParams(str) {
      var result = {};
      const arr =str.split('?')
      const url = arr[0];
      if(arr.length>1){
        var strParams = arr[1];
        var arrParams = strParams.split('&');
        arrParams.forEach((item) => {
          var temKey = item.split('=')[0];
          var temVal = item.split('=')[1];
          result[temKey] = temVal;
        });
      }
      return {
        path: url,
        params: result,
      };
    },
  },
};
</script>

<style lang="scss" scoped>
.rounded15rpx {
  border-radius: 15rpx;
}

.m40rpx {
  font-size: 40rpx;
  color: $uni-color-primary;
}

.swipers {
  transform: translateY(0) !important;
}

.badge {
  @apply bg-badge;
}
</style>
