/**
 * 支付成功页面
 * 显示支付成功信息和后续操作
 */

import Taro, { useRouter } from '@tarojs/taro'
import React, { useState, useEffect } from 'react'
import { View, Text } from '@tarojs/components'
import { useQuery,useMutation } from '@tanstack/react-query'
import { orderClient,userClient } from '@/api'
import { useAuth } from '@/utils/auth'
import { Navbar } from '@/components/ui/navbar'
import { Button } from '@/components/ui/button'
import dayjs from 'dayjs'

interface PaymentSuccessParams {
  orderId: number
  amount: number
  paymentMethod?: string // 支付方式：wechat 或 credit
}

const PaymentSuccessPage = () => {
  // 使用useRouter钩子获取路由参数
  const router = useRouter()
  const params = router.params
  const orderId = params?.orderId ? parseInt(params.orderId) : 0
  const amount = params?.amount ? parseFloat(params.amount) : 0
  const paymentMethod = params?.paymentMethod || 'wechat' // 默认微信支付

  // 引导用户订阅发货通知
  const handleSubscribe = async (): Promise<boolean> => {
    try {
      // // 检查用户是否已经订阅过
      // if (checkHasSubscribed()) {
      //   console.log('用户已订阅过发货通知，跳过引导')
      //   return true
      // }

      // 发货成功通知模板ID
      const templateId = 'T00N0Wq3ECjksXSvPWUBgOUukl1TCE7PhxqeDnFPfso'

      // 先显示一个友好的提示，让用户知道为什么要订阅
      const modalRes = await Taro.showModal({
        title: '订阅发货通知',
        content: '订阅后，当订单发货时您会收到微信通知，方便您及时了解物流状态。',
        confirmText: '立即订阅',
        cancelText: '稍后再说'
      })

      if (modalRes.confirm) {
        // 用户点击确认，调用微信订阅消息API
        try {
          const result = await Taro.requestSubscribeMessage({
            tmplIds: [templateId],
            entityIds:[]
          })

          //console.log('订阅消息结果:', result)

          // 根据用户选择处理结果
          if (result[templateId] === 'accept') {
           // console.log('用户接受了订阅消息')
            Taro.showToast({
              title: '订阅成功，发货时会收到通知',
              icon: 'success',
              duration: 2000
            })
            
            return true
          } else if (result[templateId] === 'reject') {
           // console.log('用户拒绝了订阅消息')
            Taro.showToast({
              title: '已取消订阅',
              icon: 'none',
              duration: 1500
            })
            
            return false
          } else {
           // console.log('用户未做出选择或发生错误')
            // 如果用户没有明确选择，不记录状态，下次再询问
            return false
          }
        } catch (error) {
          console.error('订阅消息失败:', error)
          // 订阅失败不影响主要流程
          return false
        }
      } else {
        console.log('用户选择稍后再说')
        // 用户选择稍后再说，不记录状态，下次再询问
        return false
      }
    } catch (error) {
      console.error('订阅消息引导失败:', error)
      // 引导失败不影响主要流程
      return false
    }
  }


  // 检查参数有效性
  const hasValidParams = orderId > 0 && amount > 0

  // 查询订单详情
  const { data: orderDetail } = useQuery({
    queryKey: ['order', orderId],
    queryFn: async () => {
      if (!orderId) throw new Error('订单ID无效')
      const response = await orderClient[':id'].$get({ param: { id: orderId } })
      if (response.status !== 200) {
        throw new Error('获取订单详情失败')
      }
      const data = await response.json()
      return data
    },
    enabled: hasValidParams
  })

  // 查看订单详情
  const handleViewOrderDetail = () => {
    if (orderId) {
      Taro.redirectTo({
        url: `/pages/order-detail/index?id=${orderId}`
      })
    }
  }

  // 返回首页
  const handleBackToHome = () => {
    Taro.switchTab({
      url: '/pages/index/index'
    })
  }

  // 查看订单列表
  const handleViewOrderList = () => {
    Taro.redirectTo({
      url: '/pages/order-list/index'
    })
  }

  if (!hasValidParams) {
    return (
      <View className="min-h-screen bg-gray-50">
        <Navbar title="支付结果" leftIcon="" />
        <View className="flex flex-col items-center justify-center flex-1">
          <View className="bg-white rounded-2xl p-8 text-center">
            <Text className="text-xl text-red-500 mb-4 block">参数错误</Text>
            <Button onClick={handleBackToHome} className="w-48">
              返回首页
            </Button>
          </View>
        </View>
      </View>
    )
  }

  return (
    <View className="min-h-screen bg-gray-50">
      <Navbar title="支付成功" leftIcon="" />
      <View className="p-5">
      {/* 成功图标 */}
      <View className="flex justify-center mb-6">
        <View className="w-24 h-24 bg-green-500 rounded-full flex items-center justify-center">
          <Text className="text-white text-4xl font-bold">✓</Text>
        </View>
      </View>

      {/* 成功信息 */}
      <View className="bg-white rounded-2xl p-8 mb-5 text-center">
        <Text className="text-2xl font-bold text-green-500 block mb-4">支付成功</Text>
        <Text className="text-3xl font-bold text-orange-500 block mb-2">¥{amount.toFixed(2)}</Text>
        <Text className="text-sm text-gray-600 block">订单支付成功，感谢您的购买</Text>
      </View>

      {/* 订单信息 */}
      <View className="bg-white rounded-2xl p-6 mb-5">
        <View className="flex justify-between items-center py-3 border-b border-gray-100">
          <Text className="text-sm text-gray-600">订单号:</Text>
          <Text className="text-sm text-gray-800">{orderDetail?.orderNo || `ORD${orderId}`}</Text>
        </View>
        <View className="flex justify-between items-center py-3 border-b border-gray-100">
          <Text className="text-sm text-gray-600">支付时间:</Text>
          <Text className="text-sm text-gray-800">
            {orderDetail?.updatedAt
              ? dayjs(orderDetail.updatedAt).format('YYYY-MM-DD HH:mm:ss')
              : dayjs().format('YYYY-MM-DD HH:mm:ss')
            }
          </Text>
        </View>
        <View className="flex justify-between items-center py-3">
          <Text className="text-sm text-gray-600">支付方式:</Text>
          <Text className="text-sm text-gray-800">
            {paymentMethod === 'credit' ? '额度支付' : '微信支付'}
          </Text>
        </View>
      </View>

      {/* 操作按钮 */}
      <View className="space-y-3 mb-5">
        <Button
          onClick={handleViewOrderDetail}
          className="w-full h-12"
          size="lg"
        >
          查看订单详情
        </Button>
        <Button
          onClick={handleViewOrderList}
          className="w-full h-12"
          variant="outline"
          size="lg"
        >
          查看订单列表
        </Button>
        <Button
            onClick={handleSubscribe}
            className="w-full h-12"
            variant="outline"
            size="lg"
          >
            📦 订阅发货通知
          </Button>
      </View>

      {/* 温馨提示 */}
      <View className="bg-white rounded-2xl p-6">
        <Text className="text-sm font-bold text-gray-800 block mb-4">温馨提示</Text>
        <Text className="text-xs text-gray-600 leading-relaxed whitespace-pre-line">
          • 订单详情可在订单列表中查看
          {'\n'}
          • 订阅发货通知后，订单发货时会收到微信提醒
          {'\n'}
          • 如有问题请联系客服
          {'\n'}
          • 感谢您的支持
        </Text>
      </View>
      </View>
    </View>
  )
}

export default PaymentSuccessPage