<template>
  <view class="page-container">
    <view class="camera-wrapper">
      <camera mode= "scanCode" device-position="back" flash="off" @scancode="onScanCodeSuccess" @error="onCameraError" style="width: 100%; height: 450rpx;"></camera>
    </view>

    <view class="scan-result-card">
      <view class="card-header">
        <view class="header-left">
          <uni-icons type="scan" size="20" color="#333"></uni-icons>
          <text class="header-title">已扫二维码</text>
        </view>
        <view class="header-actions">
          <view class="count-badge">
            <text>总数：{{ totalCount }}个</text>
          </view>
          <button class="wx-scan-btn" @click="scanWithWeChat">微信扫一扫</button>
        </view>
      </view>

      <scroll-view scroll-y="true" class="code-list-scroll">
        <view class="code-list-grid">
          <view v-if="numberList.length === 0" class="empty-tip">等待扫描...</view>
          <view class="code-item" v-for="(code, index) in numberList" :key="index">
            {{ formatIndex(index + 1) }}.{{ code }}
          </view>
        </view>
      </scroll-view>

      <view class="footer-buttons">
        <button class="btn clear-btn" @click="clearAll">全部清空</button>
        <button class="btn submit-btn" @click="submit">提交</button>
      </view>
    </view>
  </view>
</template>

<script>
import {getQrcodeNum,active ,writeOff} from '@/api/hexiao.js';

export default {
  data() {
    return {
      // 列表初始为空
      codeList: [],
      storeId:0,
      numberList: [],
      // 用于播放提示音
      audioContext: null,
      // 1上货 2是核销
      type:0
    };
  },
  onReady() {
    // 提前创建好音频上下文，提高性能
    // 您需要在 static 目录下放置一个提示音文件，例如 beep.mp3
    this.audioContext = uni.createInnerAudioContext();
    this.audioContext.src = '/static/beep.mp3'; // 请替换为您的提示音文件路径
  },
  onLoad(opt) {
    this.storeId = opt.storeId
    this.type = opt.type
    let title = "";
    if(this.type == 1){
      title = "上货列表"
    }else{
      title = "核销列表"
    }
    uni.setNavigationBarTitle({
      title: title
    });

    // 获取二维码列表
    // this.codeList = this.$store.state.qrCodeList;
  },
  computed: {
    totalCount() {
      return this.codeList.length;
    }
  },
  methods: {
    getCodeNumber(code){

      if (this.codeList.includes(code)) {
        uni.showToast({
          title: '该码已存在',
          icon: 'none'
        });
        return;
      }
      uni.showLoading();
      getQrcodeNum(code,this.type).then(res=>{
        uni.hideLoading();
        if(res.code === 0){
          let data = res.data;
          //检查是否已存在，防止重复添加
          if (this.codeList.includes(code)) {
            uni.showToast({
              title: '该码已存在',
              icon: 'none'
            });
            return;
          }

          // 添加到列表顶部
          this.codeList.unshift(code);
          this.numberList.unshift(data);
          // 给予用户反馈
          this.playBeep();
          uni.vibrateShort();
        }else{
          uni.showToast({
            title: res.msg,
            icon: 'none'
          });
        }
      });

    },
    // 3. 处理相机扫码成功的事件
    onScanCodeSuccess(e) {
      this.processScanResult(e.detail.result);
    },

    // 相机初始化失败
    onCameraError(e) {
      console.log(e.detail);
      uni.showModal({
        title: '相机错误',
        content: '无法启动相机，请检查权限或重启应用',
        showCancel: false
      })
    },

    // 播放提示音
    playBeep() {
      this.audioContext.play();
    },

    // 格式化序号
    formatIndex(num) {
      return num < 10 ? '0' + num : num;
    },

    // 清空事件
    clearAll() {
      if (this.totalCount === 0) return;
      uni.showModal({
        title: '确认',
        content: '您确定要清空所有已扫描的二维码吗？',
        success: (res) => {
          if (res.confirm) {
            this.codeList = [];
            this.numberList = [];
            uni.showToast({ title: '已清空', icon: 'success' });
          }
        }
      });
    },

    // 提交事件
    submit() {
      if (this.totalCount === 0) {
        uni.showToast({ title: '没有可提交的内容', icon: 'none' });
        return;
      }
      console.log('提交的二维码列表:', this.codeList);
      uni.showLoading({ title: '提交中...' });
      let obj = {};
      obj.storeId = this.storeId;
      obj.qrcodeIds = this.codeList;
      if(this.type == 1){
        active(obj).then(res=>{
          uni.hideLoading();
          if(res.code == 0){
            uni.showToast({ title: '操作成功', icon: 'none' });
            this.numberList = []
            this.codeList = [];
            setTimeout(()=>{
              uni.navigateBack();
            },1000)
          }else{
            uni.showToast({ title: res.msg, icon: 'none' });
          }
        })
      }else if(this.type == 2){
        writeOff(obj).then(res=>{
          uni.hideLoading();
          if(res.code == 0){
            uni.showToast({ title: '操作成功', icon: 'none' });
            this.numberList = []
            this.codeList = [];
            uni.navigateBack();
          }else{
            uni.showToast({ title: res.msg, icon: 'none' });
          }
        })
      }
    },
    processScanResult(rawCode) {
      const content = (rawCode || '').trim();
      if (!content) {
        uni.showToast({
          title: '二维码有误',
          icon: 'none'
        });
        return;
      }
      const targetLength = 'abce563011c5347f'.length;
      let code = content;
      const index = code.lastIndexOf('/');
      if (index !== -1) {
        code = code.substring(index + 1);
      }
      if (code.length !== targetLength) {
        uni.showToast({
          title: '二维码有误',
          icon: 'none'
        });
        return;
      }
      this.getCodeNumber(code);
    },

    scanWithWeChat() {
      // #ifdef MP-WEIXIN
      wx.scanCode({
        scanType: ['qrCode'],
        success: (res) => {
          this.processScanResult(res.result || res.path || '');
        },
        fail: () => {
          uni.showToast({
            title: '微信扫一扫失败',
            icon: 'none'
          });
        }
      });
      // #endif
      // #ifndef MP-WEIXIN
      uni.showToast({
        title: '当前环境不支持微信扫一扫',
        icon: 'none'
      });
      // #endif
    }
  }
}
</script>

