<template>
  <view>
    <view class="page-index" :class="{ bgf: navIndex > 0 }">
      <view class="header">
        <view class="serch-wrapper flex">
          <view class="logo">
            <image :src="logoUrl" mode=""></image>
          </view>
          <navigator
            url="/pages/goods_search/index"
            class="input"
            hover-class="none"
            ><text class="iconfont icon-xiazai5"></text> 搜索商品</navigator
          >
        </view>
      </view>

      <!-- 快捷入口 -->
      <div class="top-bg-box">
        <view class="nav-list">
          <navigator
            class="item"
            :url="item.url"
            v-for="item in navMenus"
            :key="item.type"
          >
            <uni-icons
              :size="item.size"
              customPrefix="iconfont"
              :type="item.icon"
            ></uni-icons>
            <view class="txt">{{ item.name }}</view>
          </navigator>
        </view>

        <UserGrowthPanel />
      </div>

      <!-- <up-sticky :offsetTop="stickyTop" customNavHeight="62px"> -->
      <view class="sticky-box">
        <view class="scroll-view_H">
          <view class="tab nav-bd" id="tab_list">
            <view
              id="tab_item"
              :class="{ active: listActive == index }"
              class="item"
              v-for="(item, index) in goodsNavs"
              :key="index"
              @click="ProductNavTab(item, index)"
            >
              <uni-icons
                customPrefix="iconfont"
                :color="listActive == index ? '#CD9933' : '#000'"
                :type="item.icon"
                :size="item.size"
              ></uni-icons>
              <!-- <i class="item-icon iconfont" :class="item.icon"></i> -->
              <view class="txt">{{ item.name }}</view>
              <!-- <view class="label">{{ item.info }}</view> -->
            </view>
          </view>
        </view>
      </view>
      <!-- </up-sticky> -->

      <!-- 首发新品 -->
      <view class="index-product-wrapper" :class="iSshowH ? 'on' : ''">
        <view
          class="list-box animated"
          :class="goodsList.length > 0 ? 'fadeIn on' : ''"
        >
          <view
            class="item"
            v-for="(item, index) in goodsList"
            :key="index"
            @click="goDetail(item)"
          >
            <view class="pictrue">
              <image :src="item.image" mode=""></image>
            </view>
            <view class="text-info">
              <view class="title line2"
                ><text class="tip">现货</text>{{ item.storeName }}</view
              >
              <view class="bottom-row">
                <text class="price">工费: {{ item.price }}/克</text>
                <text class="sales"
                  >已售{{
                    Number(item.sales || 0) + Number(item.ficti || 0)
                  }}件</text
                >
                <!-- <view class="txt">券</view> -->
              </view>
            </view>
          </view>
        </view>
        <view class="loadingicon acea-row row-center-wrapper" v-if="goodScroll">
          <text
            class="loading iconfont icon-jiazai"
            :hidden="loading == false"
          ></text>
        </view>
        <view class="no-data" v-if="isNoDataState">
          <img src="/static/images/noShopper.png" />
        </view>
        <view class="mores-txt flex" v-if="!goodScroll && !isNoDataState">
          <text>我是有底线的</text>
        </view>
      </view>
      <!-- </view> -->
    </view>
    <drag-button
      :isDock="true"
      :existTabBar="true"
      @btnClick="btnClick"
    />
  </view>
</template>

<script setup>
// 测试拖拽
import dragButton from "@/components/drag-button/drag-button.vue";
import { onLoad, onShow } from "@dcloudio/uni-app";
import { ref, onMounted, computed, getCurrentInstance } from "vue";
import Auth from "@/libs/wechat";
import Cache from "@/utils/cache";
import { getIndexData, getCoupons, setCouponReceive } from "@/api/api.js";
import { getShare, kefuConfig } from "@/api/public.js";
import UserGrowthPanel from "@/components/UserGrowthPanel";

import { getGroomList as getGroomListApi } from "@/api/store.js";
import { goShopDetail } from "@/libs/order.js";
import { silenceBindingSpread } from "@/utils";

import { useAppStore } from "@/stores/app";
const appStore = useAppStore();
const app = getApp();
const instance = getCurrentInstance();

const navH = ref("");
const marTop = ref(0);
const searchH = ref(0);
const loading = ref(false);

// Authorization
const isShowAuth = ref(false);
const iShidden = ref(false);
const window = ref(false);

