import {useState, useEffect, useCallback} from 'react'
import {View, Text} from '@tarojs/components'
import Taro from '@tarojs/taro'
import {Loading, Space, Tabs, TabPane, Tag, Button} from '@nutui/nutui-react-taro'
import {Phone} from '@nutui/icons-react-taro'
import type {ShopDealerApply, ShopDealerApply as UserType} from "@/api/shop/shopDealerApply/model";
import {
  CustomerStatus,
  getStatusText,
  getStatusTagType,
  getStatusOptions,
  mapApplyStatusToCustomerStatus,
  mapCustomerStatusToApplyStatus
} from '@/utils/customerStatus';
import FixedButton from "@/components/FixedButton";
import navTo from "@/utils/common";
import {pageShopDealerApply, updateShopDealerApply} from "@/api/shop/shopDealerApply";

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

const CustomerIndex = () => {
  const [list, setList] = useState<CustomerUser[]>([])
  const [loading, setLoading] = useState<boolean>(false)
  const [activeTab, setActiveTab] = useState<CustomerStatus>('all')
  const [searchValue, _] = useState<string>('')

  // Tab配置
  const tabList = getStatusOptions();


  // 获取客户数据
  const fetchCustomerData = useCallback(async (statusFilter?: CustomerStatus) => {
    setLoading(true);
    try {
      // 构建API参数，根据状态筛选
      const params: any = {};
      const applyStatus = mapCustomerStatusToApplyStatus(statusFilter || activeTab);
      if (applyStatus !== undefined) {
        params.applyStatus = applyStatus;
      }

      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);
    }
  }, [activeTab]);


  // 根据搜索条件筛选数据（状态筛选已在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;
  };

  // 获取各状态的统计数量
  const [statusCounts, setStatusCounts] = useState({
    all: 0,
    pending: 0,
    signed: 0,
    cancelled: 0
  });

  // 获取所有状态的统计数量
  const fetchStatusCounts = useCallback(async () => {
    try {
      // 并行获取各状态的数量
      const [allRes, pendingRes, signedRes, cancelledRes] = await Promise.all([
        pageShopDealerApply({}), // 全部
        pageShopDealerApply({applyStatus: 10}), // 跟进中
        pageShopDealerApply({applyStatus: 20}), // 已签约
        pageShopDealerApply({applyStatus: 30})  // 已取消
      ]);

      setStatusCounts({
        all: allRes?.count || 0,
        pending: pendingRes?.count || 0,
        signed: signedRes?.count || 0,
        cancelled: cancelledRes?.count || 0
      });
    } catch (error) {
      console.error('获取状态统计失败:', error);
    }
  }, []);

  const getStatusCounts = () => statusCounts;

  // 取消操作
  const handleCancel = (customer: ShopDealerApply) => {
    updateShopDealerApply({
      ...customer,
      applyStatus: 30
    }).then(() => {
      Taro.showToast({
        title: '取消成功',
        icon: 'success'
      });
      fetchCustomerData().then();
      fetchStatusCounts().then();
    })
  };

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

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

  // 渲染客户项
  const renderCustomerItem = (customer: CustomerUser) => (
    <View key={customer.userId} className="bg-white rounded-lg p-4 mb-3 shadow-sm">
      <View className="flex items-center mb-3" onClick={() => navTo(`/dealer/customer/add?id=${customer.applyId}`, true)}>
        <View className="flex-1">
          <View className="flex items-center justify-between mb-1">
            <Text className="font-semibold text-gray-800 mr-2">
              {customer.realName || customer.dealerName || customer.dealerCode}
            </Text>
            {customer.customerStatus && (
              <Tag type={getStatusTagType(customer.customerStatus)}>
                {getStatusText(customer.customerStatus)}
              </Tag>
            )}
          </View>
          <View className="flex items-center mb-1">
            <Space direction="vertical">
              <Text className="text-xs text-gray-500">联系人：{customer.realName}</Text>
              <Text className="text-xs text-gray-500">联系电话：{customer.mobile}<Phone size={12}
                                                                                       className="ml-1 text-green-500"/></Text>
            </Space>
          </View>
          <Text className="text-xs text-gray-500">
            添加时间：{customer.createTime}
          </Text>
        </View>
      </View>

      {/* 跟进中状态显示操作按钮 */}
      {customer.applyStatus === 10 && (
        <Space className="flex justify-end">
          <Button
            size="small"
            onClick={() => navTo(`/dealer/customer/add?id=${customer.applyId}`, true)}
            style={{marginRight: '8px', backgroundColor: '#52c41a', color: 'white'}}
          >
            签约
          </Button>
          <Button
            size="small"
            onClick={() => handleCancel(customer)}
            style={{backgroundColor: '#ff4d4f', color: 'white'}}
          >
            取消
          </Button>
        </Space>
      )}
    </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">

      {/* 顶部Tabs */}
      <View className="bg-white">
        <Tabs
          value={activeTab}
          onChange={(value) => setActiveTab(value as CustomerStatus)}
        >
          {tabList.map(tab => {
            const counts = getStatusCounts();
            const count = counts[tab.value as keyof typeof counts] || 0;
            return (
              <TabPane
                key={tab.value}
                title={`${tab.label}${count > 0 ? `(${count})` : ''}`}
                value={tab.value}
              />
            );
          })}
        </Tabs>
      </View>

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

      <FixedButton text={'客户报备'} onClick={() => Taro.navigateTo({url: '/dealer/customer/add'})}/>
    </View>
  );
};

export default CustomerIndex;
