<template>
  <!-- 盒条件-换货+上报 -->
  <div id="topDiv">
    <van-nav-bar
        title="单据确认"
        left-text=""
        left-arrow
        @click-left="$router.go(-1)"
        style="background-color: rgba(0, 105, 83, 1)"
    >
      <template #right>
        {{ $store.state.user.name }}
      </template>
    </van-nav-bar>
  </div>
  <div class="pinnumwrapbox">
    <div class="pinnumwrap" id="orderDetails">
      <h3 class="mesTitle">单据确认</h3>
      <div class="pinnum">
        <div>
          <div>
            可替换旧烟码数量：<span class="titleOne">{{ qrOrderDetail.length }}条</span>
          </div>
        </div>
        <div>
          <div>替换完成新烟码数量:<span class="titleTwo">{{ replacedSum }}条</span></div>
        </div>
      </div>
      <van-cell-group class="listname">
        <van-cell
            class="listCont"
            v-for="(item,index) in mergedList"
            :key="index">
          <div :style="titleStyle(item)" class="itemtitle">{{ item.brandName }}</div>
          <div :style="titleStyle(item)" class="ContNum">
            <p class="borderBottom" :style="titleStyle(item)">需替换:{{ item.count }}条</p>
            <p style="height: 30px;line-height: 30px;">已替换:{{ item.replaced }}条</p>
          </div>
          <div :style="ToptitleStyle(item)" class="LTtitle">
            <span v-if="false">已处理</span>
            <span v-if="true">待替换</span>
          </div>
        </van-cell>
      </van-cell-group>
    </div>
  </div>

  <van-row id="scrapButton">
    <van-button :class="relevanceButton ? 'btn_enable' : 'btn_disabled'" :disabled="!relevanceButton"
                @click="relevanceSendButton">确认
    </van-button>
  </van-row>
</template>

<script>
import {NavBar, CellGroup, Cell, List, Button, Dialog, Sticky, Col, Row, Notify, RadioGroup, Radio, Field} from "vant";

import {editRecordDetail, recordDetailInfo} from "@/api/qrcode/relation/qrDiscardCode";
import {getStringByTwo} from "@/utils/transition";
import ScanOverlay from "@/components/overlay/scanOverlay/ScanOverlay";
import {QrCodeUtil} from "@/api/qrcode/device/brand/brand";
import {getQrcodeInsByCode} from "@/api/qrcode/relation/qrcodeIns";