// Navigation and Tabs
const navIndex = ref(0);
const ProductNavindex = ref(0);
const listActive = ref(0);
const tabsScrollLeft = ref(0);
const scrollLeft = ref(0);
const lineStyle = ref({});
const duration = ref(0.2);

// Home Page Data
const logoUrl = ref("");
const site_name = ref("");
const imgUrls = ref([]);
const menus = ref([]);
const roll = ref([]);
const explosiveMoney = ref([]);
const goodType = ref(1);
const goodScroll = ref(true);
const iSshowH = ref(false);
const stickyTop = ref(0);
const navMenus = ref([
  {
    name: "商城订单",
    icon: "icon-wodedingdan1",
    type: 1,
    url: "/pages/order_list/index",
    size: 25,
  },
  {
    name: "购物车",
    icon: "icon-gouwuche",
    type: 2,
    url: "/pages/order_addcart/order_addcart",
    size: 26,
  },
  {
    name: "卡卷包",
    icon: "icon-kabao",
    type: 3,
    url: "/pages/users/user_coupon/index",
    size: 28,
  },
  {
    name: "客服消息",
    icon: "icon-xiaoxi",
    type: 4,
    url: "/pages/users/customer_service_message/index",
    size: 26,
  },
]);

// const primaryGoldColor =

// Product Lists
const sortProduct = ref([]);
const goodsList = ref([]);
const goodsNavs = ref([
  { name: "新品推荐", type: 1, icon: "icon-xinpintuijian", size: 25 },
  { name: "黄金金条", type: 2, icon: "icon-touzijintiao1", size: 25 },
  { name: "黄金首饰", type: 3, icon: "icon-huangjinshoushi", size: 25 },
  { name: "其他", type: 4, icon: "icon-a-ziyuan97", size: 22 },
]);

// Pagination
const params = ref({
  page: 1,
  limit: 10,
});
const hotScroll = ref(false);
const headerHeight = ref(0);

// Other
const couponList = ref([]);
const configApi = ref({});

// pinia
const isLogin = appStore.isLogin;
const uid = appStore.uidComputed;

const arrTemp = [
  "beforePay",
  "afterPay",
  "refundApply",
  "beforeRecharge",
  "createBargain",
  "pink",
];

// Coupon Functions
const getCoupon = async (id, index) => {
  try {
    await setCouponReceive(id);
    couponList.value[index].isUse = true;
    uni.showToast({ title: "领取成功" });
  } catch (err) {
    uni.showToast({ title: err.message, icon: "none" });
  }
};

// Tab Navigation Functions
const clickSort = (index) => {
  listActive.value = index;
};

const scroll = (e) => {
  scrollLeft.value = e.detail.scrollLeft || 0;
};

// Home Page Data Functions
const getIndexConfig = async () => {
  try {
    loading.value = true;
    const res = await getIndexData();
    uni.setNavigationBarTitle({ title: "首页" });
    logoUrl.value = res.data.logoUrl;
    site_name.value = "首页";
    imgUrls.value = res.data.banner;
    menus.value = res.data.menus;
    roll.value = res.data.roll || [];
    // #ifdef H5
    appStore.SET_CHATURL(res.data.yzfUrl);
    Cache.set("chatUrl", res.data.yzfUrl);
    // #endif

    const iconTypes = [
      "icon-shouye",
      "icon-shouye",
      "icon-shouye",
      "icon-shouye",
    ];
    explosiveMoney.value = res.data.explosiveMoney.map((v, i) => ({
      ...v,
      icon: iconTypes[i] || "icon-shouye",
    }));
    await getGroomList();
    await shareApi();
    await getcouponList();
  } catch (err) {
    console.error(err);
  } finally {
    loading.value = false;
  }
};

const btnClick = () => {
  // uni.navigateTo({ url: "/pages/index/mindex" });
};

const getcouponList = async () => {
  try {
    const res = await getCoupons({ page: 1, limit: 6 });
    couponList.value = res.data;
    // #ifdef MP
    uni.getSetting({
      success(res) {
        window.value =
          !res.authSetting["scope.userInfo"] && couponList.value.length
            ? true
            : false;
        iShidden.value = res.authSetting["scope.userInfo"];
      },
    });
    // #endif
    // #ifndef MP
    window.value = isLogin ? false : res.data.length ? true : false;
    // #endif
  } catch (err) {
    uni.showToast({ title: err.message, icon: "none" });
  }
};

