<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>
  </div>

  <div class="centerDiv" id="centerDiv">
    <p class="codetitle">
      <span class="title">{{ this.title }}</span>
      <span class="value">{{ this.value }}</span>
    </p>
    <p class="codetitle">
      <span class="title">卷烟信息</span>
      <span class="value">{{ this.qrBrand.cgtName }}</span>
    </p>
    <div class="codeitem" v-for="(item, index) in combinedList">
      <p>
        <span class="oldcode">编码</span>
        <span class="oldcodecon">{{ item.order }}</span>
      </p>
      <p>
        <span class="oldcode">旧烟码{{ index + 1 }}</span>
        <span class="oldcodecon">{{ this.getcode(item.old) }}</span>
      </p>
      <p>
        <span class="newcode">新烟码{{ index + 1 }}</span>
        <span class="newcodecon">{{ this.getcode(item.new) }}</span>
      </p>
      <p>
        <span class="newcode">类型{{ index + 1 }}</span>
        <span class="newcodecon" v-if="item.type == 1">条烟换货</span>
        <span class="newcodecon" v-if="item.type == 2">盒条上报</span>
      </p>
    </div>
    <van-dialog v-model:show="show" title="请选择换货模式" @cancel="cancelbtn()" @confirm="confirmbtn"
                show-cancel-button style="width: 300px">
      <van-cell-group>
        <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>

  <van-row id="scrapButton">
    <van-button :class="relevanceButton ? 'btn_disabled' : 'btn_enable'" :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 {barterOrUpQrCodeIns, pieceActivate} from "@/api/qrcode/relation/qrDiscardCode";
import ScanOverlay from "@/components/overlay/scanOverlay/ScanOverlay";
import {QrCodeUtil} from "@/api/qrcode/device/brand/brand";
import {getQrcodeInsByCode} from "@/api/qrcode/relation/qrcodeIns";
import {getStringByTwo} from "@/utils/transition";
import OpenDataWap from "@/common/nativeJSdk/OperData";
import $store from "@/store/modules/user";
import {qrCodeFlowNodes, qrCodeParent, qrCodeSubcodes} from "@/api/qrcode/upload/uploadTaskDetail";

