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 { TContactItem } from "@/types/contact";
import ContactCard from "@/components/AgentCard/index";
import WemetaRadio from "@/components/WemetaRadio/index";

import { createKey, useLoadMoreInfinite } from "@/utils/loadMoreInfinite";
import EmptyData from "@/components/EmptyData";

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


export default function Index({selected, setSelected}: IProps) {

  const fetcher = async ([_url, {nextId, pageSize}]) => {
    const res = await getContactList({ startId: nextId, pageSize });
    return res.data;
  };
  const { list, loadMore } = useLoadMoreInfinite<TContactItem[]>(
    createKey('/blue-aiagent/api/v1/my/contacts',),
    fetcher,
  );

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


  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 <EmptyData type='search'></EmptyData>;
  };

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