<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 id="centerDiv">
    <van-cell-group>
      <van-cell :title="$route.meta.type" :value="manualAssociationList.parentCode"/>
      <van-cell :title="$route.meta.smokeList">
        {{manualAssociationList.code.length}}/{{qrBrand.pkgNum != null? qrBrand.pkgNum: 10}}
      </van-cell>
      <van-cell title="卷烟信息名称" :value="qrBrand.cgtName"/>
    </van-cell-group>
  </div>
  <van-list class="list" :style="{height:listHeight + 'px',overflow:'auto'}">
    <van-cell v-for="codex in manualAssociationList.code" v-show="manualAssociationList != null">
      <van-row v-if="errorList.indexOf(codex) != -1" class="li" style="color: #FF0000">
        <van-col span="24">{{ codex }}</van-col>

      </van-row>
      <van-row class="li" v-else>
        <van-col span="24">{{ codex }}</van-col>

      </van-row>
    </van-cell>
  </van-list>

  <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} from "vant";
import {related, relatedBefore} 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 {encryptAES} from "@/utils/cryptoJS ";

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,
    [Notify.Component.name]: Notify.Component,
  },
  mounted() {
    this.initHeight();
    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/AC20150710025V12GTGRVRWVWMELBCDVY030")
    // setTimeout(() => {
    //   this.getQrBrandByCode("HTTPS://Y2WM.CN/99.1000.1/AC1015070002RPVY1IVSMGQTIJDCCOSP054");
    //   this.getQrBrandByCode("HTTPS://Y2WM.CN/99.1000.1/AC1015070002RPVY1IVSMGQTIJDCCOSP055");
    // }, 1000)
  },
  data() {
    return {
      listHeight: '',
      manualAssociationList: {
        parentCode: '',
        code: [],
        errorCode:"",
        type: 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,
    }
  },
  computed: {

    // 判断按钮是否能够点击
    relevanceButton() {
        if (this.forbidden==1){
            return true;
        }
      if (this.manualAssociationList.parentCode != null && this.manualAssociationList.parentCode != '') {
        return this.manualAssociationList.code.length == this.packageBoxNum.strip ? false : true
      }
      return true
    }
  },
  methods: {
    // 计算高度
    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 (res.data.pkgNum == null || res.data.pkgNum == 0){
          Notify({type: 'warning', message: '该品规小盒数量为0，无法进行盒条关联'});
          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});
          }
        }
      })
    },

    // 扫描二维码操作
    onScanQrCode(qrCode) {
      // 当扫码为件码 赋值件码，或者覆盖原有件码
      if (qrCode.typeCode == '20') {
        let qrcode = qrCode.code
        getQrcodeInsByCode({qrcode}).then(r=>{
          if (r.data.bTaskId != null){
            Notify({type: 'warning', message: '该烟码已迁移，无法再次操作', duration: 1500});
            this.isClearBrand()
            return
          }
          // if (r.data.qrCodeIns.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(res => {
              if (res.data.status == 30){
                Notify({type: 'warning', message: '该烟码关联的件烟已报废，无法再次关联', duration: 1500});
                this.isClearBrand()
              }else if (res.data.operUserId == 60) {
                Notify({type: 'warning', message: '该条烟有旧条件关联关系，并且关联的件已出库，无法再次操作', duration: 1500});
                this.isClearBrand()
              }else {
                if (res.data.status == 40){
                  Notify({type: 'warning', message: '该条烟码已成件，无法再次关联', duration: 1500});
                  this.isClearBrand()
                }else if (res.data.childrenList.length > 0){
                  Dialog.confirm({
                    message:'该烟码已有条件关联关系，是否再次关联',
                  }).then(() => {
                    this.manualAssociationList.parentCode = qrCode.code
                  }).catch(()=>{
                    this.isClearBrand()
                    ScanOverlay.show('请扫描二维码')
                  })
                } else {
                  this.manualAssociationList.parentCode = qrCode.code
                }
              }
            })
          }else {
            if (r.data.childrenList.length > 0){
              Dialog.confirm({
                message:'该烟码已有盒条关联关系，是否再次关联',
              }).then(() => {
                this.manualAssociationList.parentCode = qrCode.code
              }).catch(()=>{
                this.isClearBrand()
                ScanOverlay.show('请扫描二维码')
              })
            } else {
              this.manualAssociationList.parentCode = qrCode.code
            }
          }
        }).catch(()=>{
          this.manualAssociationList.parentCode = qrCode.code
          Notify({type: 'warning', message: '', duration:1});
        })
      } else if (qrCode.typeCode == '10') {
        // 条码
        if (this.manualAssociationList.code.indexOf(qrCode.code) > -1) {
          Dialog.alert({title: "重复扫码"});
        } else if (this.isMoreNum()) {
          let qrcode = qrCode.code
          getQrcodeInsByCode({qrcode}).then(res => {
            if (res.data.bTaskId != null){
              Notify({type: 'warning', message: '该烟码已迁移，无法再次操作', duration: 1500});
              this.isClearBrand()
              return
            }
            // if (res.data.unregistered == 5){
            //   Notify({type: 'warning', message: '该烟是黑户烟，无法再次关联，请先做解绑操作', duration: 1500});
            //   return
            // }
            //盒存在父节点
            if (res.data.parentCode != null && res.data.parentCode != '') {
              let pCode = res.data.parentCode
              // 判断盒码是否已成件
              getQrcodeInsByCode({"qrcode": pCode}).then(r => {
                if (r.data.parentCode != null && r.data.parentCode != '') {
                  Notify({type: 'warning', message: '该盒码已成件，无法再次关联', duration: 1500});
                  this.isClearBrand()
                }else {
                  this.showArr.unshift(qrCode.code)
                  let arr = [...new Set(this.showArr.map(item => JSON.stringify(item)))].map(item => JSON.parse(item));
                  this.manualAssociationList.code = arr
                }
              })
            }else {
              this.showArr.unshift(qrCode.code)
              let arr = [...new Set(this.showArr.map(item => JSON.stringify(item)))].map(item => JSON.parse(item));
              this.manualAssociationList.code = arr
            }
            // this.manualAssociationList.code.unshift(qrCode.code)
          }).catch(()=>{
            Notify({type: 'warning', message: '', duration: 1});
            // this.manualAssociationList.code.unshift(qrCode.code)
            this.showArr.unshift(qrCode.code)
            let arr = [...new Set(this.showArr.map(item => JSON.stringify(item)))].map(item => JSON.parse(item));
            this.manualAssociationList.code = arr
          })
        } else {
          Dialog.alert({title: "超过扫码数量"});
        }
      } else if (qrCode.typeCode == '30') {
        // 件吗或者其他
        Notify({type: 'warning', message: '此为件码', duration: 1500});
      } else {
        Notify({type: 'warning', message: '请扫描正确烟码', duration: 1500});
      }

    },
    //判断是否超过数量
    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() {
      this.manualAssociationList.type = 1
      this.forbidden=1
      ScanOverlay.show('关联中')
      // 保存操作记录到本地
      // let disassociationPo = {
      //   "qrCode": this.manualAssociationList.parentCode,
      //   "operationType": 1,
      //   "cgtName": this.qrBrand.cgtName,
      //   "userName": $store.state.user.name,
      // }
      relatedBefore(this.manualAssociationList).then(res => {
        if (res.code == 200 && res.data != null) {
          this.errorList = res.data
          this.manualAssociationList.errorCode = res.data
          Dialog.confirm({
            message: '二维码中存在关联数据,提交后会对老关联关系进行解绑,是否提交',
          }).then(() => {
            this.forbidden=0
            ScanOverlay.hide()
            related(this.manualAssociationList).then((res) => {
              if (res.code == 200) {
                this.forbidden=0
                this.resetAll();
                // OpenDataWap.pkgbox.insertQrCodeDisassociationPo(JSON.stringify(disassociationPo));
                Notify({type: 'success', message: '关联成功'});
                ScanOverlay.show('请扫描二维码')
              }
            })
          }).catch(() => {
            this.forbidden=0
            ScanOverlay.hide()
            Notify({type: 'warning', message: '关联取消'});
          });
        } else if (res.code == 200) {
          this.forbidden=0
          this.resetAll();
          // OpenDataWap.pkgbox.insertQrCodeDisassociationPo(JSON.stringify(disassociationPo));
          Notify({type: 'success', message: '关联成功'});
          ScanOverlay.show('请扫描二维码')
        }
      }).catch(()=>{
        ScanOverlay.hide()
        this.forbidden=0
      })
    },
    // 重置所有数据
    resetAll() {
      this.manualAssociationList = {
        parentCode: '',
        code: [],
        type: null
      }
      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 scoped>
:deep(.van-cell-group) {
  width: 660px;
  margin: auto;
  margin-top: 20px;
  background: none;
}

:deep(.van-cell-group .van-cell:nth-of-type(1)) {
  height: 147px;
  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: 20px;
}

:deep(.van-cell-group .van-cell:nth-of-type(1) .van-cell__title) {
  flex: .3;
}

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

:deep(.van-cell-group .van-cell:nth-of-type(2)) {
  height: 104px;
  border-radius: 15px;
  font-size: 26px;
  font-family: 'SourceHanSansCN-Medium',sans-serif;
  font-weight: 500;
  color: #000000;
  line-height: 104px;
  align-items: center;
  margin-bottom: 20px;
}

:deep(.van-cell-group .van-cell:nth-of-type(2) .van-cell__value) {
  display: block;
  line-height: 20px;
  font-family: 'SourceHanSansCN-Regular',sans-serif;
  font-weight: 400;
  color: #434343;
}
:deep(.van-cell-group .van-cell:nth-of-type(3)) {
  height: 104px;
  border-radius: 15px;
  font-size: 26px;
  font-family: 'SourceHanSansCN-Medium',sans-serif;
  font-weight: 500;
  color: #000000;
  line-height: 104px;
  align-items: center;
  margin-bottom: 20px;
}

:deep(.van-cell-group .van-cell:nth-of-type(3) .van-cell__value) {
  display: block;
  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;
}
</style>
