<template>
  <!-- 盒条件-无码烟换货-->
  <div id="topDiv">
    <van-nav-bar
        :title="$route.meta.name"
        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>
    <van-cell-group class="cell-flexA">
      <van-cell :title="title" :value="value"/>
      <van-cell title="卷烟信息" :value="qrBrand.cgtName"/>
    </van-cell-group>
    <van-cell-group class="cell-flex-1-3 cell-flex-1-3_1">
      <van-cell
          v-for="(item, index) in combinedList"
          :key="index"
          :value="item.new"
      />
    </van-cell-group>

    <van-dialog v-model:show="show" title="请选择换货模式" @cancel="cancelbtn()" @confirm="confirmbtn"
                show-cancel-button style="width: 300px">
      <van-cell-group class="groups">
        <van-cell title="换货类型">
          <template #value>
            <van-radio-group v-model="checked" @change="radioclick" shape="square">
              <van-radio name="1">
                工工换货
              </van-radio>
              <van-radio name="2">
                工商换货
              </van-radio>
            </van-radio-group>
          </template>
        </van-cell>
        <van-cell :title="title">
          <template #value>
            <van-field
                v-model="value"
                :error-message="errorMessage"
                required
                placeholder="请输入内容"
            />
          </template>
        </van-cell>
      </van-cell-group>
    </van-dialog>

  </div>

  <div class="btns">
    <van-button @click="clearSubmit()">清&nbsp;&nbsp;&nbsp;空</van-button>
    <van-button @click="recombinationSubmit()" :disabled="relevanceButton">上&nbsp;&nbsp;&nbsp;报</van-button>
  </div>
</template>

<script>
import ScanOverlay from "@/components/overlay/scanOverlay/ScanOverlay";
import {getQrcodeInsByCode} from "@/api/qrcode/relation/qrcodeIns";
import {
  Notify,
  Cell,
  CellGroup,
  Loading,
  NavBar,
  Overlay,
  Tab,
  Tabs,
  Button,
  Row,
  Col,
  Dialog,
  RadioGroup,
  Radio, Field
} from "vant";
import {barQrcodeUp} from "@/api/qrcode/relation/qrDiscardCode";
import {QrCodeUtil} from "@/api/qrcode/device/brand/brand";
import {getStringByTwo} from "@/utils/transition";

