<template>
  <view class="index" :style="{ backgroundImage: `url(${bgImage.image1})` }">
    <view class="top-box" :class="showTopSearch ? '' : 'hide'">
      <view :style="[{ height: `${statusBarHeight}px` }]"></view>
      <view class="title" :style="[{ height: `${menuButtonHeight}px` }]">
        <text class="titlt-txt">商城</text>
      </view>
      <view class="input-box">
        <view
          class="status-bar"
          :style="[{ height: `${statusBarHeight}px` }]"
          @click="searchClick"
        ></view>
        <view class="input-placeholder" @click="searchClick"
          >请输入检索关键字</view
        >
        <text class="iconfont2 msgCenter" @click="goToMsg()">
          <!-- &#xe67c; -->
          <uv-icon name="chat" color="#ffffff" size="28"></uv-icon>
          <text v-if="msgCenter == 0 ? false : msgCenter">{{ msgCenter }}</text>
        </text>
      </view>
    </view>
    <view class="u-skeleton">
      <view
        class="swiper u-skeleton-rect"
        :class="showTopSearch ? '' : 'mt120'"
        v-if="(shopBanner && shopBanner.length > 0) || skeletonShow"
      >
        <view class="uni-margin-wrap">
          <swiper
            class="swiper"
            :indicator-dots="true"
            :autoplay="true"
            :interval="2000"
            :duration="1000"
            circular="false"
          >
            <swiper-item
              v-for="item in skeletonShow ? 1 : shopBanner"
              :key="item.id"
            >
              <view class="swiper-item" @click="$mUtil.imgLink(item)">
                <image
                  class="bannersize"
                  :src="`${item.image}`"
                  mode="aspectFill"
                ></image>
              </view>
            </swiper-item>
          </swiper>
        </view>
      </view>
      <!-- 首页一级分类 -->
      <div class="one-cate">
        <!-- cateList.slice(0,4) -->
        <div
          class="item"
          v-for="item in skeletonShow ? 4 : cateList"
          @click="jumpHxCate(item, 0)"
          :key="item.id"
        >
          <!-- ?x-oss-process=style/w_350 -->
          <image
            class="u-skeleton-fillet"
            mode="widthFix "
            :src="`${item.icon}`"
          >
          </image>
          <div class="word u-skeleton-fillet">{{ item.name || "加载中" }}</div>
        </div>
      </div>
      <view
        v-if="(homeBanner1 && homeBanner1.image) || skeletonShow"
        class="banner1Cls"
        @click="$mUtil.imgLink(homeBanner1)"
      >
        <!-- ?x-oss-process=style/w_350 -->
        <image
          class="font u-skeleton-fillet"
          :src="`${homeBanner1.image}`"
          mode=""
        ></image>
      </view>
      <!-- 惠选专区 hxCateList-->
      <ChoiceZone
        :hxCateList="hxCateList"
        :skeletonShow="skeletonShow"
        @jumpHxCate="jumpHxCate"
      />

      <!-- 限时秒杀 -->
      <Seckill
        :currSeckill="currSeckill"
        :skeletonShow="skeletonShow"
        :currTime="currTime"
        :time2="time2"
        :itemsDis2="itemsDis2"
        :activeBannerIndex2="activeBannerIndex2"
        @goDetail="goDetail"
        @overDown2="overDown2"
        @imgActiveFun2="imgActiveFun2"
        @goProductDetails="goProductDetails"
      />

      <!-- 拼团购 -->
      <GroupBuy
        :groupList="groupList"
        :skeletonShow="skeletonShow"
        :bgImage="bgImage.image2"
        @goDetail="goDetail"
        @goProductDetails="goProductDetails"
      />

      <!-- 热门推荐 -->
      <HotRecommend
        :recommendList="recommendList"
        :skeletonShow="skeletonShow"
        :bgImage="bgImage.image3"
        @goDetail="goDetail"
        @goProductDetails="goProductDetails"
      />

      <!-- 本月热销 -->
      <MonthlyBestSeller
        :hotList="hotList"
        :skeletonShow="skeletonShow"
        :bgImage="bgImage.image4"
        :itemsDis="itemsDis"
        :lineList="lineList"
        :activeBannerIndex="activeBannerIndex"
        @goDetail="goDetail"
        @goProductDetails="goProductDetails"
        @imgActiveFun="imgActiveFun"
      />

      <!-- 猜你喜欢 -->
      <GuessYouLike
        :goodsList="goodsList"
        :skeletonShow="skeletonShow"
        :bgImage="bgImage.image5"
        :status="status"
        @goDetail="goDetail"
        @goProductDetails="goProductDetails"
      />

      <view class="cart-entrance" @click="toCartPage()">
        <!-- <image :src="imgUrl + '/static/czd/car.png'" alt=""></image> -->
        <uv-icon name="shopping-cart" color="#000" size="32"></uv-icon>
      </view>
      <uv-skeleton
        :loading="skeletonShow"
        :animation="true"
        bgColor="#FFF"
      ></uv-skeleton>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance } from "vue";
