<template>
  <Theme>
    <view class="wrap" id="pageContainer">
      <Navbar
        border
        fixed
        autoBack
        @leftClick="leftClick"
        @rightClick="searchConfirm"
      >
        <template #center>
          <view class="nav_center">
            <view class="img_left" v-if="defaultParams.img">
              <up-avatar
                :src="defaultParams.img"
                shape="square"
                size="34"
                @click="previewImage(defaultParams.img)"
              ></up-avatar>
              <up-icon
                name="close-circle-fill"
                color="#ef4444"
                size="14"
                class="del"
                @click="searchConfirm"
              ></up-icon>
            </view>

            <Search
              v-model="searchValue"
              :placeholder="t('商品的链接或名称')"
              confirm-type="search"
            >
              <template #prefix>
                <i class="icon-font icon-search"></i>
              </template>
              <template #suffix>
                <i class="icon-font icon-camera" @click="openCamera"></i>
              </template>
            </Search>
          </view>
        </template>
        <template #right>
          <view class="nav_right">
            <trans _t="搜索" />
          </view>
        </template>
      </Navbar>
      <view class="tops" id="tabs" :style="{ top: tabTop + 'px' }">
        <view class="tab">
          <Tab
            :active="actvieNum"
            keyName="text"
            :tabList="tabList"
            @confirm="tabClick"
          />
        </view>
        <view class="product_sort">
          <view
            class="sort_list"
            :class="sortActive == index ? 'sort_active' : ''"
            v-for="(item, index) in sortList"
            :key="index"
            @click="item.callback(item, index)"
          >
            <trans :_t="item.text" />
            <template v-if="item.isTrue == 1">
              <view class="sort_arrow">
                <view
                  class="sort_arrow_top"
                  :style="
                    defaultParams.sort == 'moneyAsc'
                      ? { borderBottom: '4px solid var(--black)' }
                      : {}
                  "
                ></view>
                <view
                  class="sort_arrow_bottom"
                  :style="
                    defaultParams.sort == 'moneyDesc'
                      ? { borderTop: '4px solid var(--black)' }
                      : {}
                  "
                ></view>
              </view>
            </template>
          </view>
        </view>
      </view>
      <view class="content">
        <List
          :url="defaultParams.img ? '/shop/goods/search' : '/shop/goods/list'"
          isCache
          :topHeight="tabHeight"
          :defaultParams="defaultParams"
          :pageSize="20"
          isLoading
          ref="listRef"
          @datas="getList"
        >
          <template #item="{ item, index }">
            <shopList
              :channel="defaultParams.channel"
              :item="item"
              :search="defaultParams.keyWord"
              @collect="collectClick($event, index)"
            />
          </template>
        </List>
      </view>
    </view>
    <popup title="搜索条款" isClose ref="popupRef">
      <template #content>
        <view class="pop_cont">
          <trans _t="搜索条款内容" />
        </view>
        <view class="pop_tip">
          <trans _t="您已同意搜索条款" />
        </view>
        <view class="pop_btn" @click="popClose">
          <trans _t="关闭" />
        </view>
      </template>
    </popup>

    <CameraUpload @confirm="getUrl" ref="cameraUploadRef" />
  </Theme>
</template>
<script setup>
import { ref, computed, reactive, watch, onMounted, nextTick } from "vue";
import Navbar from "@/components/navbar";
import Search from "@/components/input";
import CameraUpload from "@/components/CameraUpload";
import { t } from "@/locale";
import { onLoad, onReachBottom, onPageScroll } from "@dcloudio/uni-app";
import List from "@/components/list";
import {
  query,
  systemInfo,
  setStorage,
  getStorage,
  removeStorage,
} from "@/utils";
import shopList from "./components/shop_list";
import popup from "@/components/popup";
import Tab from "@/components/tabs";
import { SHOP_USER_COLLECT } from "@/api";

const searchList = ref(JSON.parse(getStorage("search_list") || "[]"));
const search_list = computed(() => searchList.value || []);