const shareApi = async () => {
  try {
    const res = await getShare();
    configApi.value = res.data;
    // #ifdef H5
    setOpenShare(res.data);
    // #endif
  } catch (err) {
    console.error(err);
  }
};

const getChatUrL = async () => {
  try {
    const res = await kefuConfig();
    appStore.SET_CHATURL(res.data.yzfUrl);
    Cache.set("chatUrl", res.data.yzfUrl);
  } catch (err) {
    console.error(err);
  }
};

const setOpenShare = (data) => {
  if (Auth.isWeixin()) {
    const configAppMessage = {
      desc: data.synopsis,
      title: data.title,
      link: location.href,
      imgUrl: data.img,
    };
    Auth.wechatEvevt(
      ["updateAppMessageShareData", "updateTimelineShareData"],
      configAppMessage
    );
  }
};

// Authorization
const authColse = (e) => {
  isShowAuth.value = e;
};

// Product Navigation
const ProductNavTab = (item, index) => {
  listActive.value = index;
  goodType.value = item.type;
  ProductNavindex.value = index;
  goodsList.value = [];
  params.value.page = 1;
  goodScroll.value = true;
  getGroomList(true);
};

// Product Details
const goDetail = async (item) => {
  if (item.activityH5 && item.activityH5.type === "2" && !isLogin) {
    toLogin();
  } else {
    await goShopDetail(item, uid);
    uni.navigateTo({ url: `/pages/goods_details/index?id=${item.id}` });
  }
};

const godDetail = async (item) => {
  await goShopDetail(item, uid);
  uni.navigateTo({ url: `/pages/goods_details/index?id=${item.id}` });
};

const isNoDataState = computed(() => {
  return goodsList.value.length === 0 && !loading.value;
});

// Product Lists
const getGroomList = async (onloadH = false) => {
  if (!goodScroll.value) return;
  if (onloadH) iSshowH.value = true;
  try {
    loading.value = true;
    const { data } = await getGroomListApi(goodType.value, params.value);
    iSshowH.value = false;
    goodScroll.value =
      data.list.length > 0 && data.list.length >= params.value.limit;
    params.value.page++;
    goodsList.value = goodsList.value.concat(data.list);
  } catch (err) {
    console.error(err);
  } finally {
    loading.value = false;
  }
};

const get_host_product = async () => {
  if (hotScroll.value) return;
  try {
    loading.onMounted(() => {});
  } catch (err) {
    console.error(err);
  } finally {
    loading.value = false;
  }
};

onLoad((option) => {
  uni.getSystemInfo({
    success(res) {
      appStore.SYSTEM_PLATFORM(res.platform);
    },
  });

  // uni.getLocation({
  //   type: "gcj02",
  //   altitude: true,
  //   geocode: true,
  //   success: (res) => {
  //     try {
  //       uni.setStorageSync("user_latitude", res.latitude);
  //       uni.setStorageSync("user_longitude", res.longitude);
  //     } catch {}
  //   },
  // });

  navH.value = app.globalData.navHeight;

  // #ifndef MP
  navH.value = 0;
  // #endif

  isLogin && silenceBindingSpread();
  getIndexConfig();
});

onShow(() => {
  uni.setNavigationBarTitle({ title: site_name.value });
});

onMounted(() => {
  // #ifdef H5
  const appSearchH = uni.createSelectorQuery().select(".serch-wrapper");
  appSearchH
    .boundingClientRect((data) => {
      searchH.value = data.height;
    })
    .exec();
  // #endif

  const query = uni.createSelectorQuery().in(instance.proxy);

  query.select(".header").boundingClientRect((data) => {
    headerHeight.value = Math.ceil(data.height);
  });

  query
    .select(".sticky-box")
    .boundingClientRect((data) => {
      // marTop.value = Util.pxToRpx(data.height);
      // stickyTop.value = data.height;
      // console.log({ data });

      marTop.value = data.height + 5;
    })
    .exec();
});

// #ifdef MP
const onShareAppMessage = () => {
  return {
    title: configApi.value.title,
    imageUrl: configApi.value.img,
    desc: configApi.value.synopsis,
    path: "/pages/index/index",
  };
};
// #endif

const onReachBottom = () => {
  if (navIndex.value === 0) {
    if (params.value.page !== 1) {
      getGroomList();
    }
  } else {
    if (sortProduct.value.length > 0) {
      // get_product_list();
    } else {
      get_host_product();
    }
  }
};
</script>