import {
  onLoad,
  onShow,
  onPullDownRefresh,
  onReachBottom,
  onPageScroll,
  onShareAppMessage,
} from "@dcloudio/uni-app";
import { getAdList_Api, getQuickLinkList_Api } from "@/api/index.js";
import { shopProductList_Api } from "@/api/shop.js";
import {
  messageUnreadNum_Api,
} from "@/api/userInfo.js";

import ChoiceZone from "./components/ChoiceZone.vue";
import Seckill from "./components/Seckill.vue";
import GroupBuy from "./components/GroupBuy.vue";
import HotRecommend from "./components/HotRecommend.vue";
import MonthlyBestSeller from "./components/MonthlyBestSeller.vue";
import GuessYouLike from "./components/GuessYouLike.vue";
import utils from "@/util/index.js";

// 响应式数据
const statusBarHeight = ref(uni.getSystemInfoSync().statusBarHeight);
const menuButtonHeight = ref(0);
try {
  menuButtonHeight.value = uni.getSystemInfoSync().menuButtonHeight + 10;
} catch (error) {
  console.log(error);
}
const showTopSearch = ref(true);

const keyWord = ref("");
const groupList = ref([]); //团购
const hotList = ref([]); //本月热销
const recommendList = ref([]); //推荐
const shopBanner = ref([]); //轮播图
const currSeckill = ref([]); //秒杀
const time2 = ref([0, 0, 0, 0]); //秒杀倒计时
const goodsList = ref([]); //猜你喜欢
const currTime = ref(null);
const itemsDis = ref(1);
const activeBannerIndex = ref(0);
const itemsDis2 = ref(1);
const activeBannerIndex2 = ref(0);
const page = ref(1);
const status = ref("more");
const msgCenter = ref(null);
const cateList = ref([]); // 一级分类
const hxCateList = ref([]);
const lineList = ref(0);
const homeBanner1 = ref({});
const skeletonShow = ref(true);

// 背景图片
const bgImage = reactive({
  // image1: "/static/home/home_bg1.png",
  // image2: "/static/home/home_bg2.png",
  // image3: "/static/home/home_bg3.png",
  // image4: "/static/home/home_bg4.png",
  // image5: "/static/home/home_bg5.png",
  image1:
    "https://chaonong-shop.oss-cn-beijing.aliyuncs.com/20260104/fc2943f1d3894cf6aebe9a4ed5455cec.png", // 顶部背景图
  image2:
    "https://chaonong-shop.oss-cn-beijing.aliyuncs.com/20260104/c99cd4841fca414bbc5bc0bb21b6e0f3.png", // 拼团购背景图
  image3:
    "https://chaonong-shop.oss-cn-beijing.aliyuncs.com/20260104/21296e0cec1e49e6aa44bca3d7758362.png", // 热门推荐背景图
  image4:
    "https://chaonong-shop.oss-cn-beijing.aliyuncs.com/20260104/afc6def5b92a41eaa243c557d73b588c.png", // 本月热销背景图
  image5:
    "https://chaonong-shop.oss-cn-beijing.aliyuncs.com/20260104/67d5c6eebace46f1abd3435352561968.png", // 猜你喜欢背景图
});

// 方法定义
const getHomeBanner1 = () => {
  getAdList_Api("home_ad").then((res) => {
    if (res && res.data && res.data.length > 0) {
      homeBanner1.value = res.data[0];
      // console.log("homeBanner1", homeBanner1.value);
    }
  });
};

const init = () => {
  page.value = 1;
  getAll();
  getOneCate();
  // getHxCateList();
};

// 跳转消息页面
const goToMsg = () => {
  if (!utils.isLoginTo(true)) {
    uni.navigateTo({
      url: "/pages/user/myMsg",
    });
  }
};

const searchClick = () => {
  uni.navigateTo({
    url: "/pages/research/homepage/search",
  });
};

const goProductDetails = (url) => {
  uni.navigateTo({
    url: url,
  });
};