const searchValue = ref("");
const listRef = ref(null);
const popupRef = ref(null);
const actvieNum = ref(1);
const tabHeight = ref(0);
const tabTop = ref(44);
const sortActive = ref(0);
const dataList = ref([]);
const tabList = ref([
  {
    img: "../../static/shop/icon_0.png",
    text: "1688",
    channel: 0,
  },
  {
    img: "../../static/shop/icon_1.png",
    text: "淘宝",
    channel: 1,
  },
  {
    img: "../../static/shop/icon_3.png",
    text: "JD",
    channel: 3,
  },
]);
const defaultParams = reactive({
  channel: tabList.value[actvieNum.value].channel,
  keyWord: "",
  start_price: "",
  end_price: "",
  sort: "",
  img: "",
});
const sortList = reactive([
  {
    text: "综合",
    sort: "",
    callback: (item, index) => {
      sortActive.value = index;
      defaultParams.sort = "";
      nextTick(() => {
        listRef.value && listRef.value.handleRefresh();
      });
    },
  },
  {
    text: "价格",
    isTrue: 1,
    sort: "moneyDesc", // moneyAsc 升序
    callback: (item, index) => {
      priceClick(item, index);
    },
  },
]);

const cameraUploadRef = ref(null);
const openCamera = () => {
  cameraUploadRef.value && cameraUploadRef.value.open();
};
const getUrl = (url) => {
  defaultParams.img = url;
  defaultParams.keyWord = searchValue.value = "";
  listRef.value && listRef.value.handleRefresh(url);
};
// 防抖标记（防止重复触发）
const isLoading = ref(false);
// 自定义触发阈值：距离底部 200px 时触发
const triggerThreshold = ref(600);
// 页面总高度（用于计算距离底部距离）
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(defaultParams.img);
    });
  });
});

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 previewImage = (url) => {
  uni.previewImage({
    urls: [url],
  });
};
const searchConfirm = () => {
  if (searchValue.value) {
    const searchText =
      searchValue.value.length > 20
        ? searchValue.value.substring(0, 20) + "..."
        : searchValue.value;

    search_list.value.unshift(searchText);
    let arr = search_list.value.slice(0, 8);
    setStorage("search_list", JSON.stringify([...new Set(arr)]));
    defaultParams.keyWord = searchValue.value;
  }

  defaultParams.img = "";
  nextTick(() => {
    listRef.value && listRef.value.handleRefresh();
  });
};

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

const priceClick = (item, index) => {
  if (sortActive.value == index) {
    if (defaultParams.sort == "moneyAsc") {
      defaultParams.sort = "";
      sortActive.value = 0;
    } else {
      defaultParams.sort = "moneyAsc";
    }
  } else {
    sortActive.value = index;
    defaultParams.sort = item.sort;
  }
  nextTick(() => {
    listRef.value && listRef.value.handleRefresh();
  });
};

onLoad((options) => {
  const { searchText = "", channel = 1, searchImg = "" } = options;
  searchValue.value = searchText;
  actvieNum.value = channel == 3 ? 2 : Number(channel);
  defaultParams.channel = Number(channel);
  defaultParams.keyWord = searchText;
  defaultParams.img = searchImg || "";
});

const leftClick = () => {
  uni.navigateBack();
  // uni.switchTab({ url: '/pages/index/index' });
};

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

const collectClick = (item, index) => {
  setCollect(
    {
      channel: tabList.value[actvieNum.value].channel,
      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);
  }
};

// onReachBottom(() => {
//   nextTick(() => {
//     listRef.value && listRef.value.scrolltolower();
//   });
// });
</script>
<style lang="less" scoped>
@import url("@/style.less");

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

  .nav_center {
    display: flex;
    width: calc(100% - 240rpx);

    .icon-camera {
      color: #adb8cc;
      font-size: 56rpx;
    }
    .img_left {
      position: relative;
      .del {
        position: absolute;
        right: -10rpx;
        top: -10rpx;
      }
    }
  }
  /deep/ .u-navbar {
    .u-navbar__content__left,
    .u-navbar__content__right {
      position: unset;
    }
  }
  .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;
    }

    .product_sort {
      .flex();
      padding: 24rpx 32rpx;

      .sort_list {
        color: var(--text-01);
        .size(24rpx);
        line-height: 40rpx;
        margin-right: 72rpx;
        padding: 16rpx 0;
        .ver();

        .sort_arrow {
          margin-left: 20rpx;

          &_top {
            border-bottom: 4px solid #adb8cc;
            border-left: 4px solid transparent;
            border-right: 4px solid transparent;
            font-size: 0;
            height: 0;
            line-height: 0;
            margin-bottom: 1px;
            width: 0;
          }

          &_bottom {
            border-left: 4px solid transparent;
            border-right: 4px solid transparent;
            border-top: 4px solid #adb8cc;
            font-size: 0;
            height: 0;
            line-height: 0;
            margin-top: 1px;
            width: 0;
          }
        }
      }

      .sort_active {
        color: var(--black);
      }
    }
  }

  .content {
    padding: 16rpx 32rpx;

    /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>