import {useEffect, useState, useRef} from "react";
import {Loading, CellGroup, Input, Form} from '@nutui/nutui-react-taro'
import {Edit} from '@nutui/icons-react-taro'
import Taro from '@tarojs/taro'
import {useRouter} from '@tarojs/taro'
import {View} from '@tarojs/components'
import FixedButton from "@/components/FixedButton";
import {useUser} from "@/hooks/useUser";
import {ClinicPatientUser} from "@/api/clinic/clinicPatientUser/model";
import {
  addClinicPatientUser,
  getClinicPatientUser,
  updateClinicPatientUser
} from "@/api/clinic/clinicPatientUser";

const AddPatient = () => {
  const {user} = useUser()
  const {params} = useRouter();
  const [loading, setLoading] = useState<boolean>(true)
  const [formData, setFormData] = useState<ClinicPatientUser>()
  const formRef = useRef<any>(null)
  const [isEditMode, setIsEditMode] = useState<boolean>(false)

  console.log('AddPatient Component Rendered');

  const reload = async () => {
    if (!params.id) {
      return false;
    }
    // 查询患者信息
    try {
      const patient = await getClinicPatientUser(Number(params.id));
      if (patient) {
        setFormData(patient)
        setIsEditMode(true);

        Taro.setNavigationBarTitle({title: '编辑患者'})
      }
    } catch (error) {
      setLoading(true)
      console.error('查询患者信息失败:', error);
      setIsEditMode(false);
    }
  }

  // 提交表单
  const submitSucceed = async (values: any) => {
    try {
      // 验证必填字段
      if (!values.phone || values.phone.trim() === '') {
        Taro.showToast({
          title: '请填写联系方式',
          icon: 'error'
        });
        return;
      }

      // 验证手机号格式
      const phoneRegex = /^1[3-9]\d{9}$/;
      if (!phoneRegex.test(values.phone)) {
        Taro.showToast({
          title: '请填写正确的手机号',
          icon: 'error'
        });
        return;
      }

      // 准备提交的数据
      const submitData: ClinicPatientUser = {
        ...values,
        realName: values.realName || user?.nickname,
        phone: values.phone,
      };

      // 调试信息
      console.log('=== 提交数据调试 ===');
      console.log('是否编辑模式:', isEditMode);
      console.log('提交的数据:', submitData);
      console.log('==================');

      // 如果是编辑模式，添加现有患者的id
      if (isEditMode && formData?.id) {
        submitData.id = formData.id;
      }

      // 执行新增或更新操作
      if (isEditMode) {
        await updateClinicPatientUser(submitData);
      } else {
        await addClinicPatientUser(submitData);
      }

      Taro.showToast({
        title: `${isEditMode ? '更新' : '添加'}成功`,
        icon: 'success'
      });

      setTimeout(() => {
        Taro.navigateBack();
      }, 1000);

    } catch (error) {
      console.error('提交失败:', error);
      Taro.showToast({
        title: '提交失败，请重试',
        icon: 'error'
      });
    }
  }

  // 处理固定按钮点击事件
  const handleFixedButtonClick = () => {
    // 触发表单提交
    formRef.current?.submit();
  };

  const submitFailed = (error: any) => {
    console.log(error, 'err...')
  }

  useEffect(() => {
    reload().then(() => {
      setLoading(false)
    })
  }, []); // 依赖用户ID，当用户变化时重新加载

  if (loading) {
    return <Loading className={'px-2'}>加载中</Loading>
  }

  return (
    <>
      <Form
        ref={formRef}
        divider
        initialValues={formData}
        labelPosition="left"
        onFinish={(values) => submitSucceed(values)}
        onFinishFailed={(errors) => submitFailed(errors)}
      >
        <View className={'bg-gray-100 h-3'}></View>
        <CellGroup style={{padding: '4px 0'}}>
          <Form.Item name="realName" label="姓名" initialValue={formData?.realName} required>
            <Input placeholder="请输入患者姓名" />
          </Form.Item>
          <Form.Item name="phone" label="联系方式" initialValue={formData?.phone} required>
            <Input placeholder="请输入手机号" maxLength={11}/>
          </Form.Item>
          <Form.Item name="comments" label="备注" initialValue={formData?.comments}>
            <Input placeholder="请填写备注信息" />
          </Form.Item>
        </CellGroup>
      </Form>

      {/* 底部浮动按钮 */}
      <FixedButton
        icon={<Edit/>}
        text={isEditMode ? '更新患者' : '添加患者'}
        onClick={handleFixedButtonClick}
      />

    </>
  );
};

export default AddPatient;