const getAll = () => {
  // rest();
  getBanner();
  // seckillList();
  // getgroupList();
  recommend();
  hotSale();
  // guessLike();
};

/**获得消息数量 */
const getmessageNum = () => {
  let token = uni.getStorageSync("apiToken");
  if (token) {
    messageUnreadNum_Api().then((res) => {
      if (res && res.code == 200) {
        msgCenter.value = res.data;
      }
    });
  } else {
    msgCenter.value = 0;
  }
};

// 一级分类
const getOneCate = () => {
  getQuickLinkList_Api("home").then((res) => {
    if (res && res.code == 200) {
      cateList.value = res.data || [];
      // console.log("cateList", cateList.value);
    }
  });
};

const getHxCateList = () => {
  uni.$uv.$http.get("/hxcategory/home/recommend/4").then((res) => {
    if (res && res.code == 200) {
      hxCateList.value = res.list;
    }
  });
};

// 跳转一级分类
const jumpCate = (id) => {
  // uni.$uv.$store.commit("changeCateId", id || "");
  uni.switchTab({
    url: "/pages/index/list",
    success: (res) => {},
  });
};

const jumpHxCate = (item, area_feature) => {
  let url = `/pages/freeCollection/index`;
  if (area_feature == 0) {
    url += `?categoryId=${item.id}&title=${item.name}`;
  } else {
    url += `?hxCategoryId=${item.id}&title=${item.name}`;
  }
  uni.navigateTo({
    url: url,
  });
};

/**轮播图 */
const getBanner = () => {
  getAdList_Api("home_banner")
    .then((res) => {
      uni.stopPullDownRefresh();
      if (res && res.code == 200) {
        shopBanner.value = res.data || [];
      }
    })
    .catch((err) => {
      console.log("err");
      console.log(err);
    });
};

const imgActiveFun = (e) => {
  activeBannerIndex.value = e.detail.current;
};

const imgActiveFun2 = (e) => {
  activeBannerIndex2.value = e.detail.current;
};

const overDown2 = () => {
  isOver2.value = true;
};

/**限时秒杀 */
const seckillList = () => {
  uni.$uv.$http
    .get(
      `/marketing/seckillActivityGoods/flash-sale`,
      {
        limit: 10,
        page: 1,
      },
      false
    )
    .then((res) => {
      if (res && res.code == 200) {
        currTime.value = res.data.start_hour;
        if (res.data.list) {
          currSeckill.value = oneArrToTwoArr(res.data.list);
        }

        if (res.data.finish_time) {
          time2.value = uni.$uv.$mUtil
            .countDown(Math.floor(res.data.finish_time / 1000))
            .split(":")
            .map((val) => Number(val));
        }
      }
    });
};

const oneArrToTwoArr = (data) => {
  let newData = [];
  let zyf = 4; //一维数组转二维数组长度(此处是二维数组每一个长度控制)
  for (var i = 0; i < Math.ceil(data.length / zyf); i++) {
    newData[i] = [];
    newData[i].push(data[i * zyf]);
    for (var j = 1; j < zyf; j++) {
      if (data[i * zyf + j] == undefined) {
        //超出长度控住
        return newData;
      } else {
        newData[i].push(data[i * zyf + j]);
      }
    }
  }
  return newData;
};

/**团购 */
const getgroupList = () => {
  uni.$uv.$http
    .get(
      `/groupbuy/activitygoods/will-you-spell`,
      {
        limit: 10,
        page: 1,
      },
      false
    )
    .then((res) => {
      if (res && res.code == 200) {
        if (res.list.length > 0) {
          groupList.value = res.list;
        }
      }
    });
};

/**热门推荐 */
const recommend = () => {
  shopProductList_Api({
    limit: 6,
    recommendStatus: 1,
  }).then((res) => {
    if (res && res.code == 200) {
      recommendList.value = res.data;
    }
  });
};

/**本月热销 */
const hotSale = () => {
  shopProductList_Api({
    limit: 12,
    hot: 1,
  }).then((res) => {
    if (res && res.code == 200) {
      let list = res.data || [];
      hotList.value = res.data;
      if (hotList.value.length > 2) {
        lineList.value = hotList.value.length - 2;
      }
      if (list.length <= 3) {
        itemsDis.value = list.length;
      }
      if (list.length > 3 && list.length <= 6) {
        itemsDis.value = 3;
      }
      if (list.length > 6 && list.length <= 9) {
        itemsDis.value = 3;
      }
      if (list.length > 9 && list.length <= 12) {
        itemsDis.value = 3;
      }
    }
  });
};

