<template>
  <div id="topDiv">
    <van-nav-bar
        title="件烟扫描结果"
        left-text=""
        left-arrow
        @click-left="$router.go(-1)"
        class="nav-bar"
    >
      <template #right> ？ </template>
    </van-nav-bar>
  </div>

  <div id="centerDiv">
    <div class="code-info-card">
      <p class="card-title">件码信息</p>
      <div class="code-info-content">
        <p class="info-item">
          <span class="total-count">件码值：</span>
          <span>{{ formatQrCode(data.qrCode) }}</span>
        </p>
        <p class="info-item">
          <span class="total-count">生产时间：</span>
          <span>{{ data.relationTime }}</span>
        </p>
        <p class="info-item">
          <span class="total-count">机台号：</span>
          <span>{{ data.barPieceProductLineDeviceCode }}</span>
        </p>
        <p class="info-item">
          <span class="total-count">总条数：</span>
          <span>{{ data.num }}</span>
        </p>
      </div>
    </div>
    <div class="form-container from">
      <van-field
          v-model="fieldValue"
          is-link
          readonly
          placeholder="选择机台号"
          @click="showPicker = true"
      />
      <van-popup
          v-model:show="showPicker"
          destroy-on-close
          round
          position="bottom"
      >
        <van-picker
            :columns="uniqueNumColumns"
            :model-value="pickerValue"
            @cancel="showPicker = false"
            @confirm="textsch"
        />
      </van-popup>
      <van-button class="Resetbtn" @click="Reset()" type="default">重置</van-button>
    </div>
    <div class="barcode-container">
      <p class="barcode-title">
        <span>条码分布（5×5）</span>
        <span><van-icon name="passed" />{{ currentPage }}/{{ totalPages }}</span>
      </p>
      <div class="contbox">
        <van-icon class="btnleft" name="arrow-left" @click="switchPage(1)" />
        <van-icon class="btnright" name="arrow-left" @click="switchPage(2)" />
        <div class="list-wrapper">
          <div
              class="contboxitem"
              v-for="(item, index) in currentPageList"
              :key="item.BrandId || index"
              :class="{
              'selected-item': fieldValue && item.boxBarProductLineDeviceCode === fieldValue,
              'scanned-item': isScannedItem(item)
            }"
          >
            <p class="item-index">{{ (currentPage - 1) * pageSize + index + 1 }}</p>
            <p class="item-code">{{ formatQrCode(item.qrCode) }}</p>
          </div>
        </div>
      </div>
    </div>
    <div class="btn-container">
      <van-button plain @click="gousearch()" class="query-btn query-btns" type="success">
        <van-icon name="scan" />
        扫码确认
      </van-button>
    </div>
  </div>
</template>

