import {useEffect, useState, CSSProperties} from "react";
import {Search} from '@nutui/icons-react-taro'
import {Button, Input, InfiniteLoading} from '@nutui/nutui-react-taro'
import {pageHjmViolation} from "@/api/hjm/hjmViolation";
import {HjmViolation} from "@/api/hjm/hjmViolation/model";
import Taro from '@tarojs/taro'
import Items from "./Items";
import {useRouter} from '@tarojs/taro'
import {getUserInfo} from "@/api/layout";
import navTo from "@/utils/common";
import FixedButton from "@/components/FixedButton";

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

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

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

  const loadList = async (isRefresh = false) => {
    if (loading) return;

    setLoading(true)

    // 搜索条件
    const where: any = {
      keywords: keywords.trim(),
      page,
      limit: 10,  // 直接使用10，不通过state
    }

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

    // 判断身份
    const roleCode = Taro.getStorageSync('RoleCode');
    if(roleCode == 'kuaidiyuan'){
      // @ts-ignore
      where.driverId = user.userId;
    }
    if(roleCode == 'zhandian'){
      // @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(roleCode == 'user'){
      setLoading(false)
      return false;
    }
    if(params.id){
      where.code = params.id;
    }

    // 获取车辆列表
    try {
      const res = await pageHjmViolation(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(true);
  }

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

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

  // 页面显示时刷新列表（从添加页返回时触发）
  Taro.useDidShow(() => {
    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="没有更多了"
        >
          <Items data={list}/>
        </InfiniteLoading>
      </div>
      {
        Taro.getStorageSync('RoleCode') == 'jiaojing' && (
          <>
            <FixedButton onClick={() => navTo(`/hjm/violation/add`)} />
          </>
        )
      }
    </>
  )
}
export default ViolationList