/**猜你喜欢 */
const guessLike = () => {
  keyWord.value = uni.getStorageSync("history")
    ? uni.getStorageSync("history").join(",")
    : "";
  uni.$uv.$http
    .get(
      `/goods/smart`,
      {
        page: page.value,
        limit: 6,
        keywords: keyWord.value,
      },
      false
    )
    .then((res) => {
      if (res && res.code == 200) {
        goodsList.value =
          page.value == 1
            ? res.page.list
            : goodsList.value.concat(res.page.list);
        if (res.page.totalPage <= res.page.currPage) {
          status.value = "noMore";
        } else {
          status.value = "more";
        }
        skeletonShow.value = false;
      }
    });
};

const goDetail = (url, isNeedLogin, tabShow = false) => {
  if ((isNeedLogin && uni.getStorageSync("apiToken") == "") || null) {
    uni.$uv.$mUtil.toast("请先登录");
    return false;
  }
  if (tabShow) {
    uni.switchTab({
      url: url,
    });
  } else {
    uni.navigateTo({
      url: url,
    });
  }
};

/**重置数据*/
const rest = () => {
  goodsList.value = [];
  currSeckill.value = [];
  shopBanner.value = [];
  recommendList.value = [];
  hotList.value = [];
  groupList.value = [];
};

const toCartPage = () => {
  uni.switchTab({
    url: "/pages/tabtar/shoppingCart",
  });
};

// 生命周期钩子
onLoad(() => {
  skeletonShow.value = false;
  init();
  getHomeBanner1();
});

onShow(() => {
  getmessageNum();
});

onPullDownRefresh(() => {
  return;
  page.value = 1;
  getAll();
  getOneCate();
  getHxCateList();
  getHomeBanner1();
  setTimeout(() => {
    uni.stopPullDownRefresh();
  }, 300);
});

onReachBottom(() => {
  return;
  if (status.value == "more") {
    page.value++;
    guessLike();
  }
});

onPageScroll((e) => {
  //nvue暂不支持滚动监听，可用bindingx代替
  if (e.scrollTop > uni.upx2px(49 + 30)) {
    showTopSearch.value = false;
  } else {
    showTopSearch.value = true;
  }
});

onShareAppMessage((res) => {
  let user = uni.getStorageSync("personal");
  if (res.from === "button") {
    // 来自页面内分享按钮
    console.log(res.target);
  }
  return {
    title: "商城",
    path: `/pages/index/lidaPage?shareId=${user.id || ""}`,
  };
});
</script>

<style scoped lang="scss">
.swiper {
  width: 690rpx;
  height: 370rpx !important;
  // border-radius: 20rpx;
  overflow: hidden;
  margin: 0 auto;

  ::v-deep .uni-swiper-dot {
    width: 16rpx !important;
    height: 6rpx;
    border-radius: 4rpx !important;
    background-color: #ffffff !important;
    opacity: 0.5;
  }

  ::v-deep .uni-swiper-dot-active {
    width: 32rpx !important;
    height: 6rpx;
    border-radius: 4rpx !important;
    background-color: #ffffff !important;
    opacity: 1;
  }
}

::v-deep.hx-navbar__content__main_search_hxicon {
  span {
    font-size: 30rpx;
  }
}

::v-deep.hx-navbar__content__main_search_input {
  background-color: #4a705e;
}