export default {
  name: "cartonBox",
  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,
  },
  mounted() {
    const _this = this;
    this.initHeight();
  },
  data() {
    return {
      title:'申请企业',
      listHeight: '',
      manualAssociationList: {
        parentCode: '',
        code: [],
        errorCode: "",
        type: null,
        barterCode: [],
        recordName: "",
        recordType: null
      },
      errorList: [],
      packageBoxNum: {
        strip: null, // 条
        piece: null, // 件
      },
      qrBrand: {
        code: null,//二维码数据
        typeCode: null,
        typeName: null,
        cgtName: null,
        cgtCode: null,
        pkgNum: null,// 盒条关联数之比
        boxNum: null,// 条件关联数之比
        qrBrand: null
      },
      showArr: [],
      forbidden: 0,
      show: true,
      checked: '1',
      errorMessage: "",
      value: "",
      canClose: true,  // 用于控制是否可以关闭弹窗
      // 需要激活的旧件码
      pieceActivateList: [],
    }
  },
  computed: {

    // 判断按钮是否能够点击
    relevanceButton() {
      if (this.forbidden == 1) {
        return true;
      }
      // 获取最后一个元素
      let lastElement = this.manualAssociationList.barterCode[this.manualAssociationList.barterCode.length - 1];
      if (lastElement) {
        return (lastElement.old != null && lastElement.new != null) ? false : true
      }
      return true
    },


    combinedList() {
      let list = [];
      // 确保 barterCode 是一个有效的数组
      if (Array.isArray(this.manualAssociationList.barterCode)) {
        this.manualAssociationList.barterCode.forEach((item, index) => {
          // 添加旧烟码
          list.push({
            old: item.old,
            new: item.new,
            type: item.type,
            order: item.order
          });
        });

      }
      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.getQrBrandByCode(qrCode);
      });
      this.$nativeQRCode.setStatusBarColor("#006953", "white");
      ScanOverlay.show('请扫描二维码')

      // this.getQrBrandByCode("HTTPS://Y2WM.CN/99.1000.1/AC21150711041ZOLDX0WVBQ5WSPCXE6FYYYX");
      // setTimeout(() => {
      //   this.getQrBrandByCode("HTTPS://Y2WM.CN/99.1000.1/AC21150711041ZOLDX0WVBQ5WMPCXE6FYY29")
      // }, 1500)
      // setTimeout(() => {
      //   this.getQrBrandByCode("HTTPS://Y2WM.CN/99.1000.1/AC21150711041ZOLDX0WVBQ5WSPCXE6FYYYX01")
      // }, 3000)
      // setTimeout(() => {
      //   this.getQrBrandByCode("HTTPS://Y2WM.CN/99.1000.1/AC21150711041ZOLDX0WVBQ5WMPCXE6FYY65")
      // }, 4500)
    },
    // 取消按钮点击事件
    cancelbtn() {
      this.show = false
      this.$router.go(-1)
    },
    // 截取二维码后六位
    getcode(code) {
      if (code) {
        return "..." + code.slice(code.length - 10, code.length)
      }
    },
    // 计算高度
    initHeight() {
      this.$nextTick(() => {
        // 屏幕宽度
        let windowW = document.documentElement.clientHeight;
        let topDivH = document.getElementById("topDiv").offsetHeight;
        let centerDivH = document.getElementById("centerDiv").offsetHeight;
        let scrapButtonH = document.getElementById("scrapButton").offsetHeight;
        this.listHeight = windowW - topDivH - centerDivH - scrapButtonH - 60;
      });
    },

    //二维码获取卷烟信息卷烟信息获取
    getQrBrandByCode(qrcode) {
      ScanOverlay.hide()
      QrCodeUtil({"qrcode": qrcode}).then(res => {
        if (res.code == 500 || res.data.qrBrand == null) {
          Notify({type: 'warning', message: '无法获取到品规'});
          return;
        }
        // 第一次没有获取到卷烟信息 , 获取卷烟信息
        if (!this.qrBrand.cgtCode) {
          // 获取当前卷烟信息相关信息
          this.qrBrand = res.data;
          // 获取盒条比值
          this.packageBoxNum.strip = this.qrBrand.pkgNum;
          // 获取条件比值
          this.packageBoxNum.piece = this.qrBrand.boxNum;
          // 执行扫描二维码操作
          this.onScanQrCode(res.data);
        } else {
          // 如果当前二维码卷烟信息编码与之前编码相同
          if (this.qrBrand.cgtCode == res.data.cgtCode) {
            this.onScanQrCode(res.data)
          } else {
            // 当前二维码与之前卷烟信息不同
            Notify({type: 'warning', message: '卷烟信息不同', duration: 1500});
          }
        }
      })
    },


    // 显示通知
    showNotification(type, message, duration = 1500) {
      Notify({ type, message, duration });
    },
    // 检查烟码是否已迁移
    async checkCodeMigrated(qrcode) {
      const r = await getQrcodeInsByCode({ qrcode });
      if (r.data.bTaskId != null) {
        this.showNotification('warning', '该烟码已迁移，无法再次操作');
        return true;
      }
      return false;
    },
    // 检查父码状态
    async checkParentStatus(parentCode) {
      const pres = await getQrcodeInsByCode({ qrcode: parentCode });
      if (pres.data.status === 30) {
        this.showNotification('warning', '该烟码关联的件烟已报废，无法再次换货');
        return null;
      }
      if (pres.data.operUserId!== 60) {
        this.showNotification('warning', '该条烟未出库，无法进行换货');
        return null;
      }
      return pres.data;
    },
    // 检查是否重复扫码
    checkDuplicateCode(code, isOldCode) {
      const key = isOldCode? 'old' : 'new';
      const existingQRCode = this.manualAssociationList.barterCode.find(item => item[key] === code);
      if (existingQRCode) {
        this.showNotification('warning', `条烟已存在，重复扫码`);
        return true;
      }
      return false;
    },
    // 处理旧码扫码逻辑
    async handleOldCodeScan(qrcode, lastElement, res, resCodeSubcodes) {
      if (res.data.length > 0) {
        // 查询旧码信息
        try {
          const oldPieceCode = await getQrcodeInsByCode({ qrcode });
          if (oldPieceCode.data.bTaskId != null) {
            this.pieceActivateList.push(oldPieceCode.data.parentCode);
          }
        } catch (error) {
          Notify({type: 'warning', message: '', duration: 1});
        }
        // 查询流通记录
        let arr = []
        arr.push(qrcode)
        const qrFlowNodes = await qrCodeFlowNodes(arr);

        // 检查是否有关联关系
        if (qrFlowNodes.data.length > 0) {
          // 使用 for...of 循环，可以用 break 跳出循环，用 return 跳出函数
          for (const item of qrFlowNodes.data[0].flowInfos) {
            if (item.flowNodeCode==="AC_O_005" ) {
              this.showNotification('warning', `该条烟已有条零关联关系，无法进行换货`);
              return; // 直接终止函数，不再执行后面的所有代码
            }
          }
        }
        // 在获取一次，防止快速扫描未拿到信息
        lastElement = this.manualAssociationList.barterCode[this.manualAssociationList.barterCode.length - 1];
        if (!lastElement) {
            if (!this.checkDuplicateCode(qrcode, true)) {
              // 有流通记录，走盒条上报逻辑，否则走换货逻辑
              if (qrFlowNodes.data.length > 0){
                this.manualAssociationList.barterCode.push({ old: qrcode, type: 2, order: (this.manualAssociationList.barterCode.length + 1), piece: res.data[0].parentCodeTid, oldChildCodes: resCodeSubcodes.data[qrcode]});
              }else {
                this.manualAssociationList.barterCode.push({ old: qrcode, type: 1, order: (this.manualAssociationList.barterCode.length + 1), piece: res.data[0].parentCodeTid, oldChildCodes: resCodeSubcodes.data[qrcode]});
              }
            }
        } else {
          if (lastElement.new && lastElement.old) {
            lastElement = {};
          }
          if (!lastElement.old) {
              if (Object.keys(lastElement).length === 0) {
                if (!this.checkDuplicateCode(qrcode, true)) {
                  if (qrFlowNodes.data.length > 0){
                    this.manualAssociationList.barterCode.push({ old: qrcode, type: 2, order: (this.manualAssociationList.barterCode.length + 1), piece: res.data[0].parentCodeTid, oldChildCodes: resCodeSubcodes.data[qrcode]});
                  }else {
                    this.manualAssociationList.barterCode.push({ old: qrcode, type: 1, order: (this.manualAssociationList.barterCode.length + 1), piece: res.data[0].parentCodeTid, oldChildCodes: resCodeSubcodes.data[qrcode]});
                  }
                }
              } else {
                if (!this.checkDuplicateCode(qrcode, true)) {
                  lastElement.old = qrcode;
                  if (qrFlowNodes.data.length > 0){
                    lastElement.type = 2;
                  }else {
                    lastElement.type = 1;
                  }

                  lastElement.oldChildCodes = resCodeSubcodes.data[qrcode];
                }
              }
          }else if (!lastElement.new && lastElement.old) {
            if (res.data[0].parentCodeTid == null){
              lastElement.new = qrcode;
              lastElement.newChildCodes = oldPieceCode.data.childrenList
                  .map(child => child.qrCode)
                  .filter(qrCode => qrCode != null);
            }else {
              this.showNotification('warning', `请新烟码`);
            }

          }
        }
      } else {
        try {
          const r = await getQrcodeInsByCode({ qrcode });
          if (r.data.bTaskId != null) {
            this.pieceActivateList.push(r.data.parentCode)
          }

          // 在获取一次，防止快速扫描未拿到信息
          lastElement = this.manualAssociationList.barterCode[this.manualAssociationList.barterCode.length - 1];
          if (!lastElement) {
            if (r.data.parentCode) {
              const parentData = await this.checkParentStatus(r.data.parentCode);
              if (parentData) {
                if (!this.checkDuplicateCode(qrcode, true)) {
                  this.manualAssociationList.barterCode.push({ old: qrcode, type: 2,order: (this.manualAssociationList.barterCode.length + 1), piece: r.data.parentCode, oldChildCodes: r.data.childrenList
                        .map(child => child.qrCode)
                        .filter(qrCode => qrCode != null) });
                }
              }
            } else {
              this.showNotification('warning', '请先扫旧烟码进行操作');
              if (this.manualAssociationList.barterCode.length <= 0){
                this.resetAll();
              }
            }
          } else {
            if (lastElement.new && lastElement.old) {
              lastElement = {};
            }
            if (r.data.parentCode){
              if (Object.keys(lastElement).length === 0){
                if (!this.checkDuplicateCode(qrcode, true)) {
                  this.manualAssociationList.barterCode.push({ old: qrcode, type: 2,order: (this.manualAssociationList.barterCode.length + 1), piece: r.data.parentCode, oldChildCodes: r.data.childrenList
                        .map(child => child.qrCode)
                        .filter(qrCode => qrCode != null) });
                }
              }
              if (!lastElement.new && lastElement.old && r.data.childrenList.length === this.qrBrand.pkgNum) {
                this.showNotification('warning', '新条烟关联已关联件码并关联完整，无法进行换货');
              }
            }else {
              if (!lastElement.new && lastElement.old) {
                if (r.data.brandCode.startsWith("AD") || r.data.childrenList.length === this.qrBrand.pkgNum) {
                  if (!this.checkDuplicateCode(qrcode, false)) {
                    lastElement.new = qrcode;
                    lastElement.newChildCodes = r.data.childrenList
                        .map(child => child.qrCode)
                        .filter(qrCode => qrCode != null);  // 排除 null 或 undefined
                  }
                } else {
                  this.showNotification('warning', '该条烟关联关系不完整，无法进行换货');
                }
              } else {
                this.showNotification('warning', '请先扫旧烟码进行操作')
              }
              if (this.manualAssociationList.barterCode.length <= 0){
                this.resetAll();
              }
            }
          }
        } catch (error) {
          this.resetAll();
        }
      }
    },
    // 处理扫码事件
    async onScanQrCode(qrCode) {
      if (this.manualAssociationList.type === null && qrCode.typeCode === '20') {
        this.manualAssociationList.type = qrCode.typeCode;
      }
      if (this.manualAssociationList.type!== qrCode.typeCode) {
        this.showNotification('warning', '请扫描同类行型的二维码进行换货');
        return;
      }
      const lastElement = this.manualAssociationList.barterCode[this.manualAssociationList.barterCode.length - 1];
      if (qrCode.typeCode === '20') {
        const qrcode = qrCode.code;
        const arr = [qrcode];
        const resCodeParent = await qrCodeParent(arr);
        const resCodeSubcodes = await qrCodeSubcodes(arr);
        await this.handleOldCodeScan(qrcode, lastElement, resCodeParent, resCodeSubcodes);
      } else if (qrCode.typeCode === '30' || qrCode.typeCode === '10') {
        this.showNotification('warning', '请扫描条码进行换货');
      } else {
        this.showNotification('warning', '请扫描正确烟码');
      }
      if (this.manualAssociationList.barterCode.length <= 0){
        this.resetAll();
      }
    },
    //判断是否超过数量
    isMoreNum() {
      if (this.manualAssociationList.code.length < this.packageBoxNum.strip) return true;
      return false;
    },

    //判断是否要清空品规信息内容
    isClearBrand() {
      if (this.manualAssociationList.code.length === 0 && this.manualAssociationList.parentCode === '') {
        this.resetAll()
      }
    },

    // 完成关联 发送
    relevanceSendButton() {
      if (this.manualAssociationList.type == '10') {
        this.manualAssociationList.type = 1
      } else if (this.manualAssociationList.type == '20') {
        this.manualAssociationList.type = 1
      }

      this.forbidden = 1
      ScanOverlay.show('换货中')
      if (this.pieceActivateList.length>0){
        this.pieceActivateList.forEach(item => {
          let activate = {
            parentCode: item,
            type: 2,
          }
          pieceActivate(activate).then(() => {});
        })
        this.barterOrUpQrCodeIns()
      }else{
        this.barterOrUpQrCodeIns()
      }

    },
    // 调用后端接口提交
    barterOrUpQrCodeIns(){
      barterOrUpQrCodeIns(this.manualAssociationList).then(res => {
        if (res.code == 200) {
          this.forbidden = 0
          this.resetAll();
          Notify({type: 'success', message: '换货成功'});
          ScanOverlay.show('请扫描二维码')
        }
      }).catch(() => {
        ScanOverlay.hide()
        this.forbidden = 0
      })
    },
    // 重置所有数据
    resetAll() {
      this.manualAssociationList = {
        parentCode: '',
        code: [],
        errorCode: "",
        type: null,
        barterCode: [],
        recordName: this.value,
        recordType: this.manualAssociationList.recordType
      }
      this.showArr = []
      this.errorList = []
      this.packageBoxNum = {
        strip: null, // 条
        piece: null, // 件
      }
      this.qrBrand = {
        code: null,//二维码数据
        typeCode: null,
        typeName: null,
        cgtName: null,
        cgtCode: null,
        pkgNum: null,// 盒条关联数之比
        boxNum: null,// 条件关联数之比
        qrBrand: null
      }
    }
  },
}
</script>

