import {useState, useEffect, useCallback} from 'react'
import {View, Text} from '@tarojs/components'
import {Loading, 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 fetchCustomerData = useCallback(async () => {
    setLoading(true);
    try {
      // 构建API参数，根据状态筛选
      const params: any = {};

      const res = await pageShopDealerApply(params);
      if (res?.list) {
        // 正确映射状态
        const mappedList = res.list.map(customer => ({
          ...customer,
          customerStatus: mapApplyStatusToCustomerStatus(customer.applyStatus || 10)
        }));
        setList(mappedList);
      }
    } catch (error) {
      console.error('获取客户数据失败:', error);
    } finally {
      setLoading(false);
    }
  }, []);


  // 根据搜索条件筛选数据（状态筛选已在API层面处理）
  const getFilteredList = () => {
    let filteredList = list;

    // 按搜索关键词筛选
    if (searchValue.trim()) {
      const keyword = searchValue.trim().toLowerCase();
      filteredList = filteredList.filter(customer =>
        (customer.realName && customer.realName.toLowerCase().includes(keyword)) ||
        (customer.dealerName && customer.dealerName.toLowerCase().includes(keyword)) ||
        (customer.dealerCode && customer.dealerCode.toLowerCase().includes(keyword)) ||
        (customer.mobile && customer.mobile.includes(keyword)) ||
        (customer.userId && customer.userId.toString().includes(keyword))
      );
    }

    return filteredList;
  };

  // 初始化数据
  useEffect(() => {
    fetchCustomerData().then();
  }, [fetchCustomerData]);

  // 当activeTab变化时重新获取数据
  useEffect(() => {
    fetchCustomerData().then();
  }, []);

  // 渲染客户项
  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();

    if (loading) {
      return (
        <Space className="flex items-center justify-center py-8">
          <Loading/>
          <Text className="text-gray-500 mt-2">加载中...</Text>
        </Space>
      );
    }

    if (filteredList.length === 0) {
      return (
        <View className="flex items-center justify-center py-8">
          <Text className="text-gray-500">暂无客户数据</Text>
        </View>
      );
    }

    return (
      <View className="p-4">
        {filteredList.map(renderCustomerItem)}
      </View>
    );
  };

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

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

    </View>
  );
};

export default CustomerTrading;
