import SearchBar from "../../components/SearchBar";
import FilterPopup from "@/components/FilterPopup";
import styles from "./index.module.scss";
import { useEffect } from "react";
import Taro, { usePageScroll } from "@tarojs/taro";
import { useListStore } from "@/store/listStore";
import { useGlobalState } from "@/store/global";
import { View } from "@tarojs/components";
import CustomerNavBar from "@/container/listCustomNavbar";
import GuideBar from "@/components/GuideBar";
import ListContainer from "@/container/listContainer";
import DistanceQuickFilter from "@/components/DistanceQuickFilter";
import { withAuth } from "@/components";
// import img from "@/config/images";




const ListPage = () => {

  // 从 store 获取数据和方法
  const store = useListStore() || {};

  const { statusNavbarHeightInfo, location = {}, getCurrentLocationInfo } = useGlobalState() || {};

  useEffect(() => {
    getCurrentLocationInfo?.();
  }, [getCurrentLocationInfo]);

  const { totalHeight } = statusNavbarHeightInfo || {};
  const {
    isShowFilterPopup,
    error,
    matches,
    recommendList,
    loading,
    getMatchesData,
    updateState,
    filterCount,
    updateFilterOptions, // 更新筛选条件
    filterOptions,
    clearFilterOptions,
    distanceData,
    quickFilterData,
    distanceQuickFilter,
    isScrollTop,
    searchValue,
    isShowInputCustomerNavBar,
    initialFilterSearch,
    loadMoreMatches,
    dateRangeOptions
  } = store;

  usePageScroll((res) => {
    if (res?.scrollTop >= totalHeight) {
      !isShowInputCustomerNavBar &&
        updateState({ isShowInputCustomerNavBar: true });
    } else {
      isShowInputCustomerNavBar &&
        updateState({ isShowInputCustomerNavBar: false });
    }
  });

  useEffect(() => {

    if (location?.address) {
      // 保存位置
      updateState({ location });
      // 页面加载时获取数据
      getMatchesData();
    }
  }, [location]);

  const refreshMatches = () => {
    initialFilterSearch();
  };

  // const getLoadMoreMatches = () => {
  //   loadMoreMatches()
  // }

  // 下拉刷新处理函数 - 使用Taro生命周期钩子
  Taro.usePullDownRefresh(() => {
    console.log("===触发下拉刷新");
    clearFilterOptions()

    // 调用 store 的刷新方法
    // refreshMatches()
    //   .then(() => {
    //     // 刷新完成后停止下拉刷新动画
    //     Taro.stopPullDownRefresh();

    //     // 显示刷新成功提示
    //     Taro.showToast({
    //       title: "刷新成功",
    //       icon: "success",
    //       duration: 1500,
    //     });
    //   })
    //   .catch(() => {
    //     // 刷新失败时也停止动画
    //     Taro.stopPullDownRefresh();

    //     Taro.showToast({
    //       title: "刷新失败",
    //       icon: "error",
    //       duration: 1500,
    //     });
    //   });
  });

  const toggleShowPopup = () => {
    updateState({ isShowFilterPopup: !isShowFilterPopup });
  };

  /**
   * @description 更新筛选条件
   * @param {Record<string, any>} params 筛选项
   */
  const handleUpdateFilterOptions = (params: Record<string, any>) => {
    updateFilterOptions(params);
  };

  const handleSearchChange = () => { };

  // 距离筛选
  const handleDistanceOrQuickChange = (name, value) => {
    updateState({
      distanceQuickFilter: {
        ...distanceQuickFilter,
        [name]: value,
      },
    });
  };

  const handleSearchClick = () => {
    Taro.navigateTo({
      url: "/pages/search/index",
    });
  };

  return (
    <View>
      {/* 自定义导航 */}
      <CustomerNavBar />
      <View className={styles.listPage}>
        <View
          className={`${styles.listTopSearchWrapper} ${isScrollTop ? styles.isScroll : ""
            }`}
        >
          <SearchBar
            handleFilterIcon={toggleShowPopup}
            isSelect={filterCount > 0}
            filterCount={filterCount}
            onChange={handleSearchChange}
            value={searchValue}
            onInputClick={handleSearchClick}
          />
          {/* 综合筛选 */}
          {isShowFilterPopup && (
            <View>
              <FilterPopup
                loading={loading}
                onCancel={toggleShowPopup}
                onConfirm={toggleShowPopup}
                onChange={handleUpdateFilterOptions}
                filterOptions={filterOptions}
                onClear={clearFilterOptions}
                visible={isShowFilterPopup}
                onClose={toggleShowPopup}
                statusNavbarHeigh={statusNavbarHeightInfo?.totalHeight}
              />
            </View>
          )}
        </View>
        {/* 筛选 */}
        <View className={styles.listTopFilterWrapper}>
          <DistanceQuickFilter
            cityOptions={distanceData}
            quickOptions={quickFilterData}
            onChange={handleDistanceOrQuickChange}
            cityName="distance"
            quickName="quick"
            cityValue={distanceQuickFilter?.distance}
            quickValue={distanceQuickFilter?.quick}
          />
        </View>

        {/* 列表内容 */}
        <ListContainer
          data={matches}
          recommendList={recommendList}
          loading={loading}
          error={error}
          reload={refreshMatches}
          loadMoreMatches={loadMoreMatches}
        />
      </View>

      <GuideBar currentPage="list" />
    </View>
  );
};

export default withAuth(ListPage);
