/**
 * 关灯重开页面
 */
import { View, Text, Image } from '@tarojs/components'
import Taro, { useLoad, useRouter } from '@tarojs/taro'
import { useState } from 'react'
import { observer } from 'mobx-react'
import { turnOffRestart, invokeWechatPay } from '../../api/startDevice'
import { userStore, tableStore } from '../../store'
import './index.scss'

// 使用本地图片资源
const phoneIcon = require('../startTable/images/phone.png')
const locationIcon = require('../../assets/icon/locationIcon.png')

const TurnOffRestart = observer(() => {
  const router = useRouter()
  const [loading, setLoading] = useState(false) // 加载状态

  // 从路由参数获取设备信息和操作记录ID，如果没有则从 store 获取
  const grpSn = tableStore.getGrpSn(router.params.grpSn)
  const operationId = tableStore.getOperationId(Number(router.params.operationId))

  const scanInfo = tableStore.scanInfo
  const opInfo = scanInfo?.opInfo
  const priceInfo = scanInfo?.price

  useLoad(() => {
    console.log('关灯重开页面加载, 设备编码:', grpSn, '操作记录ID:', operationId)
    if (grpSn) tableStore.setCurrentGrpSn(grpSn)
    if (operationId) tableStore.setCurrentOperationId(operationId)
  })

  // 拨打电话
  const handlePhoneCall = () => {
    Taro.makePhoneCall({
      phoneNumber: '100-666-XXXX',
    }).catch((err) => {
      console.error('拨打电话失败:', err)
    })
  }

  // 确认结算
  const handleConfirmSettle = async () => {
    if (loading) return
    
    // 获取用户 openId
    const openId = userStore.userInfo?.wxOpenId || Taro.getStorageSync('openId')
    if (!openId) {
      Taro.showToast({
        title: '请先登录',
        icon: 'none',
        duration: 2000
      })
      return
    }

    if (!grpSn) {
      Taro.showToast({
        title: '设备信息异常',
        icon: 'none',
        duration: 2000
      })
      return
    }

    // 确认结算
    const confirmResult = await Taro.showModal({
      title: '确认结算',
      content: '结算本次消费金额，押金于最后关台时结算。确定要继续吗？',
      confirmText: '确定',
      cancelText: '取消'
    })

    if (!confirmResult.confirm) {
      return
    }

    setLoading(true)
    
    try {
      console.log('关灯重开，设备编码:', grpSn, '操作记录ID:', operationId)

      // 调用关灯重开接口
      const result = await turnOffRestart(grpSn, openId)

      console.log('关灯重开接口返回:', result)

      // 判断是否需要支付
      if (result.data.paymentResponseDto?.payParameters) {
        // 调起微信支付
        try {
          await invokeWechatPay(result.data.paymentResponseDto.payParameters)
          
          // 支付成功
          Taro.showToast({
            title: '结算成功',
            icon: 'success',
            duration: 2000
          })

          // 返回关台页面或跳转到首页
          setTimeout(() => {
            Taro.navigateBack()
          }, 2000)
        } catch (payError: any) {
          console.log('支付错误:', payError)
          // 用户取消支付或支付失败
          if (payError.errMsg?.includes('cancel')) {
            Taro.showToast({
              title: '已取消支付',
              icon: 'none',
              duration: 2000
            })
          } else {
            Taro.showToast({
              title: payError.errMsg || '支付失败',
              icon: 'none',
              duration: 2000
            })
          }
        }
      } else {
        // 无需支付
        Taro.showToast({
          title: '结算成功',
          icon: 'success',
          duration: 2000
        })

        setTimeout(() => {
          Taro.navigateBack()
        }, 2000)
      }
    } catch (error: any) {
      console.error('关灯重开失败:', error)
      // 错误提示由 request 拦截器处理
    } finally {
      setLoading(false)
    }
  }

  return (
    <View className="turn-off-restart-page">
      {/* 内容区域 */}
      <View className="content-area">
        {/* 台球桌信息卡片 */}
        <View className="table-card">
          {/* 顶部：类型和店名 */}
          <View className="card-header">
            <Text className="table-type">中式台球</Text>
            <View className="phone-box" onClick={handlePhoneCall}>
              <Image className="phone-icon" src={phoneIcon} mode="aspectFit" />
              <Text className="phone-text">联系店长</Text>
            </View>
          </View>

          {/* 台球桌标题和使用状态 */}
          <View className="table-title-row">
            <Text className="table-title">{scanInfo?.tableInfo?.name || '--'}</Text>
            <Text className="table-status">{scanInfo?.tableInfo?.statusDescription || '使用中...'}</Text>
          </View>

          {/* 位置信息 */}
          <View className="location-info">
            <Image className="location-icon" src={locationIcon} mode="aspectFit" />
            <Text className="location-text">{scanInfo?.shopName || '--'}</Text>
          </View>
        </View>

        {/* 温馨提示 */}
        <View className="tip-card">
          <Text className="tip-label">温馨提示：</Text>
          <Text className="tip-text">结算本次消费金额，押金于最后关台时结算。</Text>
        </View>

        {/* 开台订单信息卡片 */}
        <View className="order-info-card">
          {/* 开台方式标签 */}
          <View className="order-header">
            <View className="order-tag">
              <Text className="tag-text">开台方式</Text>
            </View>
          </View>

          {/* 订单统计 */}
          <View className="order-stats">
            <View className="stat-item">
              <Text className="stat-value">{opInfo?.usedTime || '--'}</Text>
              <Text className="stat-label">消费时长</Text>
            </View>
            <View className="stat-item">
              <Text className="stat-value">{opInfo ? `${opInfo.currentAmount.toFixed(2)}元` : '--'}</Text>
              <Text className="stat-label">消费金额</Text>
            </View>
          </View>

          {/* 收费规则 */}
          <View className="pricing-rules">
            <View className="rules-content">
              <Text className="rules-title">收费规则</Text>
              <View className="price-row">
                <View className="price-item">
                  <Text className="price-label">价格：</Text>
                  <Text className="price-value">{priceInfo ? `${priceInfo.standard.toFixed(2)}元/小时` : '--'}</Text>
                </View>
                {priceInfo && priceInfo.memberPrice > 0 && (
                  <View className="price-item">
                    <Text className="price-label">折扣价：</Text>
                    <Text className="price-value">{priceInfo.memberPrice.toFixed(2)}元/小时</Text>
                  </View>
                )}
              </View>
            </View>
          </View>
        </View>
      </View>

      {/* 底部固定区域 */}
      <View className="footer-bar">
        <View className={`confirm-btn ${loading ? 'disabled' : ''}`} onClick={handleConfirmSettle}>
          <Text className="confirm-text">{loading ? '处理中...' : '确认结算'}</Text>
        </View>
      </View>
    </View>
  )
})

export default TurnOffRestart
