import Taro, { useReachBottom } from "@tarojs/taro";
import { View, Text } from "@tarojs/components";
import EmptyData from "@/components/empty-data";
import NavBarNormal from "@/components/NavBarNormal/index";
import SearchBar from "@/components/search-bar/index";
import style from "./index.module.less";
import { useEffect, useState } from "react";
import ContactCard from "./components/contact-card/index";
import { getContactList, setContactToTop } from "@/service/contact";
import { useLoadMore } from "@/utils/loadMore";
import PageCustom from "@/components/page-custom/index";
import { TContactItem } from "@/types/contact";
import { isSuccess } from "@/utils";
import useSWRInfinite from "swr/infinite";

export default function Index() {
  const [searchValue, setSearchValue] = useState("");

  const fetcher = async ([_url, params, keyword]) => {
    params = params || {};
    console.log("fetcher", _url, params);
    const res = await getContactList({
      startId: params.nextId,
      pageSize: params.pageSize,
      keyword: keyword,
    });
    return res.data;
  };

  const getKey = (pageIndex:number, previousPageData) => {
    if (pageIndex === 0)
      return [
        "/my/contacts",
        { nextId: undefined, pageSize: 2, keyword: "" },
        searchValue,
      ];
    if (previousPageData && previousPageData.nextId) {
      return [
        "/my/contacts",
        { pageSize: 2, nextId: previousPageData.nextId },
        searchValue,
      ];
    }

    return null;
  };
  const { data, setSize } = useSWRInfinite(getKey, fetcher, {
    revalidateIfStale: false,
    onErrorRetry(err, key, config, revalidate, revalidateOpts) {
      if(err.status === 404) return 
      if(err.status === 401) return
      if(revalidateOpts.retryCount >=3 )return
    },
  });

  const list = data?.flatMap((page) => page?.data || []) || [];
  

  const resetFetchList = () => {
    setSize(1);
  };

  const handleSearchBarChanged = (v: string) => {
    setSearchValue(v);
  };

  const handleClear = () => {
    setSearchValue("");
  };

  useReachBottom(() => {
    // 加载更多数据
    // 如果搜索框中有数据由不加载更多数据
    if (searchValue.length) {
      return;
    }
    setSize((prevSize) => prevSize + 1);
  });


  const handleHello = async (e: any) => {
    const detail = e.detail as { type: string; id: string };
    console.log(detail);
    // 置顶与取消置顶
    if (detail.type === "pin" || detail.type === "unpin") {
      const reseponse = await setContactToTop({
        isTop: detail.type === "pin",
        contactId: detail.id,
      });
      if (isSuccess(reseponse.status)) {
        resetFetchList();
        return;
      }
    }
  };

  const renderContent = () => {
    if (list?.length) {
      return list.map((item) => (
        // @ts-ignore
        <slide-delete
          pid={item.contactId}
          pinned={item.isTop}
          onAction={handleHello}
        >
          <View className={`${item.isTop ? "bg-gray" : "bg-white"}`}>
            <ContactCard
              refresh={resetFetchList}
              deleteable={!item.isEnt}
              key={item.contactId}
              data={item}
              fromContact
            ></ContactCard>
          </View>
        </slide-delete>
      ));
    }
    return <EmptyData type={2} />;
  };

  return (
    <PageCustom>
      <NavBarNormal
        scrollFadeIn
        leftColumn={() => <Text className="text-16 font-medium">联系人</Text>}
      ></NavBarNormal>
      <View className="flex flex-col w-full">
        <View className="px-16 pb-12">
          <SearchBar
            value={searchValue}
            onChange={(e) => handleSearchBarChanged(e)}
            onClear={() => handleClear()}
          ></SearchBar>
        </View>

        <View className={style.contactContent}>{renderContent()}</View>
      </View>
    </PageCustom>
  );
}