<script>
import {
  NavBar,
  CellGroup,
  Cell,
  List,
  Button,
  Dialog,
  Sticky,
  Col,
  Row,
  Notify,
  Icon,
  Tab,
  Tabs,
  Picker,
  Popup,
  Field,
} from "vant";
import ScanOverlay from "@/components/overlay/scanOverlay/ScanOverlay";
import {getStringByTwo} from "@/utils/transition";
import {queryQrCode, queryQrCodeMap} from "@/api/qrcode/scanCode/scanCode";
export default {
  name: "",
  components: {
    [NavBar.name]: NavBar,
    [CellGroup.name]: CellGroup,
    [Cell.name]: Cell,
    [List.name]: List,
    [Button.name]: Button,
    [Dialog.Component.name]: Dialog.Component,
    [Sticky.name]: Sticky,
    [Col.name]: Col,
    [Row.name]: Row,
    [Icon.name]: Icon,
    [Notify.Component.name]: Notify.Component,
    [Tabs.name]: Tabs,
    [Tab.name]: Tab,
    [Picker.name]: Picker,
    [Popup.name]: Popup,
    [Field.name]: Field,
  },
  mounted() {
    // 扫码回调函数
    this.$nativeQRCode.setCallBackFun((res) => {
      let qrCode = getStringByTwo(res)
      if(!this.scanned){
        this.queryQrCodeMap(qrCode);
      }else {
        this.handleScannedQrCode(qrCode);
      }
    });
    ScanOverlay.show('请扫描二维码')
    // 测试调用：传入固定二维码，实际使用时删除这行
    // this.queryQrCodeMap("HTTPS://T2DC.CN/99.1000.1/AC30938762037000169010280752062202604020016460168A00296L4DUJDGOLTNA38RAN5XBRJ7T");
  },

  data() {
    return {
      currentPage: 1,
      pageSize: 25,
      fieldValue: "",
      pickerValue: "",
      showPicker: false,
      scanned: false,
      scannedCodes: [],  // 新增：存储已扫描的条码
      // 仅保留基础结构，无静态数据
      data: {
        qrCode: "",
        relationTime: "",
        barPieceProductLineDeviceCode: "",
        barPieceProductLineName: "",
        num: "",
        childrenList: [] // 匹配后端返回的字段名
      },
    };
  },
  computed: {
    // 机台号去重，用于选择器（数据源改为 boxBarProductLineDeviceCode）
    uniqueNumColumns() {
      // 先判断 childrenList 是否有数据
      if (!this.data.childrenList || this.data.childrenList.length === 0) {
        return [{ text: "暂无机台号" }]; // 兜底提示，避免选择器为空
      }
      // 过滤掉 boxBarProductLineDeviceCode 为空/undefined 的项，再去重
      const numList = this.data.childrenList
          .map(item => item.boxBarProductLineDeviceCode)
          .filter(code => code && code.trim() !== ""); // 过滤空值
      const uniqueNums = Array.from(new Set(numList));
      // 去重后仍为空，返回兜底提示
      if (uniqueNums.length === 0) {
        return [{ text: "暂无机台号" }];
      }
      return uniqueNums.map(code => ({ text: code }));
    },
    // 总页数
    totalPages() {
      return Math.ceil((this.data.childrenList || []).length / this.pageSize) || 1;
    },
    // 分页逻辑：当前页数据
    currentPageList() {
      const list = this.data.childrenList || [];
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return list.slice(start, end);
    }
  },
  methods: {
    // 核心接口调用：查询件码详情
    queryQrCodeMap(qrCode) {
      if(qrCode!=null&&(qrCode.substring(qrCode.indexOf("AC")+2,qrCode.indexOf("AC")+4)!=30)){
        this.$message.warning('请扫件码');
        return;
      }
      console.log("调用接口查询件码：", qrCode);
      const query = { qrCode: qrCode };
      queryQrCodeMap(query).then(response => {
        if (response.code === 200) {
          const resData = response.data;
          console.log("接口返回完整数据：", resData);
          console.log("接口返回childrenList：", resData.childrenList);
          // 直接替换整个data，强制触发响应式
          this.data = {
            qrCode: resData.qrCode || "",
            relationTime: resData.relationTime || "",
            barPieceProductLineDeviceCode: resData.barPieceProductLineDeviceCode || "",
            barPieceProductLineName: resData.barPieceProductLineName || "",
            num: resData.childrenList.length || "",
            childrenList: resData.childrenList || []
          };
          console.log("赋值后data：", this.data);
          console.log("赋值后childrenList：", this.data.childrenList);
          this.Reset();
        } else {
          Notify({ type: 'danger', message: response.msg || '查询件码失败' });
        }

      }).catch(error => {
        console.error("查询接口异常：", error);
        Notify({type: 'danger', message: '网络异常或服务错误'});
      });
    },
    // 切换分页
    switchPage(page) {
      // 限制页码范围，避免超出
      if (page < 1) page = 1;
      if (page > this.totalPages) page = this.totalPages;
      this.currentPage = page;
    },
    // 选择器确认选中的机台号（修复空值报错）
    textsch(e) {
      this.showPicker = false;
      // 空值保护，避免Cannot read properties of undefined
      if (e && e.text) {
        this.fieldValue = e.text;
      } else {
        this.fieldValue = "";
      }
    },
    // 重置：清空选中、扫码状态
    Reset() {
      this.fieldValue = "";
      this.scanned = false;
      this.scannedCodes = [];  // 清空已扫描的条码
      this.currentPage = 1; // 重置回到第一页
    },
    // 格式化条码：截取后10位，前面拼接...
    formatQrCode(qrCode) {
      if (!qrCode) return "";
      // 截取后10位，前面拼接...
      return `...${qrCode.slice(-4)}`;
    },
    // 扫码确认：校验并标记状态
    gousearch() {
      if (!this.fieldValue) {
        Notify({type: 'warning', message: '请先选择机台号'});
        return;
      }
      this.scanned = true;
      // 显示扫码提示
      ScanOverlay.show('请扫描条码');
      Notify({type: 'success', message: '请扫描条码'});
    },
    // 处理扫描到的条码
    handleScannedQrCode(scannedQrCode) {
      if (!this.scanned) {
        Notify({type: 'warning', message: '请先点击扫码确认按钮'});
        return;
      }
      console.log("扫描到的条码：", scannedQrCode);
      // 检查条码是否属于当前选择的机台号
      const scannedItem = this.data.childrenList.find(item =>
          item.qrCode === scannedQrCode &&
          item.boxBarProductLineDeviceCode === this.fieldValue
      );

      if (!scannedItem) {
        Notify({type: 'warning', message: '条码不属于当前机台号'});
        return;
      }

      // 检查是否已扫描过
      if (!this.scannedCodes.includes(scannedQrCode)) {
        this.scannedCodes.push(scannedQrCode);
        Notify({type: 'success', message: '扫描成功'});
      } else {
        Notify({type: 'warning', message: '条码已扫描'});
      }
    },
    // 判断是否高亮：条码是否在已扫描列表中
    isScannedItem(item) {
      return this.scannedCodes.includes(item.qrCode);
    }
  },
};
</script>