export default {
  name: "replaceHandExamine",
  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,
    [RadioGroup.name]: RadioGroup,
    [Radio.name]: Radio,
    [Field.name]: Field,
    [Notify.Component.name]: Notify.Component,
  },
  data() {
    return {
      qrOrderDetail: [],
      mergedList: [],
      replacedSum: 0,
    }
  },
  mounted() {
    this.getRecordDetailInfo();
    this.$nativeQRCode.setCallBackFun((res) => {
      // 通过二维码获取卷烟信息信息
      let qrCode = getStringByTwo(res)
      this.onScanQrCode(qrCode);
    });
    this.$nativeQRCode.setStatusBarColor("#006953", "white");
    // setTimeout(()=>{
    //   this.onScanQrCode("HTTPS://Y2WM.CN/99.1000.1/AC21150711041ZOLDX0WVBQ5WSPCXE6FY1403")
    // },1000)
    // setTimeout(()=>{
    //   this.onScanQrCode("HTTPS://Y2WM.CN/99.1000.1/AC21150711041ZOLDX0WVBQ5WSPCXE6FY1401")
    // },2000)
    // setTimeout(()=>{
    //   this.onScanQrCode("HTTPS://Y2WM.CN/99.1000.1/AC20169250008DUI91R4C89H4J4JD4E6F")
    // },3000)

  },

  computed: {
    // 判断按钮是否能够点击
    relevanceButton() {
      return this.qrOrderDetail.length === this.replacedSum
    }
  },
  methods: {
    // 完成 发送
    relevanceSendButton() {
      ScanOverlay.show('正在确认...')
      editRecordDetail(this.qrOrderDetail).then(res => {
        if (res.code == 200) {
          Notify({type: 'success', message: '确认成功'});
          this.$router.go(-1)
        }
      })
      ScanOverlay.hide()
    },
    // 扫码
    onScanQrCode(qrcode) {
      this.scanning = false;
      ScanOverlay.hide()
      QrCodeUtil({"qrcode": qrcode}).then(res => {
        if (res.code == 500 || res.data.qrBrand == null) {
          Notify({type: 'warning', message: '无法获取到品规'});
          return;
        }
        getQrcodeInsByCode({qrcode}).then(r => {
          this.initQrcodeInfo(r.data);
        })
      })
    },
    // 初始化二维码信息
    initQrcodeInfo(qrcodeInfo) {
      // 进入页面首次扫码
      if (qrcodeInfo.type != '20') {
        Notify({type: 'warning', message: "此功能只支持条码换货", duration: 1500});
        return;
      }
      if (!this.checkDuplicateCode(qrcodeInfo.qrCode)) {
        if (this.qrOrderDetail.length <= this.replacedSum){
          this.showNotification('warning', `超过扫码数量`);
          return
        }
        for (let i = 0; i < this.qrOrderDetail.length; i++) {
          if (this.qrOrderDetail[i].newCode === "" || this.qrOrderDetail[i].newCode == null) {
            if (this.qrOrderDetail[i].brandCode === qrcodeInfo.brandCode) {
              this.qrOrderDetail[i].newCode = qrcodeInfo.qrCode;
              const targetObject = this.mergedList.find(item => item.brandCode === qrcodeInfo.brandCode);
              if (targetObject) {
                targetObject.replaced += 1;  // 增加 count 字段的值
                this.replacedSum += 1;
              }
              Notify({type: 'success', message: `扫入条码为：`+ this.getcode(qrcodeInfo.qrCode)});
              break;
            }
          }
          if ((i+1) === this.qrOrderDetail.length){
            this.showNotification('warning', `卷烟品规不同`);
            return
          }
        }
      }
    },
    // 获取二维码后六位
    getcode(code) {
      //截取二维码后六位
      if (code) {
        return "..." + code.slice(code.length - 10, code.length)
      }
    },
    // 重复扫码判断
    checkDuplicateCode(code) {
      const existingQRCode = this.qrOrderDetail.find(item => item['newCode'] === code);
      if (existingQRCode) {
        this.showNotification('warning', `条烟已存在，重复扫码`);
        return true;
      }
      return false;
    },
    // 显示提示信息
    showNotification(type, message, duration = 1500) {
      Notify({type, message, duration});
    },
    // 获取记录详情
    getRecordDetailInfo() {
      recordDetailInfo({barterId: this.$route.query.id}).then(res => {
        this.qrOrderDetail = res.data;
        // 使用 Map 来存储品牌名称及其数量
        const brandCountMap = new Map();

        // 遍历数据时记录 replaced 状态
        res.data.forEach(item => {
          const brandName = item.brandName;
          const brandCode = item.brandCode;
          const replaced = 0;

          // 更新 Map 中的数量
          brandCountMap.set(brandName, {
            count: (brandCountMap.get(brandName)?.count || 0) + 1,
            brandCode: brandCode,
            replaced: replaced
          });
        });

        // 创建合并后的新列表
        this.mergedList = Array.from(brandCountMap, ([brandName, {count, brandCode, replaced}]) => ({
          brandName,
          brandCode,
          count,
          replaced
        }));
      })
    },
    // 标题样式
    titleStyle(item) {
      return {
        backgroundColor: "#F0D0D0"
      };
    },
    // 标题样式
    ToptitleStyle(item) {
      return {
        backgroundColor: "#9B3333"
      }
    },
  },
}
</script>

<style lang="scss" scoped>
@import "/public/assets/css/styles.scss";

* {
  margin: 0;
  padding: 0;
}

.btn_enable {
  width: 50%;
  text-align: center;
  margin: auto;
  height: 70px;
  background: rgba(33, 143, 120, 0.9);
  border-radius: 30px;
  color: rgba(230, 230, 230, 1);
}
.btn_disabled {
  width: 50%;
  text-align: center;
  margin: auto;
  height: 70px;
  background: #AFD4CC;
  border-radius: 30px;
  color: rgba(230, 230, 230, 1);
}

#scrapButton {
  height: 80px;
  width: 100%;
  position: fixed;
  bottom: 0px;
  padding-top: 15px;
  background: #FFFFFF;
}

.pinnumwrapbox {
  background-color: rgb(255, 255, 255);
  box-sizing: border-box;
  padding-left: 15px;
  padding-right: 15px;
  margin-bottom: 40px;
  height: 13.6rem;
  overflow-y: auto;
}

.pinnumwrap {
  width: 100%;
  background-color: rgb(255, 255, 255);
  padding-left: 15px;
  padding-right: 15px;
  box-sizing: border-box;
}

.listname {
  overflow-y: auto;
}

.listCont {
  font-size: 25px;
  font-weight: 400;
  color: #434343;
  height: 100px;
  line-height: 100px;
  margin-bottom: 10px;
  position: relative;
}

.itemtitle {
  width: 75%;
  padding-left: 20px;
  border-radius: 10px 0 0 10px;
  margin-right: .8%;
  font-weight: 700;
}

.ContNum {
  line-height: 50px;
  width: 25%;
  box-sizing: border-box;
  border-radius: 0 10px 10px 0;
}

.borderBottom {
  border-bottom: 4px solid white;
  height: 50px;
  border-radius: 0 10px 0 0;
}

.LTtitle span {
  font-size: 20px;
}

.LTtitle {
  position: absolute;
  width: 100px;
  height: 30px;
  line-height: 30px;
  border-radius: 10px 0 10px 0;
  color: #FFFFFF;
  text-align: center;
  top: 0;
  box-sizing: border-box;

}
</style>
  