import Taro, { useReachBottom,} from "@tarojs/taro";
import { View, ScrollView } from "@tarojs/components";
import { getEntAgentPartners } from "@/service/agent";
import ContactCard from "@/components/AgentCard/index";
import WemetaRadio from "@/components/WemetaRadio/index";
import { useAgentStore } from "@/store/agentStore";
import { TAgent } from "@/types/agent";
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  agent = useAgentStore((state) => state.agent);
  
  const fetcher = async ([_url, {nextId, pageSize}, [entId]]) => {
    const res = await getEntAgentPartners({ startId: nextId, pageSize, entId });
    return res.data;
  };

  const entId = agent?.entId ?? 0;


  const { list, loadMore } = useLoadMoreInfinite<TAgent[]>(
    createKey(`/blue-aiagent/api/v1/my/ent/${entId}/agent/partners`, 10, [entId]),
    fetcher,
  );

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

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

  const renderContent = () => {
    if (list.length) {
      return list.map((item) => (
        <View className='bg-white'>
          <ContactCard
              className="border-bottom1-gray py-16"
              key={item.agentId}
              data={item}
              onClick={()=> handleClick(item)}
              renderRight={() => {
                return (
                  <View className="flex items-center">
                    <WemetaRadio
                      checkbox
                      checked={!!selected.find(_item =>  _item.agentId === item.agentId)}
                    ></WemetaRadio>
                  </View>
                );
              }}
            ></ContactCard>
        </View>
      ));
    }
    return (
      <EmptyData type='search'></EmptyData>
    );
  };

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