import {useState, useCallback} from 'react'
import {View, Text} from '@tarojs/components'
import Taro from '@tarojs/taro'
import {Loading, InfiniteLoading, Empty, Space, SearchBar} from '@nutui/nutui-react-taro'
import type {ShopDealerApply as UserType} from "@/api/shop/shopDealerApply/model";
import {
  CustomerStatus,
  mapApplyStatusToCustomerStatus,
} from '@/utils/customerStatus';
import {pageShopDealerApply} from "@/api/shop/shopDealerApply";

// 扩展User类型，添加客户状态
interface CustomerUser extends UserType {
  customerStatus?: CustomerStatus;
}

const CustomerTrading = () => {
  const [list, setList] = useState<CustomerUser[]>([])
  const [loading, setLoading] = useState<boolean>(false)
  const [searchValue, setSearchValue] = useState<string>('')
  const [page, setPage] = useState(1)
  const [hasMore, setHasMore] = useState(true)

  // 获取客户数据
  const fetchCustomerData = useCallback(async (resetPage = false, targetPage?: number, searchKeyword?: string) => {
    setLoading(true);
    try {
      const currentPage = resetPage ? 1 : (targetPage || page);

      // 构建API参数，根据状态筛选
      const params: any = {
        type: 3,
        page: currentPage
      };

      // 添加搜索关键词
      if (searchKeyword && searchKeyword.trim()) {
        params.keywords = searchKeyword.trim();
      }

      const res = await pageShopDealerApply(params);

      if (res?.list && res.list.length > 0) {
        // 正确映射状态
        const mappedList = res.list.map(customer => ({
          ...customer,
          customerStatus: mapApplyStatusToCustomerStatus(customer.applyStatus || 10)
        }));

        // 如果是重置页面或第一页，直接设置新数据；否则追加数据
        if (resetPage || currentPage === 1) {
          setList(mappedList);
        } else {
          setList(prevList => prevList.concat(mappedList));
        }

        // 正确判断是否还有更多数据
        const hasMoreData = res.list.length >= 10; // 假设每页10条数据
        setHasMore(hasMoreData);
      } else {
        if (resetPage || currentPage === 1) {
          setList([]);
        }
        setHasMore(false);
      }

      setPage(currentPage);
    } catch (error) {
      console.error('获取客户数据失败:', error);
      Taro.showToast({
        title: '加载失败，请重试',
        icon: 'none'
      });
    } finally {
      setLoading(false);
    }
  }, [page]);

  const reloadMore = async () => {
    if (loading || !hasMore) return; // 防止重复加载
    const nextPage = page + 1;
    await fetchCustomerData(false, nextPage, searchValue);
  }


  // 获取列表数据（现在使用服务端搜索，不需要客户端过滤）
  const getFilteredList = () => {
    return list;
  };

  // 搜索处理函数
  const handleSearch = (keyword: string) => {
    if(keyword.length < 4){
      return;
    }
    setSearchValue(keyword);
    setList([]);
    setPage(1);
    setHasMore(true);
    fetchCustomerData(true, 1, keyword);
  };

  // 清空搜索
  // const handleClearSearch = () => {
  //   setSearchValue('');
  //   setList([]);
  //   setPage(1);
  //   setHasMore(true);
  //   fetchCustomerData(true, 1, '');
  // };

  // 渲染客户项
  const renderCustomerItem = (customer: CustomerUser) => (
    <View key={customer.userId} className="bg-white rounded-lg p-4 mb-3 shadow-sm">
      <View className="flex items-center">
        <View className="flex-1">
          <View className="flex items-center justify-between mb-1">
            <Text className="font-semibold text-gray-800 mr-2">
              {customer.dealerName}
            </Text>
          </View>
          <Space direction={'vertical'}>
            {/*<Text className="text-xs text-gray-500">统一代码：{customer.dealerCode}</Text>*/}
            <Text className="text-xs text-gray-500">
              更新时间：{customer.createTime}
            </Text>
          </Space>
        </View>
      </View>
    </View>
  );

  // 渲染客户列表
  const renderCustomerList = () => {
    const filteredList = getFilteredList();

    return (
      <View className="p-4" style={{
        height: '90vh',
        overflowY: 'auto',
        overflowX: 'hidden'
      }}>
        <InfiniteLoading
          target="scroll"
          hasMore={hasMore}
          onLoadMore={reloadMore}
          onScroll={() => {
            // 滚动事件处理
          }}
          onScrollToUpper={() => {
            // 滚动到顶部事件处理
          }}
          loadingText={
            <>
              加载中...
            </>
          }
          loadMoreText={
            filteredList.length === 0 ? (
              <Empty
                style={{backgroundColor: 'transparent'}}
                description={loading ? "加载中..." : "暂无客户数据"}
              />
            ) : (
              <View className={'h-12 flex items-center justify-center'}>
                <Text className="text-gray-500 text-sm">没有更多了</Text>
              </View>
            )
          }
        >
          {loading && filteredList.length === 0 ? (
            <View className="flex items-center justify-center py-8">
              <Loading/>
              <Text className="text-gray-500 mt-2 ml-2">加载中...</Text>
            </View>
          ) : (
            filteredList.map(renderCustomerItem)
          )}
        </InfiniteLoading>
      </View>
    );
  };

  return (
    <View className="min-h-screen bg-gray-50">
      {/* 搜索栏 */}
      <View className="bg-white shadow-sm">
        <SearchBar
          placeholder="请输入搜索关键词"
          value={searchValue}
          onChange={(value) => handleSearch(value)}
        />
      </View>

      {/* 客户列表 */}
      {renderCustomerList()}

    </View>
  );
};

export default CustomerTrading;