<style lang="scss" scoped>
/* 1. 页面整体使用flex布局，高度占满屏幕 */
.page-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f6fa;
}

.camera-wrapper {
  // 相机区域高度固定
  height: 450rpx;
}

/* 1. 卡片区域自动撑满剩余空间 */
.scan-result-card {
  flex: 1; /* flex: 1 是关键，让此元素占据所有剩余空间 */
  display: flex; /* 内部也使用flex布局，方便内容区滚动 */
  flex-direction: column;

  background-color: #ffffff;
  margin: 0 20rpx 20rpx 20rpx;
  border-radius: 20rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
  overflow: hidden; /* 防止内容溢出圆角 */
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-bottom: 25rpx;
  border-bottom: 1rpx solid #f0f0f0;
  // 头部高度固定，不参与flex缩放
  flex-shrink: 0;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 15rpx;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 16rpx;
}

.wx-scan-btn {
  margin: 0;
  padding: 0 24rpx;
  height: 60rpx;
  line-height: 60rpx;
  border-radius: 30rpx;
  background-color: #07c160;
  color: #ffffff;
  font-size: 26rpx;
}

.header-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-left: 15rpx;
}

.count-badge {
  background-color: #e3efff;
  color: #409eff;
  font-size: 24rpx;
  padding: 6rpx 15rpx;
  border-radius: 30rpx;
  margin-left: 20rpx;
  font-weight: 500;
}

/* 2. 列表滚动区域 */
.code-list-scroll {
  flex: 1; /* 关键：让滚动区域占据头部和底部之间的所有空间 */
  // height: 0;  // flex布局中的一个常用技巧，确保flex:1正常工作
  padding: 20rpx 0;
  max-height: 300px;
}

.empty-tip {
  text-align: center;
  color: #999;
  padding-top: 100rpx;
}

.code-list-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20rpx 40rpx;
}

.code-item {
  font-size: 28rpx;
  color: #606266;
  word-break: break-all;
}

.footer-buttons {
  display: flex;
  justify-content: space-between;
  gap: 30rpx;
  padding-top: 20rpx;
  border-top: 1rpx solid #f0f0f0;
  // 底部高度固定，不参与flex缩放
  flex-shrink: 0;
}

.btn {
  flex: 1;
  margin: 0;
  font-size: 30rpx;
  border-radius: 40rpx;
  height: 80rpx;
  line-height: 80rpx;
  background-color: #409eff;
  color: #ffffff;
  &::after {
    border: none;
  }
}
</style>
