<template>
  <view class="verify-page">
    <!-- 顶部导航 -->
    <view class="top-nav-bar">
      <view class="nav-back" @click="goBack">
        <text class="back-arrow">‹</text>
      </view>
      <view class="nav-title">
        <text class="title-text">扫码核销</text>
      </view>
      <view class="nav-right" @click="goToRecords">
        <text class="records-link">核销记录</text>
      </view>
    </view>

    <!-- 主内容区域 -->
    <scroll-view class="verify-scroll" scroll-y>
      <!-- 扫描区域 -->
      <view class="scan-container">
        <!-- 背景装饰 -->
        <view class="scan-bg-decoration"></view>
        
        <!-- 扫描框 -->
        <view class="scan-frame-container">
          <view class="scan-frame">
            <!-- 四角装饰 -->
            <view class="corner top-left"></view>
            <view class="corner top-right"></view>
            <view class="corner bottom-left"></view>
            <view class="corner bottom-right"></view>
            
            <!-- 扫描线动画 -->
            <view class="scan-line"></view>
          </view>
          
          <!-- 扫描提示文字 -->
          <view class="scan-tip">
            <iconfont name="icon-scan" size="40rpx" color="#fff" propClass="lh-il va-m"></iconfont>
            <text class="tip-text">将票码放入扫描框内</text>
            <text class="tip-sub">自动扫描验证券码</text>
          </view>
        </view>

        <!-- 今日统计 -->
        <view class="today-stats">
          <view class="stat-item">
            <text class="stat-value">{{ todayCount }}</text>
            <text class="stat-label">今日核销</text>
          </view>
          <view class="stat-divider"></view>
          <view class="stat-item">
            <text class="stat-value">{{ totalCount }}</text>
            <text class="stat-label">累计核销</text>
          </view>
        </view>
      </view>

      <!-- 核销员信息 -->
      <view class="verifier-info" v-if="verifierName">
        <view class="verifier-badge">
          <text class="verifier-name">{{ verifierName }}</text>
        </view>
        <text class="verifier-tip">授权核销员</text>
      </view>
    </scroll-view>

    <!-- 底部扫码按钮 -->
    <view class="bottom-action">
      <view class="safe-area-bottom"></view>
      <button class="scan-btn" @click="startScan" :disabled="isScanning">
        <iconfont name="icon-scan" size="40rpx" color="#fff" propClass="lh-il va-m"></iconfont>
        <text class="scan-btn-text">开始扫码核销</text>
      </button>
    </view>

    <!-- 核销结果弹窗 -->
    <view class="result-modal" v-if="showResult" @click="closeResult">
      <view class="result-content" @click.stop>
        <!-- 成功状态 -->
        <block v-if="resultType === 'success'">
          <view class="result-icon-wrap success">
            <text class="result-icon">✓</text>
          </view>
          <text class="result-title success-text">核销成功</text>
          
          <view class="result-detail">
            <view class="detail-row">
              <text class="detail-label">演出</text>
              <text class="detail-value">{{ resultData.goods_name }}</text>
            </view>
            <view class="detail-row">
              <text class="detail-label">场次</text>
              <text class="detail-value">{{ formatSeatInfo(resultData.seat_info) }}</text>
            </view>
            <view class="detail-row">
              <text class="detail-label">观演人</text>
              <text class="detail-value highlight">{{ resultData.real_name }}</text>
            </view>
          </view>

          <view class="result-actions">
            <button class="action-btn primary" @click="continueScan">继续扫码</button>
            <button class="action-btn secondary" @click="goToRecords">查看记录</button>
          </view>
        </block>

        <!-- 失败状态 -->
        <block v-else>
          <view class="result-icon-wrap" :class="resultType">
            <text class="result-icon">{{ resultType === 'used' ? '⚠' : '✕' }}</text>
          </view>
          <text class="result-title" :class="resultType + '-text'">{{ resultMsg }}</text>
          
          <view class="result-tip" v-if="resultType === 'used'">
            <text>该票已被核销，请核实票码</text>
          </view>
          <view class="result-tip" v-else-if="resultType === 'refunded'">
            <text>该票已退款，无法核销</text>
          </view>
          <view class="result-tip" v-else-if="resultType === 'notfound'">
            <text>票码不存在或无效</text>
          </view>
          <view class="result-tip" v-else>
            <text>{{ resultMsg }}</text>
          </view>

          <view class="result-actions single">
            <button class="action-btn primary" @click="closeResult">知道了</button>
          </view>
        </block>
      </view>
    </view>

    <!-- 加载中遮罩 -->
    <view class="loading-mask" v-if="isScanning">
      <view class="loading-content">
        <view class="loading-spinner"></view>
        <text class="loading-text">核销中...</text>
      </view>
    </view>

    <!-- 非核销员提示 -->
    <view class="no-permission-modal" v-if="showNoPermission">
      <view class="modal-content">
        <iconfont name="icon-lock" size="80rpx" color="#999"></iconfont>
        <text class="modal-title">无权核销</text>
        <text class="modal-tip">您不是授权核销员，无法使用此功能</text>
        <button class="modal-btn" @click="goBack">返回</button>
      </view>
    </view>

    <!-- 公共组件 -->
    <component-common ref="common"></component-common>
  </view>