<style>
page {
  display: flex;
  flex-direction: column;
  height: 100%;
  /* #ifdef H5 */
  background-color: #fff;
  /* #endif */
}
</style>
<style lang="scss" scoped>
.couponIndex {
  width: auto;
  height: 238rpx;
  background-image: url("~@/static/images/yhjsy.png");
  background-size: 100% 100%;
  padding-left: 42rpx;
  margin-bottom: 30rpx;

  .titBox {
    padding: 47rpx 0;
    text-align: center;
    height: 100%;

    .tit1 {
      color: #ffebd2;
      font-size: 34rpx;
      font-weight: 600;
    }

    .tit2 {
      color: #ffebd2;
      font-size: 22rpx;
      margin: 10rpx 0 26rpx 0;
    }

    .tit3 {
      color: #ffdaaf;
      font-size: 24rpx;

      .iconfont {
        font-size: 20rpx;
      }
    }
  }

  .listBox {
    padding: 14rpx 0;

    .listActive {
      background-image: url("~@/static/images/lingyhj.png");
      background-size: 100% 100%;
    }

    .listHui {
      background-image: url("~@/static/images/weiling.png");
      background-size: 100% 100%;
    }

    .list {
      width: 170rpx;
      height: 210rpx;
      padding: 16rpx 0;
      text-align: center;
      margin-left: 24rpx;

      .tit {
        font-size: 18rpx;
        padding: 0 26rpx;
      }

      .titActive {
        color: #c99959;
      }

      .price {
        font-size: 46rpx;
        font-weight: 900;
        margin-top: 4rpx;
      }

      .pricehui {
        color: #b2b2b2;
      }

      .fonthui {
        background-color: #f5f5f5 !important;
      }

      .yuan {
        font-size: 24rpx;
      }

      .ling {
        font-size: 24rpx;
        margin-top: 9.5rpx;
        width: 102rpx;
        height: 36rpx;
        line-height: 36rpx;
        background-color: #ffe5c7;
        border-radius: 28rpx;
        margin: auto;
      }

      .priceM {
        color: #ffdaaf;
        font-size: 22rpx;
        margin-top: 14rpx;
      }
    }
  }
}

.sticky-box {
  margin: 0 40rpx;
  display: flex;
  // position: -webkit-sticky;
  // position: sticky;
  z-index: 99;
  flex-direction: row;
  // margin: 0px;
  // background: #fff;
  padding: 30rpx 0;

  .active {
    color: #cd9933;
  }

  .nav-bd {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .item {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;

      .txt {
        font-size: 28rpx;
        color: #282828;
      }

      .label {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 124rpx;
        height: 32rpx;
        margin-top: 5rpx;
        font-size: 24rpx;
        color: #999;
      }

      &.active {
        color: $theme-color;

        .txt {
          color: $theme-color;
        }

        .label {
          background: linear-gradient(90deg, $bg-star 0%, $bg-end 100%);
          border-radius: 16rpx;
          color: #fff;
        }
      }
    }
  }
}

.listAll {
  width: 20%;
  text-indent: 62rpx;
  font-size: 30rpx;
  border-left: 1px #eee solid;
  margin: 1% 0;
  padding: 5rpx;
  position: relative;

  image {
    position: absolute;
    left: 20rpx;
    top: 8rpx;
  }
}

.tab {
  position: relative;
  display: flex;
  font-size: 28rpx;
  white-space: nowrap;

  &__item {
    flex: 1;
    padding: 0 20rpx;
    text-align: center;
    height: 60rpx;
    line-height: 60rpx;
    color: #666;

    &.active {
      color: #09c2c9;
    }
  }
}

.tab__line {
  display: block;
  height: 6rpx;
  position: absolute;
  bottom: 0;
  left: 0;
  z-index: 1;
  border-radius: 3rpx;
  position: relative;
  background: #2fc6cd;
}

.scroll-view_H {
  /* 文本不会换行，文本会在在同一行上继续，直到遇到 <br> 标签为止。 */
  white-space: nowrap;
  width: 100%;
}