<style scoped>
/* CSS样式保持不变 */
:deep(.van-nav-bar__right) {
  font-size: 0.45rem;
  color: #ffffff;
}

#centerDiv {
  height: 91%;
}

.nav-bar {
  background-color: rgba(0, 105, 83, 1);
}

.total-count {
  color: #979797;
}

.query-btn {
  width: 92%;
  margin: auto;
  display: block;
  border-radius: 0.1rem;
  height: 1.3rem;
  position: fixed;
  bottom: .3rem;
  left: .4rem;
  border: 1px solid #d7d4d8;
}

:deep(.van-field) {
  width: 40%;
  font-size: 0.4rem;
}

.from {
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-sizing: border-box;
  padding: 0 0.25rem;
}

:deep(.van-icon-arrow) {
  font-size: 0.4rem;
  line-height: 0.65rem;
  display: none;
}

.Resetbtn {
  font-size: 0.4rem !important;
  border: none;
  color: #979797;
}

:deep(.van-icon-passed) {
  color: #07C160;
}

.code-info-card {
  width: 95%;
  height: 3.2rem;
  margin: auto;
  margin-top: 0.3rem;
  border-radius: 0.2rem;
  background: #ffffff;
  box-sizing: border-box;
  padding: 0 0.25rem;
}

.card-title {
  font-size: 0.45rem;
  padding-left: 0.4rem;
  padding-top: 0.15rem;
  margin: 0;
}

.code-info-content {
  width: 100%;
  height: 2.3rem;
  display: flex;
  align-items: center;
  font-size: 0.35rem;
  line-height: 1.2rem;
  justify-content: space-between;
  flex-wrap: wrap;
}
.code-info-content .info-item {
  margin-bottom: 8px; /* 增加下边距 */
  line-height: 1.5; /* 增加行高 */
}
.info-item {
  width: 49%;
  height: 50%;
  margin: 0;
}

.form-container {
  width: 95%;
  height: 1.5rem;
  margin: 0.3rem auto;
  border-radius: 0.2rem;
  background: #ffffff;
}

.barcode-container {
  width: 95%;
  margin: auto;
}

.barcode-title {
  font-size: 0.4rem;
  display: flex;
  justify-content: space-between;
  margin-top: 0.2rem;
  margin-bottom: .2rem;
  align-items: center;
  margin: 0;
  margin-bottom: .2rem;
}

.contbox {
  height: 7rem;
  position: relative;
}

.list-wrapper {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
}

.btnleft {
  position: absolute;
  top: 50%;
  z-index: 10;
}

.btnright {
  position: absolute;
  right: 0;
  top: 50%;
  transform: rotate(180deg);
  z-index: 10;
}

.contboxitem {
  width: 18.3%;
  height: 17%;
  background-color: #F0FDF4;
  border-radius: .2rem;
  display: inline-block;
  margin-right: .13rem;
  margin-bottom: .2rem;
  border: 1px solid;
  border-color: #CEF8DD;
}

.contboxitem.selected-item {
  background-color: #FEFCE8 !important;
  border-color: #FCF8D4 !important;
}

.contboxitem.scanned-item {
  background-color: #E0F2FF !important;
  border-color: #94D3FF !important;
}

.list-wrapper .contboxitem:nth-child(5n) {
  margin-right: 0;
}

.item-index {
  font-size: .3rem;
  margin: 0.25rem .35rem 0 1.3rem;
  color: #979797;
}

.item-code {
  font-size: .4rem;
  margin-left: .2rem;
  margin-bottom: 0;
}

.query-btns {
  bottom: 1.2rem;
}
</style>