<style lang="scss" scoped>
:deep(.van-cell-group) {
  width: 660px;
  margin: auto;
  margin-top: 20px;
  background: none;
}

:deep(.van-cell-group .van-cell) {
  height: 1rem;
  border-radius: 15px;
  font-size: 26px;
  font-family: 'SourceHanSansCN-Medium',sans-serif;
  font-weight: 500;
  color: #000000;
  line-height: 147px;
  align-items: center;
  margin-bottom: 0;
}

:deep(.van-cell-group .van-cell .van-cell__title) {
  flex: (.4);
}

:deep(.van-cell-group .van-cell .van-cell__value) {
  display: block;
  line-height: 20px;
  text-align: left;
  font-family: 'SourceHanSansCN-Regular',sans-serif;
  font-weight: 400;
  color: #434343;
}


.list {
  width: 660px !important;
  margin: auto;
  border-radius: 15px;
}

:deep(.li) {
  height: 127px !important;
  font-size: 26px;
  font-family: 'SourceHanSansCN-Regular',sans-serif;
  font-weight: 400;
  color: #434343;
  line-height: 40px;
  padding-top: 20px;
  box-sizing: border-box;
}

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

#scrapButton {
  height: 100px;
  width: 100%;
  position: fixed;
  bottom: 0px;
  padding-top: 20px;

  background: #FFFFFF;
}