</template>

<script>
const app = getApp();

export default {
  data() {
    return {
      // 核销员信息
      verifierName: '',
      // 统计数据
      todayCount: 0,
      totalCount: 0,
      // 扫描状态
      isScanning: false,
      // 结果弹窗
      showResult: false,
      resultType: '', // success | used | refunded | notfound | error
      resultMsg: '',
      resultData: {},
      // 无权限提示
      showNoPermission: false,
    };
  },

  onLoad(params) {
    // 记录来源
    if (params && params.from) {
      this.sourceFrom = params.from;
    }
    
    // 检查核销员权限
    this.checkVerifierPermission();
    
    // 获取统计数据
    this.fetchStats();
  },

  onShow() {
    // 每次显示时刷新统计数据
    this.fetchStats();
  },

  methods: {
    // 返回上一页
    goBack() {
      const pages = getCurrentPages();
      if (pages.length > 1) {
        uni.navigateBack();
      } else {
        uni.reLaunch({ url: '/pages/index/index' });
      }
    },

    // 跳转到核销记录
    goToRecords() {
      uni.navigateTo({
        url: '/pages/plugins/vr-ticket-wallet/records/index'
      });
    },

    // 检查核销员权限
    checkVerifierPermission() {
      uni.request({
        url: app.globalData.get_request_url('checkVerifier', 'ticket', 'vr_ticket'),
        method: 'GET',
        dataType: 'json',
        success: (res) => {
          if (res.data.code == 0 && res.data.data) {
            var data = res.data.data;
            if (data.is_verifier) {
              this.verifierName = data.verifier_name || '';
              // 权限通过，正常显示页面
            } else {
              this.showNoPermission = true;
            }
          } else if (res.data.code == 401) {
            // 未登录
            app.globalData.get_user_info(this, 'checkVerifierPermission');
          } else {
            this.showNoPermission = true;
          }
        },
        fail: () => {
          // 网络错误，默认可用（生产环境应更严格处理）
          console.log('checkVerifier API failed, assuming permitted');
        }
      });
    },

    // 获取统计数据
    fetchStats() {
      uni.request({
        url: app.globalData.get_request_url('myVerifications', 'ticket', 'vr_ticket'),
        method: 'GET',
        data: { page: 1, page_size: 1 },
        dataType: 'json',
        success: (res) => {
          if (res.data.code == 0) {
            var data = res.data.data || {};
            this.totalCount = data.total || 0;
            // 计算今日核销数（从列表中筛选）
            this.calculateTodayCount(data.list || []);
          }
        },
        fail: () => {
          // 静默失败
        }
      });
    },

    // 计算今日核销数
    calculateTodayCount(list) {
      if (!list || list.length === 0) {
        this.todayCount = 0;
        return;
      }
      
      const today = new Date();
      today.setHours(0, 0, 0, 0);
      const todayStart = today.getTime() / 1000;
      
      // 粗略估算：请求更多数据来统计今日（生产环境建议后端提供专门接口）
      uni.request({
        url: app.globalData.get_request_url('myVerifications', 'ticket', 'vr_ticket'),
        method: 'GET',
        data: { page: 1, page_size: 100 },
        dataType: 'json',
        success: (res) => {
          if (res.data.code == 0) {
            var list = res.data.data.list || [];
            var count = 0;
            list.forEach(item => {
              if (item.created_at >= todayStart) {
                count++;
              }
            });
            this.todayCount = count;
          }
        }
      });
    },

    // 开始扫码
    startScan() {
      var self = this;
      
      // #ifdef H5
      // H5 环境提示使用手机扫码
      app.globalData.showToast('请使用手机端扫码功能');
      return;
      // #endif
      
      uni.scanCode({
        onlyFromCamera: true,
        success: function(res) {
          if (res.result) {
            self.processScanResult(res.result);
          } else {
            app.globalData.showToast('未识别到票码');
          }
        },
        fail: function(err) {
          if (err.errMsg && err.errMsg.indexOf('cancel') !== -1) {
            // 用户取消，不提示
          } else {
            app.globalData.showToast('扫码失败，请重试');
          }
        }
      });
    },

    // 处理扫码结果
    processScanResult(code) {
      // 提取票码（可能包含URL等前缀）
      var ticketCode = this.extractTicketCode(code);
      
      if (!ticketCode) {
        this.showErrorResult('notfound', '无效的票码格式');
        return;
      }

      this.isScanning = true;
      
      uni.request({
        url: app.globalData.get_request_url('verify', 'ticket', 'vr_ticket'),
        method: 'POST',
        data: { ticket_code: ticketCode },
        dataType: 'json',
        success: (res) => {
          this.isScanning = false;
          
          if (res.data.code == 0) {
            // 核销成功
            this.resultType = 'success';
            this.resultData = res.data.data || {};
            this.showResult = true;
            
            // 震动反馈
            uni.vibrateShort();
            
            // 更新统计
            this.todayCount++;
            this.totalCount++;
          } else if (res.data.code == -2) {
            // 已核销
            this.showErrorResult('used', '该票已核销');
            uni.vibrateShort();
          } else if (res.data.code == -3) {
            // 已退款
            this.showErrorResult('refunded', '该票已退款');
            uni.vibrateShort();
          } else if (res.data.code == -4) {
            // QR数据异常
            this.showErrorResult('error', '票码数据异常');
          } else if (res.data.code == -1) {
            // 票码不存在
            this.showErrorResult('notfound', '票码不存在');
          } else if (res.data.code == -403) {
            // 无权限（理论上不应该走到这里）
            this.showErrorResult('error', '您不是授权核销员');
          } else {
            this.showErrorResult('error', res.data.msg || '核销失败');
          }
        },
        fail: () => {
          this.isScanning = false;
          this.showErrorResult('error', '网络错误，请重试');
        }
      });
    },

    // 提取票码
    extractTicketCode(result) {
      if (!result) return '';
      
      // 如果是纯票码（短码或UUID），直接返回
      // 短码: 9位 Base36
      // UUID: 36位带连字符
      var trimmed = result.trim();
      
      // UUID 格式
      var uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
      if (uuidPattern.test(trimmed)) {
        return trimmed;
      }
      
      // 短码格式（8-10位 Base36）
      var shortPattern = /^[0-9a-zA-Z]{8,10}$/;
      if (shortPattern.test(trimmed)) {
        return trimmed;
      }
      
      // 可能是URL，尝试解析
      try {
        // 尝试提取URL参数中的code
        var url = new URL(trimmed);
        var code = url.searchParams.get('code') || url.searchParams.get('ticket_code');
        if (code) return code;
        
        // 尝试从路径提取
        var match = trimmed.match(/\/([0-9a-f-]{20,})\/?$/i) || trimmed.match(/([0-9a-zA-Z]{8,10})$/);
        if (match) return match[1];
      } catch (e) {
        // 不是有效URL，使用原始值
      }
      
      return trimmed;
    },

    // 显示错误结果
    showErrorResult(type, msg) {
      this.resultType = type;
      this.resultMsg = msg;
      this.resultData = {};
      this.showResult = true;
    },

    // 格式化座位信息
    formatSeatInfo(seatInfo) {
      if (!seatInfo) return '';
      var parts = seatInfo.split('|');
      if (parts.length >= 5) {
        return parts[0] + ' ' + parts[1] + ' ' + parts[3] + ' ' + parts[4];
      }
      return seatInfo;
    },

    // 继续扫码
    continueScan() {
      this.showResult = false;
      this.resultData = {};
      this.resultType = '';
      this.resultMsg = '';
      
      // 延迟一下再开始扫码，提升体验
      setTimeout(() => {
        this.startScan();
      }, 300);
    },

    // 关闭结果弹窗
    closeResult() {
      this.showResult = false;
      this.resultData = {};
      this.resultType = '';
      this.resultMsg = '';
    },
  },
};
</script>

<style>
@import './index.css';
</style>
