import React, {useEffect, useState} from "react";
import {
  Loading,
  Empty,
  Button,
  Input,
  Tag,
  Space
} from '@nutui/nutui-react-taro'
import {Search, Calendar, Truck, File} from '@nutui/icons-react-taro'
import Taro from '@tarojs/taro'
import {UserVerify} from "@/api/system/userVerify/model";
import {pageUserVerify, updateUserVerify} from "@/api/system/userVerify";
import {listUserRole, updateUserRole} from "@/api/system/userRole";
import {listOrganizations} from "@/api/system/organization";
import {useUser} from "@/hooks/useUser";


/**
 * 报险记录列表页面
 */
const UserVerifyAdmin: React.FC = () => {
  const [list, setList] = useState<UserVerify[]>([])
  const [loading, setLoading] = useState<boolean>(false)
  const [keywords, setKeywords] = useState<string>('')
  // const [showTextArea, setShowTextArea] = useState<boolean>(false)
  const [refreshing, setRefreshing] = useState<boolean>(false)
  const {user, fetchUserInfo} = useUser()
  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) => {
    try {
      if (showLoading) setLoading(true)
      setRefreshing(true)

      const where = {
        organizationIds: undefined,
        keywords: keywords.trim(),
      }

      // 如果当前登录用户可管理商户存在，则直接按商户ID过滤
      const normalizeOrganizationIds = (value: any): any[] | undefined => {
        if (value == null) return undefined
        if (Array.isArray(value)) return value
        if (typeof value === 'string') {
          const trimmed = value.trim()
          if (!trimmed) return []
          try {
            const parsed = JSON.parse(trimmed)
            if (Array.isArray(parsed)) return parsed
          } catch (_e) {}
          return trimmed
            .split(',')
            .map(s => s.trim())
            .filter(Boolean)
        }
        return [value]
      }

      let merchants = user?.merchants
      if (merchants == null) {
        const storedUser = Taro.getStorageSync('User')
        if (storedUser) {
          if (typeof storedUser === 'string') {
            try {
              merchants = JSON.parse(storedUser)?.merchants
            } catch (_e) {}
          } else {
            merchants = storedUser?.merchants
          }
        }
      }

      // 本地没有拿到 merchants 时，尝试从接口刷新一次用户信息
      if (merchants == null && user?.userId) {
        const latestUser = await fetchUserInfo()
        merchants = latestUser?.merchants
      }

      // 查询机构列表：如果 merchants 存在，则用 organizationIds=merchants 来查
      const organizationIdsParam = normalizeOrganizationIds(merchants)
      const hasMerchants = Boolean(organizationIdsParam && organizationIdsParam.length > 0)

      const organizations = await listOrganizations(
        hasMerchants
          ? // @ts-ignore
            { organizationIds: organizationIdsParam }
          : { parentId: Taro.getStorageSync('OrganizationId') }
      )

      const organizationIds = organizations.map(item => item.organizationId).filter(Boolean) as any[]
      // 把 merchants/当前机构 也放入数组
      if (hasMerchants) {
        organizationIds.push(...(organizationIdsParam as any[]))
      } else {
        organizationIds.push(Taro.getStorageSync('OrganizationId'))
      }

      // @ts-ignore
      where.organizationIds = Array.from(new Set(organizationIds))

      const res = await pageUserVerify(where)

      setList(res?.list || [])
    } 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 hasRole = (roleCode: string) => {
    if (!user || !user.roles) {
      return false
    }
    return user.roles.some(role => role.roleCode === roleCode)
  }


  const onPass = async (item: UserVerify) => {
    try {
      const role = await listUserRole({roleId: 1701, userId: item.userId})
      const userRole = role[0]

      // 审核通过 - 先更新实名认证状态
      await updateUserVerify({
        ...item,
        status: 1
      })

      // 再更新用户角色（如果存在对应角色）
      if (userRole) {
        await updateUserRole({
          ...userRole,
          roleId: 1738
        })
      }

      Taro.showToast({
        title: '操作成功',
        icon: 'success'
      })
      await reload(false)
    } catch (error: any) {
      console.error('审核通过失败:', error)
      Taro.showToast({
        title: error?.message || '操作失败',
        icon: 'error'
      })
    }
  }

  const onReject = async (item: UserVerify) => {
    try {
      const role = await listUserRole({roleId: 1738, userId: item.userId})
      const userRole = role[0]

      // 审核驳回 - 先恢复用户角色（如果存在）
      if (userRole) {
        userRole.roleId = 1701
        await updateUserRole(userRole)
      }

      await updateUserVerify({
        ...item,
        status: 2
      })

      Taro.showToast({
        title: '操作成功',
        icon: 'success'
      })
      await reload(false)
    } catch (error: any) {
      console.error('审核驳回失败:', error)
      Taro.showToast({
        title: error?.message || '操作失败',
        icon: 'error'
      })
    }
  }

  useEffect(() => {
    if (!user?.userId) return
    reload().then()
  }, [user?.userId])

  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'
                  }}
                >
                  <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.realName}
                        </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.organizationName}
                          </span>
                        </div>

                        <div style={{
                          display: 'flex',
                          alignItems: 'center',
                          gap: '8px'
                        }}>
                          <Truck size={14} color="#8c8c8c"/>
                          <span style={{fontSize: '13px', color: '#8c8c8c'}}>
                            手机号码：{item.phone}
                          </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'
                      }}
                    >
                      {item.statusText || 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>
                  )}
                  {(hasRole('admin') || hasRole('kuaidi') || hasRole('zhandian')) && (
                    <Space className={'pt-4 flex justify-end'}>
                      <Button type="success" onClick={() => onPass(item)}>通过</Button>
                      <Button type="warning" onClick={() => onReject(item)}>驳回</Button>
                    </Space>
                  )}

                  {/*{showTextArea && (*/}
                  {/*  <TextArea*/}
                  {/*    placeholder={'个性签名'}*/}
                  {/*    value={item?.comments}*/}
                  {/*    onChange={(value) => changeComments(value)}*/}
                  {/*  />*/}
                  {/*)}*/}
                </div>
              )
            })}
          </div>
        )}
      </div>
    </>
  )
}

export default UserVerifyAdmin
