import Taro, { useDidShow } from "@tarojs/taro";
import { View, Image } from "@tarojs/components";
import WidgetCard from "@/components/widgets/widget-card/index";
import ContactCard from "@/components/AgentCard/index";
import style from "./index.module.less";
import IconArrowRight from "@/images/icon_24_right.png";
import { axios } from "taro-axios";
import { useEffect, useState } from "react";
import { TAgent, TComponentItem } from "@/types/agent";
import { TContactItem } from "@/types/contact";
import { getAgentBatch } from "@/service/agent";
import { isSuccess } from "@/utils";
import { AvatarMedia } from "@/components/AvatarMedia";

interface Props {
  index: number;
  editMode: boolean;
  component: TComponentItem;
  components: TComponentItem[];
  onSwitchChanged: (c: TComponentItem, checked: boolean) => void;
  onDelete: (c: TComponentItem) => void;
  onMove: (c: TComponentItem, direction: number) => void;
  onClick: () => void;
  onStyleChanged: (c: TComponentItem) => void
}

export default ({
  index,
  editMode,
  component,
  components,
  onSwitchChanged,
  onDelete,
  onMove,
  onClick,
  onStyleChanged,
}: Props) => {
  
  const contacts = (component.data.values ?? []) as (TAgent|TContactItem)[]

  const [list, setList] = useState<(TAgent|TContactItem)[]>(contacts);


  // 非编辑模式且垂直平铺，背景显示为白色
  const bgStyle = (component.data?.layout === "mini" || editMode) ? style.bgMini : style.bgFull


  
  const fetchData = async () => {
    const response = await getAgentBatch(contacts.map(item=> item.agentId).join(','));
    if(isSuccess(response.status)){ 
      console.log('获取名片数据', response.data);
      setList(response.data);
    }
  }
    
  
  useDidShow(()=> {
    fetchData()
  })

  useEffect(()=> {
    fetchData()
  }, [])

  const handleClick= (item: TAgent|TContactItem) => {
    if(!editMode){
      Taro.navigateTo({
        url: "/pages/profile/index?agentId=" + item?.agentId,
      });
    }
  }

  
  const renderEmpty = ()=> {
    if(list.length){
      return <></>
    }
    return <View className="px-16"><View className="component-card-empty">
      <View className="component-card-content">
        <View className="component-card-empty-figure"></View>
        <View className="component-card-empty-tips">点击配置小蓝本名片跳转</View>
      </View>
    </View>
    </View>
  }
  const renderList = () => {
    

    if (component.data?.layout === "mini") {
      return (
        <View className="grid grid-cols-3 gap-x-18 gap-y-20 px-16">
          {list.map((item) => {
            return (
              <View className="flex flex-col gap-8" onClick={()=> {handleClick(item)}}>
                <View className={style.avatar}>
                  <AvatarMedia source={item.avatarUrl ?? ''} mode='aspectFill' className='w-92 h-92 rounded-full' />
                </View>
                <View className={`truncate ${style.nickName}`}>
                  {item.name}
                </View>
              </View>
            );
          })}
        </View>
      );
    }

    // 
    return (
      <View className={`flex flex-col gap-8 ${editMode ? 'px-16' : ''}`}>
        {list.map((item) => {
          return (
            <ContactCard
              className={`${bgStyle} p-16`}
              key={item.agentId}
              data={item}
              onClick={()=> {handleClick(item)}}
              renderRight={() => {
                return (
                  <Image
                    src={IconArrowRight}
                    className={style.arrow}
                    mode="aspectFill"
                    lazyLoad
                  ></Image>
                );
              }}
            ></ContactCard>
          );
        })}
      </View>
    );
  };

  // 非编辑模式下样式需要特殊处理，与其它组件不同
  if(!editMode && component.data?.layout !== "mini"){
    return (
      <>
        {renderList()}
      </>
    )
  }
  
  // 编辑模式下，添加一个外包框
  return (
    <>
      <WidgetCard
        key={component.data.id}
        enabled={component.enabled}
        onSwitchChanged={(checked) => onSwitchChanged(component, checked)}
        index={index}
        components={components}
        editMode={editMode}
        onDelete={() => onDelete(component)}
        onMove={(direction) =>  onMove(component, direction)}
        onClick={onClick}
        onChanged={()=> {
          if(component.data?.layout === 'mini'){
            onStyleChanged({...component, data: {...component.data, layout: 'full'}})
          }else{
            onStyleChanged({...component, data: {...component.data, layout: 'mini'}})
          }
        }}
      >
        {renderEmpty()}
        {renderList()}
      </WidgetCard>
    </>
  );
};