.privacy-wrapper {
  z-index: 999;
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background: #7f7f7f;

  .privacy-box {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    width: 560rpx;
    padding: 50rpx 45rpx 0;
    background: #fff;
    border-radius: 20rpx;

    .title {
      text-align: center;
      font-size: 32rpx;
      text-align: center;
      color: #333;
      font-weight: 700;
    }

    .content {
      margin-top: 20rpx;
      line-height: 1.5;
      font-size: 26rpx;
      color: #666;
      text-indent: 54rpx;

      i {
        font-style: normal;
        color: $theme-color;
      }
    }

    .btn-box {
      margin-top: 40rpx;
      text-align: center;
      font-size: 30rpx;

      .btn-item {
        height: 82rpx;
        line-height: 82rpx;
        background: linear-gradient(90deg, #f67a38 0%, #f11b09 100%);
        color: #fff;
        border-radius: 41rpx;
      }

      .btn {
        padding: 30rpx 0;
      }
    }
  }
}

.page-index {
  // display: flex;
  // flex-direction: column;
  // min-height: 100vh;
  position: relative;
  z-index: 1;
  // background: linear-gradient(180deg, #fff 0%, #f5f5f5 100%);

  // background-color: transparent;
}

.header {
  position: sticky;
  top: 0;
  z-index: 200000;
  width: 100%;
  background-color: $header-color;
  padding: 28rpx 30rpx;

  .serch-wrapper {
    margin-top: var(--status-bar-height);
    align-items: center;

    /* #ifdef MP-WEIXIN */
    width: 75%;
    /* #endif */

    .logo {
      width: 118rpx;
      height: 42rpx;
      margin-right: 24rpx;
    }

    image {
      width: 118rpx;
      height: 42rpx;
    }

    .input {
      display: flex;
      align-items: center;
      width: 546rpx;
      height: 58rpx;
      padding: 0 0 0 30rpx;
      background: rgba(247, 247, 247, 1);
      border: 1px solid rgba(241, 241, 241, 1);
      border-radius: 29rpx;
      color: #bbbbbb;
      font-size: 26rpx;

      .iconfont {
        margin-right: 20rpx;
        font-size: 26rpx;
        color: #666666;
      }
    }
  }

  .tabNav {
    padding-top: 24rpx;
  }
}

.page_content {
  padding: 0 30rpx;
}

.index-product-wrapper {
  padding: 0 30rpx;
  margin-bottom: 110rpx;

  &.on {
    min-height: 1500rpx;
  }

  .list-box {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;

    .item {
      width: 335rpx;
      margin-bottom: 20rpx;
      background-color: #fff;
      border-radius: 10rpx;
      overflow: hidden;
      display: flex;
      flex-direction: column;
      justify-content: space-between;

      .pictrue {
        position: relative;
        image {
          width: 100%;
          height: 330rpx;
        }
      }

      .text-info {
        padding: 10rpx 20rpx 15rpx;

        .title {
          color: #222222;

          .tip {
            font-size: 22rpx;
            padding: 0 2px;
            margin-right: 4rpx;
            border: 1px solid #b4b4b4;
            background-color: $theme-color;
            border-radius: 4rpx;
            color: #fff;
            position: relative;
            bottom: 4rpx;
          }
        }

        .bottom-row {
          color: $theme-color;
          display: flex;
          justify-content: space-between;
          align-items: center;
          font-size: 28rpx;
          margin: 10rpx 0 0;

          .price {
            padding-bottom: 4rpx;
            font-weight: 800;
            white-space: nowrap;
          }

          .sales {
            color: #b4b4b4;
            font-size: 22rpx;
            white-space: nowrap;
          }
        }
      }
    }

    &.on {
      display: flex;
    }
  }
}

.top-bg-box {
  overflow: hidden;
  background-image: linear-gradient(
    to bottom,
    $header-color 0%,
    $header-color 10%,
    #f0dab2 50%,
    transparent 100%
  );
}

.nav-list {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 40rpx 0;
  margin: 25rpx 0;

  .item {
    text-align: center;
  }
}

.no-data {
  margin: 150rpx auto 0;
  text-align: center;

  img {
    width: 65%;
    height: auto;
  }
}

.mores-txt {
  width: 100%;
  align-items: center;
  justify-content: center;
  height: 70rpx;
  color: #999;
  font-size: 24rpx;

  .iconfont {
    margin-top: 2rpx;
    font-size: 20rpx;
  }
}

.menu-txt {
  font-size: 24rpx;
  color: #454545;
}

.stats {
  position: absolute;
  left: 0px;
  top: 0px;
  z-index: 2000000;
  width: 750rpx;
  height: var(--status-bar-height);
  background: #ffffff;
}
</style>
