import Taro, { useReachBottom,} from "@tarojs/taro";
import { View, ScrollView } from "@tarojs/components";
import style from "./index.module.less";
import { useEffect, useState } from "react";
import { getContactList } from "@/service/contact";
import { useLoadMore } from "@/utils/loadMore";
import { TContactItem } from "@/types/contact";
import ContactCard from "@/components/contact-card/index";
import WemetaRadio from "@/components/WemetaRadio/index";

export interface IProps {
  selected: any[]
  setSelected: (values) => void
}


export default function Index({selected, setSelected}: IProps) {
  const [list, setList] = useState<TContactItem[]>([]);

  const fetcher = async ([_url, nextId, page, pageSize, _keyword]) => {
    let keyword = _keyword
    const res = await getContactList({ startId: nextId, pageSize, keyword });
    return res.data;
  };
  const { data, loadMore, refetch } = useLoadMore<{
    data?: TContactItem[]
    nextId?: string,
    totalCount?: number
  }>({
    url: '/blue-aiagent/api/v1/my/contacts',
    fetcher,
  });

  const onScrollToLower = () => {
    // 加载更多数据
    loadMore();
  };

  useEffect(() => {
    if (data?.data) {
      setList([...list, ...data.data]);
    }
  }, [data]);


  const handleClick = (item: TContactItem) => {
    console.log(item)
    const exist = selected.find(_item =>  _item.contactId === item.contactId)
    console.log(exist)
    if(exist){
      const filtered = selected.filter(_item => _item.contactId !== item.contactId)
      setSelected(filtered)
    }else{
      setSelected([...selected, item])
    }
  };

  const renderContent = () => {
    if (list?.length) {
      return list.map((item) => (
        <View className=''>
          <ContactCard
              className="border-bottom1-gray py-16"
              key={item.contactId}
              data={item}
              onClick={()=> handleClick(item)}
              renderRight={() => {
                return (
                  <View className="flex items-center">
                    <WemetaRadio
                      checkbox
                      checked={!!selected.find(_item =>  _item.contactId === item.contactId)}
                    ></WemetaRadio>
                  </View>
                );
              }}
            ></ContactCard>
        </View>
      ));
    }
    return (
      <View className="flex flex-col pt-56 items-center">
        <View className="data-empty"></View>
        <View className="text-12 text-gray-45 text-center leading-24 mt-12">
          暂无数据
        </View>
      </View>
    );
  };

  return (
    <ScrollView
      scrollY
      onScrollToLower={onScrollToLower}
      style={{
        flex: 1,
        height: "100%", // 高度自适应
      }}
    >
      {renderContent()}
    </ScrollView>
  );
}
