import {useEffect, useState} from "react";
import Taro, {useRouter} from '@tarojs/taro'
import {
  Button,
  TextArea,
  Cell,
  Input,
  Picker
} from '@nutui/nutui-react-taro'
import {addHjmViolation, getHjmViolation, updateHjmViolation} from "@/api/hjm/hjmViolation";
import {HjmViolation} from "@/api/hjm/hjmViolation/model";

/**
 * 添加/编辑违章记录页面
 */
function Add() {
  const {params} = useRouter();
  const [loading, setLoading] = useState<boolean>(false)
  const [lastSubmitTime, setLastSubmitTime] = useState<number>(0) // 最后提交时间
  const [isEditMode, setIsEditMode] = useState<boolean>(false) // 是否为编辑模式
  const [isPickerVisible, setIsPickerVisible] = useState<boolean>(false) // 处理状态选择器可见性
  // 处理状态选项
  const statusOptions = [
    {text: '未处理', value: 0},
    {text: '已处理', value: 1}
  ]
  const [formData, setFormData] = useState<HjmViolation>({
    code: '',
    title: '',
    money: '',
    score: '',
    comments: '',
    status: 0 // 默认为未处理
  })

  // 初始化页面数据
  const initPageData = async () => {
    try {
      // 检查是否为编辑模式
      if (params.id) {
        setIsEditMode(true)
        // 获取违章记录详情
        try {
          const violation = await getHjmViolation(Number(params.id));
          if (violation) {
            setFormData({
              ...violation,
              status: violation.status ?? 0 // 如果没有状态值，默认为0(未处理)
            });
          } else {
            Taro.showToast({
              title: '未找到该违章记录',
              icon: 'none'
            })
          }
        } catch (error) {
          console.error('获取违章记录详情失败:', error)
          Taro.showToast({
            title: '获取违章记录详情失败',
            icon: 'none'
          })
        }
      } else {
        // 新增模式下设置默认状态
        setFormData(prev => ({
          ...prev,
          status: 0
        }))
      }
      setLoading(false)
    } catch (error) {
      console.error('初始化失败:', error)
      Taro.showToast({
        title: '初始化失败',
        icon: 'none'
      })
    }
  }

// 提交表单
  const handleSubmit = async () => {
    // 防止重复提交 - 检查loading状态
    if (loading) {
      Taro.showToast({
        title: '正在提交中，请稍候...',
        icon: 'loading'
      })
      return
    }

    // 防止快速连续点击 - 2秒内不允许重复提交
    const now = Date.now()
    if (now - lastSubmitTime < 2000) {
      Taro.showToast({
        title: '请勿频繁提交',
        icon: 'none'
      })
      return
    }
    setLastSubmitTime(now)

    // 表单验证
    if (!formData.code?.trim()) {
      Taro.showToast({
        title: '请输入车辆编号',
        icon: 'none'
      })
      return
    }

    if (!formData.title?.trim()) {
      Taro.showToast({
        title: '请输入违章标题',
        icon: 'none'
      })
      return
    }

    setLoading(true)

    try {
      if (isEditMode) {
        // 编辑模式 - 更新违章记录
        await updateHjmViolation(formData);
        Taro.showToast({
          title: '更新成功',
          icon: 'success'
        })
        // 通知列表页面刷新
        Taro.eventCenter.trigger('violationListRefresh')
      } else {
        // 新增模式 - 添加违章记录
        await addHjmViolation(formData);
        Taro.showToast({
          title: '提交成功',
          icon: 'success'
        })
        // 通知列表页面刷新
        Taro.eventCenter.trigger('violationListRefresh')
        // 清空表单
        setFormData({
          code: '',
          title: '',
          money: '',
          score: '',
          comments: '',
          status: 0
        })
      }

      setTimeout(() => {
        return Taro.navigateBack()
      }, 1000)
    } catch (error) {
      Taro.showToast({
        title: isEditMode ? '更新失败' : '提交失败',
        icon: 'none'
      })
    } finally {
      setLoading(false)
    }
  }

  // 处理状态选择确认
  const handleStatusConfirm = (_: any[], values: (string | number)[]) => {
    setFormData({
      ...formData,
      status: values[0] as number
    })
    setIsPickerVisible(false)
  }

  useEffect(() => {
    initPageData().then(r => {
      console.log(r, 'rr')
    })
  }, [])

  return (
    <div style={{
      backgroundColor: '#f5f5f5',
      minHeight: '100vh',
      paddingBottom: '80px'
    }}>
      {/* 页面标题 */}
      {/*<div style={{*/}
      {/*  backgroundColor: '#fff',*/}
      {/*  margin: '16px',*/}
      {/*  borderRadius: '12px',*/}
      {/*  padding: '16px',*/}
      {/*  boxShadow: '0 2px 8px rgba(0,0,0,0.06)'*/}
      {/*}}>*/}
      {/*  <div style={{*/}
      {/*    display: 'flex',*/}
      {/*    alignItems: 'center',*/}
      {/*    gap: '8px',*/}
      {/*    marginBottom: '12px'*/}
      {/*  }}>*/}
      {/*    <Truck size={18} color="#1890ff"/>*/}
      {/*    <span style={{fontSize: '16px', fontWeight: 'bold'}}>*/}
      {/*      {isEditMode ? '编辑违章记录' : '添加违章记录'}*/}
      {/*    </span>*/}
      {/*  </div>*/}
      {/*</div>*/}


      {/* 违章信息表单 */}
      <div style={{
        backgroundColor: '#fff',
        margin: '16px 16px 16px',
        borderRadius: '12px',
        overflow: 'hidden'
      }}>
        <div style={{
          padding: '16px',
          borderBottom: '1px solid #f0f0f0'
        }}>
          <span style={{fontSize: '16px', fontWeight: 'bold'}}>
            {isEditMode ? '编辑违章记录' : '添加违章记录'}
          </span>
        </div>
        <Cell.Group>
          <Cell title={'车辆编号'} description={'请填写车辆编号'} extra={
            <Input
              placeholder="YT000001"
              value={formData.code}
              onChange={(value) => setFormData({...formData, code: value})}
              style={{backgroundColor: '#ffffff', borderRadius: '8px'}}
              disabled={isEditMode} // 编辑模式下禁用车辆编号输入
            />
          } style={{padding: '12px 16px'}}>
          </Cell>
          <Cell title="违章项目" description={'逆行|闯红灯|不按规定停车'} extra={
            <Input
              placeholder="不按规定停车"
              value={formData.title}
              onChange={(value) => setFormData({...formData, title: value})}
              style={{backgroundColor: '#ffffff', borderRadius: '8px'}}
            />
          } style={{padding: '12px 16px'}}>

          </Cell>
          <Cell title="违章描述" description="违章描述" extra={
            <TextArea
              placeholder={'XX路1号...'}
              value={formData.comments}
              onChange={(value) => setFormData({...formData, comments: value})}
              style={{backgroundColor: '#ffffff', borderRadius: '8px'}}
            />
          } style={{padding: '12px 16px'}}>

          </Cell>
          <Cell title="处罚金额" extra={
            <Input
              type="number"
              placeholder="200(元)"
              maxLength={3}
              value={formData.money}
              onChange={(value) => setFormData({...formData, money: value})}
              style={{backgroundColor: '#ffffff', borderRadius: '8px'}}
            />
          } style={{padding: '12px 16px'}}>

          </Cell>
          <Cell title="扣分" extra={
            <Input
              type="number"
              maxLength={2}
              placeholder="2(分)"
              value={formData.score}
              onChange={(value) => setFormData({...formData, score: value})}
              style={{backgroundColor: '#ffffff', borderRadius: '8px'}}
            />
          } style={{padding: '12px 16px'}}>

          </Cell>
          {/*<Cell title="处理状态" description={'请选择'} extra={*/}
          {/*  <div style={{*/}
          {/*    display: 'flex',*/}
          {/*    alignItems: 'center',*/}
          {/*    justifyContent: 'flex-end',*/}
          {/*    height: '24px'*/}
          {/*  }}>*/}
          {/*    <span style={{color: '#333', fontSize: '14px'}}>*/}
          {/*      {statusOptions.find(option => option.value === formData.status)?.text || '请选择'}*/}
          {/*    </span>*/}
          {/*  </div>*/}
          {/*} style={{padding: '12px 16px'}} onClick={() => setIsPickerVisible(true)}>*/}
          {/*</Cell>*/}
        </Cell.Group>
      </div>

      {/* 处理状态选择器 */}
      <Picker
        visible={isPickerVisible}
        options={statusOptions}
        value={[formData.status ?? 0]}
        onConfirm={handleStatusConfirm}
        onCancel={() => setIsPickerVisible(false)}
        onClose={() => setIsPickerVisible(false)}
      />

      {/* 提交按钮 */}
      <div style={{
        position: 'fixed',
        bottom: 0,
        left: 0,
        right: 0,
        backgroundColor: '#fff',
        padding: '16px',
        borderTop: '1px solid #f0f0f0'
      }}>
        <Button
          type="primary"
          block
          loading={loading}
          disabled={loading}
          onClick={handleSubmit}
        >
          {loading ? (isEditMode ? '更新中...' : '提交中...') : (isEditMode ? '更新违章记录' : '提交违章记录')}
        </Button>
      </div>
    </div>
  )
}

export default Add
