import {useState, useCallback, useRef, useEffect} from "react";
import {Space, Button, Input} from '@nutui/nutui-react-taro'
import {View} from '@tarojs/components';
import OrderList from "./components/OrderList";
import {useRouter} from '@tarojs/taro'
import {ShopOrderParam} from "@/api/shop/shopOrder/model";
import './index.scss'

function ClinicPrescriptionList() {
  const {params} = useRouter();
  const [searchParams, setSearchParams] = useState<ShopOrderParam>({
    statusFilter: params.statusFilter != undefined && params.statusFilter != '' ? parseInt(params.statusFilter) : -1
  })
  const [showSearch] = useState(false)
  const [searchKeyword, setSearchKeyword] = useState('')
  const searchTimeoutRef = useRef<NodeJS.Timeout>()

  const reload = async (where?: ShopOrderParam) => {
    console.log(where,'where...')
    setSearchParams(prev => ({ ...prev, ...where }))
  }

  // 防抖搜索函数
  const debouncedSearch = useCallback((keyword: string) => {
    if (searchTimeoutRef.current) {
      clearTimeout(searchTimeoutRef.current);
    }

    searchTimeoutRef.current = setTimeout(() => {
      if (keyword.trim()) {
        handleSearch({keywords: keyword.trim()});
      } else {
        // 如果搜索关键词为空，清除keywords参数
        const newSearchParams = { ...searchParams };
        delete newSearchParams.keywords;
        setSearchParams(newSearchParams);
        reload(newSearchParams).then();
      }
    }, 500); // 500ms防抖延迟
  }, [searchParams]);

  // 处理搜索
  const handleSearch = (where: ShopOrderParam) => {
    // 合并搜索参数，保留当前的statusFilter
    const newSearchParams = {
      ...searchParams, // 保留当前的所有参数（包括statusFilter）
      ...where // 应用新的搜索条件
    };
    setSearchParams(newSearchParams)
    reload(newSearchParams).then()
  }
  useEffect(() => {
    reload().then()
  }, []);

  return (
    <View className="bg-gray-50 min-h-screen">
      {/* 搜索组件 */}
      {showSearch && (
        <View className="bg-white p-3 shadow-sm border-b border-gray-100">
          <View className="flex items-center">
            <View className="flex-1 mr-2">
              <Input
                placeholder="搜索订单号、商品名称"
                value={searchKeyword}
                onChange={(value) => {
                  setSearchKeyword(value);
                  debouncedSearch(value); // 使用防抖搜索
                }}
                onConfirm={() => {
                  if (searchKeyword.trim()) {
                    handleSearch({keywords: searchKeyword.trim()});
                  }
                }}
                style={{
                  padding: '8px 12px',
                  border: '1px solid #e5e5e5',
                  borderRadius: '4px',
                  backgroundColor: '#f8f9fa'
                }}
              />
            </View>
            <Space>
              <Button
                type="primary"
                onClick={() => {
                  if (searchKeyword.trim()) {
                    handleSearch({keywords: searchKeyword.trim()});
                  }
                }}
              >
                搜索
              </Button>
            </Space>
          </View>
        </View>
      )}

      {/*订单列表*/}
      <OrderList
        onReload={() => reload(searchParams)}
        searchParams={searchParams}
        showSearch={showSearch}
        onSearchParamsChange={(newParams) => {
          console.log('父组件接收到searchParams变化:', newParams);
          setSearchParams(newParams);
        }}
      />
    </View>
  );
}

export default ClinicPrescriptionList;
