<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-flex-1-3 cell-flex-1-3_1">
      <van-cell style="height: 110px" :title="qrCodeTypeName" :value="qrCodeIns.qrCode"/>
      <van-cell title="卷烟信息" :value="qrCodeIns.brandName"/>
    </van-cell-group>

  </div>

  <div id="centerDiv" :style="{height : tabs.height + 'px'}">

    <van-tabs v-model:active="tabs.active" duration="0">
      <van-tab>
        <template #title> 准备关联
          <span class="text-primary">{{ relationQrCodeList.length }}</span>
        </template>
        <van-cell-group class="cell-flex-1-3" :style="{height: tabs.conHeight + 'px', overflow: 'scroll' }">
          <van-cell v-for="item in relationQrCodeList" :key="item">
                       <span >{{ item }}</span>
          </van-cell>
        </van-cell-group>
      </van-tab>

      <van-tab>
        <template #title> 准备解绑 <span class="text-danger">{{ unboundQrCodeList.length }}</span></template>
        <van-cell-group class="cell-flex-1-3" :style="{height: tabs.conHeight + 'px', overflow: 'scroll' }">
          <van-cell v-for="item in unboundQrCodeList" :key="item">
                       <span >{{ item }}</span>
          </van-cell>
        </van-cell-group>
      </van-tab>
      <van-tab>
        <template #title> 已关联
          <span>{{ qrCodeChildrenList.length + relationQrCodeList.length }}</span>
        </template>
        <van-cell-group class="cell-flex-1-3 box1-3-1" :style="{height: tabs.conHeight + 'px', overflow: 'scroll' }">
          <!-- 本身存在 -->
          <van-cell v-for="item in qrCodeChildrenList" :key="item">
            <span>{{ item }}</span>
          </van-cell>
          <!-- 准备关联 -->
          <van-cell v-for="item in relationQrCodeList" :key="item">
            <span>{{ item }}</span>
          </van-cell>
        </van-cell-group>
      </van-tab>
    </van-tabs>


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

<script>
import ScanOverlay from "@/components/overlay/scanOverlay/ScanOverlay";
import {getQrcodeInsByCode} from "@/api/qrcode/relation/qrcodeIns";
import {QrCodeUtil} from "@/api/qrcode/device/brand/brand";
import {Notify, Cell, CellGroup, Loading, NavBar, Overlay, Tab, Tabs, Button, Row, Col, Dialog} from "vant";
import {unbondQrCodeOne, updateAndAddQrCodeIns} from "@/api/qrcode/relation/qrDiscardCode";
import {endWith} from "postcss-pxtorem/lib/filter-prop-list";
import {getStringByTwo} from "@/utils/transition";

