import {useEffect, useState, CSSProperties} from "react";
import {Search} from '@nutui/icons-react-taro'
import {Button, Input, InfiniteLoading} from '@nutui/nutui-react-taro'
import {pageHjmCar} from "@/api/hjm/hjmCar";
import {HjmCar} from "@/api/hjm/hjmCar/model";
import Taro from '@tarojs/taro'
import './location.scss'
import BestSellers from "./BestSellers";
import {getUserInfo} from "@/api/layout";

const InfiniteUlStyle: CSSProperties = {
  height: '80vh',
  width: '100%',
  padding: '0',
  overflowY: 'auto',
  overflowX: 'hidden',
}

/**
 * 文章终极列表
 * @constructor
 */
const List = () => {
  const [keywords, setKeywords] = useState<string>('')
  const [list, setList] = useState<HjmCar[]>([])
  const [page, setPage] = useState(1)
  const [hasMore, setHasMore] = useState(true)
  const [loading, setLoading] = useState(false)

  const onKeywords = (keywords: string) => {
    setKeywords(keywords)
  }

  const loadList = async (pageNum: number, isRefresh = false) => {
    if (loading) return;

    setLoading(true)
    // 搜索条件
    const where = {status: 1, deleted: 0, keywords, page: pageNum, limit: 10}

    // 读取用户信息
    const user = await getUserInfo();

    // 判断身份
    const roleCode = Taro.getStorageSync('RoleCode');
    if(roleCode == 'kuaidiyuan'){
      // @ts-ignore
      where.driverId = user.userId;
    }
    if(roleCode == 'zhandian' && user.merchants == null){
      // @ts-ignore
      where.organizationId = user.organizationId;
    }
    if(roleCode == 'kuaidi'){
      // @ts-ignore
      where.organizationParentId = user.organizationId;
    }
    if(roleCode == 'Installer'){
      // @ts-ignore
      where.installerId = user.userId;
    }
    if(user.merchants != null){
      // @ts-ignore
      where.organizationIds = user.merchants;
    }
    if(roleCode == 'user'){
      setLoading(false)
      return false;
    }

    // 获取车辆列表
    try {
      const res = await pageHjmCar(where);
      if (res?.list && res?.list.length > 0) {
        if (isRefresh) {
          setList(res.list);
        } else {
          setList(prevList => [...prevList, ...res.list]);
        }
        setHasMore(res.list.length >= 10); // 如果返回的数据少于10条，说明没有更多了
      } else {
        if (isRefresh) {
          setList([]);
        }
        setHasMore(false);
      }
    } catch (error) {
      console.error('获取车辆列表失败:', error);
      if (isRefresh) {
        setList([]);
      }
      setHasMore(false);
    } finally {
      setLoading(false);
    }
  }

  const reload = async () => {
    setPage(1);
    await loadList(1, true);
  }

  const loadMore = async () => {
    if (!hasMore || loading) return;
    const nextPage = page + 1;
    setPage(nextPage);
    await loadList(nextPage);
  }

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

  return (
    <>
      <div className={'fixed z-20 top-5 left-0 w-full'}>
        <div className={'px-4'}>
          <div
            style={{
              display: 'flex',
              alignItems: 'center',
              background: '#fff',
              padding: '0 10px',
              borderRadius: '20px'
            }}
          >
            <Search/>
            <Input
              placeholder="车辆编号"
              value={keywords}
              onChange={onKeywords}
              onConfirm={reload}
            />
            <div
              className={'flex items-center'}
            >
              <Button type="warning" onClick={reload}>
                查询
              </Button>
            </div>
          </div>
        </div>
      </div>
      <div style={InfiniteUlStyle} id="scroll">
        <InfiniteLoading
          target="scroll"
          className={'w-full fixed left-0 top-20'}
          hasMore={hasMore}
          onLoadMore={loadMore}
          loadingText="加载中..."
          loadMoreText="没有更多了"
        >
          <BestSellers data={list}/>
        </InfiniteLoading>
      </div>
    </>
  )
}
export default List