export default {
  name: "RecombinationPiece",
  components: {
    [NavBar.name]: NavBar,
    [CellGroup.name]: CellGroup,
    [Cell.name]: Cell,
    [Tabs.name]: Tabs,
    [Tab.name]: Tab,
    [Overlay.name]: Overlay,
    [Loading.name]: Loading,
    [Button.name]: Button,
    [Row.name]: Row,
    [Col.name]: Col,
    [RadioGroup.name]: RadioGroup,
    [Radio.name]: Radio,
    [Field.name]: Field,
    [Dialog.Component.name]: Dialog.Component,
  },
  data() {
    return {
      title: '申请企业',
      qrCodeTypeName: "烟码",
      qrCodeType: {
        '10': '盒烟码',
        '20': '条烟码',
        '30': '件烟码',
      },
      scanning: true,

      manualAssociationList: {
        parentCode: '',
        code: [],
        errorCode: "",
        type: null,
        barterCode: [],
        recordName: "",
        recordType: "",
      },
      qrBrand: {
        code: null,//二维码数据
        typeCode: null,
        typeName: null,
        cgtName: null,
        cgtCode: null,
        pkgNum: null,// 盒条关联数之比
        boxNum: null,// 条件关联数之比
        qrBrand: null
      },
      packageBoxNum: {
        strip: null, // 条
        piece: null, // 件
      },
      show: true,
      checked: '1',
      value: "",
      errorMessage: "",
      canClose: true,  // 用于控制是否可以关闭弹窗
    }
  },

  mounted() {
    this.initHeight();
  },
  computed: {
    // 判断按钮是否能够点击
    relevanceButton() {
      return this.manualAssociationList.barterCode.length <= 0;
    },
    // 提取码值数据
    combinedList() {
      let list = [];
      // 确保 barterCode 是一个有效的数组
      if (Array.isArray(this.manualAssociationList.barterCode)) {
        this.manualAssociationList.barterCode.forEach((item, index) => {
          // 添加旧烟码
          list.push({
            new: item.new,
          });
        });

      }
      return list;
    },
  },

  watch: {
    // 监听 show 属性变化
    show(newValue) {
      if (!newValue && !this.canClose) {
        this.show = true;  // 如果不能关闭，保持弹窗显示
      }
    }
  },
  methods: {
    // 名称显示
    radioclick(val) {
      if (val == 1) {
        this.title = '申请企业'
      } else {
        this.title = '物流公司名称'
      }
    },
    // 确认按钮
    confirmbtn() {
      if (!this.value) {
        this.errorMessage = '此项为必填';  // 设置错误提示
        this.canClose = false;
        return;  // 不关闭弹窗
      }
      // 如果 value 有值，则关闭弹窗，并重置 canClose
      this.$nextTick(() => {
        this.show = false;
        this.canClose = true;  // 重新允许关闭弹窗
      });
      if (this.checked == '1') {
        this.manualAssociationList.recordName = this.value
        this.manualAssociationList.recordType = 0
      } else if (this.checked == '2') {
        this.manualAssociationList.recordName = this.value
        this.manualAssociationList.recordType = 1
      }
      this.$nativeQRCode.setCallBackFun((res) => {
        // 通过二维码获取卷烟信息信息
        let qrCode = getStringByTwo(res)
        this.onScanQrCode(qrCode);
      });
      this.$nativeQRCode.setStatusBarColor("#006953", "white");
      ScanOverlay.show('请扫描二维码')
      // this.onScanQrCode("HTTPS://Y2WM.CN/99.1000.1/AC20169250008DUI91R4C89H4J4JD4E6F")
      // setTimeout(() => {
      // // this.onScanQrCode("HTTPS://Y2WM.CN/99.1000.1/AC20169250008DUI91R4C89H4J4JD4E6F")
      //   this.onScanQrCode("HTTPS://Y2WM.CN/99.1000.1/AC20150710025V12GTGRVRWVWMELBCDVY018");
      // }, 1000)
    },
    // 取消按钮
    cancelbtn() {
      this.show = false
      this.$router.go(-1)
    },
    // 初始化高度
    initHeight() {
      this.$nextTick(() => {
        // 屏幕高度
        let windowH = document.documentElement.clientHeight;
        // 顶部内容区域高度
        let topDivH = document.getElementById('topDiv').offsetHeight;
        this.tabs.height = windowH - topDivH;
        this.tabs.conHeight = this.tabs.height - 160;
      })
    },
    // 根据二维码获取二维码实例
    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;
        }
        if (this.manualAssociationList.barterCode.length === 0) {
          // 获取当前卷烟信息相关信息
          this.qrBrand = res.data;
          // 获取盒条比值
          this.packageBoxNum.strip = this.qrBrand.pkgNum;
          // 获取条件比值
          this.packageBoxNum.piece = this.qrBrand.boxNum;
        }

        // 如果当前二维码卷烟信息编码与之前编码相同
        if (this.qrBrand.cgtCode == res.data.cgtCode) {
          getQrcodeInsByCode({qrcode}).then(r => {
            this.initQrcodeInfo(r.data);
          }).catch(() => {
            Notify({type: 'warning', message: '该烟码未关联，请先做盒条关联', duration: 1500});
          })
        } else {
          // 当前二维码与之前卷烟信息不同
          Notify({type: 'warning', message: '卷烟信息不同', duration: 1500});
        }
      })


    },
    // 初始化二维码信息
    initQrcodeInfo(qrCodeInfo) {
      // 进入页面首次扫码
      if (qrCodeInfo.type != '20') {
        Notify({type: 'warning', message: "此功能只支持条码上报", duration: 1500});
        return;
      }
      if (qrCodeInfo.parentCode != null && qrCodeInfo.parentCode != '') {
        Notify({type: 'warning', message: "该条烟已成件，无法进行上报", duration: 1500});
        return;
      }
      if (qrCodeInfo.brandCode.startsWith("AD")) {
        let qrCode = qrCodeInfo.qrCode
        if (!this.checkDuplicateCode(qrCode)) {
          this.manualAssociationList.barterCode.push({new:qrCodeInfo.qrCode})
        }

      } else if (qrCodeInfo.childrenList.length === this.qrBrand.pkgNum) {
        let qrCode = qrCodeInfo.qrCode
        if (!this.checkDuplicateCode(qrCode)) {
          this.manualAssociationList.barterCode.push({new:qrCodeInfo.qrCode})
        }
      } else {
        Dialog.confirm({title: "条码关联关系不完整,无法上报",}).then(() => {
        });
      }
      if (this.manualAssociationList.barterCode.length <= 0){
        this.clearSubmit();
      }
    },
    // 检查是否重复扫码
    checkDuplicateCode(code) {
      const existingQRCode = this.manualAssociationList.barterCode.find(item => item['new'] === code);
      if (existingQRCode) {
        this.showNotification('warning', `条烟已存在，重复扫码`);
        return true;
      }
      return false;
    },
    //提示方法
    showNotification(type, message, duration = 1500) {
      Notify({ type, message, duration });
    },
    // 清空当前数据
    clearSubmit() {
      this.manualAssociationList = {
        parentCode: '',
        code: [],
        errorCode: "",
        type: null,
        barterCode: [],
        recordName: this.value,
        recordType: this.manualAssociationList.recordType
      }
      this.qrBrand = {
        code: null,
        typeCode: null,
        typeName: null,
        cgtName: null,
        cgtCode: null,
        pkgNum: null,
        boxNum: null,
        qrBrand: null
      }
    },
    // 关联提交
    recombinationSubmit() {

      ScanOverlay.show('上报中')
      barQrcodeUp(this.manualAssociationList).then(res => {
        if (res.code == 200) {
          Notify({type: 'success', message: '盒条上报成功'});
          this.clearSubmit();
          ScanOverlay.show('请扫描二维码')
        } else {
          ScanOverlay.hide()
        }
      }).catch(() => {
        ScanOverlay.hide()
      })
    },

  }

}
</script>

