/**
 * 关台页面底部按钮组件
 */
import { View, Text } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { useState } from 'react'
import { immediateClose, invokeWechatPay } from '../../../api/startDevice'
import { userStore } from '../../../store'
import './FooterButtons.scss'

interface FooterButtonsProps {
  type: 'owner' | 'guest' // owner: 开台人员扫码, guest: 非开台人扫码
  grpSn: string // 设备编码
  operationId: number // 操作记录ID
}

const FooterButtons = ({ type, grpSn, operationId }: FooterButtonsProps) => {
  const [loading, setLoading] = useState(false)

  // 立即关台
  const handleCloseNow = 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 immediateClose(grpSn, openId)

      console.log('关台接口返回:', result)

      // 判断是否需要支付（可能需要补差价）
      if (result.data.payParameters) {
        // 调起微信支付
        try {
          await invokeWechatPay(result.data.payParameters)
          
          // 支付成功
          Taro.showToast({
            title: '关台成功',
            icon: 'success',
            duration: 2000
          })

          // 跳转到订单详情或首页
          setTimeout(() => {
            Taro.switchTab({
              url: '/pages/index/index'
            })
          }, 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.switchTab({
            url: '/pages/index/index'
          })
        }, 2000)
      }
    } catch (error: any) {
      console.error('关台失败:', error)
      // 错误提示由 request 拦截器处理
    } finally {
      setLoading(false)
    }
  }

  // 续费
  const handleRecharge = () => {
    console.log('续费')
    Taro.navigateTo({
      url: `/pageScan/renewFee/index?grpSn=${grpSn}&operationId=${operationId}`
    })
  }

  // 帮他付款关台
  const handlePayForOther = () => {
    console.log('帮他付款关台')
    Taro.showToast({
      title: '功能开发中',
      icon: 'none',
      duration: 2000
    })
  }

  // AA制付款关台
  const handleAAPay = () => {
    console.log('AA制付款关台')
    Taro.showToast({
      title: '功能开发中',
      icon: 'none',
      duration: 2000
    })
  }

  // 邀请球友
  const handleInviteFriend = () => {
    console.log('邀请球友')
    Taro.showToast({
      title: '功能开发中',
      icon: 'none',
      duration: 2000
    })
  }

  // 关灯重开
  const handleTurnOffRestart = () => {
    console.log('关灯重开')
    Taro.navigateTo({
      url: `/pageScan/turnOffRestart/index?grpSn=${grpSn}&operationId=${operationId}`
    })
  }

  return (
    <View className="footer-buttons">
      {type === 'owner' ? (
        <>
          {/* 开台人员扫码 - 图1 */}
          <View className={`primary-button green ${loading ? 'disabled' : ''}`} onClick={handleCloseNow}>
            <Text className="button-text">{loading ? '处理中...' : '立即关台'}</Text>
          </View>
          <View className="primary-button green" onClick={handleRecharge}>
            <Text className="button-text">续费</Text>
          </View>
          <View className="secondary-buttons">
            <View className="secondary-button" onClick={handleInviteFriend}>
              <Text className="secondary-text">邀请球友</Text>
            </View>
            <View className="secondary-button right" onClick={handleTurnOffRestart}>
              <Text className="secondary-text">关灯重开</Text>
            </View>
          </View>
        </>
      ) : (
        <>
          {/* 非开台人扫码 - 图2 */}
          <View className="primary-button green" onClick={handlePayForOther}>
            <Text className="button-text">帮他付款关台</Text>
          </View>
          <View className="primary-button green" onClick={handleAAPay}>
            <Text className="button-text">AA制付款关台</Text>
          </View>
          <View className="secondary-buttons">
            <View className="secondary-button" onClick={handleInviteFriend}>
              <Text className="secondary-text">邀请球友</Text>
            </View>
            <View className="secondary-button right" onClick={handleTurnOffRestart}>
              <Text className="secondary-text">关灯重开</Text>
            </View>
          </View>
        </>
      )}
    </View>
  )
}

export default FooterButtons