export default {
  name: "recombination",
  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,
    [Dialog.Component.name]: Dialog.Component,
  },
  data() {
    return {
      qrCodeTypeName: "烟码",
      qrCodeType: {
        '10': '盒烟码',
        '20': '条烟码',
        '30': '件烟码',
      },
      tabs: {
        active: 0,
        height: 0,
        conHeight: 0,
      },
      // 用于判断是否条替换
      // isPieceReplace:false,
      // oldParentCode:'',
      // 是否正在扫描
      scanning: true,
      // 当前校验的二维码实例
      qrCodeIns: {
        childrenList: []
      },
      // 存放已关联二维码数据
      qrCodeChildrenList: [],
      // 存放准备解绑二维码数组
      unboundQrCodeList: [],
      // 存放准备关联二维码数组
      relationQrCodeList: [],
      // 存放校验数组
      qcQrCodeList: [],
      smokeNum: {
        box: 0,
        pkg: 10
      },
      forbidden:0,
      cgtCode:"",
      showArr:[],
      dialogPromise: true,
    }
  },

  mounted() {
    this.initHeight();
    // 扫描二维码
    this.$nativeQRCode.setCallBackFun((res) => {
      let qrCode = getStringByTwo(res)
      this.onScanQrCode(qrCode);
    });
    this.$nativeQRCode.setStatusBarColor("#006953", "white");
    ScanOverlay.show('请扫描二维码')

    //  this.onScanQrCode("HTTPS://T2DC.CN/99.1000.1/AC30150750037000169010280752062202404290016460168A01297CCBF1F6636OQI9I9VHV4PGLM")
    //     setTimeout(()=>{
    //      this.onScanQrCode("HTTPS://Y2WM.CN/99.1000.1/AD21032301051ZOLDX0WVBQ7WLPCXE7FY004")
    //   },1000)
    // setTimeout(()=>{
    //   this.onScanQrCode("HTTPS://Y2WM.CN/99.1000.1/AD21032301051ZOLDX0WVBQ7WLPCXE7FY000")
    //     },2000)
  },
  computed: {

    // 判断按钮是否能够点击
    relevanceButton() {
      if (this.forbidden==1){
        return true;
      }
      if (this.relationQrCodeList.length != null && this.unboundQrCodeList.length != '') {
        return this.relationQrCodeList.length == this.unboundQrCodeList.length ? false : true
      }
      return true
    }
  },
  methods: {
    // 初始化高度
    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;
      // 进入页面首次扫码
      if (!this.qrCodeIns.qrCode) {
        ScanOverlay.hide()
        QrCodeUtil({"qrcode": qrcode}).then(res=>{
          if (res.data.typeCode != null && res.data.typeCode == 30) {
            if (qrcode.length != '105' && qrcode.length != '96') {
              Notify({type: 'warning', message: '请扫描正确烟码', duration: 1500});
              return;
            }
          }
          if (res.data.cgtCode !=null){
            this.smokeNum.box=res.data.boxNum
            this.cgtCode=res.data.cgtCode
            getQrcodeInsByCode({qrcode}).then(r => {
              if(r.data.type != 30){
                Notify({type: 'warning', message: '请先扫描件码', duration: 1500});
                return
              }
              if(r.data.status == 30) {
                Notify({type: 'warning', message: '该件烟是报废烟码，无法再次操作', duration: 1500});
                return
              }
              if(r.data.operUserId == 60){
                Notify({type: 'warning', message: '该件已出库，无法再次操作', duration: 1500});
                return
              }
              if(r.data.unregistered == 5){
                Notify({type: 'warning', message: '该烟是黑户烟，无法进行替换，请先做解绑操作', duration: 1500});
                return
              }
              if(r.data.bTaskId != null){
                Notify({type: 'warning', message: '该件已迁移，无法再次操作', duration: 1500});
                return
              }
              this.initQrcodeInfo(r.data);
            })
          }else {
            Notify({type: 'warning', message: '无法获取到品规', duration: 1500});
          }
        })
        // 切换到已关联界面
        this.tabs.active = 2;
      } else {
        // 判断是否件替换
        // 件替换
        // if (this.isPieceReplace) this.pieceReplace(qrcode)
            // 非件替换
        // else
          this.checkQrcode(qrcode)
      }
    },
    // 初始化二维码信息
    initQrcodeInfo(qrCodeInfo) {
      // 进入页面首次扫码
      if (!this.qrCodeIns.qrCode) {
        this.qrCodeIns = qrCodeInfo;
        this.qrCodeTypeName = this.qrCodeType[this.qrCodeIns.type];
        qrCodeInfo.childrenList.forEach((_qrcode) => {
          this.qrCodeChildrenList.push(_qrcode.qrCode);
          this.qcQrCodeList.push({qrCode: _qrcode.qrCode, scan: 0});
        })
      }
    },
    // 校验二维码
    checkQrcode(qrCode) {
      QrCodeUtil({"qrcode": qrCode}).then(res=>{
        if (res.code==500){
          Notify({type: 'warning', message: '无法获取到品规', duration: 1500 });
          return;
        }
        if (this.cgtCode != res.data.cgtCode){
          Notify({type: 'warning', message: '卷烟品规不同', duration: 1500 });
          return;
        }
        if (res.data.typeCode==10){
          Notify({type: 'warning', message: '不支持盒烟关联', duration: 1500 });
          return;
        }
        // 判断当前是否盒烟
        if (this.qrCodeIns.type == 10) {
          Notify({type: 'warning', message: '不支持盒烟关联', duration: 1500});
          return;
        }
        if (res.data.typeCode==30) {
          Notify({type: 'warning', message: '请扫描条烟码', duration: 1500});
          return;
        }

        // 判断是否重复扫描
        // 情况一: 扫描二维码为父code
        // 情况二: 扫描二维码为准备剔除或者准备关联
        if (qrCode == this.qrCodeIns.qrCode || this.unboundQrCodeList.indexOf(qrCode) != -1 || this.relationQrCodeList.indexOf(qrCode) != -1) {
          Notify({type: 'warning', message: '请勿重复扫码', duration: 1500 });
          return;
        }
        this.smokeNum.box=res.data.boxNum
        //判断是否存在于 已关联二维码中
        // 情况一: 若存在则放如准备剔除队列中
        // 情况二: 若不存在则添加到准备关联队列中
        if (this.qrCodeChildrenList.indexOf(qrCode) != -1) {
          // 剔除已关联队列并添加到准备移除队列中
          this.qrCodeChildrenList.splice(this.qrCodeChildrenList.indexOf(qrCode), 1)
          this.unboundQrCodeList.unshift(qrCode)
          //切换到解绑界面
          this.tabs.active = 1;
        } else {
          if (this.relationQrCodeList.length>=this.smokeNum.box){
            Notify({type: 'warning', message: '已超过扫码数量', duration: 1500});
          } else {
            let qrcode=qrCode
            //判断条烟的盒条关联关系是否完整
            getQrcodeInsByCode({qrcode}).then(r=>{
              if (r.data.cClassId==2){
                Notify({type: 'warning', message: '该条烟二次关联，无法进行替换', duration: 1500});
                return;
              }
              if(r.data.unregistered == 5){
                Notify({type: 'warning', message: '该烟是黑户烟，无法进行替换，请先做解绑操作', duration: 1500});
                return;
              }
              if (r.data.parentCode != null && r.data.parentCode != ''){
                let pCode = r.data.parentCode
                getQrcodeInsByCode({"qrcode": pCode}).then(re => {
                  if (re.data.status == 30) {
                    Notify({type: 'warning', message: '该条烟有旧条件关联关系，并且关联的件是报废烟码，无法再次操作', duration: 1500});
                  } else if (re.data.operUserId == 60) {
                    Notify({type: 'warning', message: '该条烟有旧条件关联关系，并且关联的件已出库，无法再次操作', duration: 1500});
                  } else if (r.data.bTaskId != null) {
                    Notify({type: 'warning', message: '该条烟有旧条件关联关系，并且已迁移，无法再次操作', duration: 1500});
                  }else if (re.data.status == 40){
                    Notify({type: 'warning', message: '该条烟有条件关联关系，无法再次关联', duration: 1500});
                  } else {
                    Dialog.confirm({
                      message: '该条已关联,提交后会对老关联关系进行解绑,是否提交',
                    }).then(() => {
                      if (r.data.childrenList.length==res.data.pkgNum){
                        // 添加 到 准备关联队列
                        if (this.dialogPromise){
                          this.showArr.unshift(qrCode)
                          let arr = [...new Set(this.showArr.map(item => JSON.stringify(item)))].map(item => JSON.parse(item));
                          this.relationQrCodeList = arr
                        }
                      }else if (this.cgtCode.startsWith("AD")){
                        this.showArr.unshift(qrCode)
                        let arr = [...new Set(this.showArr.map(item => JSON.stringify(item)))].map(item => JSON.parse(item));
                        this.relationQrCodeList = arr
                        return
                      } else {
                        this.dialogPromise = false
                        Dialog.confirm({title: "盒条关联关系不完整,无法替换",}).then(() => {
                          this.dialogPromise = true
                        });
                      }
                    })
                  }
                })
              }else {
                if (r.data.childrenList.length==res.data.pkgNum){
                  // 添加 到 准备关联队列
                  if (this.dialogPromise){
                    this.showArr.unshift(qrCode)
                    let arr = [...new Set(this.showArr.map(item => JSON.stringify(item)))].map(item => JSON.parse(item));
                    this.relationQrCodeList = arr
                  }
                }else if (this.cgtCode.startsWith("AD")){
                  this.showArr.unshift(qrCode)
                  let arr = [...new Set(this.showArr.map(item => JSON.stringify(item)))].map(item => JSON.parse(item));
                  this.relationQrCodeList = arr
                  return
                } else {
                  this.dialogPromise = false
                  Dialog.confirm({title: "盒条关联关系不完整,无法替换",}).then(() => {
                    this.dialogPromise = true
                  });
                }
              }
            }).catch(()=>{
              Notify({type: 'warning', message: '', duration: 1});
              if (this.cgtCode.startsWith("AD")){
                this.showArr.unshift(qrCode)
                let arr = [...new Set(this.showArr.map(item => JSON.stringify(item)))].map(item => JSON.parse(item));
                this.relationQrCodeList = arr
                return
              }
              this.dialogPromise = false
              Dialog.confirm({title: "盒条关联关系不完整,无法关联",}).then(() => {
                this.dialogPromise = true
              });
            })

            // 添加 到 准备关联队列
            // this.relationQrCodeList.unshift(qrCode)
          }
          // 切换到关联界面
          this.tabs.active = 0
        }
      })
    },
    // 清空当前数据
    clearSubmit() {
      this.qrCodeIns = {
        childrenList: []
      }
      // 存放已关联二维码数据
      this.qrCodeChildrenList = []
      // 存放准备解绑二维码数组
      this.unboundQrCodeList = []
      // 存放准备关联二维码数组
      this.relationQrCodeList = []
      this.qrCodeTypeName = '烟码'
      this.qcQrCodeList = []
      this.showArr = []
      // this.oldParentCode = ''
    },
    // 关联提交
    recombinationSubmit() {
      //只能提交一次
      this.forbidden=1
      ScanOverlay.show('替换中')
      // 如果是条烟
      if (this.qrCodeIns.type == 20) {
        if (this.qrCodeChildrenList.length + this.relationQrCodeList.length != this.smokeNum.pkg) {
          //无法提交
          //Notify({type: 'warning', message: '与指定数量' + this.smokeNum.pkg + '盒不符'});
          //return;
          Dialog.confirm({ message: '与指定数量' + this.smokeNum.pkg + '盒不符' }).then(() => {
              this.submitQrCodeIns()
          }).catch(() => {
            ScanOverlay.hide()
            this.forbidden=0
          });
        } else {
          this.submitQrCodeIns()
        }
      } else if (this.qrCodeIns.type == 30) {
        // 件烟
        console.log(this.qrCodeChildrenList.length + this.relationQrCodeList.length )
        if (this.qrCodeChildrenList.length + this.relationQrCodeList.length  != this.smokeNum.box) {
          Dialog.confirm({message:'与指定数量' + this.smokeNum.box + '条不符'}).then(() => {
            this.submitQrCodeIns()
          }).catch(() => {
            ScanOverlay.hide()
            this.forbidden=0
          });
        } else {
          this.submitQrCodeIns()
        }
      } else {
        Dialog.alert({
          message: '盒码不能提交',
        }).then(() => {
          // on close
          this.forbidden=0
        });
      }


    },
    // 提交功能
    submitQrCodeIns() {
      // 判断当前烟码类型
      const type = this.qrCodeIns.type == 20 ? 1 : 2;

      // 提交功能
      updateAndAddQrCodeIns({
        'parentCode': this.qrCodeIns.qrCode,
        'type': type,
        'code': this.relationQrCodeList,
        'originalCode': this.qrCodeChildrenList,
        'deleteCode': this.unboundQrCodeList
        // 'oldParentCode':this.oldParentCode
      }).then( res => {
        if (res.code == 200){
          this.forbidden=0
          Notify({type: 'success', message: '重组成功'});
          this.clearSubmit()
          ScanOverlay.show('请扫描二维码')
        }
        // else if (res.code == 500){
        //   ScanOverlay.hide()
        //   this.forbidden=0
        // }
        else {
          ScanOverlay.hide()
          this.forbidden=0
          Dialog.confirm({ message: '替换失败，请重新替换' })
        }
      }).catch(()=>{
        ScanOverlay.hide()
        this.forbidden=0
        Dialog.confirm({ message: '替换失败，请重新替换' })
      })
    },
    // 件替换按钮
    pieceReplace(qrcode){
      // 件码与扫码相同
      if (this.qrCodeIns.qrCode.indexOf(qrcode) != -1){
        Notify({type: 'warning', message: '重复扫码', duration: 1500 });
        return ;
        // 第一次替换
      }else if (this.oldParentCode == null || this.oldParentCode == ""){
        this.oldParentCode = this.qrCodeIns.qrCode
        this.qrCodeIns.qrCode = qrcode
        Notify({type: 'success', message: '件码已替换'});
        // 第二次扫码
      }else if (this.oldParentCode != null && this.oldParentCode != null){
        Notify({type: 'success', message: '件码已替换'});
        if(this.oldParentCode.indexOf(qrcode) != -1){
          this.oldParentCode = ""
          this.qrCodeIns.qrCode = qrcode
        }else {
          this.qrCodeIns.qrCode = qrcode
        }

      }
    }
  }

}
</script>

<style scoped>
:deep(.van-cell-group){
  width: 660px;
  margin: auto;
  background: none !important;
}
:deep(.cell-flex-1-3_1 .van-cell){
  height: 147px;
  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)){
  height: 147px;
  margin-bottom: 20px;
  line-height: 147px;
  margin-top: 20px;
  border-radius: 15px;
  align-items: center;
}
:deep(.cell-flex-1-3_1 .van-cell:nth-of-type(1) .van-cell__value){
    display: block;
    height: 100%;
    line-height: 35px;
    text-align: left;
    padding-top: 50px;

}
:deep(.cell-flex-1-3_1 .van-cell:nth-of-type(2)){
  height: 104px;
  margin-bottom: 20px;
  line-height: 104px;
  margin-top: 20px;
  border-radius: 15px;
  align-items: center;
}
: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;
  }
</style>