<style scoped>
:deep(.van-cell-group) {
  width: 660px;
  margin: auto;
  background: none !important;
}
.cell-flex-1-3 {
  width: 660px;
  margin: auto;
  background: none !important;
  height: 18rem;
  overflow: auto;
}
:deep(.groups .van-radio-group) {
  display: flex;
  font-size: 0.36111rem;
}
:deep(.groups .van-cell) {
  height: 1.2rem;
  margin-bottom: 0;
}
:deep(.groups .van-cell .van-cell__title) {
  flex: .4 !important;;
}
:deep(.groups .van-cell__title) {
  height: 1.2rem;
  line-height: inherit;
  font-size:  0.36111rem;
  font-weight: bold;
  display: flex;
  flex-direction: column;  /* 垂直排列 */
  justify-content: center;  /* 垂直居中 */
  align-items: flex-start;  /* 水平靠左 */
}
:deep(.cell-flex-1-3_1 .van-cell) {
  height: 1.6rem;
  margin-bottom: 20px;
  font-size: 26px;
  font-family: 'SourceHanSansCN-Medium',sans-serif;
  font-weight: 500;
  color: #000000;
}

:deep(.cell-flex-1-3_1 .van-cell:nth-of-type(1)) {
  margin-bottom: 20px;
  margin-top: 20px;
  border-radius: 15px;
}

:deep(.cell-flex-1-3_1 .van-cell .van-cell__value) {
  display: block;
  height: 100%;
  line-height: .6rem;
  text-align: left;
  color: #777777;

}

:deep(.van-field) {
  font-size: .35rem;
}

:deep(.van-radio) {
  height: 1rem;
  padding: 0 .2rem;
}

:deep(.van-radio__icon) {
  height: .45rem;
}

:deep(.van-radio__icon--round .van-icon) {
  font-size: .3rem;
}

:deep(.van-cell__value) {
  font-family: 'SourceHanSansCN-Regular',sans-serif;
  color: rgba(67, 67, 67, 1);
}

:deep(.van-tabs__wrap) {
  width: 660px;
  margin: auto;
  height: 95px;
  border-radius: 15px 15px 0 0;

}

:deep(.van-tab) {
  font-size: 26px;
  font-family: 'SourceHanSansCN-Medium',sans-serif;
  font-weight: 500;
  color: #000000;
}

:deep(.van-tab__text--ellipsis) {
  overflow: visible;
}

:deep(.van-tabs__line) {
  width: 115px;
  background-color: rgba(0, 105, 83, 1);
  height: 4px;
}

:deep(.van-tabs__content) {
  height: 600px !important;
  box-sizing: border-box;
  border-radius: 0px 0px 15px 15px;
  overflow: hidden;
}

:deep(.van-tabs__content .van-cell__value) {
  height: 127px;
  line-height: 50px;
  font-size: 26px;
  font-family: Source Han Sans CN,sans-serif;
  font-weight: 400;
  color: #434343;
  padding-top: 5px;
}

:deep(.van-cell:after) {
  border-bottom: 2px solid rgba(231, 231, 231, 1);
  height: 3px;
}

.box1-3-1 {
  border-radius: 0 0 15px 15px;
  /* height: 600px !important; */
}

.btns {
  position: absolute;
  bottom: 0;
  width: 720px;
  height: 94px;
  background: #FFFFFF;
  display: flex;
  justify-content: center;
}

.btns > button {
  width: 271px;
  height: 70px;
  background: #E4E9E8;
  border-radius: 35px;
  margin: auto;
  font-size: 26px;
  font-family: 'SourceHanSansCN-Medium',sans-serif;
  font-weight: 500;
  color: #006953;
}

.btns > button:nth-of-type(2) {
  background-color: rgba(33, 143, 120, 1);

  color: #FFFFFF;
}

:deep(.van-nav-bar__right) {
  font-size: 32px;
  font-family: Source Han Sans CN,sans-serif;
  font-weight: 400;
  color: #FFFFFF;
}

:deep(.cell-flexA .van-cell) {
  height: 1.3rem;
  line-height: 1.1rem;
  font-size: .35rem;
  margin-top: .2rem;
  border-radius: .12rem;
}
</style>