.btn_disabled {
  width: 100%;
  height: 80px;
  background: #AFD4CC;
  border-radius: 20px;
  color: rgba(230, 230, 230, 1);
}

.btn_enable {
  width: 100%;
  height: 80px;
  background: rgba(33, 143, 120, 0.9);
  border-radius: 20px;
  color: rgba(230, 230, 230, 1);
}

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

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

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

:deep(.van-radio__icon) {
  height: .45rem;
}
:deep(.van-radio-group) {
  display: flex;
}
:deep(.van-cell__title) {
  height: 1rem;
  line-height: 1rem;
}
:deep(.van-radio__icon--round .van-icon) {
  font-size: .3rem;
}

.centerDiv {
  height: 78%;
  box-sizing: border-box;
  margin: .35rem .25rem;
  background: #ffffff;
  padding: .15rem .2rem;

}
.title {
  text-align: left;  /* 确保名称靠左 */
  padding-left: 15px;  /* 左边添加间距，调整为你需要的值 */
}

.value {
  text-align: right;  /* 确保信息靠右 */
  padding-right: 15px;  /* 左边添加间距，调整为你需要的值 */
}
p {
  margin: 0;
}

.codetitle {
  background: #efefef;
  text-align: center;
  height: 1rem;
  line-height: 1rem;
  font-size: .35rem;
  font-weight: bold;
  border-radius: .1rem;
  color: #303030;
  display: flex;
  justify-content: space-between;  /* 将名称和信息分开 */
  margin-bottom: 5px;  /* 调整两者之间的间距 */
  // margin-bottom: .2rem;
}

.codeitem {
  border-bottom: 1px solid #e7e7e7;
  padding: .2rem 0 .35rem 0;
  text-align: center;
  display: flex;
  justify-content: space-between;

  p {
    color: #313131;
    background: #efefef;
    width: 49%;
    height: 1.6rem;
    line-height: .83rem;

    span {
      display: block;
      font-size: .35rem;
      font-weight: bold;
    }
  }

  .newcode, .oldcode {
    border-bottom: 1px solid #c5c5c5;

  }

  .oldcodecon, .newcodecon {
    color: #575757;
  }

}
</style>
