import {useEffect, useState} from "react";
import {
  Button,
  Cell,
  CellGroup,
  Avatar,
  Tag,
  Image,
  Space
} from '@nutui/nutui-react-taro'
import {Edit} from '@nutui/icons-react-taro'
import {View, Text} from '@tarojs/components'
import Taro from '@tarojs/taro'
import FixedButton from "@/components/FixedButton";
import {ClinicPatientUser} from "@/api/clinic/clinicPatientUser/model";
import {ClinicPrescription} from "@/api/clinic/clinicPrescription/model";
import {addClinicOrder} from "@/api/clinic/clinicOrder";
import './confirm.scss'

// 订单数据接口
interface OrderData {
  patient: ClinicPatientUser;
  prescription?: ClinicPrescription;
  diagnosis: string;
  treatmentPlan: string;
  decoctionInstructions?: string;
  images?: Array<{
    url: string;
    name?: string;
    uid?: string;
  }>;
  orderPrice?: string;
}

const DoctorOrderConfirm = () => {
  const [orderData, setOrderData] = useState<OrderData | null>(null)
  const [loading, setLoading] = useState<boolean>(false)
  const [submitLoading, setSubmitLoading] = useState<boolean>(false)

  // 计算药品总价
  const getMedicinePrice = () => {
    if (!orderData?.prescription?.items) return '0.00'
    const total = orderData.prescription.items.reduce((sum, item) => {
      const price = parseFloat(item.unitPrice || '0')
      const quantity = item.quantity || 1
      return sum + (price * quantity)
    }, 0)
    return total.toFixed(2)
  }

  // 计算服务费（可根据实际业务调整）
  const getServiceFee = () => {
    return '10.00' // 固定服务费10元
  }

  // 计算订单总价
  const getTotalPrice = () => {
    const medicinePrice = parseFloat(getMedicinePrice())
    const serviceFee = parseFloat(getServiceFee())
    return (medicinePrice + serviceFee).toFixed(2)
  }

  // 获取处方类型文本
  const getPrescriptionType = () => {
    if (!orderData?.prescription) return ''
    return orderData.prescription.prescriptionType === 0 ? '中药' : '西药'
  }

  // 返回编辑
  const handleBack = () => {
    Taro.navigateBack()
  }

  // 确认并发送订单
  const handleConfirmOrder = async () => {
    if (!orderData) {
      Taro.showToast({
        title: '订单数据缺失',
        icon: 'error'
      })
      return
    }

    try {
      setSubmitLoading(true)

      // 构建诊所订单数据
      const clinicOrderData = {
        userId: orderData.patient.userId,
        doctorId: Taro.getStorageSync('UserId'), // 当前医生ID
        type: 0, // 订单类型：诊所订单
        title: `${orderData.patient.realName}的处方订单`,
        totalPrice: getTotalPrice(),
        payPrice: getTotalPrice(),
        buyerRemarks: orderData.diagnosis,
        merchantRemarks: orderData.treatmentPlan,
        comments: JSON.stringify({
          diagnosis: orderData.diagnosis,
          treatmentPlan: orderData.treatmentPlan,
          decoctionInstructions: orderData.decoctionInstructions,
          prescriptionId: orderData.prescription?.id,
          images: orderData.images
        }),
        payStatus: '0', // 未付款
        orderStatus: 0, // 待支付
        deliveryStatus: 10, // 未发货
      }

      console.log('提交订单数据:', clinicOrderData)

      // 调用API创建订单
      await addClinicOrder(clinicOrderData)

      // 清除临时数据
      Taro.removeStorageSync('tempOrderData')

      Taro.showToast({
        title: '处方已发送给患者',
        icon: 'success',
        duration: 2000
      })

      setTimeout(() => {
        // 跳转到订单列表
        Taro.redirectTo({
          url: '/doctor/orders/index'
        })
      }, 2000)

    } catch (error: any) {
      console.error('创建订单失败:', error)
      Taro.showToast({
        title: error.message || '发送失败，请重试',
        icon: 'error'
      })
    } finally {
      setSubmitLoading(false)
    }
  }

  useEffect(() => {
    try {
      setLoading(true)

      // 从本地存储获取订单数据
      const tempData = Taro.getStorageSync('tempOrderData')

      if (!tempData) {
        Taro.showToast({
          title: '订单数据缺失，请重新填写',
          icon: 'error'
        })
        setTimeout(() => {
          Taro.navigateBack()
        }, 1500)
        return
      }

      const parsedData = JSON.parse(tempData)
      console.log('订单确认页获取数据:', parsedData)

      setOrderData(parsedData)
    } catch (error) {
      console.error('解析订单数据失败:', error)
      Taro.showToast({
        title: '数据解析失败',
        icon: 'error'
      })
    } finally {
      setLoading(false)
    }
  }, [])

  if (loading || !orderData) {
    return (
      <View className="order-confirm-loading">
        <Text>加载中...</Text>
      </View>
    )
  }

  return (
    <>
      {/* 页面标题提示 */}

      {/* 患者信息 */}
      <CellGroup>
        <View className={'p-3'}>患者信息</View>
        <Cell>
          <Space>
            <Avatar
              src={orderData.patient.avatar}
              size="large"
            />
            <View className="flex flex-col gap-1">
              <Text className="font-medium">{orderData.patient.realName}</Text>
              <Text className="text-gray-500">{orderData.patient.phone}</Text>
              <Space className="patient-extra">
                <Text className="text-gray-500">{orderData.patient.age}岁</Text>
              </Space>
            </View>
          </Space>
        </Cell>
      </CellGroup>

      {/* 诊断信息 */}
      <CellGroup>
        <View className={'p-3'}>诊断信息</View>
        <Cell
          extra={
            <Button
              size="small"
              icon={<Edit size="12"/>}
              onClick={handleBack}
            >
              修改
            </Button>
          }
        >
          <View className="text-gray-500">
            <Text>{orderData.diagnosis}</Text>
          </View>
        </Cell>
        <View className={'p-3'}>治疗方案</View>
        <Cell>
          <View className={'text-gray-500'}>
            <Text>{orderData.treatmentPlan}</Text>
          </View>
        </Cell>
      </CellGroup>

      {/* 处方信息 */}
      {orderData.prescription && (
        <CellGroup>
          <View className={'p-3'}>处方信息</View>
          <Cell>
            <Space>
              <Text className="text-gray-500">
                RP: {getPrescriptionType()}
              </Text>
              <Tag type="success">
                共 {orderData.prescription.items?.length || 0} 味药
              </Tag>
            </Space>
          </Cell>

          {/* 药品列表 */}
          {orderData.prescription.items?.map((item, index) => (
            <Cell key={index}>
              <View className={'flex justify-between w-full text-gray-500'}>
                <Space>
                  <Text className="medicine-name">{item.medicineName}</Text>
                  <Text className="medicine-price">¥{item.unitPrice}</Text>
                  <Text className="medicine-spec">
                    {item.specification || '规格未知'} × {item.quantity || 1}
                  </Text>
                </Space>
                <View className="medicine-sub">
                  <Text className="medicine-subtotal">
                    小计：¥{(parseFloat(item.unitPrice || '0') * (item.quantity || 1)).toFixed(2)}
                  </Text>
                </View>
              </View>
            </Cell>
          ))}

          {/* 煎药说明 */}
          {orderData.decoctionInstructions && (
            <>
              <View className={'p-3'}>煎药说明</View>
              <Cell>
                <Text className={'text-gray-500'}>{orderData.decoctionInstructions}</Text>
              </Cell>
            </>
          )}
        </CellGroup>
      )}

      {/* 上传的图片 */}
      {orderData.images && orderData.images.length > 0 && (
        <CellGroup title="病例图片" className="section-group">
          <Cell>
            <View className="image-gallery">
              {orderData.images.map((image, index) => (
                <View
                  key={image.uid || index}
                  className="image-item"
                  onClick={() => {
                    // 预览图片
                    Taro.previewImage({
                      urls: orderData.images!.map(img => img.url),
                      current: image.url
                    })
                  }}
                >
                  <Image
                    src={image.url}
                    mode="aspectFill"
                    width="100%"
                    height="100%"
                  />
                </View>
              ))}
            </View>
          </Cell>
        </CellGroup>
      )}

      {/* 费用明细 */}
      <CellGroup>
        <View className={'p-3'}>费用明细</View>
        <Cell
          title={<Text className="text-gray-500">药品费用</Text>}
          extra={<Text className="price-text">¥{getMedicinePrice()}</Text>}
        />
        <Cell
          title={<Text className="text-gray-500">服务费</Text>}
          extra={<Text className="price-text">¥{getServiceFee()}</Text>}
        />
        <Cell extra={
          (
            <Space className="total-price-row">
              <Text className="total-label">订单总计</Text>
              <Text className="total-amount">¥{getTotalPrice()}</Text>
            </Space>
          )
        }>
        </Cell>
      </CellGroup>

      {/* 温馨提示 */}
      <CellGroup>
        <View className={'p-3'}>📌 温馨提示</View>
        <View className={'flex flex-col px-3 pb-5 text-gray-500 text-sm'}>
          <Text>• 请仔细核对订单信息</Text>
          <Text>• 处方发送后，患者将收到支付通知</Text>
          <Text>• 患者支付成功后，订单将自动流转至配药环节</Text>
          <Text>• 如需修改处方信息，请点击对应模块的"修改"按钮</Text>
        </View>
      </CellGroup>

      {/* 底部操作按钮 */}
      <FixedButton
        text={submitLoading ? '发送中...' : '确认并发送给患者'}
        icon={<Edit />}
        onClick={handleConfirmOrder}
      />
      <View className="fixed-bottom-bar">
        <View className="bottom-price">
          <Text className="price-label">订单总计：</Text>
          <Text className="price-value">¥{getTotalPrice()}</Text>
        </View>
        <View className="bottom-actions">
          <Button
            size="large"
            fill="outline"
            onClick={handleBack}
            disabled={submitLoading}
          >
            返回修改
          </Button>
          <Button
            type="primary"
            size="large"
            onClick={handleConfirmOrder}
            loading={submitLoading}
            disabled={submitLoading}
            style={{flex: 1}}
          >
            {submitLoading ? '发送中...' : '确认并发送给患者'}
          </Button>
        </View>
      </View>
    </>
  )
}

export default DoctorOrderConfirm
