<template>
  <Theme>
    <view class="wrap" id="pageContainer">
      <Navbar border fixed autoBack title="免邮专区" @leftClick="leftClick">
      </Navbar>
      <view class="tops" id="tabs" :style="{ top: tabTop + 'px' }">
        <view class="tab">
          <Tab
            :active="actvieNum"
            keyName="name"
            isTran
            :tabList="tabList"
            @confirm="tabClick"
          />
        </view>
      </view>
      <view class="content">
        <List
          url="/shop/activity/list"
          :topHeight="tabHeight"
          :defaultParams="defaultParams"
          :pageSize="20"
          isLoading
          ref="listRef"
          @datas="getList"
        >
          <template #item="{ item, index }">
            <shopList
              channel="1"
              isFree="1"
              :item="item"
              @collect="collectClick($event, index)"
            />
          </template>
        </List>
      </view>
    </view>
  </Theme>
</template>
<script setup>
import { ref, reactive, watch, onMounted, nextTick } from "vue";
import Navbar from "@/components/navbar";
import { t } from "@/locale";
import { onLoad, onShow, onReachBottom, onPageScroll } from "@dcloudio/uni-app";
import List from "@/components/list";
import { query, systemInfo } from "@/utils";
import shopList from "./components/shop_list";
import Tab from "@/components/tabs";
import { SHOP_USER_COLLECT, SHOP_GOODS_CATEGORY } from "@/api";

const searchValue = ref("");
const listRef = ref(null);
const popupRef = ref(null);
const actvieNum = ref(0);
const tabHeight = ref(0);
const tabTop = ref(44);
const dataList = ref([]);
const tabList = ref([]);
const defaultParams = reactive({
  cid: 0,
});

// 防抖标记（防止重复触发）
const isLoading = ref(false);
// 自定义触发阈值：距离底部 200px 时触发
const triggerThreshold = ref(200);
// 页面总高度（用于计算距离底部距离）
const pageTotalHeight = ref(0);
// 列表加载完成后调用（需在列表组件的加载回调中执行）
const handleLoadComplete = async () => {
  isLoading.value = false;
  const rect = await query("#pageContainer", this);
  pageTotalHeight.value = rect.height;
};

onMounted(() => {
  nextTick(async () => {
    const res = await query("#tabs", this);
    tabTop.value = res.top + systemInfo().statusBarHeight;
    tabHeight.value = res.height;
    const rect = await query("#pageContainer", this);
    pageTotalHeight.value = rect.height;
    nextTick(() => {
      listRef.value && listRef.value.getData();
    });
  });
});

onPageScroll((e) => {
  nextTick(() => {
    if (isLoading.value || !pageTotalHeight.value) return;
    const systemInfo = uni.getSystemInfoSync();
    const windowHeight = systemInfo.windowHeight;
    const scrollTop = e.scrollTop;

    // 计算距离底部的距离：总高度 - 滚动距离 - 可视高度
    const distanceToBottom = pageTotalHeight.value - scrollTop - windowHeight;
    if (distanceToBottom <= triggerThreshold.value) {
      isLoading.value = true;
      listRef.value && listRef.value.scrolltolower();
    }
  });
});

const rightClick = () => {
  popupRef.value && popupRef.value.open();
};

const getList = (list) => {
  dataList.value = list;
  handleLoadComplete();
};

const popClose = () => {
  popupRef.value && popupRef.value.close();
};

onLoad((options) => {});
onShow(() => {
  getCategory();
});

const leftClick = () => {
  uni.navigateBack();
};
const getCategory = async () => {
  try {
    const res = await SHOP_GOODS_CATEGORY();
    tabList.value = res.data || [];
  } catch (error) {
    Toast(error.msg);
  }
};

const tabClick = (item, index) => {
  defaultParams.cid = item.id;
  if (actvieNum.value == index) return;
  actvieNum.value = index;
  nextTick(() => {
    listRef.value && listRef.value.handleRefresh();
  });
};

const collectClick = (item, index) => {
  setCollect(
    {
      channel: 1,
      type: "good",
      goods_id: item.num_iid,
      seller_id: item.seller_id,
      title: item.title,
      pic_url: item.pic_url,
      price: item.price,
    },
    index
  );
};

const setCollect = async (params, index) => {
  try {
    const res = await SHOP_USER_COLLECT(params);
    nextTick(() => {
      dataList.value[index].isCollect = res.data.collect;
      listRef.value && listRef.value.setList(dataList.value);
    });
  } catch (error) {
    Toast(error.msg);
  }
};
</script>
<style lang="less" scoped>
@import url("@/style.less");

.wrap {
  min-height: 100vh;
  background-color: var(--bg);

  .nav_center {
    display: flex;
    width: calc(100% - 46px - 50px);

    .icon-camera {
      color: #adb8cc;
      font-size: 56rpx;
    }
    .img_left {
      position: relative;
      .del {
        position: absolute;
        right: -10rpx;
        top: -10rpx;
      }
    }
  }

  .nav_right {
    color: var(--black);
    .size(12px);
    font-weight: 700;
  }

  .tops {
    position: fixed;
    top: 44px;
    left: 0;
    right: 0;
    background-color: var(--bg);
    z-index: 1;
    .tab {
      padding: 0 24rpx;
    }
  }

  .content {
    padding: 120rpx 32rpx 16rpx;

    /deep/ .wrap_list {
      .uni-scroll-view-content {
        > uni-view {
          .flex();
          flex-wrap: wrap;
          gap: 16rpx;

          .u-list-item {
            width: calc((100% - 16rpx) / 2);
          }
        }
      }
    }
  }
}

.pop_cont {
  color: var(--text);
  .size(28rpx);
  line-height: 60rpx;
}

.pop_tip {
  color: var(--text-01);
  .size(28rpx);
  line-height: 60rpx;
}

.pop_btn {
  margin-top: 32rpx;
  height: 76rpx;
  padding: 16rpx 30rpx;
  color: var(--text-01);
  border: 1px solid var(--text-01);
  border-radius: 16rpx;
  .size(24rpx);
  .flex_center();
}
</style>