<template>
  <view class="verify-page">
    
    <barcode 
      ref="barcode"
      class="barcode-view" 
      autostart="true" 
      flash="false" 
      zoom="false"
      frameColor="#FF4767"      scanbarColor="#FF4767"
      @marked="onScanCode">
    </barcode>

    <view class="full-mask"></view>

    <view class="nav-bar" :style="{ paddingTop: statusBarHeight + 'px', height: (statusBarHeight + 44) + 'px' }">
      <view class="back-btn" @tap="goBack">
        <image class="back-icon" src="https://mrrplus.oss-cn-beijing.aliyuncs.com/photo/system/ea671fc8-435e-46fe-ba69-6d728328149a.png"></image>
      </view>
      <text class="nav-title">扫码验券</text>
      <view class="right-placeholder"></view>
    </view>

    <view class="bottom-bar">
      <view class="action-btn" @tap="goToManualVerify">
        <image class="btn-icon" src="https://mrrplus.oss-cn-beijing.aliyuncs.com/photo/system/acb1ead0-d0d7-4db1-b779-7bb1cffa6594.png"></image>
        <text class="btn-text">输入核销码</text>
      </view>
      
      <view class="action-btn" @tap="chooseFromAlbum">
        <image class="btn-icon" src="https://mrrplus.oss-cn-beijing.aliyuncs.com/photo/system/7d6de32b-091d-4103-8138-14ae217e5f47.png"></image>
        <text class="btn-text">相册</text>
      </view>
    </view>

  </view>
</template>

<script>
import request from "@/utils/request";

export default {
  data() {
    return {
      statusBarHeight: 44, // 默认状态栏高度
      isProcessing: false  // 防抖开关
    }
  },
  onLoad() {
    const sysInfo = uni.getSystemInfoSync();
    if(sysInfo.statusBarHeight) {
      this.statusBarHeight = sysInfo.statusBarHeight;
    }
  },
  onShow() {
    // 从失败页退回来时，确保开关打开，并重新唤醒底层的扫码引擎
    this.isProcessing = false;
    if (this.$refs.barcode) {
      this.$refs.barcode.start(); // 重新开始扫描
    }
  },
  methods: {
    goBack() {
      uni.navigateBack();
    },

    // nvue 下 barcode 的回调事件叫 @marked
    onScanCode(e) {
      if (this.isProcessing) return;
      this.isProcessing = true;
      
      // 并且扫码获取的内容在 e.detail.message 里
      const code = e.detail.message;
      this.handleCodeResult(code);
    },

    // 统一处理扫码结果
    handleCodeResult(code) {
      if (!code) {
        this.isProcessing = false;
        return;
      }
      
      uni.showLoading({ title: '查询订单中...' });
      
      request.post('/sj/poster/getOrderByCode', { server_code: code }).then(result => {
        uni.hideLoading();
        
        if (result.code === 200 && result.data) {
          uni.showToast({ title: '扫码成功！', icon: 'none' });
          const orderDataStr = encodeURIComponent(JSON.stringify(result.data));
          uni.navigateTo({
            url: `/pages/shop/verify/verify-order-detail?data=${orderDataStr}`
          });
          // 延迟重置防抖，避免重复扫码跳转
          setTimeout(() => { this.isProcessing = false; }, 1000);
        } else {
          // 失败直接跳 fail 页
          this.isProcessing = false; // 必须马上重置，保证退回该页时能继续扫
          uni.navigateTo({ url: '/pages/shop/verify/verify-fail' });
        }
      }).catch((err) => {
        uni.hideLoading();
        this.isProcessing = false;
        uni.navigateTo({ url: '/pages/shop/verify/verify-fail' });
      });
    },

    // 从相册选择图片并识别二维码
    chooseFromAlbum() {
      uni.chooseImage({
        count: 1,
        sourceType: ['album'], // 仅限相册
        success: (res) => {
          const filePath = res.tempFilePaths[0];
          uni.showLoading({ title: '识别中...' });

          // #ifdef APP-PLUS
          // 调用 App 底层引擎，静默解析本地图片，绝不弹出原生扫码界面
          plus.barcode.scan(
            filePath,
            (type, result) => {
              uni.hideLoading();
              // 成功识别到二维码，直接将内容丢给你的处理逻辑
              this.handleCodeResult(result);
            },
            (error) => {
              uni.hideLoading();
              uni.showToast({ title: '未识别到有效二维码', icon: 'none' });
            }
          );
          // #endif

          // #ifndef APP-PLUS
          // 非 App 环境（比如小程序兜底），才走普通的 scanCode
          uni.hideLoading();
          uni.scanCode({
            success: (scanRes) => {
              this.handleCodeResult(scanRes.result);
            }
          });
          // #endif
        }
      });
    },

    goToManualVerify() {
      uni.navigateTo({ url: '/pages/shop/verify/manual-verify' }); 
    }
  }
};
</script>

<style>
.verify-page {
  flex: 1;
  background-color: #000000;
}

.barcode-view {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.full-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.3);
}

.nav-bar {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  padding-left: 30rpx;
  padding-right: 30rpx;
}

.back-btn {
  width: 60rpx;
  height: 88rpx;
  justify-content: center;
  align-items: flex-start;
}

.back-icon {
  width: 18rpx;
  height: 36rpx;
}

.nav-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #FFFFFF;
}

.right-placeholder {
  width: 60rpx;
}

.bottom-bar {
  position: absolute;
  bottom: 80rpx;
  left: 0;
  right: 0;
  height: 120rpx;
  flex-direction: row;
  align-items: center;
  justify-content: space-around;
}

.action-btn {
  flex-direction: row;
  align-items: center;
  justify-content: center;
  width: 325rpx;
  height: 105rpx;
  background-color: rgba(0, 0, 0, 0.4);
  border-radius: 20rpx;
}

.btn-icon {
  width: 40rpx;
  height: 38rpx;
  margin-right: 16rpx;
}

.btn-text {
  font-weight: 500;
  font-size: 32rpx;
  color: #FFFFFF;
}
</style>