import {useEffect, useState, useRef} from "react";
import {useRouter} from '@tarojs/taro'
import {
  Loading,
  Button,
  Form,
  Cell,
  Avatar,
  Input,
  Space,
  TextArea
} from '@nutui/nutui-react-taro'
import {ArrowRight} from '@nutui/icons-react-taro'
import {View, Text} from '@tarojs/components'
import Taro from '@tarojs/taro'
import FixedButton from "@/components/FixedButton";
import navTo from "@/utils/common";
import {ClinicPatientUser} from "@/api/clinic/clinicPatientUser/model";
import {ClinicPrescription} from "@/api/clinic/clinicPrescription/model";
import {TenantId} from "@/config/app";
import {getClinicPatientUser} from "@/api/clinic/clinicPatientUser";
import {addClinicOrder} from "@/api/clinic/clinicOrder";

// 图片数据接口
interface UploadedImageData {
  url?: string;
  src?: string;
  name?: string;
  uid?: string;
  message?: string;
  type?: string;
}

const AddClinicOrder = () => {
  const {params} = useRouter();
  const [toUser, setToUser] = useState<ClinicPatientUser>()
  const [loading, setLoading] = useState<boolean>(false)
  const formRef = useRef<any>()
  const [fileList, setFileList] = useState<UploadedImageData[]>([]) // 图片文件列表

  // 患者和处方状态
  const [selectedPatient, setSelectedPatient] = useState<ClinicPatientUser>()
  const [selectedPrescription, setSelectedPrescription] = useState<ClinicPrescription>()

  // 表单数据
  const [formData, setFormData] = useState<ClinicPrescription>({
    userId: undefined,
    doctorId: undefined,
    diagnosis: '',
    treatmentPlan: '',
    orderPrice: '',
    decoctionInstructions: '',
    items: [],
    image: '' // 添加image字段
  })

  // 判断是编辑还是新增模式
  const isEditMode = !!params.id
  const toUserId = params.id ? Number(params.id) : undefined

  const reload = async () => {
    if (toUserId) {
      getClinicPatientUser(Number(toUserId)).then(data => {
        setToUser(data)
      })
    }
  }

  // 设置选中的患者（供其他页面调用）
  // @ts-ignore
  const setSelectedPatientFunc = (patient: ClinicPatientUser) => {
    console.log('设置选中的患者:', patient)
    setToUser(patient)
    setSelectedPatient(patient)
  }

  // 设置选中的处方（供其他页面调用）
  // @ts-ignore
  const setSelectedPrescriptionFunc = (prescription: ClinicPrescription) => {
    setSelectedPrescription(prescription)
  }

  // 处理表单字段变化
  const handleFormChange = (field: string, value: string) => {
    setFormData(prev => ({
      ...prev,
      [field]: value
    }))
  }

  // 选择并上传图片
  const handleChooseImage = () => {
    if (fileList.length >= 5) { // 修正最大图片数量为5
      Taro.showToast({
        title: '最多只能上传5张图片',
        icon: 'none'
      })
      return
    }

    Taro.chooseImage({
      count: 5 - fileList.length, // 剩余可选择的数量
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        console.log('选择图片成功:', res)

        // 逐个上传选中的图片
        res.tempFilePaths.forEach((filePath, index) => {
          uploadSingleImage(filePath, index)
        })
      },
      fail: (err) => {
        console.log('选择图片失败:', err)
        Taro.showToast({
          title: '选择图片失败',
          icon: 'error'
        })
      }
    })
  }

  // 处理文件删除
  const handleFileRemove = (file: any) => {
    console.log('删除文件:', file)
    const newFileList = fileList.filter(f => f.uid !== file.uid)
    setFileList(newFileList)

    // 更新表单数据 - 使用JSON格式存储
    if (newFileList.length === 0) {
      setFormData(prev => ({
        ...prev,
        image: ''
      }))
    } else {
      const imageData: UploadedImageData[] = newFileList.map(f => ({
        url: f.url,
        src: f.url,
        name: f.name,
        uid: f.uid
      }))
      setFormData(prev => ({
        ...prev,
        image: JSON.stringify(imageData)
      }))
    }
  }

  // 上传单张图片
  const uploadSingleImage = (filePath: any, index: number) => {
    Taro.uploadFile({
      url: 'https://server.websoft.top/api/oss/upload',
      filePath: filePath,
      name: 'file',
      header: {
        'content-type': 'multipart/form-data',
        TenantId
      },
      success: (res) => {
        try {
          const data = JSON.parse(res.data);
          console.log('上传成功', data)
          if (data.code === 0 && data.data && data.data.url) {
            // 更新文件列表
            const newFile = {
              name: `图片${Date.now()}_${index}`,
              url: data.data.url,
              status: 'success',
              message: '上传成功',
              type: 'image',
              uid: `${Date.now()}_${index}`,
            }

            setFileList(prev => {
              const newList = [...prev, newFile]
              // 同时更新表单数据 - 使用JSON格式存储
              const imageData: UploadedImageData[] = newList.map(f => ({
                url: f.url,
                name: f.name,
                uid: f.uid
              }))
              setFormData(prevForm => ({
                ...prevForm,
                image: JSON.stringify(imageData)
              }))
              return newList
            })

            Taro.showToast({
              title: '上传成功',
              icon: 'success'
            })
          } else {
            Taro.showToast({
              title: data.message || '上传失败',
              icon: 'error'
            })
          }
        } catch (error) {
          console.error('解析响应失败:', error)
          Taro.showToast({
            title: '上传失败: 数据格式错误',
            icon: 'error'
          })
        }
      },
      fail: (err) => {
        console.log('上传请求失败', err);
        Taro.showToast({
          title: '上传失败: 网络错误',
          icon: 'error'
        })
      }
    })
  }

  // 提交表单 - 修改为跳转到确认页
  const submitSucceed = async (values: any) => {
    try {
      console.log('提交数据:', values)

      // 参数校验
      if (!toUser && !selectedPatient) {
        Taro.showToast({
          title: `请选择发送对象或患者`,
          icon: 'error'
        });
        return false;
      }

      if (!values.diagnosis) {
        Taro.showToast({
          title: `请输入诊断结果`,
          icon: 'error'
        });
        return false;
      }
      if (!values.treatmentPlan) {
        Taro.showToast({
          title: `请输入治疗方案`,
          icon: 'error'
        });
        return false;
      }

      // 构建订单数据
      const orderData = {
        patient: toUser || selectedPatient,
        prescription: selectedPrescription,
        diagnosis: values.diagnosis,
        treatmentPlan: values.treatmentPlan,
        decoctionInstructions: values.decoctionInstructions || formData.decoctionInstructions,
        images: fileList,
        orderPrice: selectedPrescription?.orderPrice || '0.00'
      }

      // 保存到本地存储
      Taro.setStorageSync('tempOrderData', JSON.stringify(orderData))

      console.log('跳转到订单确认页，订单数据:', orderData)

      // 跳转到确认页
      Taro.navigateTo({
        url: '/doctor/orders/confirm'
      })

    } catch (error: any) {
      console.error('数据处理失败:', error);
      Taro.showToast({
        title: `数据处理失败: ${error.message || error || '未知错误'}`,
        icon: 'error'
      });
    }
  }

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

  useEffect(() => {
    reload().then(() => {
      setLoading(false)
    })

    // 设置页面实例的方法，供其他页面调用
    try {
      // @ts-ignore
      if (Taro.getCurrentInstance() && Taro.getCurrentInstance().page) {
        // @ts-ignore
        Taro.getCurrentInstance().page.setSelectedPatient = setSelectedPatientFunc;
        // @ts-ignore
        Taro.getCurrentInstance().page.setSelectedPrescription = setSelectedPrescriptionFunc;
      }
    } catch (error) {
      console.error('设置页面实例方法失败:', error);
    }

    // 从本地存储获取之前选择的患者和处方
    try {
      const storedPatient = Taro.getStorageSync('selectedPatient');
      if (storedPatient) {
        const parsedPatient = JSON.parse(storedPatient);
        setSelectedPatient(parsedPatient);
        Taro.removeStorageSync('selectedPatient');
      }
    } catch (error) {
      console.error('解析存储的患者数据失败:', error);
      Taro.removeStorageSync('selectedPatient');
    }

    try {
      const storedPrescription = Taro.getStorageSync('selectedPrescription');
      if (storedPrescription) {
        const parsedPrescription = JSON.parse(storedPrescription);
        setSelectedPrescription(parsedPrescription);
        Taro.removeStorageSync('selectedPrescription');
      }
    } catch (error) {
      console.error('解析存储的处方数据失败:', error);
      Taro.removeStorageSync('selectedPrescription');
    }
  }, [isEditMode]);

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

  return (
    <>
      {/* 显示已选择的用户（如果有的话） */}
      <Cell title={(
        <View className={'flex items-center'}>
          <Avatar src={toUser?.avatar}/>
          <View className={'ml-2 flex flex-col'}>
            <Text>{toUser?.realName || '请选择'}</Text>
            <Text className={'text-gray-300'}>{toUser?.phone}</Text>
          </View>
        </View>
      )} extra={(
        <ArrowRight color="#cccccc" className={'mt-2'} size={20}/>
      )} onClick={() => navTo(`/doctor/orders/selectPatient`, true)}
      />

      {toUser && (
        <Form
          ref={formRef}
          divider
          initialValues={formData}
          labelPosition={'top'}
          onFinish={(values) => submitSucceed(values)}
          onFinishFailed={(errors) => submitFailed(errors)}
        >
          {/* 基本信息 */}
          <Form.Item
            name="diagnosis"
            label={'诊断结果'}
            required
            rules={[{required: true, message: '请填写诊断结果'}]}
            initialValue={formData.diagnosis}
          >
            <Input placeholder="请输入诊断结果" style={{
              backgroundColor: '#f9f9f9',
              padding: '4px',
            }}/>
          </Form.Item>
          <Form.Item
            name="treatmentPlan"
            label={'治疗方案'}
            required
            rules={[{required: true, message: '请填写治疗方案'}]}
            initialValue={formData.treatmentPlan}
          >
            <TextArea
              value={formData.treatmentPlan}
              onChange={(value) => handleFormChange('treatmentPlan', value)}
              placeholder="请填写治疗方案"
              style={{
                backgroundColor: '#f9f9f9',
                padding: '4px',
              }}
            />
          </Form.Item>
          <Form.Item
            label={'拍照上传'}
            name="image"
            rules={[{message: '请上传照片'}]}
          >
            <View style={{
              display: 'flex',
              flexDirection: 'row',
              flexWrap: 'wrap',
              gap: '8px',
              padding: '0'
            }}>
              {/* 显示已上传的图片 */}
              {fileList.map((file) => (
                <View key={file.uid} style={{
                  position: 'relative',
                  width: '80px',
                  height: '80px',
                  borderRadius: '8px',
                  overflow: 'hidden',
                  border: '1px solid #d9d9d9'
                }}>
                  <img
                    src={file.url}
                    alt={file.name}
                    style={{
                      width: '100%',
                      height: '100%',
                      objectFit: 'cover'
                    }}
                  />
                  <Button
                    size="small"
                    type="default"
                    style={{
                      position: 'absolute',
                      top: '-8px',
                      right: '-8px',
                      width: '20px',
                      height: '20px',
                      borderRadius: '10px',
                      fontSize: '12px',
                      minWidth: '20px',
                      padding: 0,
                      lineHeight: '20px'
                    }}
                    onClick={() => handleFileRemove(file)}
                  >
                    ×
                  </Button>
                </View>
              ))}

              {/* 添加图片按钮 */}
              {fileList.length < 5 && (
                <View
                  onClick={handleChooseImage}
                  style={{
                    width: '80px',
                    height: '80px',
                    borderRadius: '8px',
                    display: 'flex',
                    flexDirection: 'column',
                    alignItems: 'center',
                    justifyContent: 'center',
                    border: '2px dashed #d9d9d9',
                    backgroundColor: '#fafafa',
                    cursor: 'pointer'
                  }}
                >
                  <span style={{fontSize: '20px', color: '#d9d9d9'}}>+</span>
                  <span style={{fontSize: '10px', marginTop: '2px', color: '#666'}}>
                      添加图片
                    </span>
                </View>
              )}
            </View>
            <View className="text-xs text-gray-500">
              可上传病例/舌苔/面相等，已上传{fileList.length}张图片
            </View>
          </Form.Item>
        </Form>
      )}



      {/* 选择处方 */}
      <Cell
        title="选择处方"
        extra={selectedPrescription ? (
          <View className={'flex items-center'}>
            <Text className={'mr-2'}>{selectedPrescription.treatmentPlan || '未知处方'}</Text>
            <ArrowRight color="#cccccc" size={18}/>
          </View>
        ) : (
          <Text className={'text-gray-400'}>请选择处方</Text>
        )}
        onClick={() => navTo(`/doctor/orders/selectPrescription`, true)}
      />
      {/* 药方信息 */}
      {selectedPrescription && (
        <>
          <Cell extra={'药方信息'}>
            <View className={'flex flex-col'}>
              <View className={'py-3'}>RP: {selectedPrescription.prescriptionType === 0 ? '中药' : '西药'} 共{selectedPrescription.items?.length}味、共{selectedPrescription.orderPrice}元</View>
              <Space className={'flex flex-wrap'}>
                {selectedPrescription.items?.map(item => (
                  <Button>{item.medicineName} 105克</Button>
                ))}
              </Space>
            </View>
          </Cell>

          {/* 煎药说明 */}
          <TextArea
            value={formData.decoctionInstructions}
            onChange={(value) => handleFormChange('decoctionInstructions', value)}
            placeholder="请填写用药说明"
            rows={2}
            maxLength={200}
          />
        </>
      )}

      {/* 底部浮动按钮 */}
      <FixedButton text={'下一步：确认订单信息'} onClick={() => formRef.current?.submit()}/>

    </>
  );
};

export default AddClinicOrder;
