/**
 * 关台页面
 */
import { View, Text, Image } from '@tarojs/components'
import Taro, { useLoad, useRouter } from '@tarojs/taro'
import { useState } from 'react'
import { observer } from 'mobx-react'
import { ArrowDown } from '@taroify/icons'
import FooterButtons from './components/FooterButtons'
import { tableStore } from '../../store'
import './index.scss'

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

const CloseTable = observer(() => {
  const router = useRouter()
  const { type = 'owner' } = router.params as { type?: 'owner' | 'guest' } // owner: 开台人员, guest: 非开台人
  const [expanded, setExpanded] = useState(false) // 订单详情是否展开
  const [couponExpanded, setCouponExpanded] = useState(false) // 优惠券详情是否展开
  const [priceExpanded, setPriceExpanded] = 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('关台页面加载，类型:', type, '设备编码:', 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 handleToggleExpand = () => {
    setExpanded(!expanded)
  }

  return (
    <View className="close-table-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="order-info-card">
          {/* 顶部：开台方式和详情按钮 */}
          <View className="order-header" onClick={handleToggleExpand}>
            <View className="order-tag">
              <Text className="tag-text">{opInfo?.ctrlTypeDescription || '开台方式'}</Text>
            </View>
            <View className="detail-btn">
              <Text className="detail-text">详情</Text>
              <ArrowDown 
                className={`arrow-icon ${expanded ? 'expanded' : ''}`} 
                size="16px" 
                color="#646566"
              />
            </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>

        {/* 展开的详细信息 */}
        {expanded && (
          <>
            {/* 支付信息卡片 */}
            <View className="info-card">
                <Text className="card-title">支付信息</Text>

                <View className="info-row">
                  <Text className="info-label">在线总支付：</Text>
                  <View className="info-value-box">
                    <Text className="info-desc">{opInfo ? `${opInfo.deposit.toFixed(2)}元` : '0元'}</Text>
                  </View>
                </View>

                <View className="info-row">
                  <Text className="info-label">押金</Text>
                  <Text className="info-value">{opInfo ? `${opInfo.deposit.toFixed(2)}元${opInfo.depositStatus ? `（${opInfo.depositStatus}）` : ''}` : '--'}</Text>
                </View>

                <View className="info-row">
                  <Text className="info-label">订单原价</Text>
                  <Text className="info-value">{opInfo ? `${opInfo.currentAmount.toFixed(2)}元` : '--'}</Text>
                </View>

                {/* 优惠券抵扣 - 可展开 */}
                <View className="info-row expandable" onClick={() => setCouponExpanded(!couponExpanded)}>
                  <Text className="info-label">优惠券抵扣</Text>
                  <View className="info-right">
                    <Text className="info-desc">{opInfo && opInfo.discountAmount > 0 ? '已使用' : '不可用'}</Text>
                    <Text className="info-value">{opInfo && opInfo.discountAmount > 0 ? `-${opInfo.discountAmount.toFixed(2)}元` : '-0.00元'}</Text>
                    <ArrowDown
                      className={`arrow-icon ${couponExpanded ? 'expanded' : ''}`}
                      size="16px"
                      color="#646566"
                    />
                  </View>
                </View>

                {/* 优惠券展开内容 */}
                {couponExpanded && (
                  <View className="expand-content coupon">
                    {opInfo && opInfo.discountAmount > 0
                      ? <Text className="expand-text">优惠金额：{opInfo.discountAmount.toFixed(2)}元</Text>
                      : <Text className="expand-text">暂无优惠券</Text>
                    }
                  </View>
                )}

                <View className="info-row total">
                  <Text className="info-label">待结算：</Text>
                  <Text className="info-value">{opInfo ? `${opInfo.payableAmount.toFixed(2)}元` : '--'}</Text>
                </View>
              </View>

              {/* 开台信息卡片 */}
              <View className="info-card">
                <Text className="card-title">开台信息</Text>

                <View className="info-row">
                  <Text className="info-label">门店信息</Text>
                  <Text className="info-value">{scanInfo?.shopName || '--'}</Text>
                </View>

                <View className="info-row">
                  <Text className="info-label">桌台信息</Text>
                  <Text className="info-value">{scanInfo?.tableInfo?.name || '--'}</Text>
                </View>

                <View className="info-row">
                  <Text className="info-label">开始时间</Text>
                  <Text className="info-value">{opInfo?.startTime || '--'}</Text>
                </View>

                <View className="info-row">
                  <Text className="info-label">使用时长</Text>
                  <Text className="info-value">{opInfo?.usedTime || '--'}</Text>
                </View>

                <View className="info-row">
                  <Text className="info-label">订单编号</Text>
                  <Text className="info-value">{opInfo?.orderNo || '--'}</Text>
                </View>

                {/* 收费标准 - 可展开 */}
                <View className="info-row expandable" onClick={() => setPriceExpanded(!priceExpanded)}>
                  <Text className="info-label">收费标准</Text>
                  <View className="info-right">
                    <Text className="info-value">{priceInfo ? `${priceInfo.currentPrice.toFixed(2)}元/小时` : '--'}</Text>
                    <ArrowDown 
                      className={`arrow-icon ${priceExpanded ? 'expanded' : ''}`}
                      size="16px"
                      color="#646566"
                    />
                  </View>
                </View>

                {/* 收费标准展开内容 */}
                {priceExpanded && (
                  <View className="expand-content">
                    {priceInfo?.descript && <Text className="expand-text">{priceInfo.descript}</Text>}
                    {priceInfo?.timePrices?.map((tp, i) => (
                      <Text key={i} className="expand-text">• {tp.startTime}-{tp.endTime}  {tp.description || `${tp.price}元/小时`}</Text>
                    ))}
                  </View>
                )}

                <View className="info-row">
                  <Text className="info-label">支付方式</Text>
                  <Text className="info-value">{opInfo?.payTypeDescription || '--'}</Text>
                </View>
              </View>
            </>
          )}
      </View>

      {/* 底部按钮区域 */}
      <FooterButtons type={type} grpSn={grpSn} operationId={operationId} />
    </View>
  )
})

export default CloseTable