.one-cate {
  display: flex;
  // width: 750rpx;
  flex-wrap: wrap;
  justify-content: space-between;
  padding: 0 31rpx;
  margin-top: 30rpx;
  color: #373737;

  .item {
    width: 120rpx;
    text-align: center;
    // margin-right: 40rpx;

    // &:last-child {
    //   margin-right: 0;
    // }

    image {
      width: 94rpx !important;
      height: 94rpx !important;
    }

    .word {
      // margin-top: 17rpx;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }

  .item:first-child {
    margin-left: 0;
  }

  .item:nth-child(5n + 1) {
    margin-left: 0;
  }
}

.bannersize {
  display: block;
  overflow: hidden;
  width: 100%;
  height: 100%;
  border-radius: 10rpx;
}

.classlist {
  margin: 30rpx;
  display: flex;
  justify-content: space-between;
  color: #373737;

  .item {
    width: 120rpx;
    text-align: center;
    // margin-right: 38rpx;

    // &:last-child {
    //   margin-right: 0;
    // }

    .img-box {
      width: 100%;
      // height: 110rpx;
      display: flex;
      align-items: center;
      justify-content: center;

      image {
        width: 70rpx;
        height: 70rpx;
        margin-bottom: 8rpx;
      }

      text {
        font-size: 70rpx;
      }

      .word {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }

      .alarmClock {
        color: #eb963a;
      }

      .spell {
        color: #4581f6;
      }

      .integral {
        color: #4ea700;
      }

      .discounts {
        color: #f55f40;
      }

      .activeRegion {
        color: #4581f6;
      }
    }

    .font {
      // margin-top: 17rpx;
    }

    .imgbox {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 100%;
      // height: 110rpx;

      image {
        width: 70rpx;
        height: 70rpx !important;
        margin-bottom: 8rpx;
      }
    }
  }
}

.swiper {
  // margin-top: 105rpx;
  height: 360rpx;

  .swiper-item {
    width: 100%;
    height: 100%;
  }
}

.index {
  position: relative;
  background-color: #f5f5f5;
  overflow-x: hidden;

  background-repeat: no-repeat;
  background-size: 100% 509rpx;
}

.cart-entrance {
  position: fixed;
  right: 30rpx;
  bottom: 180rpx;
  width: 50px;
  height: 50px;
  background-size: 100% 100%;
  border-radius: 50%;
  filter: drop-shadow(1px 2px 4px rgba(26, 58, 70, 0.3));
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;

  image {
    width: 55%;
    height: 55%;
    margin-right: 5rpx;
  }
}

.top-box {
  width: 100%;

  &.hide {
    background: #069d4d;
  }

  .title {
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
    margin: 0 auto;
    // height: 45rpx;
    padding: 0 30rpx;
    font-size: 36rpx;
    font-family: PingFang SC, PingFang SC-Bold;
    font-weight: 700;
    color: #fff;
    // line-height: 45rpx;
    text-align: center;

    image {
      width: 41rpx;
      height: 31rpx;
      margin-right: 4rpx;
    }

    .titlt-txt {
      font-size: 36rpx;
    }
  }

  .input-box {
    display: flex;
    justify-content: space-between;
    align-items: center;
    position: sticky;
    top: 0;
    z-index: 100;
    width: 100%;
    padding: 23rpx 30rpx 30rpx;
    box-sizing: border-box;

    .text {
      margin-right: 20rpx;
      margin-left: 0rpx;
      font-weight: 500;
      font-size: 28rpx;
      color: #aed8b9;
    }

    .input-placeholder {
      // flex: 1;
      box-sizing: border-box;
      display: inline-block;
      vertical-align: middle;
      width: 630rpx;
      height: 70rpx;
      line-height: 66rpx;
      // background: rgba(2,81,43,0.3);
      background: rgba(255, 255, 255, 0.3);
      padding-left: 80rpx;
      // color: #666666;
      background: rgba(255, 255, 255, 0.3);
      background-image: url("/static/czd/search.png");
      background-size: 40rpx 40rpx;
      background-position: 24rpx 50%;
      background-repeat: no-repeat;
      border: 1rpx solid rgba(255, 255, 255, 0.36);
      border-radius: 36rpx;
    }

    text {
      margin-left: 10rpx;
      display: inline-block;
      vertical-align: middle;
      font-size: 42rpx;
      font-weight: 400;
      text-align: right;
      color: #ffffff;
      line-height: 42rpx;

      &.iconfont2 {
        font-size: 55rpx;
      }
    }

    .msgCenter {
      position: relative;

      text {
        min-width: 50rpx;
        font-size: 20rpx;
        color: #ffffff;
        font-weight: 400;
        padding: 0 4rpx;
        background-color: #ff0000;
        border-radius: 13rpx;
        border: 2rpx solid #fff;
        text-align: center;
        position: absolute;
        left: 10rpx;
        top: -30rpx;
        line-height: normal;
      }
    }
  }

  .input-placeholder {
    color: #fee3cf;
    opacity: 0.74;
    font-size: 28rpx;
    font-family: PingFang SC, PingFang SC-Regular;
    font-weight: 400;
    text-align: left;
    line-height: 70rpx;
  }
}

.top-box.hide {
  position: fixed;
  z-index: 9999;
}

.notice-box {
  height: 92rpx;
  font-size: 28rpx;
  margin-bottom: 0;

  ::v-deep .uni-noticebar-icon {
    width: 40rpx;
    // background-image: url('/static/home/noticebar-icon.png');
    background-size: cover;
    color: transparent !important;
  }
}

.mt120 {
  margin-top: 240rpx;
}

.banner1Cls {
  text-align: center;
  margin-top: 20rpx;

  image {
    width: 690rpx;
    height: 200rpx;
  }
}
</style>