import React, {useEffect, useState} from "react";
import {
  Loading,
  Empty,
  Button,
  Input,
  Tag,
  Space,
  Pagination
} from '@nutui/nutui-react-taro'
import {Search, Calendar, Truck, File, AddCircle} from '@nutui/icons-react-taro'
import Taro, {useDidShow} from '@tarojs/taro'
import {pageHjmViolation, removeHjmViolation} from "@/api/hjm/hjmViolation";
import {HjmViolation} from "@/api/hjm/hjmViolation/model";


/**
 * 报险记录列表页面
 */
const List: React.FC = () => {
  const [list, setList] = useState<HjmViolation[]>([])
  const [loading, setLoading] = useState<boolean>(false)
  const [keywords, setKeywords] = useState<string>('')
  const [refreshing, setRefreshing] = useState<boolean>(false)
  const [page, setPage] = useState<number>(1)
  const [limit, setLimit] = useState<number>(10)
  const [total, setTotal] = useState<number>(0)
  const [needRefresh, setNeedRefresh] = useState<boolean>(true)

  console.log(refreshing)
  // 获取状态显示
  const getStatusDisplay = (status?: number) => {
    switch (status) {
      case 0:
        return {text: '未处理', color: '#faad14', bgColor: '#fffbe6'}
      case 1:
        return {text: '已处理', color: '#52c41a', bgColor: '#f6ffed'}
      case 2:
        return {text: '已驳回', color: '#ff4d4f', bgColor: '#fff2f0'}
      default:
        return {text: '未知', color: '#8c8c8c', bgColor: '#f5f5f5'}
    }
  }

  const reload = async (showLoading = true) => {
    setLimit(10)
    try {
      if (showLoading) setLoading(true)
      setRefreshing(true)

      const where: any = {
        keywords: keywords.trim(),
        page,
        limit,
      }

      const roleCode = Taro.getStorageSync('RoleCode');
      if (roleCode == 'kuaidi') {
        if (Taro.getStorageSync('OrganizationParentId') == 0) {
          // @ts-ignore
          where.organizationParentId = Taro.getStorageSync('OrganizationId');
        } else {
          // @ts-ignore
          where.organizationId = Taro.getStorageSync('OrganizationId');
        }
      }
      const res = await pageHjmViolation(where)

      setList(res?.list || [])
      setTotal(res?.count || 0)
    } catch (error) {
      console.error('获取报险记录失败:', error)
      Taro.showToast({
        title: '获取报险记录失败',
        icon: 'error'
      })
    } finally {
      setLoading(false)
      setRefreshing(false)
    }
  }

  const onSearch = () => {
    reload()
  }

  const onKeywordsChange = (value: string) => {
    setKeywords(value)
  }

  const onAddInsurance = () => {
    Taro.navigateTo({
      url: '/hjm/violation/add'
    })
  }

  // 页面显示时触发，包括从其他页面返回
  useDidShow(() => {
    if (needRefresh) {
      reload(false);
      setNeedRefresh(false);
    }
  });

  useEffect(() => {
    // 监听刷新事件
    const handleRefresh = () => {
      setNeedRefresh(true);
    };

    Taro.eventCenter.on('violationListRefresh', handleRefresh);

    // 初始加载数据
    reload().then();

    // 清理事件监听器
    return () => {
      Taro.eventCenter.off('violationListRefresh', handleRefresh);
    };
  }, [page, limit]);

  const onPageChange = (current: number) => {
    setPage(current)
  }

  return (
    <>
      {/* 搜索栏 */}
      <div style={{
        position: 'fixed',
        top: '20px',
        left: 0,
        right: 0,
        display: "none",
        zIndex: 20,
        padding: '0 16px',
        backgroundColor: '#f5f5f5'
      }}>
        <div style={{
          display: 'flex',
          alignItems: 'center',
          backgroundColor: '#fff',
          padding: '8px 12px',
          borderRadius: '20px',
          boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
        }}>
          <Search size={16} color="#999"/>
          <Input
            placeholder="搜索报险记录"
            value={keywords}
            onChange={onKeywordsChange}
            onConfirm={onSearch}
            style={{
              border: 'none',
              backgroundColor: 'transparent',
              flex: 1,
              marginLeft: '8px'
            }}
          />
          <Button
            type="primary"
            size="small"
            onClick={onSearch}
            loading={loading}
          >
            搜索
          </Button>
        </div>
      </div>

      {/* 报险记录列表 */}
      <div style={{
        marginTop: '10px',
        paddingBottom: '80px'
      }}>
        {loading && list.length === 0 ? (
          <div style={{
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            height: '200px'
          }}>
            <Loading type="spinner">加载中...</Loading>
          </div>
        ) : list.length === 0 ? (
          <Empty description="暂无报险记录">
          </Empty>
        ) : (
          <div style={{padding: '0 16px'}}>
            {list.map((item, index) => {
              const statusDisplay = getStatusDisplay(item.status)

              return (
                <div
                  key={index}
                  style={{
                    backgroundColor: '#fff',
                    borderRadius: '12px',
                    padding: '16px',
                    marginBottom: '12px',
                    boxShadow: '0 2px 8px rgba(0,0,0,0.06)',
                    border: '1px solid #f0f0f0'
                  }}
                  onClick={() => {
                    Taro.navigateTo({
                      url: `/hjm/violation/detail?id=${item.code}`
                    })
                  }}
                >
                  <div style={{
                    display: 'flex',
                    justifyContent: 'space-between',
                    alignItems: 'flex-start',
                    marginBottom: '12px'
                  }}>
                    <div style={{flex: 1}}>
                      <div style={{
                        display: 'flex',
                        alignItems: 'center',
                        gap: '8px',
                        marginBottom: '8px'
                      }}>
                        <File size={16} color="#1890ff"/>
                        <span style={{
                          fontSize: '16px',
                          fontWeight: 'bold',
                          color: '#262626'
                        }}>
                          {item.title}
                        </span>
                      </div>

                      <Space direction="vertical">
                        <div style={{
                          display: 'flex',
                          alignItems: 'center',
                          gap: '8px'
                        }}>
                          <Truck size={14} color="#8c8c8c"/>
                          <span style={{fontSize: '13px', color: '#8c8c8c'}}>
                            车辆编号：{item.code}
                          </span>
                        </div>

                        <div style={{
                          display: 'flex',
                          alignItems: 'center',
                          gap: '8px'
                        }}>
                          <Calendar size={14} color="#8c8c8c"/>
                          <span style={{fontSize: '13px', color: '#8c8c8c'}}>
                            创建时间：{item.createTime}
                          </span>
                        </div>
                      </Space>
                    </div>

                    <Tag
                      color={statusDisplay.color}
                      style={{
                        backgroundColor: statusDisplay.bgColor,
                        border: `1px solid ${statusDisplay.color}`,
                        fontSize: '12px'
                      }}
                    >
                      {statusDisplay.text}
                    </Tag>
                  </div>

                  {/* 备注信息 */}
                  {item.comments && (
                    <div style={{
                      backgroundColor: '#f8f9fa',
                      padding: '8px 12px',
                      borderRadius: '6px',
                      fontSize: '13px',
                      color: '#595959',
                      lineHeight: '1.4'
                    }}>
                      {item.comments.length > 50
                        ? `${item.comments.substring(0, 50)}...`
                        : item.comments
                      }
                    </div>
                  )}
                  {item.userId == Taro.getStorageSync('UserId') && (
                    <div className={'flex justify-end mt-4'}>
                      <Space>
                        <Button type="default" onClick={(event: any) => {
                          event.stopPropagation()
                          Taro.navigateTo({
                            url: `/hjm/violation/add?id=${item.id}`
                          })
                        }}>修改</Button>
                        <Button type="primary" onClick={(event: any) => {
                          event.stopPropagation()
                          removeHjmViolation(item.id).then(() => {
                            Taro.showToast({
                              title: '删除成功',
                              icon: 'success'
                            })
                            // 删除成功后重新加载列表
                            reload(false)
                          }).catch((error) => {
                            Taro.showToast({
                              title: error.message || '删除失败',
                              icon: 'error'
                            })
                          })
                        }}>删除</Button>
                      </Space>
                    </div>
                  )}
                </div>
              )
            })}
          </div>
        )}
      </div>

      {
        Taro.getStorageSync('RoleCode') == 'jiaojing' && (
          <div
            style={{
              position: 'fixed',
              bottom: '20px',
              right: '20px',
              zIndex: 30,
              padding: '8px',
              borderRadius: '20px',
              overflow: "hidden",
              backgroundColor: '#ff0000',
            }}>
            <AddCircle size={28} color={'#ffffff'} onClick={onAddInsurance}/>
          </div>
        )
      }

      {/* 分页 */}
      {list.length > 0 && (
        <div style={{
          display: 'flex',
          justifyContent: 'center',
          padding: '20px 0',
          backgroundColor: '#f5f5f5'
        }}>
          <Pagination
            value={page}
            total={total}
            pageSize={limit}
            onChange={onPageChange}
          />
        </div>
      )}
    </>
  )
}

export default List
