import {useState} from "react";
import Taro, {useDidShow} from '@tarojs/taro'
import {Button, Cell, CellGroup, Space, Empty, ConfigProvider, Tag, Popup} from '@nutui/nutui-react-taro'
import {View, Text} from '@tarojs/components'
import {ClinicPrescription} from "@/api/clinic/clinicPrescription/model";
import {
  pageClinicPrescription,
  WxPayResult
} from "@/api/clinic/clinicPrescription";
import {copyText} from "@/utils/common";
import {updateShopOrder} from "@/api/shop/shopOrder";
import {listShopUserAddress} from "@/api/shop/shopUserAddress";
import {ShopUserAddress} from "@/api/shop/shopUserAddress/model";

const ClinicPrescriptionList = () => {
  const [list, setList] = useState<ClinicPrescription[]>([])
  const [loading, setLoading] = useState<boolean>(false)
  const [addressList, setAddressList] = useState<ShopUserAddress[]>([])
  const [addressPopupVisible, setAddressPopupVisible] = useState<boolean>(false)
  const [addressLoading, setAddressLoading] = useState<boolean>(false)
  const [addressSaving, setAddressSaving] = useState<boolean>(false)
  const [selectedAddressId, setSelectedAddressId] = useState<number | null>(null)
  const [pendingOrder, setPendingOrder] = useState<ClinicPrescription | null>(null)

  const reload = () => {
    setLoading(true)
    pageClinicPrescription({
      userId: Taro.getStorageSync('UserId'),
      withDoctor: true,
    })
      .then(data => {
        setList(data?.list || [])
      })
      .catch(() => {
        Taro.showToast({
          title: '获取数据失败',
          icon: 'error'
        });
      })
      .finally(() => {
        setLoading(false)
      })
  }


  const fetchAddressList = async () => {
    try {
      setAddressLoading(true)
      const data = await listShopUserAddress({
        userId: Taro.getStorageSync('UserId')
      })
      const addressData = data || []
      setAddressList(addressData)
      if (addressData.length > 0) {
        setSelectedAddressId(addressData[0].id || null)
      } else {
        setSelectedAddressId(null)
      }
      return addressData
    } catch (error) {
      console.error('加载收货地址失败:', error)
      Taro.showToast({
        title: '加载收货地址失败',
        icon: 'error'
      })
      setAddressList([])
      setSelectedAddressId(null)
      return []
    } finally {
      setAddressLoading(false)
    }
  }

  const closeAddressPopup = () => {
    setAddressPopupVisible(false)
    setPendingOrder(null)
  }

  const formatFullAddress = (address?: ShopUserAddress) => {
    if (!address) return ''
    return address.fullAddress || `${address.province || ''}${address.city || ''}${address.region || ''}${address.address || ''}`
  }

  const ensureAddressBeforePay = async (item: ClinicPrescription) => {
    setPendingOrder(item)
    const addresses = await fetchAddressList()
    if (addresses.length === 0) {
      Taro.showModal({
        title: '暂无收货地址',
        content: '请先添加收货地址后再支付',
        confirmText: '去添加',
        success: (res) => {
          if (res.confirm) {
            Taro.navigateTo({url: '/user/address/index'})
          }
        }
      })
      return
    }
    setAddressPopupVisible(true)
  }

  const handleAddressConfirm = async () => {
    if (!selectedAddressId) {
      Taro.showToast({
        title: '请选择收货地址',
        icon: 'error'
      })
      return
    }
    if (!pendingOrder || !(pendingOrder as any).shopOrder || !(pendingOrder as any).shopOrder.orderId) {
      Taro.showToast({
        title: '订单信息缺失',
        icon: 'error'
      })
      return
    }
    const targetAddress = addressList.find(addr => addr.id === selectedAddressId)
    if (!targetAddress) {
      Taro.showToast({
        title: '地址不存在',
        icon: 'error'
      })
      return
    }
    try {
      setAddressSaving(true)
      await updateShopOrder({
        orderId: (pendingOrder as any).shopOrder.orderId,
        addressId: targetAddress.id,
        realName: targetAddress.name,
        address: formatFullAddress(targetAddress)
      } as any)
      Taro.showToast({
        title: '地址已更新',
        icon: 'success'
      })
      const orderToPay = pendingOrder
      closeAddressPopup()
      await onPay(orderToPay, true)
    } catch (error: any) {
      console.error('更新收货地址失败:', error)
      Taro.showToast({
        title: error?.message || '更新地址失败',
        icon: 'error'
      })
    } finally {
      setAddressSaving(false)
    }
  }

  /**
   * 处理微信支付
   */
  const handleWechatPay = async (result: WxPayResult): Promise<void> => {
    console.log('处理微信支付:', result);

    if (!result) {
      throw new Error('微信支付参数错误');
    }

    try {
      await Taro.requestPayment({
        timeStamp: result.timeStamp,
        nonceStr: result.nonceStr,
        package: result.package,
        signType: result.signType as any,
        paySign: result.paySign,
      });

      console.log('微信支付成功');
    } catch (payError: any) {
      console.error('微信支付失败:', payError);

      // 处理微信支付特定错误
      if (payError.errMsg) {
        if (payError.errMsg.includes('cancel')) {
          throw new Error('用户取消支付');
        } else if (payError.errMsg.includes('fail')) {
          throw new Error('微信支付失败，请重试');
        }
      }

      throw new Error('微信支付失败');
    }
  };

  /**
   * 统一支付入口
   */
  const onPay = async (item: ClinicPrescription | null, skipAddressCheck: boolean = false) => {
    if (!item) {
      Taro.showToast({
        title: '处方信息缺失',
        icon: 'error'
      });
      return;
    }
    if (!item.id) {
      Taro.showToast({
        title: '处方信息缺失',
        icon: 'error'
      });
      return;
    }

    const shopOrder = (item as any).shopOrder
    if (!skipAddressCheck) {
      if (shopOrder && (!shopOrder.addressId || shopOrder.addressId === 0)) {
        await ensureAddressBeforePay(item)
        return
      }
    }

    await Taro.showLoading({title: '支付中...'});

    try {
      // 调用统一支付接口
      // @ts-ignore
      const {data} = await updateShopOrder(
        {
          orderId: shopOrder.orderId,
          makePay: true
        }
      );
      const result = data as WxPayResult;
      console.log('订单创建结果:', result);

      // 调用微信支付
      await handleWechatPay(result);

      // 支付成功
      // console.log('支付成功，订单号:', result.orderNo);

      // await updateClinicPrescription({
      //   id: item.id,
      //   orderNo: result.orderNo,
      //   status: 2
      // })

      Taro.showToast({
        title: '支付成功',
        icon: 'success'
      });

      // 延迟刷新列表
      setTimeout(() => {
        reload();
      }, 2000);

    } catch (error: any) {
      console.error('支付失败:', error);

      // 获取错误信息
      const errorMessage = error.message || '支付失败，请重试';

      Taro.showToast({
        title: errorMessage,
        icon: 'error'
      });
    } finally {
      Taro.hideLoading();
    }
  };

  useDidShow(() => {
    reload()
  });

  if (list.length === 0 && !loading) {
    return (
      <ConfigProvider>
        <View className={'h-full flex flex-col justify-center items-center'} style={{
          height: 'calc(100vh - 300px)',
        }}>
          <Empty
            style={{
              backgroundColor: 'transparent'
            }}
            description="暂无用药订单"
          />
        </View>
      </ConfigProvider>
    )
  }

  return (
    <>
      <View className="p-3">
        {list.map((item) => (
          <CellGroup key={item.id} className="mb-3">
            <Cell
              title={`${item.id}`}
              extra={
                <Tag type={'warning'} className="font-medium">{item?.shopOrder.payStatus == 1 ? '已支付' : '待支付'}</Tag>
              }
              onClick={() => copyText(`${item.orderNo}`)}
            />
            {item.diagnosis && (
              <Cell
                title="开方信息"
                extra={
                  <Text className="text-gray-600 text-sm">
                    {item.diagnosis.length > 20
                      ? `${item.diagnosis.substring(0, 20)}...`
                      : item.diagnosis}
                  </Text>
                }
              />
            )}
            <Cell
              title={'开方医生'}
              extra={
                <Space>
                  <Text className="font-medium">{item.doctorName}</Text>
                </Space>
              }
            />

            <Cell
              title="订单金额"
              extra={
                <Text className="text-red-500 font-medium">
                  ¥{item.orderPrice || '0.00'}
                </Text>
              }
            />
            <Cell
              title="开方时间"
              extra={
                <Text className="text-gray-500 text-xs">
                  {item.createTime}
                </Text>
              }
            />
            <Cell>
              <Space className="w-full justify-end">
                <Button
                  size="small"
                  type="warning"
                  onClick={() => Taro.navigateTo({url: `/clinic/clinicPatientUser/detail?id=${item.id}`})}
                >
                  查看详情
                </Button>
                {item?.shopOrder?.payStatus == 0 && (
                  <Button
                    type={'danger'}
                    size="small"
                    onClick={() => onPay(item)}
                  >
                    去支付
                  </Button>
                )}
              </Space>
            </Cell>
          </CellGroup>
        ))}
      </View>

      <Popup
        visible={addressPopupVisible}
        position="bottom"
        round
        onClose={closeAddressPopup}
      >
        <View className="p-4 bg-white">
          <View className="text-lg font-medium mb-3">请选择收货地址</View>
          {addressLoading ? (
            <View className="text-center text-gray-500 py-6">加载地址中...</View>
          ) : addressList.length === 0 ? (
            <View className="text-center text-gray-500 py-6">暂无收货地址，请先添加</View>
          ) : (
            <View style={{maxHeight: '300px', overflow: 'auto'}}>
              {addressList.map(address => (
                <View
                  key={address.id}
                  className={`border rounded-lg p-3 mb-2 ${selectedAddressId === address.id ? 'border-orange-400 bg-orange-50' : 'border-gray-200'}`}
                  onClick={() => setSelectedAddressId(address.id || null)}
                >
                  <View className="flex justify-between mb-1">
                    <Text className="font-medium">{address.name}</Text>
                    <Text className="text-gray-600">{address.phone}</Text>
                  </View>
                  <Text className="text-gray-500 text-sm">{formatFullAddress(address)}</Text>
                  {address.isDefault && (
                    <Text className="text-orange-500 text-xs mt-1">默认地址</Text>
                  )}
                </View>
              ))}
            </View>
          )}

          <View className="flex gap-3 mt-4">
            <Button
              className="flex-1"
              onClick={() => Taro.navigateTo({url: '/user/address/index'})}
            >
              管理地址
            </Button>
            <Button
              type="primary"
              className="flex-1"
              loading={addressSaving}
              onClick={handleAddressConfirm}
            >
              确定
            </Button>
          </View>
        </View>
      </Popup>
    </>
  )
}

export default ClinicPrescriptionList;
